-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew.py
More file actions
executable file
·2134 lines (1904 loc) · 69.8 KB
/
new.py
File metadata and controls
executable file
·2134 lines (1904 loc) · 69.8 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
# Genres: http://www.multimediasoft.com/amp3dj/help/amp3dj_00003e.htm
# MP3: http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
# ID3v1: http://en.wikipedia.org/wiki/Id3#Layout
# ID3v2: http://www.id3.org/Developer_Information
# RVA: http://git.savannah.gnu.org/cgit/gnupod.git/tree/src/ext/FileMagic.pm
# IFF: http://en.wikipedia.org/wiki/Interchange_File_Format
# RIFF: http://www.midi.org/about-midi/rp29spec(rmid).pdf
# MP4: http://atomicparsley.sourceforge.net/mpeg-4files.html
# Vorbis: http://www.xiph.org/vorbis/doc/v-comment.html
# FLAC: http://flac.sourceforge.net/format.html#stream
# OGG: http://en.wikipedia.org/wiki/Ogg#File_format
# CRC: http://www.ross.net/crc/download/crc_v3.txt
from struct import error as StructError, Struct
from collections import MutableMapping
from math import log
import sys
import os
import re
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
from PIL import Image
from PIL.ImageFile import ImageFile
PIL = True
except ImportError:
PIL = False
ANYITEM = -1
LANG = 'eng'
GAPLESS = u'iTunPGAP'
ENCODING = 'utf-8'
IMAGE_SAMPLE_SIZE = 512
DEFAULT_ID3V2_VERSION = 2
DEFAULT_ID3V2_PADDING = 128
FAKEMP3 = '\xff\xf3\x14\xc4' * 7
BLOCKSIZE = 4096
DICT, IDICT, TEXT, UINT16, BOOL, UINT16X2, GENRE, IMAGE, UINT32, VOLUME = [
2 ** i for i in xrange(10)]
TYPES = {'_comment': DICT,
'_image': IDICT,
'_lyrics': DICT,
'_unknown': DICT,
'album': TEXT,
'album_artist': TEXT,
'artist': TEXT,
'bpm': UINT16,
'comment': TEXT,
'compilation': BOOL,
'composer': TEXT,
'disk': UINT16X2,
'encoder': TEXT,
'gapless': BOOL,
'genre': GENRE,
'grouping': TEXT,
'image': IMAGE,
'lyrics': TEXT,
'name': TEXT,
'sort_album': TEXT,
'sort_album_artist': TEXT,
'sort_artist': TEXT,
'sort_composer': TEXT,
'sort_name': TEXT,
'sort_video_show': TEXT,
'track': UINT16X2,
'video_description': TEXT,
'video_episode': UINT32,
'video_episode_id': TEXT,
'video_season': UINT32,
'video_show': TEXT,
'volume': VOLUME,
'year': UINT16}
GENRES = ['Blues', 'Classic Rock', 'Country', 'Dance', 'Disco', 'Funk',
'Grunge', 'Hip-Hop', 'Jazz', 'Metal', 'New Age', 'Oldies', 'Other',
'Pop', 'R&B', 'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial',
'Alternative', 'Ska', 'Death Metal', 'Pranks', 'Soundtrack',
'Euro-Techno', 'Ambient', 'Trip-Hop', 'Vocal', 'Jazz+Funk', 'Fusion',
'Trance', 'Classical', 'Instrumental', 'Acid', 'House', 'Game',
'Sound Clip', 'Gospel', 'Noise', 'Alternative Rock', 'Bass', 'Soul',
'Punk', 'Space', 'Meditative', 'Instrumental Pop',
'Instrumental Rock', 'Ethnic', 'Gothic', 'Darkwave',
'Techno-Industrial', 'Electronic', 'Pop-Folk', 'Eurodance', 'Dream',
'Southern Rock', 'Comedy', 'Cult', 'Gangsta', 'Top 40',
'Christian Rap', 'Pop/Funk', 'Jungle', 'Native US', 'Cabaret',
'New Wave', 'Psychadelic', 'Rave', 'Showtunes', 'Trailer', 'Lo-Fi',
'Tribal', 'Acid Punk', 'Acid Jazz', 'Polka', 'Retro', 'Musical',
'Rock & Roll', 'Hard Rock', 'Folk', 'Folk-Rock', 'National Folk',
'Swing', 'Fast Fusion', 'Bebob', 'Latin', 'Revival', 'Celtic',
'Bluegrass', 'Avantgarde', 'Gothic Rock', 'Progressive Rock',
'Psychedelic Rock', 'Symphonic Rock', 'Slow Rock', 'Big Band',
'Chorus', 'Easy Listening', 'Acoustic', 'Humour', 'Speech',
'Chanson', 'Opera', 'Chamber Music', 'Sonata', 'Symphony',
'Booty Bass', 'Primus', 'Porn Groove', 'Satire', 'Slow Jam', 'Club',
'Tango', 'Samba', 'Folklore', 'Ballad', 'Power Ballad',
'Rhythmic Soul', 'Freestyle', 'Duet', 'Punk Rock', 'Drum Solo',
'Acapella', 'Euro-House', 'Dance Hall', 'Goa', 'Drum & Bass',
'Club - House', 'Hardcore', 'Terror', 'Indie', 'BritPop',
'Negerpunk', 'Polsk Punk', 'Beat', 'Christian Gangsta Rap',
'Heavy Metal', 'Black Metal', 'Crossover', 'Contemporary Christian',
'Christian Rock', 'Merengue', 'Salsa', 'Thrash Metal', 'Anime',
'JPop', 'Synthpop']
TRUE = 'y', 'yes', 'true', 't', '1', '\x01', 'on'
ID3V2_OPTS = {2: (Struct('3s3s0s'), False,
{'COM': '_comment',
'PIC': '_image',
'RVA': 'volume',
'TAL': 'album',
'TBP': 'bpm',
'TCM': 'composer',
'TCO': 'genre',
'TCP': 'compilation',
'TEN': 'encoder',
'TP1': 'artist',
'TP2': 'album_artist',
'TPA': 'disk',
'TRK': 'track',
'TS2': 'sort_album_artist',
'TSA': 'sort_album',
'TSC': 'sort_composer',
'TSP': 'sort_artist',
'TST': 'sort_name',
'TT1': 'grouping',
'TT2': 'name',
'TT3': 'video_description',
'TYE': 'year',
'ULT': '_lyrics'}),
3: (Struct('4s4s2s'), False,
{'APIC': '_image',
'COMM': '_comment',
'RVAD': 'volume',
'TALB': 'album',
'TBPM': 'bpm',
'TCMP': 'compilation',
'TCOM': 'composer',
'TCON': 'genre',
'TENC': 'encoder',
'TIT1': 'grouping',
'TIT2': 'name',
'TIT3': 'video_description',
'TPE1': 'artist',
'TPE2': 'album_artist',
'TPOS': 'disk',
'TRCK': 'track',
'TSO2': 'sort_album_artist',
'TSOC': 'sort_composer',
'TYER': 'year',
'USLT': '_lyrics'}),
4: (Struct('4s4s2s'), True,
{'APIC': '_image',
'COMM': '_comment',
'RVA2': 'volume',
'TALB': 'album',
'TBPM': 'bpm',
'TCMP': 'compilation',
'TCOM': 'composer',
'TCON': 'genre',
'TDRC': 'year',
'TENC': 'encoder',
'TIT1': 'grouping',
'TIT2': 'name',
'TIT3': 'video_description',
'TPE1': 'artist',
'TPE2': 'album_artist',
'TPOS': 'disk',
'TRCK': 'track',
'TSO2': 'sort_album_artist',
'TSOA': 'sort_album',
'TSOC': 'sort_composer',
'TSOP': 'sort_artist',
'TSOT': 'sort_name',
'USLT': '_lyrics'})}
ID3V2_TAGS = dict(x for y in ID3V2_OPTS.itervalues() for x in y[2].iteritems())
ID3V1_ATTRS = ['name', 'artist', 'album', 'year', 'comment', 'track', 'genre']
ID3V2_ENCS = {'\x00': ('latin-1', '\x00'),
'\x01': ('utf-16', '\x00\x00'),
'\x02': ('utf-16-be', '\x00\x00'),
'\x03': ('utf-8', '\x00')}
MP3_SAMPLESIZE = 2502
MP3_BITRATES = [
[32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448],
[32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384],
[32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
[32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256],
[8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]]
MP3_SRATES = [[11025, 12000, 8000, 0], None, [22050, 24000, 16000, 0],
[44100, 48000, 32000, 0]]
IFF_IDS = {'ANNO': 'comment',
'AUTH': 'artist',
'IART': 'artist',
'ICMT': 'comment',
'ICRD': 'year',
'INAM': 'name',
'NAME': 'name'}
A_NODE, A_SKIP, A_DATA, A_DICT = [2 ** i for i in xrange(4)]
ATOM_UTF8 = 1
ATOM_UINT = 21
ATOM_UINT16 = 0
ATOM_PNG = 14
ATOM_JPG = 13
ATOMS = {'moov': (A_NODE, None),
'moov.udta': (A_NODE, None),
'moov.udta.meta': (A_NODE | A_SKIP, None),
'moov.udta.meta.ilst': (A_NODE, None),
'moov.udta.meta.ilst.----': (A_DICT, None),
'moov.udta.meta.ilst.aART': (A_NODE | A_DATA, 'album_artist'),
'moov.udta.meta.ilst.covr': (A_NODE | A_DATA, 'image'),
'moov.udta.meta.ilst.cpil': (A_NODE | A_DATA, 'compilation'),
'moov.udta.meta.ilst.desc': (A_NODE | A_DATA, 'video_description'),
'moov.udta.meta.ilst.disk': (A_NODE | A_DATA, 'disk'),
'moov.udta.meta.ilst.gnre': (A_NODE | A_DATA, 'genre'),
'moov.udta.meta.ilst.pgap': (A_NODE | A_DATA, 'gapless'),
'moov.udta.meta.ilst.soaa': (A_NODE | A_DATA, 'sort_album_artist'),
'moov.udta.meta.ilst.soal': (A_NODE | A_DATA, 'sort_album'),
'moov.udta.meta.ilst.soar': (A_NODE | A_DATA, 'sort_artist'),
'moov.udta.meta.ilst.soco': (A_NODE | A_DATA, 'sort_composer'),
'moov.udta.meta.ilst.sonm': (A_NODE | A_DATA, 'sort_name'),
'moov.udta.meta.ilst.sosn': (A_NODE | A_DATA, 'sort_video_show'),
'moov.udta.meta.ilst.tmpo': (A_NODE | A_DATA, 'bpm'),
'moov.udta.meta.ilst.trkn': (A_NODE | A_DATA, 'track'),
'moov.udta.meta.ilst.tven': (A_NODE | A_DATA, 'video_episode_id'),
'moov.udta.meta.ilst.tves': (A_NODE | A_DATA, 'video_episode'),
'moov.udta.meta.ilst.tvsh': (A_NODE | A_DATA, 'video_show'),
'moov.udta.meta.ilst.tvsn': (A_NODE | A_DATA, 'video_season'),
'moov.udta.meta.ilst.\xa9ART': (A_NODE | A_DATA, 'artist'),
'moov.udta.meta.ilst.\xa9alb': (A_NODE | A_DATA, 'album'),
'moov.udta.meta.ilst.\xa9cmt': (A_NODE | A_DATA, 'comment'),
'moov.udta.meta.ilst.\xa9day': (A_NODE | A_DATA, 'year'),
'moov.udta.meta.ilst.\xa9gen': (A_NODE | A_DATA, 'genre'),
'moov.udta.meta.ilst.\xa9grp': (A_NODE | A_DATA, 'grouping'),
'moov.udta.meta.ilst.\xa9lyr': (A_NODE | A_DATA, 'lyrics'),
'moov.udta.meta.ilst.\xa9nam': (A_NODE | A_DATA, 'name'),
'moov.udta.meta.ilst.\xa9too': (A_NODE | A_DATA, 'encoder'),
'moov.udta.meta.ilst.\xa9wrt': (A_NODE | A_DATA, 'composer')}
VORBIS_TAGS = {'album': 'album',
'album artist': 'album_artist',
'album_artist': 'album_artist',
'albumartist': 'album_artist',
'artist': 'artist',
'beats per minute': 'bpm',
'beats_per_minute': 'bpm',
'beatsperminute': 'bpm',
'bpm': 'bpm',
'comment': 'comment',
'comments': 'comment',
'compilation': 'compilation',
'composer': 'composer',
'date': 'year',
'disc': 'disk',
'disc number': 'disk',
'disc_number': 'disk',
'discnumber': 'disk',
'disk': 'disk',
'disk number': 'disk',
'disk_number': 'disk',
'disknumber': 'disk',
'encoder': 'encoder',
'gapless': 'gapless',
'gapless playback': 'gapless',
'gapless_playback': 'gapless',
'gaplessplayback': 'gapless',
'genre': 'genre',
'grouping': 'grouping',
'lyrics': 'lyrics',
'name': 'name',
'sort album': 'sort_album',
'sort album artist': 'sort_album_artist',
'sort artist': 'sort_artist',
'sort composer': 'sort_composer',
'sort name': 'sort_name',
'sort video show': 'sort_video_show',
'sort_album': 'sort_album',
'sort_album_artist': 'sort_album_artist',
'sort_artist': 'sort_artist',
'sort_composer': 'sort_composer',
'sort_name': 'sort_name',
'sort_video_show': 'sort_video_show',
'sortalbum': 'sort_album',
'sortalbumartist': 'sort_album_artist',
'sortartist': 'sort_artist',
'sortcomposer': 'sort_composer',
'sortname': 'sort_name',
'sortvideoshow': 'sort_video_show',
'tempo': 'bpm',
'title': 'name',
'track': 'track',
'track number': 'track',
'track_number': 'track',
'tracknumber': 'track',
'video description': 'video_description',
'video episode': 'video_episode',
'video episode id': 'video_episode_id',
'video season': 'video_season',
'video show': 'video_show',
'video_description': 'video_description',
'video_episode': 'video_episode',
'video_episode_id': 'video_episode_id',
'video_season': 'video_season',
'video_show': 'video_show',
'videodescription': 'video_description',
'videoepisode': 'video_episode',
'videoepisodeid': 'video_episode_id',
'videoseason': 'video_season',
'videoshow': 'video_show',
'volume': 'volume',
'year': 'year'}
class TaglibError(Exception):
"""Base error class"""
class ValidationError(TaglibError):
"""Raised on data validation error"""
class DecodeError(TaglibError):
"""Raised on decode failure"""
class EncodeError(TaglibError):
"""Error encoding"""
class InvalidMedia(DecodeError):
"""Raised when media is unreadable"""
DecodeErrors = ValidationError, DecodeError, StructError, IOError, OSError
EncodeErrors = EncodeError, StructError, IOError, OSError
class Container(MutableMapping):
"""Flexible container object"""
types = {}
def __init__(self, *args, **kwargs):
self.__dict__.update(dict.fromkeys(self.types))
self.__dict__.update(*args, **kwargs)
self.reset()
@property
def modified(self):
"""True if public attributes have been modified"""
return bool(self.__changed)
@property
def changed(self):
"""List of modified attributes"""
return sorted(self.__changed)
def reset(self):
"""Reset modified status"""
self.__changed = set()
def getrepr(self, attr):
"""Get string representation for attribute"""
return repr(self[attr])
def __getitem__(self, attr):
"""Map dictionary access to attributes"""
return self.__getattribute__(attr)
def __getattribute__(self, attr):
"""Safe attribute access"""
try:
return super(Container, self).__getattribute__(attr)
except AttributeError:
if attr not in self.types:
raise
def __setitem__(self, attr, val):
"""Map dictionary access to attributes"""
self.__setattr__(attr, val)
def __setattr__(self, attr, val):
"""Safe attribute access"""
try:
val = self.validate(val, self.types[attr])
if val != self[attr]:
self.__changed.add(attr)
except KeyError:
pass
except ValidationError, error:
error.args = '%s: %s' % (attr, error),
raise
super(Container, self).__setattr__(attr, val)
def __delitem__(self, attr):
"""Map dictionary access to attrs"""
self.__delattr__(attr)
def __delattr__(self, attr):
"""Safe attribute access"""
if attr in self.types:
self.__setattr__(attr, None)
else:
super(Container, self).__delattr__(attr)
def __iter__(self):
"""Yields public attributes"""
return (attr for attr in sorted(self.types)
if not attr.startswith('_') and self[attr] is not None)
def __len__(self):
"""Length of public attributes"""
return sum(1 for _ in self.__iter__())
def __repr__(self):
"""String representation of public attributes"""
attrs = ', '.join('%s=%s' % (attr, self.getrepr(attr)) for attr in self)
return '<%s object at 0x%x%s%s>' % (
type(self).__name__, id(self), ': ' if attrs else '', attrs)
@classmethod
def validate(cls, val, dtype=None):
"""Validate attribute data"""
try:
return cls.transform(val, dtype)
except Exception, error:
raise ValidationError, error, sys.exc_traceback
@staticmethod
def transform(val, dtype=None):
"""Transform data to type"""
return dtype(val)
class Metadata(Container):
"""Media metadata"""
types = TYPES
@property
def image_sample(self):
"""Sample of image"""
image = self.image
if image:
val = StringIO()
image.save(val, image.format)
val.seek(0)
return val.read(IMAGE_SAMPLE_SIZE), image.size, image.format
@property
def rounded_volume(self):
"""Rounded string volume"""
if self.volume is not None:
return '%.1f' % round(self.volume)
return '0.0'
def getrepr(self, attr, encoding=None):
"""Get string representation for attribute"""
val = self[attr]
try:
dtype = self.types[attr]
except KeyError:
dtype is None
if val is None or dtype is None:
return repr(val)
if dtype == BOOL:
return 'Yes' if val else 'No'
elif dtype in (GENRE, TEXT):
if encoding is None:
encoding = ENCODING
return val.encode(encoding)
elif dtype == IMAGE:
return '%dx%d %s Image' % (val.size[0], val.size[1], val.format)
elif dtype in (UINT16, UINT32):
return str(val)
elif dtype == UINT16X2:
return '%d/%d' % tuple(val)
elif dtype == VOLUME:
return '%.1f' % val
def __eq__(self, other):
"""Compare objects"""
if not isinstance(other, Metadata):
return NotImplemented
try:
self.compare(self, other)
except ValidationError:
return False
return True
def __ne__(self, other):
"""Test inequality"""
val = self.__eq__(other)
if val is NotImplemented:
return val
return not val
@staticmethod
def transform(val, dtype=None):
"""Transform data to type"""
raise ValidationError('read-only')
@classmethod
def compare(cls, x, y):
"""Compare two metadata objects"""
for attr, dtype in cls.types.iteritems():
if dtype in (DICT, IDICT):
continue
if dtype == IMAGE:
xval, yval = x.image_sample, y.image_sample
elif dtype == VOLUME:
xval, yval = x.rounded_volume, y.rounded_volume
else:
xval, yval = x[attr], y[attr]
if xval != yval:
raise ValidationError('%s: %r != %r' % (attr, xval, yval))
class AttrMap(object):
"""Fail back attribute access to another object"""
attrmap = None
def __getattribute__(self, attr):
"""Fail back attribute access to another object"""
get = super(AttrMap, self).__getattribute__
try:
return get(attr)
except AttributeError:
if not self.attrmap:
raise
exc_type, exc_value, exc_traceback = sys.exc_info()
try:
return get(self.attrmap).__getattribute__(attr)
except AttributeError:
raise exc_type, exc_value, exc_traceback
class Open(AttrMap):
"""Flexible open container"""
attrmap = 'fp'
def __init__(self, file, mode='rb', context_close=False):
if isinstance(file, basestring):
self.fp = open(file, mode)
self.external = False
elif isinstance(file, (int, long)):
self.fp = os.fdopen(file, mode)
self.external = True
elif hasattr(file, 'seek'):
self.fp = file
self.external = True
else:
raise TypeError('file must be a path, fd, or fileobj')
self.context_close = context_close
def __enter__(self):
"""Enter open context"""
if self.external:
self.pos = self.tell()
return self
def __exit__(self, *exc_info):
"""Exit open context"""
if self.external:
self.seek(self.pos)
elif self.context_close:
self.close()
class Decoder(AttrMap, Metadata):
"""Base decoder class"""
attrmap = 'fp'
format = None
editable = False
uint32be = Struct('>L')
uint32le = Struct('<L')
int16be = Struct('>h')
uint16be = Struct('>H')
longbytes = Struct('4B')
def __init__(self, file):
if not self.format:
raise DecodeError('unable to use base decoder')
super(Decoder, self).__init__()
if self.editable:
mode = 'rb+'
context_close = False
else:
mode = 'rb'
context_close = True
with Open(file, mode, context_close) as fp:
self.fp = fp
try:
self.decode()
except DecodeErrors, error:
raise InvalidMedia, error, sys.exc_traceback
self.reset()
def getdict(self, attr, key):
"""Get managed dict item"""
d = self[attr]
if d:
if key == ANYITEM:
key = sorted(d)[0]
return d.get(key)
def setdict(self, attr, key, val):
"""Set managed dict item"""
if val is None:
self.deldict(attr, key)
else:
d = self[attr]
if not d:
d = self[attr] = {}
d[key] = val
def deldict(self, attr, key):
"""Delete managed dict item"""
d = self[attr]
if d:
if key == ANYITEM:
key = sorted(d)[0]
try:
del d[key]
if not d:
del self[attr]
except KeyError:
pass
def decode(self):
"""Decode metadata"""
raise DecodeError('not implemented')
def dump(self, file=None, **kwargs):
"""Dump to file"""
if not self.format:
raise EncodeError('unable to use base decoder')
if not self.editable:
raise EncodeError('%s does not support encoding' % self.format)
if file is None:
file = StringIO()
with Open(file, 'wb') as fp:
self.encode(fp, inplace=False, **kwargs)
if not fp.closed:
return fp
def dumps(self, **kwargs):
"""Dump to string"""
return self.dump(**kwargs).getvalue()
def save(self, **kwargs):
"""Save updated metadata"""
self.encode(self.fp, inplace=True, **kwargs)
def encode(self, fp, inplace=False, **kwargs):
"""Encode to open file"""
raise EncodeError('not implemented')
def seekend(self, pos=0):
"""Seek backwards from end of file"""
self.seek(pos * -1, os.SEEK_END)
def seekcur(self, pos):
"""Seek from current position"""
self.seek(pos, os.SEEK_CUR)
def unpack(self, struct):
"""Read and unpack based on structure"""
val = struct.unpack(self.read(struct.size))
if len(val) == 1:
return val[0]
return val
@staticmethod
def transform(val, dtype=None):
"""Transform data to type"""
if val is None or dtype is None:
return val
if dtype in (DICT, IDICT):
if not isinstance(val, dict):
raise TypeError('must be a dictionary')
return val
if dtype == IMAGE:
if not PIL:
raise ValueError('PIL required')
if not isinstance(val, ImageFile):
val = Image.open(val)
val.load()
return val
if dtype == GENRE:
if isinstance(val, (int, long)):
val = GENRES[val]
dtype = TEXT
if dtype == TEXT and not isinstance(val, basestring):
val = str(val)
if isinstance(val, str):
val = val.decode('ascii', 'ignore')
if isinstance(val, unicode):
val = val.replace('\x00', '').strip()
if not val:
return
if dtype == TEXT:
return val
if dtype == BOOL:
if isinstance(val, basestring):
return val.lower() in TRUE
elif not isinstance(val, bool):
val = bool(val)
return val
if dtype in (UINT16, UINT32):
if not isinstance(val, (int, long)):
val = int(val)
if val < 0:
val = 0
elif dtype == UINT16 and val > 0xffff:
val = 0xffff
elif dtype == UINT32 and val > 0xffffffff:
val = 0xffffffff
if not val:
return
return val
if dtype == VOLUME:
if not isinstance(val, float):
val = float(val)
if val < -99.9:
val = -99.9
elif val > 100.0:
val = 100.0
return val
if dtype == UINT16X2:
if isinstance(val, tuple):
val = list(val)
elif isinstance(val, unicode):
val = val.split('/')
elif not isinstance(val, list):
val = [val]
if not val:
return
if len(val) == 1:
val.append(0)
elif len(val) != 2:
raise ValueError('must have 1 or 2 items')
for i, item in enumerate(val):
if not isinstance(item, (int, long)):
item = int(item)
if item < 0:
item = 0
elif item > 0xffff:
item = 0xffff
val[i] = item
if val == [0, 0]:
return
return val
@classmethod
def getint(cls, bytes, struct=None):
"""Convert bytes to integer"""
if struct is None:
struct = cls.uint32be
return struct.unpack('\x00' * (struct.size - len(bytes)) + bytes)[0]
@staticmethod
def copyfile(src, dst, blocksize=None):
"""Copy source file to destination"""
if blocksize is None:
blocksize = BLOCKSIZE
while True:
data = src.read(blocksize)
if not data:
break
dst.write(data)
class MP3Head(Container):
"""Container object for mp3 frame head attributes"""
types = {'srate_idx': int, 'layer': int, 'sync': bool, 'private': int,
'mode_ext': int, 'padding': int, 'emphasis': int, 'version': int,
'bitrate_idx': int, 'mode': int, 'valid': bool, 'copyright': bool,
'protected': bool, 'original': bool}
head = Decoder.uint32be
def __init__(self, bytes):
"""Decode MP3 frame header"""
super(MP3Head, self).__init__()
val = self.head.unpack(bytes)[0]
self.sync = val & 0xffe00000 == 0xffe00000
self.version = val >> 19 & 0x03
self.layer = 4 - (val >> 17 & 0x03)
self.protected = val >> 16 & 0x01 == 0x00
self.bitrate_idx = (val >> 12 & 0x0f) - 1
self.srate_idx = val >> 10 & 0x03
self.padding = val >> 9 & 0x01
self.private = val >> 8 & 0x01
self.mode = val >> 6 & 0x03
self.mode_ext = val >> 4 & 0x03
self.copyright = val >> 3 & 0x01 == 0x01
self.original = val >> 2 & 0x01 == 0x01
self.emphasis = val & 0x03
@property
def valid(self):
"""True if this is a valid mp3 header"""
return (self.sync and self.version != 1 and self.layer != 4 and
self.bitrate_idx not in (-1, 14) and self.srate_idx != 3)
@property
def valid_bitrates(self):
"""List of valid bitrates"""
if self.version == 3:
idx = self.layer - 1
elif self.layer == 1:
idx = 3
else:
idx = 4
return MP3_BITRATES[idx]
@property
def bitrate(self):
"""This frame's bitrate"""
return self.valid_bitrates[self.bitrate_idx]
@property
def valid_srates(self):
"""List of valid sample rates"""
return MP3_SRATES[self.version]
@property
def srate(self):
"""Sample rate"""
return self.valid_srates[self.srate_idx]
@property
def length(self):
"""Length of this frame"""
if self.layer == 1:
return (self.bitrate * 12000 / self.srate + self.padding) << 2
else:
srate = self.srate
if self.version2 or self.version25:
srate <<= 1
return self.bitrate * 144000 / srate + self.padding
@property
def version2(self):
"""True if this is a version2 mp3"""
return self.version & 0x02 == 0x00
@property
def version25(self):
"""True if this is a version2.5 mp3"""
return self.version & 0x01 == 0x00
@property
def packed(self):
"""Packed header"""
val = ((0xffe00000 if self.sync else 0) |
(self.version << 19) |
((4 - self.layer) << 17) |
((0 if self.protected else 1) << 16) |
((self.bitrate_idx + 1) << 12) |
(self.srate_idx << 10) |
(self.padding << 9) |
(self.private << 8) |
(self.mode << 6) |
(self.mode_ext << 4) |
((1 if self.copyright else 0) << 3) |
((1 if self.original else 0) << 2) |
(self.emphasis))
return self.head.pack(val)
class MP3(Decoder):
"""Decode ID3 tags on MP3"""
format = 'mp3'
editable = True
id3v1 = Struct('3s30s30s30s4s30sB')
id3v2head = Struct('3s3B4s')
tag_re = re.compile(r'^[A-Z0-9 ]{3,4}$')
genre_re = re.compile(r'^\((\d+)\)$')
def __init__(self, *args, **kwargs):
self.hasid3v1 = False
self.id3v1start = 0
self.id3v1end = 0
self.hasid3v2 = False
self.id3v2start = 0
self.id3v2end = 0
self.id3v2version = None
self.hasmp3 = False
self.mp3start = 0
self.mp3end = 0
super(MP3, self).__init__(*args, **kwargs)
@property
def id3v1size(self):
"""Size of id3v1 tag"""
return self.id3v1end - self.id3v1start
@property
def id3v2size(self):
"""Size of id3v2 tag"""
return self.id3v2end - self.id3v2start
@property
def mp3size(self):
"""Size of mp3 tag"""
return self.mp3end - self.mp3start
@property
def mp3frames(self):
"""Yields each frame of MP3 data"""
if self.hasmp3:
self.seek(self.mp3start)
size = 0
while True:
try:
head = MP3Head(self.read(MP3Head.head.size))
if not head.valid:
raise DecodeError('invalid header')
yield head, self.read(head.length - MP3Head.head.size)
size += head.length
except DecodeErrors:
break
self.mp3end = self.mp3start + size
@property
def mp3bitrate(self):
"""Average bitrate"""
frames = 0
bitrate = 0.0
for head, data in self.mp3frames:
frames += 1
bitrate += head.bitrate
return bitrate / frames
def get_gapless(self):
"""Get gapless"""
return self.get_comment(key=GAPLESS)
def set_gapless(self, val):
"""Set gapless"""
self.set_comment(val, key=GAPLESS)
def del_gapless(self):
"""Delete gapless"""
self.del_comment(key=GAPLESS)
gapless = property(get_gapless, set_gapless, del_gapless)
def get_comment(self, key=None, lang=None):
"""Get comment"""
if key != ANYITEM:
if lang is None:
lang = LANG
key = lang, key
return self.getdict('_comment', key)
def set_comment(self, val, key=None, lang=None):
"""Set comment"""
if lang is None:
lang = LANG
self.setdict('_comment', (lang, self.validate(key, TEXT)),
self.validate(val, BOOL if key == GAPLESS else TEXT))
def del_comment(self, key=None, lang=None):