-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathid3
More file actions
executable file
·2331 lines (2118 loc) · 77.6 KB
/
id3
File metadata and controls
executable file
·2331 lines (2118 loc) · 77.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf8 -*-
usage = """Display or edit ID3 data in an mp3 file.
Usage: id3 [options] file.mp3 ...
Options:
With no editing options (below), dumps the id3 tag(s)
and exits.
Help:
-h --help short help (this list)
-H --long-help long help
--genres list genres and exit
--frame-types list Id3v2 frame types and exit
--image-types list picture types and exit
Output controls:
-v verbose
-s short form
-l long form output
-j json output
-1 only deal with Id3v1
-2 only deal with Id3v2
-f fmt Control output format; see long help
--write-images <dir> Extract all images to <dir>
Edit Id3 tags:
These options modify the mp3 file.
-a str Set artist
-A str Set album
-t str Set title
-c str Set comment
-c [[lang:]desc:]str Set comment with metadata. Lang defaults to "eng"
-n n Set track # (may be a string for Id3v2)
-g n Set genre by number
-g str Set genre by string (Id3v2 only)
-y nnnn Set year
-T fid:str Set arbitrary text frame, see --frame-types for list of <fid> values
-T fid: Delete text frame
-T TXXX:descr:str Set "TXXX" frame.
-T TXXX:desc: Delete "TXXX" frame.
--from-json <file> Read tags from json file.
--delete delete Id3 tag(s)
--add-image <file>:<type>[:description] Add a picture.
--remove-image <type> Remove a picture
--encoding latin1|utf16|utf16-be|utf8 Set encoding, id3v2 only (default utf8)
--2.2 Write Id3v2.2 tag
--2.3 Write Id3v2.3 tag
--2.4 Write Id3v2.4 tag (default)
--padding n Padding for new id3v2 tags (1024)
"""
long_help = """
Details:
When writing Id3v2 tags, the -a, -A, -t, -c, -n, -g, and -y options map to the
following named tags:
-a TPE1
-A TALB
-t TIT2
-c COMM
-y TYER
-n TRCK
-g TCON
Id3v1 text fields are always encoded with latin1. Avoid
strings that can't be encoded with latin1 if you're writing
an id3v1 tag, or if you've selected "--encoding latin1" for
Id3v2. Unencodable characters will be replaced with '?'.
The --2.x and --padding flags are ignored if there is already
an existing Id3v2 tag.
Editing options are processed in order. For example,
--remove -a "Annie Lennox" -t "Sisters"
would erase the existing ID3 tag and start a new one.
Where possible, this tool over-writes the existing tags in place.
Otherwise, it will re-write the entire .mp3 file, which may take
longer and requires the use of a temporary file.
By default, new Id3v2 tags are written with a certain amount
of padding, allowing them to be modified later without needing
to rewrite the entire mp3 file. The default padding is 1024
bytes, but you can change this with the --padding option. This
has no effect when modifying existing Id3v2 tags.
Output format:
The '-f' option lets you specify the format of the output.
Format string is literal text plus directives, e.g.
'%f: "%t", artist=%a, album=%A, length=%TLEN'
Directives are:
%f filename
%a artist
%A album
%t title
%c comment
%n track #
%g genre
%y year
%XXXX Id3V2 frame
Json:
The -j option writes a json file to stdout. Normally, it
generates an array of output as shown in the first example
below. If the -s (short) option is also given, then it
generates the third form, and only for the first file on
the command line.
On input, the --from-json option can accept several formats:
1: An array of id3 info blocks and filenames:
[
{"filename": "_path_",
"id3v1": {_id3_block_},
"id3v2": {_id3_block_}
},
...
]
This form does not require any filenames on the command line.
This form lets you modify multiple files. This is the format
emitted with the "-j" option.
2: A single id3 info block with a filename:
{"filename": "_path_",
"id3v1": {_id3_block_},
"id3v2": {_id3_block_}
}
This form does not require any filenames on the command line.
3: A single id3 info block with no filename. This information will
be applied to every file listed on the command line:
{"id3v1": {_id3_block_},
"id3v2": {_id3_block_}
}
4: A block of key/value pairs which will be applied to both id3 tags
on every file listed on the command line:
{_id3_block_}
The second two forms require file name(s) on the command line and
are applied equally to all files.
An _id3_block_ may consist of the following keys:
"title" string (TIT2)
"artist" string (TPE1)
"album" string (TALB)
"comment" string (COMM)
"year" string, 4 characters (TYER)
"track" number (TRCK)
"genre" number, use --genres for a list (TCON)
"Tttt" string, use --frame-types for a list
"TXXX" {"description":DESC, "value":STRING}
"Wwww" url string, use --frame-types for a list
"COMM" {"lang":LANG¹, "description":DESC, "value":STRING}
"APIC" {"type":TYPE², "description":DESC, "file":PATH}
If Id3V2 version is 2.2, the keys are the 3-character equivalents.
All strings are encoded utf-8 in json files.
¹ Language is ISO-639-2, e.g. "eng"
² Use --image-types for a list of image types.
Exit codes:
0 - command accepted, successful return
1 - ID3 data not found
2 - user error
3 - system error
Bugs and issues:
Id3v2.2, Id3v2.3, and Id3v2.4 define different sets of
frames. This app doesn't care, and supports any kind of frame
on any version of Id3v2. For example, any frame whose ident
starts with 'T' is accepted as a text frame.
Does not support Id3v2 earlier than 2.2
Id3v2.4 allows text frames to have multiple strings. This app
does not support this.
The standard allows for multiple frames with the same tag,
e.g. two "TALB" tags. This app will display all frames, but
when modifying a frame, only modifies the first instance of
a frame. Likewise, only the first instance of a frame will
be displayed when using a custom format.
Many frame types, such as "Synchronized tempo codes",
"Popularimeter", and so forth are not supported. If their size
is reasonably small (or -l is specified), they can be dumped
to json in base64 format. If you need support for any of
these, contact the author; they shouldn't be too hard to
add.
Extended headers, compression, and encryption are not
supported. I've never encountered an mp3 file in the wild
that uses these.
Python API Notes:
Read the source code for notes on the API which allows you
to use this module from your own python script.
"""
# API NOTES
#
# Sample usage:
#
# mp3info = Mp3Info(filename)
# id3v1 = Id3V1.read_from_file(filename, mp3info)
# id3v2 = Id3V2.read_from_file(filename, mp3info)
# id3v1.author = u"Billy Joel"
# id3v2.add_frame(Id3V2.TextFrame(id3v2).set("TPE1", u"Billy Joel", 3))
# rewrite_mp3_file(filename, mp3info, True, id3v1, True, id3v2)
#
#
#
# Mp3Info(filename)
# Returns an Mp3Info object that describes the locations of
# the Id3v1 and Id3v2 tags in the file. Several of the classes
# and functions below require this.
#
# Id3
# Abstract class for an Id3 tag. An Id3 object contains:
# version e.g. "1.1" or "2.3"
# title unicode string
# artist unicode string
# album unicode string
# year unicode string
# comment unicode string
# genre a number; see GENRES, below
# track a number
#
# Id3.GENRES a dict of number:"genre" pairs
#
#
# Id3V1 Class for an Id3v1 tag
#
# Id3V1.new() Factory class method that returns a new Id3V1 object
#
# Id3V1.read_from_file(filename, mp3info)
# Class method: read Id3v1 tag from file. Return None if not found.
#
# id3v1.write(ofile)
# Write this id3v1 tag to the given file. Caller must open the
# file for append. File should not already contain an Id3v1 tag.
# In practice, you should call rewrite_mp3_file() instead.
#
# id3v1.to_dict()
# Return a dict containing the contents of this id3 tag, suitable
# for e.g. writing to a json file.
#
#
# Id3V2
# Abstract class for an Id3v2 tag. An Id3v2 object contains
# the same elements as an Id3 object plus:
# frames array of Id3v2 frames in the tag
# content_size total size of all of the frames
# size size of the tag, including padding
# total_size size of the tag, including padding and headers
#
# Id3V2.IMAGE_TYPES Array of image type names
# Id3V2.FRAME_TYPES_2 Dict of Id3v2.2 frame types and their descriptions
# Id3V2.FRAME_TYPES Dict of Id3v2.[34] frame types and their descriptions
# Id3V2.ENCODINGS Array of supported string encodings
#
# Id3V22 Class for an Id3v2.2 tag
# Id3V23 Class for an Id3v2.3 tag
# Id3V24 Class for an Id3v2.4 tag
#
# Id3V2.new(major)
# Return a new empty Id3V2 tag. Major is 2, 3, or 4.
#
# Id3V2.read_from_file(filename, mp3info)
# Class method: read Id3v2 tag from file. Return None if not found.
#
# id3v2.write(ofile)
# Write this id3v2 tag to the given file. Caller must open the
# file for write and seek to the location where the tag should
# be written.
# In practice, you should call rewrite_mp3_file() instead.
#
# id3v2.to_dict()
# Return a dict containing the contents of this id3 tag, suitable
# for e.g. writing to a json file.
#
# id3v2.add_frame(frame)
# Add a frame to this tag. If there is a matching frame already
# present, it is removed.
#
# id3v2.append(frame)
# Unconditionally add a frame to the tag, even if a matching
# frame is already present.
#
# id3v2.del_frame(frame)
# Delete a frame from this tag. Input may be a minimal frame whose
# ident, and possibly other elements match the frame you want
# to delete.
#
# id3v2.compute_size()
# Recompute the content_size, size, and total_size for this tag.
# Always call this before calling set_size() or set_total_size().
#
# id3v2.set_size(size)
# Sets the size of the tag. Raise Id3V2.Id3Error if the requested
# size is less than content_size.
#
# id3v2.set_total_size(size)
# Sets the total size of the tag.
#
# Id3V2.Frame Generic frame type, superclass to other frame types
#
# Id3V2.Frame(id3v2)
# Constructor, id3v2 is the tag this frame is associated with
#
# frame.set(ident, size, flags, data)
# Set the properties of a frame. Size should normally be len(data)
#
# frame.full_str()
# Return human-readable description of frame. Examples:
# "MCDI (Music CD identifier): (%804 bytes)"
# "TPE1: Billy Joel"
# "APIC: FRONT_COVER, 41234 bytes"
#
# str(frame) Returns string representation of frame (latin1)
# unicode(frame) Returns unicode representation of frame
#
# Id3V2.TextFrame Text frame. Methods the same as for Frame, except:
#
# textframe.set(ident, string, encoding)
# Sets the string and encoding of the text frame. String is always
# unicode; encoding determines how it will be written to a file.
# Encoding is an int in 0-3, indexing into ("latin1", "utf16",
# "utf16-be", "utf8")
#
# Id3V2.TlenFrame Text frame containing length. Identical to Text
# frame except that ms are converted to hh:mm:ss.sss
# when returned as a string.
#
# Id3V2.TcopFrame Text frame containing copyright. Identical to Text
# frame except that string representation is preceded
# by "Copyright © "
#
# Id3V2.TxxxFrame User-specified text frame. Same as TextFrame except:
#
# txxxframe.set(ident, description, text, encoding)
# Sets the description of the text and the text. Meanings are
# entirely up to the user.
#
# Id3V2.UrlFrame Identical to TextFrame
#
# Id3V2.CommFrame Holds an arbitrary comment.
#
# commframe.set(ident, language, description, text, encoding)
# Language is an ISO-639-2 value, e.g. "eng". Description and
# text are entirely up to the user. Both are unicode strings
# and are encoded in the file according to encoding.
#
# Id3V2.ApicFrame Attached picture (Id3v2.3, Id3v2.4)
# Id3V2.PicFrame Attached picture (Id3v2.2)
#
# apicframe.set(filename, picture_type, description, encoding)
# Set the attached picture from the specified file (prefer .jpg or .png)
# picture_type is a value from Id3V2.IMAGE_TYPES. Description
# is an optional description of the image, encoded in the file
# according to encoding.
#
# apicframe.dummy(picture_type)
# Sets the frame's picture type, allowing the frame to be used
# as an argument to id3v2.del_frame().
#
# apicframe.write_image(destdir [,filename])
# Writes this frame's image to a file in the specified directory.
# Default filename is based on the image type, e.g. "OTHER.jpg"
# or "FRONT_COVER.png"
#
# apicframe.image()
# Returns the image data. (This is an in-memory copy in Python2.)
#
#
# rewrite_mp3_file(filename, mp3info, edit1, id3v1, edit2, id3v2)
# Function. Rewrites one or both Id3 tags in an mp3 file.
# filename filename to modify
# mp3info mp3info for this file
# edit1 flag: modify id3v1 tag
# id3v1 new Id3V1 tag to write
# edit2 flag: modify id3v2 tag
# id3v2 new Id3V2 tag to write
# If possible, the mp3 file is modified in place. Otherwise, it
# is replaced entirely, which can take longer if it's large.
# If edit1 is True but id3v1 is None, then any existing Id3V1
# frame is deleted. Ditto for edit2,id3v2.
# Programming note: most strings are stored internally as unicode (the
# exception is the ident field). The str() and repr() functions will
# convert that unicode to latin1. Id3v1 tags use latin1 internally.
# Id3v2 use latin1, utf16, or utf8.
import sys
import os
import string
import errno
import signal
import getopt
import re
import struct
import json
import locale
import codecs
verbose = 0
shortform = False
longform = False
encoding = 'utf-8'
iencoding = 3
id3v2_version = "2.3"
padding = 1024
TERM_ENC = 'UTF-8' # Terminal encoding.
class Mp3Info(object):
"""Info about the MP3 file that holds these ID3 tags."""
def __init__(self, filename = None):
self.id3v1_offset = 0 # Location and size of the Id3v1 tag, if any
self.id3v1_size = 0
self.id3v2_offset = 0 # Location and size of the Id3v2 tag, if any
self.id3v2_size = 0
self.audio_offset = 0 # Location and size of the MP3 audio data
self.audio_size = 0
self.size = 0 # Total size of the file
if filename:
self.examine(filename)
def examine(self, filename):
"""Examine an mp3 file to determine if it has id3 tags."""
self.size = os.path.getsize(filename)
self.audio_offset = 0
self.audio_size = self.size
with open(filename) as ifile:
# Look for trailing Id3v1 tag
ifile.seek(self.size - 128)
tag = ifile.read(3)
if tag == "TAG":
self.id3v1_offset = self.size - 128
self.id3v1_size = 128
self.audio_size -= 128
# Look for leading Id3v2 tag
ifile.seek(0)
header = ifile.read(10)
if header[0:3] == "ID3":
self.id3v2_offset = 0
self.id3v2_size = 10 + Id3V2.syncsafe(header[6:10])
# A couple basic sanity checks
if self.id3v2_size > self.audio_size:
print >>sys.stderr, "%s: id3 tag size %d is impossibly large" % \
(filename, self.id3v2_size)
self.id3v2_size = 0
else:
self.audio_offset += self.id3v2_size
self.audio_size -= self.id3v2_size
else:
# Look for trailing Id3v2 tag
# Look for a footer
ifile.seek(self.audio_size - 10)
foot = ifile.read(10)
if foot[0:3] == "ID3" and ord(foot[3]) >= 4 and (ord(foot[5]) & 0x10):
# Found one
self.id3v2_size = 10 + Id3V2.syncsafe(foot[6:10])
if self.id3v2_size > self.audio_size:
print >>sys.stderr, "%s: id3 tag size %d is impossibly large" % \
(filename, self.id3v2_size)
self.id3v2_size = 0
else:
self.id3v2_offset = self.audio_size - self.id3v2_size
self.audio_size -= self.id3v2_size
def __repr__(self):
return "<Mp3Info v1=(%d,%d), v2=(%d,%d), a=(%d,%d)>" % \
(self.id3v1_offset, self.id3v1_size,
self.id3v2_offset, self.id3v2_size,
self.audio_offset, self.audio_size)
class Id3(object):
"""Abstract superclass to V1 and V2"""
def __init__(self):
self.filename = None # string or None
self.version = u"" # string, e.g. "2.3"
self.title = u"" # string
self.artist = u"" # string
self.album = u"" # string
self.year = u"" # string
self.comment = u"" # string
self.genre = 0 # int
self.track = 0 # int
self.total_size = 0 # total size of this tag
def read(self, ifile, offset):
return False # subclass this
def dump(self):
global shortform, longform
if shortform:
print (u" id3v%-4s %4s %-30s %-30s %-30s %4s" % (self.version,
"" if self.track == 0 else str(self.track), self.artist,
self.title, self.album, self.year)).encode(TERM_ENC)
else:
print " id3v%s data:" % self.version
if self.title: print " title:", self.title.encode(TERM_ENC)
if self.artist: print " artist:", self.artist.encode(TERM_ENC)
if self.album: print " album:", self.album.encode(TERM_ENC)
if self.year: print " year:", self.year.encode(TERM_ENC)
if self.comment: print " comment:", self.comment.encode(TERM_ENC)
if self.genre: print " genre: %d (%s)" % (self.genre, self.genreStr())
if self.track: print " track:", self.track
def genreStr(self):
return Id3.GENRES.get(self.genre, "unknown")
def __repr__(self):
if self.track > 0:
rval = '<id3v%s: %s, %s, %s, %s, T%d, G%d>' % \
(self.version, self.artist, self.album, self.title,
self.year, self.track, self.genre)
else:
rval = '<id3v%s: %s, %s, %s, %s, G%d>' % \
(self.version, self.artist, self.album, self.title,
self.year, self.genre)
return rval.encode('latin1', 'replace')
format_scanner = re.Scanner([
(r'''\\.''', lambda s,t: t),
(r'''%[%A-Za-z]+''', lambda s,t: t),
(r'''[^%]+''', lambda s,t: t),
])
def formatted(self, format_str):
tokens, remainder = Id3.format_scanner.scan(format_str)
tokens = [self.get_field(x) if x.startswith('%') else x for x in tokens]
return u''.join(tokens) + remainder
def get_field(self, field):
if field == '%%': return '%'
if field == '%f': return self.filename
if field == '%a': return self.artist
if field == '%A': return self.album
if field == '%t': return self.title
if field == '%c': return self.comment
if field == '%n': return unicode(self.track)
if field == '%g': return unicode(self.genre)
if field == '%y': return self.year
return u''
GENRES = {
# From the standard
0: "Blues", 1: "Classic Rock", 2: "Country", 3: "Dance",
4: "Disco", 5: "Funk", 6: "Grunge", 7: "Hip-Hop",
8: "Jazz", 9: "Metal", 10: "New Age", 11: "Oldies",
12: "Other", 13: "Pop", 14: "Rhythm and Blues", 15: "Rap",
16: "Reggae", 17: "Rock", 18: "Techno", 19: "Industrial",
20: "Alternative", 21: "Ska", 22: "Death Metal", 23: "Pranks",
24: "Soundtrack", 25: "Euro-Techno", 26: "Ambient", 27: "Trip-Hop",
28: "Vocal", 29: "Jazz & Funk", 30: "Fusion", 31: "Trance",
32: "Classical", 33: "Instrumental", 34: "Acid", 35: "House",
36: "Game", 37: "Sound clip", 38: "Gospel", 39: "Noise",
40: "Alternative Rock", 41: "Bass", 42: "Soul", 43: "Punk",
44: "Space", 45: "Meditative",
46: "Instrumental Pop", 47: "Instrumental Rock",
48: "Ethnic", 49: "Gothic", 50: "Darkwave", 51: "Techno-Industrial",
52: "Electronic", 53: "Pop-Folk", 54: "Eurodance", 55: "Dream",
56: "Southern Rock", 57: "Comedy", 58: "Cult", 59: "Gangsta",
60: "Top 40", 61: "Christian Rap", 62: "Pop/Funk", 63: "Jungle music",
64: "Native US", 65: "Cabaret", 66: "New Wave", 67: "Psychedelic",
68: "Rave", 69: "Showtunes", 70: "Trailer", 71: "Lo-Fi",
72: "Tribal", 73: "Acid Punk", 74: "Acid Jazz", 75: "Polka",
76: "Retro", 77: "Musical", 78: "Rock ’n’ Roll", 79: "Hard Rock",
# Winamp extensions
80: "Folk", 81: "Folk-Rock", 82: "National Folk", 83: "Swing",
84: "Fast Fusion", 85: "Bebop", 86: "Latin", 87: "Revival",
88: "Celtic", 89: "Bluegrass", 90: "Avantgarde", 91: "Gothic Rock",
92: "Progressive Rock", 93: "Psychedelic Rock",
94: "Symphonic Rock", 95: "Slow Rock",
96: "Big Band", 97: "Chorus", 98: "Easy Listening", 99: "Acoustic",
100: "Humour", 101: "Speech", 102: "Chanson", 103: "Opera",
104: "Chamber Music", 105: "Sonata", 106: "Symphony", 107: "Booty Bass",
108: "Primus", 109: "Porn Groove", 110: "Satire", 111: "Slow Jam",
112: "Club", 113: "Tango", 114: "Samba", 115: "Folklore",
116: "Ballad", 117: "Power Ballad",
118: "Rhythmic Soul", 119: "Freestyle",
120: "Duet", 121: "Punk Rock", 122: "Drum Solo", 123: "A cappella",
124: "Euro-House", 125: "Dance Hall",
126: "Goa music", 127: "Drum & Bass",
128: "Club-House", 129: "Hardcore Techno", 130: "Terror", 131: "Indie",
132: "BritPop", 133: "Negerpunk", 134: "Polsk Punk", 135: "Beat",
136: "Christian Gangsta Rap", 137: "Heavy Metal",
138: "Black Metal", 139: "Crossover",
140: "Contemporary Christian", 141: "Christian Rock",
142: "Merengue", 143: "Salsa",
144: "Thrash Metal", 145: "Anime", 146: "Jpop", 147: "Synthpop",
148: "Abstract", 149: "Art Rock", 150: "Baroque", 151: "Bhangra",
152: "Big beat", 153: "Breakbeat", 154: "Chillout", 155: "Downtempo",
156: "Dub", 157: "EBM", 158: "Eclectic", 159: "Electro",
160: "Electroclash", 161: "Emo", 162: "Experimental", 163: "Garage",
164: "Global", 165: "IDM", 166: "Illbient", 167: "Industro-Goth",
168: "Jam Band", 169: "Krautrock", 170: "Leftfield", 171: "Lounge",
172: "Math Rock", 173: "New Romantic", 174: "Nu-Breakz", 175: "Post-Punk",
176: "Post-Rock", 177: "Psytrance", 178: "Shoegaze", 179: "Space Rock",
180: "Trop Rock", 181: "World Music",
182: "Neoclassical", 183: "Audiobook",
184: "Audio Theatre", 185: "Neue Deutsche Welle",
186: "Podcast", 187: "Indie-Rock",
188: "G-Funk", 189: "Dubstep", 190: "Garage Rock", 191: "Psybient",
}
class Id3V1(Id3):
@classmethod
def read_from_file(cls, filename, mp3info):
"""Given a file, read the Id3v1 tag from the end of it, if any."""
if mp3info.id3v1_size == 0: return None
with open(filename, "rb") as ifile:
id3v1 = Id3V1()
if id3v1.read(ifile, mp3info.id3v1_offset):
id3v1.filename = filename
return id3v1
else:
return None
@staticmethod
def new():
return Id3V1()
def __init__(self):
Id3.__init__(self)
self.version = "1"
self.total_size = 128
def read(self, ifile, offset):
ifile.seek(offset)
buf = ifile.read(128)
if buf[0:3] != "TAG": return False
self.title = buf[3:33].decode('latin1').rstrip('\0')
self.artist = buf[33:63].decode('latin1').rstrip('\0')
self.album = buf[63:93].decode('latin1').rstrip('\0')
self.year = buf[93:97].decode('latin1').rstrip('\0')
self.genre = ord(buf[127])
comment = buf[97:127]
# Look for v1.1
if comment[28] == '\0' and comment[29] != '\0':
self.track = ord(comment[29])
comment = comment[0:28]
self.version = "1.1"
self.comment = comment.decode('latin1').rstrip('\0')
return True
def write(self, ofile):
title = self.title.encode('latin1', 'replace')[:30].ljust(30,'\0')
artist = self.artist.encode('latin1', 'replace')[:30].ljust(30,'\0')
album = self.album.encode('latin1', 'replace')[:30].ljust(30,'\0')
year = self.year.encode('latin1', 'replace')[:4].ljust(4,'\0')
comment = self.comment.encode('latin1', 'replace')[:28].ljust(28,'\0')
buf = struct.pack("3s30s30s30s4s28sBBB", "TAG",
title, artist, album, year, comment,
0, int(self.track), int(self.genre))
ofile.write(buf)
def to_dict(self):
"""Return the _id3_block_ for this tag."""
rval = {}
if self.title: rval["title"] = self.title
if self.artist: rval["artist"] = self.artist
if self.album: rval["album"] = self.album
if self.comment: rval["comment"] = self.comment
if self.year: rval["year"] = self.year
if self.track: rval["track"] = self.track
if self.genre: rval["genre"] = self.genre
return rval
class Id3V2(Id3):
"""Superclass to all Id3V2 classes."""
# Id3v2 flags
F_UNSYNC = 0x80
F_COMPRESSION = 0x40 # 2.2 only
F_EXTHDR = 0x40
F_EXPERIMENTAL = 0x20
F_FOOTER = 0x10 # 2.4 and above only
@classmethod
def read_from_file(cls, filename, mp3info):
"""Given a file, read the Id3v2 tag from it, if any."""
if mp3info.id3v2_size == 0: return None
# All Id3V2 tags start with a 10-byte header. Read that
# to determine the actual tag version.
with open(filename, "rb") as ifile:
ifile.seek(mp3info.id3v2_offset)
head = ifile.read(10)
major = ord(head[3])
if major == 2: cls = Id3V22
elif major == 3: cls = Id3V23
elif major == 4: cls = Id3V24
else:
raise Id3V2.Id3Error("Id3 version 2.%d not supported" % major)
id3v2 = cls(major)
if id3v2.read(ifile, mp3info.id3v2_offset):
id3v2.filename = filename
return id3v2
else:
return None
@staticmethod
def new(major):
if major == 2: return Id3V22(major)
elif major == 3: return Id3V23(major)
elif major == 4: return Id3V24(major)
else: raise Id3V2.Id3Error("Id3 version 2.%d not supported" % major)
def __init__(self, major=3):
Id3.__init__(self)
self.frames = []
self.version = "2.%d" % major
self.major_version = major
self.ext_header = None
self.flags = 0
self.size = 0 # Size of tag, not counting headers
self.content_size = 0 # Size of actual content, including ext_header
# but not including header, padding, or footer
self.frame_header_size = 0
def read(self, ifile, offset):
"""Read Id3V2 tag from file."""
global verbose
ifile.seek(offset)
head = ifile.read(10)
#print "header:", [c for c in head]
(_, major, minor, flags, size) = struct.unpack(">3sBBB4s", head)
size = Id3V2.syncsafe(size)
self.version = "2.%d" % major
self.major_version = major
self.flags = flags
self.content_size = 0
self.size = size
self.total_size = 10 + self.size
if self.flags & Id3V2.F_FOOTER: self.total_size += 10
rem = self.size
if major >= 3 and self.flags & Id3V2.F_EXTHDR:
# There's an extended header present. There's nothing
# there we actually need. I've never heard of an app that
# even uses it.
self.ext_header = Id3V2.ExtendedHeader(self, ifile)
self.content_size += self.ext_header.size
rem -= self.ext_header.size
while rem > 0:
#print rem, "bytes remaining"
frame = self.read_frame(ifile)
if not frame: break
self.frames.append(frame)
self.content_size += frame.total_size
rem -= frame.total_size
return True
def write(self, ofile):
"""Write Id3V2 tag to file."""
global verbose
maj = self.major_version
buf = struct.pack(">3sbbbI",
"ID3", maj,0, self.flags, Id3V2.int2syncsafe(self.size))
ofile.write(buf)
if self.ext_header:
self.ext_header.write(self, ofile)
for frame in self.frames:
self.write_frame(frame, ofile)
if self.size > self.content_size:
padding = self.size - self.content_size
ofile.write('\0'*padding)
if self.flags & Id3V2.F_FOOTER:
ofile.write(buf)
def to_dict(self):
"""Return the _id3_block_ for this tag."""
rval = {}
for frame in self.frames:
k,v = frame.to_dict()
rval[k] = v
return rval
def add_frame(self, frame):
try:
idx = self.frames.index(frame)
self.frames[idx] = frame
except ValueError:
self.frames.append(frame)
def del_frame(self, frame):
"""Find a frame that matches this one and delete it."""
try:
idx = self.frames.index(frame)
del self.frames[idx]
except ValueError:
pass
def add_or_del_frame(self, frame, value):
"""If value, whatever it is, is false, delete the matching frame. Else,
replace it with this one."""
if value: self.add_frame(frame)
else: self.del_frame(frame)
def read_frame_header(self, ifile):
# Must be subclassed
return (None, 0,0)
def read_frame(self, ifile):
ident, size, flags = self.read_frame_header(ifile)
if ident == None: return None
if ident in FRAME_CLASSES:
frame = FRAME_CLASSES[ident](self).read(ident, size, flags, ifile)
elif ident[0] == 'T':
frame = Id3V2.TextFrame(self).read(ident, size, flags, ifile)
elif ident[0] == 'W':
frame = Id3V2.UrlFrame(self).read(ident, size, flags, ifile)
else:
frame = Id3V2.Frame(self).read(ident, size, flags, ifile)
# Look for a few standard fields
if ident in ('COMM', 'COM'):
if not self.comment or not frame.description:
self.comment = unicode(frame)
elif ident[0] == 'T':
if ident in ("TALB", 'TAL'): self.album = unicode(frame)
elif ident in ("TIT2", 'TT2'): self.title = unicode(frame)
elif ident in ("TPE1", 'TP1'): self.artist = unicode(frame)
elif ident in ("TYER", 'TYE'): self.year = unicode(frame)
elif ident in ('TRCK', 'TRK'): self.track = str2int(str(frame), 0)
elif ident in ('TCON', 'TCO'): self.genre = str2int(str(frame), 0)
elif ident in ("TDRC", "TDRL", "TDEN", "TDOR", "TDTG", "TORY") \
and not self.year:
self.year = unicode(frame)[:4]
return frame
def write_frame_header(self, frame, ofile):
# Must be subclassed
pass
def write_frame(self, frame, ofile):
self.write_frame_header(frame, ofile)
frame.write(ofile)
def append(self, frame):
self.frames.append(frame)
def set_size(self, size):
"""Set the size of the tag, not including header."""
header_size = 10
if size < self.content_size:
raise Id3V2.Id3Error("Attempt to set id3v2 tag size too small")
self.size = size
self.total_size = header_size + size
if self.flags & Id3V2.F_FOOTER: self.total_size += header_size
def set_total_size(self, size):
"""Set the size of the tag, including header."""
header_size = 10
self.set_size(size - header_size)
def compute_size(self):
"""Determine how much size this tag will require."""
header_size = 10
size = 0
if self.ext_header:
size += self.ext_header.total_size
for frame in self.frames:
size += frame.total_size
self.size = size
self.content_size = size
self.total_size = header_size + self.size
if self.flags & Id3V2.F_FOOTER: self.total_size += header_size
def dump(self):
global shortform, longform
if shortform:
Id3.dump(self)
else:
Id3.dump(self)
for frame in self.frames:
print " ", frame.full_str().encode(TERM_ENC)
if longform:
print "Padding: %d bytes" % (self.size - self.content_size)
def get_field(self, field):
if len(field) == 2:
return Id3.get_field(self, field)
field = field[1:]
for frame in self.frames:
if frame.ident == field:
return unicode(frame)
return u'-'
@staticmethod
def syncsafe(buf):
if type(buf) == int:
buf = [buf>>24 & 0xff, buf>>16 & 0xff, buf>>8 & 0xff, buf & 0xff]
return reduce(lambda a,b: a<<7|b, [c for c in buf])
else:
return reduce(lambda a,b: a<<7|b, [ord(c) for c in buf])
@staticmethod
def int2syncsafe(i):
"""Convert int to syncsafe int."""
buf = [i>>21 & 0x7f, i>>14 & 0x7f, i>>7 & 0x7f, i & 0x7f]
return reduce(lambda a,b: a<<8|b, [b for b in buf])
@staticmethod
def decode(buf, encoding):
if encoding == 0: return buf.decode("latin1").rstrip('\0')
if encoding == 1: return buf.decode("utf-16").rstrip('\0')
if encoding == 2: return buf.decode("utf-16BE").rstrip('\0')
return buf.decode("utf-8").rstrip('\0')
IMAGE_TYPES = ( "OTHER", "ICON", "OTHER_ICON", "FRONT_COVER", "BACK_COVER",
"LEAFLET", "MEDIA", "LEAD_ARTIST", "ARTIST", "CONDUCTOR", "BAND",
"COMPOSER", "LYRICIST", "RECORDING_LOCATION", "DURING_RECORDING",
"DURING_PERFORMANCE", "VIDEO", "BRIGHT_COLORED_FISH", "ILLUSTRATION",
"BAND_LOGO", "PUBLISHER_LOGO",)
FRAME_TYPES_2 = {
"UFI": "Unique file identifier",
"TT1": 'Content group description',
"TT2": 'Title/Songname/Content description',
"TT3": 'Subtitle/Description refinement',
"TP1": 'Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group',
"TP2": 'Band/Orchestra/Accompaniment',
"TP3": 'Conductor',
"TP4": 'Interpreted, remixed, or otherwise modified by',
"TCM": 'Composer(s)',
"TXT": 'Lyricist(s)/text writer(s)',
"TLA": 'Language(s)',
"TCO": 'Content type',
"TAL": 'Album/Movie/Show title',
"TPA": 'Part of a set',
"TRK": 'Track number/Position in set',
"TRC": 'ISRC',
"TYE": 'Year',
"TDA": 'Date',
"TIM": 'Time',
"TRD": 'Recording dates',
"TMT": 'Media type',
"TFT": 'File type',
"TBP": 'beats per minute',
"TCR": 'Copyright message',
"TPB": 'Publisher',
"TEN": 'Encoded by',
"TSS": 'Software/hardware and settings used for encoding',
"TOF": 'Original filename',
"TLE": 'Length',
"TSI": 'Size',
"TDY": 'Playlist delay',
"TKE": 'Initial key',
"TOT": 'Original album/Movie/Show title',
"TOA": 'Original artist(s)/performer(s)',
"TOL": 'Original Lyricist(s)/text writer(s)',
"TOR": 'Original release year',
"TXX": 'User defined text information frame',
"WAF": 'Official audio file webpage',