-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinytag.py
1775 lines (1651 loc) · 83.7 KB
/
tinytag.py
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
# tinytag - an audio file metadata reader
# Copyright (c) 2014-2023 Tom Wallroth
# Copyright (c) 2021-2024 Mat (mathiascode)
#
# Sources on GitHub:
# http://github.com/tinytag/tinytag
# MIT License
# Copyright (c) 2014-2024 Tom Wallroth, Mat (mathiascode)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Audio file metadata reader"""
# pylint: disable=invalid-name,protected-access
# pylint: disable=too-many-lines,too-many-arguments,too-many-boolean-expressions
# pylint: disable=too-many-branches,too-many-instance-attributes,too-many-locals
# pylint: disable=too-many-nested-blocks,too-many-statements,too-few-public-methods
from __future__ import annotations
from collections.abc import Callable, Iterator
from functools import reduce
from os import PathLike
from sys import stderr
from typing import Any, BinaryIO
from warnings import warn
import base64
import io
import os
import re
import struct
DEBUG = bool(os.environ.get('TINYTAG_DEBUG')) # some of the parsers can print debug info
class TinyTagException(Exception):
"""Base class for exceptions."""
class ParseError(TinyTagException):
"""Parsing an audio file failed."""
class UnsupportedFormatError(TinyTagException):
"""File format is not supported."""
class TinyTag:
"""A class containing audio file metadata."""
SUPPORTED_FILE_EXTENSIONS = (
'.mp1', '.mp2', '.mp3',
'.oga', '.ogg', '.opus', '.spx',
'.wav', '.flac', '.wma',
'.m4b', '.m4a', '.m4r', '.m4v', '.mp4', '.aax', '.aaxc',
'.aiff', '.aifc', '.aif', '.afc'
)
_EXTRA_PREFIX = 'extra.'
_file_extension_mapping: dict[tuple[str, ...], type[TinyTag]] | None = None
_magic_bytes_mapping: dict[bytes, type[TinyTag]] | None = None
def __init__(self) -> None:
self.filename: bytes | str | PathLike[Any] | None = None
self.filesize = 0
self.duration: float | None = None
self.channels: int | None = None
self.bitrate: float | None = None
self.bitdepth: int | None = None
self.samplerate: int | None = None
self.artist: str | None = None
self.albumartist: str | None = None
self.composer: str | None = None
self.album: str | None = None
self.disc: int | None = None
self.disc_total: int | None = None
self.title: str | None = None
self.track: int | None = None
self.track_total: int | None = None
self.genre: str | None = None
self.year: str | None = None
self.comment: str | None = None
self.extra: dict[str, str | float | int] = {}
self.images = TagImages()
self._filehandler: BinaryIO | None = None
self._default_encoding: str | None = None # allow override for some file formats
self._parse_duration = True
self._parse_tags = True
self._load_image = False
self._tags_parsed = False
@classmethod
def get(cls,
filename: bytes | str | PathLike[Any] | None = None,
tags: bool = True,
duration: bool = True,
image: bool = False,
encoding: str | None = None,
file_obj: BinaryIO | None = None,
**kwargs: Any) -> TinyTag:
"""Return a tag object for an audio file."""
should_close_file = file_obj is None
if filename and should_close_file:
file_obj = open(filename, 'rb') # pylint: disable=consider-using-with
if file_obj is None:
raise ValueError('Either filename or file_obj argument is required')
if 'ignore_errors' in kwargs:
warn('ignore_errors argument is obsolete, and will be removed in a future '
'2.x release', DeprecationWarning, stacklevel=2)
try:
file_obj.seek(0, os.SEEK_END)
filesize = file_obj.tell()
file_obj.seek(0)
parser_class = cls._get_parser_class(filename, file_obj)
tag = parser_class()
tag._filehandler = file_obj
tag._default_encoding = encoding
tag.filename = filename
tag.filesize = filesize
if filesize > 0:
try:
tag._load(tags=tags, duration=duration, image=image)
except Exception as exc:
raise ParseError(exc) from exc
return tag
finally:
if should_close_file:
file_obj.close()
@classmethod
def is_supported(cls, filename: bytes | str | PathLike[Any]) -> bool:
"""Check if a specific file is supported based on its file extension."""
return cls._get_parser_for_filename(filename) is not None
def __repr__(self) -> str:
return str(self._as_dict())
def _as_dict(self) -> dict[str, Any]:
return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
@classmethod
def _get_parser_for_filename(
cls, filename: bytes | str | PathLike[Any]) -> type[TinyTag] | None:
if cls._file_extension_mapping is None:
cls._file_extension_mapping = {
('.mp1', '.mp2', '.mp3'): _ID3,
('.oga', '.ogg', '.opus', '.spx'): _Ogg,
('.wav',): _Wave,
('.flac',): _Flac,
('.wma',): _Wma,
('.m4b', '.m4a', '.m4r', '.m4v', '.mp4', '.aax', '.aaxc'): _MP4,
('.aiff', '.aifc', '.aif', '.afc'): _Aiff,
}
filename = os.fsdecode(filename).lower()
for ext, tagclass in cls._file_extension_mapping.items():
if filename.endswith(ext):
return tagclass
return None
@classmethod
def _get_parser_for_file_handle(cls, fh: BinaryIO) -> type[TinyTag] | None:
# https://en.wikipedia.org/wiki/List_of_file_signatures
if cls._magic_bytes_mapping is None:
cls._magic_bytes_mapping = {
b'^ID3': _ID3,
b'^\xff\xfb': _ID3,
b'^OggS.........................FLAC': _Ogg,
b'^OggS........................Opus': _Ogg,
b'^OggS........................Speex': _Ogg,
b'^OggS.........................vorbis': _Ogg,
b'^RIFF....WAVE': _Wave,
b'^fLaC': _Flac,
b'^\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C': _Wma,
b'....ftypM4A': _MP4, # https://www.file-recovery.com/m4a-signature-format.htm
b'....ftypaax': _MP4, # Audible proprietary M4A container
b'....ftypaaxc': _MP4, # Audible proprietary M4A container
b'\xff\xf1': _MP4, # https://www.garykessler.net/library/file_sigs.html
b'^FORM....AIFF': _Aiff,
b'^FORM....AIFC': _Aiff,
}
header = fh.read(max(len(sig) for sig in cls._magic_bytes_mapping))
fh.seek(0)
for magic, parser in cls._magic_bytes_mapping.items():
if re.match(magic, header):
return parser
return None
@classmethod
def _get_parser_class(cls, filename: bytes | str | PathLike[Any] | None = None,
filehandle: BinaryIO | None = None) -> type[TinyTag]:
if cls != TinyTag: # if `get` is invoked on TinyTag, find parser by ext
return cls # otherwise use the class on which `get` was invoked
if filename:
parser_class = cls._get_parser_for_filename(filename)
if parser_class is not None:
return parser_class
# try determining the file type by magic byte header
if filehandle:
parser_class = cls._get_parser_for_file_handle(filehandle)
if parser_class is not None:
return parser_class
raise UnsupportedFormatError('No tag reader found to support file type')
def _load(self, tags: bool, duration: bool, image: bool = False) -> None:
self._parse_tags = tags
self._parse_duration = duration
self._load_image = image
if self._filehandler is None:
return
if tags:
self._parse_tag(self._filehandler)
if duration:
if tags: # rewind file if the tags were already parsed
self._filehandler.seek(0)
self._determine_duration(self._filehandler)
def _parse_string_field(self, fieldname: str, old_value: Any | None, value: str) -> str | None:
if fieldname in {'artist', 'genre'}:
# First artist/genre goes in tag.artist/genre, others in tag.extra.other_artists/genres
values = value.split('\x00')
value = values[0]
start_pos = 0 if old_value else 1
if len(values) > 1:
self._set_field(self._EXTRA_PREFIX + f'other_{fieldname}s', values[start_pos:])
elif old_value and value != old_value:
self._set_field(self._EXTRA_PREFIX + f'other_{fieldname}s', [value])
return None
if old_value or not value:
return None
return value
def _set_field(self, fieldname: str, value: str | int | float | list[str] | None) -> None:
write_dest = self.__dict__
original_fieldname = fieldname
if fieldname.startswith(self._EXTRA_PREFIX):
write_dest = self.extra
fieldname = fieldname[len(self._EXTRA_PREFIX):]
old_value = write_dest.get(fieldname)
if isinstance(value, str):
value = self._parse_string_field(original_fieldname, old_value, value)
if not value:
return
elif isinstance(value, list):
if not isinstance(old_value, list):
old_value = []
value = old_value + [i for i in value if i and i not in old_value]
elif not value and old_value:
return
if DEBUG:
print(f'Setting field "{original_fieldname}" to "{value!r}"')
write_dest[fieldname] = value
def _set_image_field(self, fieldname: str, value: TagImage) -> None:
write_dest = self.images.__dict__
if fieldname.startswith(self._EXTRA_PREFIX):
fieldname = fieldname[len(self._EXTRA_PREFIX):]
write_dest = self.images.extra
old_values = write_dest.get(fieldname)
values = [value]
if old_values is not None:
values = old_values + values
if DEBUG:
print(f'Setting image field "{fieldname}"')
write_dest[fieldname] = values
def _determine_duration(self, fh: BinaryIO) -> None:
raise NotImplementedError
def _parse_tag(self, fh: BinaryIO) -> None:
raise NotImplementedError
def _update(self, other: TinyTag) -> None:
# update the values of this tag with the values from another tag
excluded_attrs = {'filesize', 'extra', 'images'}
for standard_key, standard_value in other.__dict__.items():
if (not standard_key.startswith('_')
and standard_key not in excluded_attrs
and standard_value is not None):
self._set_field(standard_key, standard_value)
for extra_key, extra_value in other.extra.items():
self._set_field(self._EXTRA_PREFIX + extra_key, extra_value)
for image_key, images in other.images._as_dict().items():
for image in images:
self._set_image_field(image_key, image)
for image_extra_key, images_extra in other.images.extra.items():
for image_extra in images_extra:
self._set_image_field(self._EXTRA_PREFIX + image_extra_key, image_extra)
@staticmethod
def _bytes_to_int_le(b: bytes) -> int:
fmt = {1: '<B', 2: '<H', 4: '<I', 8: '<Q'}.get(len(b))
result: int = struct.unpack(fmt, b)[0] if fmt is not None else 0
return result
@staticmethod
def _bytes_to_int(b: tuple[int, ...]) -> int:
return reduce(lambda accu, elem: (accu << 8) + elem, b, 0)
@staticmethod
def _unpad(s: str) -> str:
# strings in mp3 and asf *may* be terminated with a zero byte at the end
return s.strip('\x00')
def get_image(self) -> bytes | None:
"""Deprecated, use images.any instead."""
warn('get_image() is deprecated, and will be removed in a future 2.x release. '
'Use images.any instead.', DeprecationWarning, stacklevel=2)
image = self.images.any
return image.data if image is not None else None
@property
def audio_offset(self) -> None:
"""Obsolete."""
warn('audio_offset attribute is obsolete, and will be '
'removed in a future 2.x release', DeprecationWarning, stacklevel=2)
class TagImages:
"""A class containing images embedded in an audio file."""
def __init__(self) -> None:
self.front_cover: list[TagImage] = []
self.back_cover: list[TagImage] = []
self.leaflet: list[TagImage] = []
self.media: list[TagImage] = []
self.other: list[TagImage] = []
self.extra: dict[str, list[TagImage]] = {}
@property
def any(self) -> TagImage | None:
"""Return a cover image.
If not present, fall back to any other available image.
"""
for image_list in self._as_dict().values():
for image in image_list:
return image
for extra_image_list in self.extra.values():
for extra_image in extra_image_list:
return extra_image
return None
def __repr__(self) -> str:
return str(vars(self))
def _as_dict(self) -> dict[str, list[TagImage]]:
return {
k: v for k, v in self.__dict__.items()
if not k.startswith('_') and k != 'extra'
}
class TagImage:
"""A class representing an image embedded in an audio file."""
def __init__(self, name: str, data: bytes, mime_type: str | None = None) -> None:
self.name = name
self.data = data
self.mime_type = mime_type
self.description: str | None = None
def __repr__(self) -> str:
variables = vars(self).copy()
data = variables.get("data")
if data is not None:
variables["data"] = (data[:45] + b'..') if len(data) > 45 else data
return str(variables)
class _MP4(TinyTag):
# https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
# https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html
class _Parser:
atom_decoder_by_type: dict[
int, Callable[[bytes], int | str | bytes | TagImage]] | None = None
_CUSTOM_FIELD_NAME_MAPPING = {
'artists': 'artist',
'conductor': 'extra.conductor',
'discsubtitle': 'extra.set_subtitle',
'initialkey': 'extra.initial_key',
'isrc': 'extra.isrc',
'language': 'extra.language',
'lyricist': 'extra.lyricist',
'media': 'extra.media',
'website': 'extra.url',
'originaldate': 'extra.original_date',
'originalyear': 'extra.original_year',
'license': 'extra.license',
'barcode': 'extra.barcode',
'catalognumber': 'extra.catalog_number',
}
@classmethod
def _unpack_integer(cls, value: bytes, signed: bool = True) -> int:
value_length = len(value)
result = -1
if value_length == 1:
result = struct.unpack('>b' if signed else '>B', value)[0]
elif value_length == 2:
result = struct.unpack('>h' if signed else '>H', value)[0]
elif value_length == 4:
result = struct.unpack('>i' if signed else '>I', value)[0]
elif value_length == 8:
result = struct.unpack('>q' if signed else '>Q', value)[0]
return result
@classmethod
def _unpack_integer_unsigned(cls, value: bytes) -> int:
return cls._unpack_integer(value, signed=False)
@classmethod
def _make_data_atom_parser(
cls, fieldname: str) -> Callable[[bytes], dict[str, int | str | bytes | TagImage]]:
def _parse_data_atom(data_atom: bytes) -> dict[str, int | str | bytes | TagImage]:
data_type = struct.unpack('>I', data_atom[:4])[0]
if cls.atom_decoder_by_type is None:
# https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html#//apple_ref/doc/uid/TP40000939-CH1-SW34
cls.atom_decoder_by_type = {
# 0: 'reserved'
1: lambda x: x.decode('utf-8', 'replace'), # UTF-8
2: lambda x: x.decode('utf-16', 'replace'), # UTF-16
3: lambda x: x.decode('s/jis', 'replace'), # S/JIS
# 16: duration in millis
13: lambda x: TagImage('front_cover', x, 'image/jpeg'), # JPEG
14: lambda x: TagImage('front_cover', x, 'image/png'), # PNG
21: cls._unpack_integer, # BE Signed int
22: cls._unpack_integer_unsigned, # BE Unsigned int
# 23: lambda x: struct.unpack('>f', x)[0], # BE Float32
# 24: lambda x: struct.unpack('>d', x)[0], # BE Float64
# 27: lambda x: x, # BMP
# 28: lambda x: x, # QuickTime Metadata atom
65: cls._unpack_integer, # 8-bit Signed int
66: cls._unpack_integer, # BE 16-bit Signed int
67: cls._unpack_integer, # BE 32-bit Signed int
74: cls._unpack_integer, # BE 64-bit Signed int
75: cls._unpack_integer_unsigned, # 8-bit Unsigned int
76: cls._unpack_integer_unsigned, # BE 16-bit Unsigned int
77: cls._unpack_integer_unsigned, # BE 32-bit Unsigned int
78: cls._unpack_integer_unsigned, # BE 64-bit Unsigned int
}
conversion = cls.atom_decoder_by_type.get(data_type)
if conversion is None:
if DEBUG:
print(f'Cannot convert data type: {data_type}', file=stderr)
return {} # don't know how to convert data atom
# skip header & null-bytes, convert rest
return {fieldname: conversion(data_atom[8:])}
return _parse_data_atom
@classmethod
def _make_number_parser(
cls, fieldname1: str, fieldname2: str) -> Callable[[bytes], dict[str, int]]:
def _(data_atom: bytes) -> dict[str, int]:
number_data = data_atom[8:14]
numbers = struct.unpack('>HHH', number_data)
# for some reason the first number is always irrelevant.
return {fieldname1: numbers[1], fieldname2: numbers[2]}
return _
@classmethod
def _parse_id3v1_genre(cls, data_atom: bytes) -> dict[str, str]:
# dunno why the genre is offset by -1 but that's how mutagen does it
idx = struct.unpack('>H', data_atom[8:])[0] - 1
result = {}
if idx < len(_ID3._ID3V1_GENRES):
result['genre'] = _ID3._ID3V1_GENRES[idx]
return result
@classmethod
def _read_extended_descriptor(cls, esds_atom: BinaryIO) -> None:
for _i in range(4):
if esds_atom.read(1) != b'\x80':
break
@classmethod
def _parse_custom_field(cls, data: bytes) -> dict[str, int | str | bytes | TagImage]:
fh = io.BytesIO(data)
header_size = 8
field_name = None
data_atom = b''
atom_header = fh.read(header_size)
while len(atom_header) == header_size:
atom_size = struct.unpack('>I', atom_header[:4])[0] - header_size
atom_type = atom_header[4:]
if atom_type == b'name':
atom_value = fh.read(atom_size)[4:].lower()
field_name = atom_value.decode('utf-8', 'replace')
field_name = cls._CUSTOM_FIELD_NAME_MAPPING.get(
field_name, TinyTag._EXTRA_PREFIX + field_name)
elif atom_type == b'data':
data_atom = fh.read(atom_size)
else:
fh.seek(atom_size, os.SEEK_CUR)
atom_header = fh.read(header_size) # read next atom
if len(data_atom) < 8 or field_name is None:
return {}
parser = cls._make_data_atom_parser(field_name)
return parser(data_atom)
@classmethod
def _parse_audio_sample_entry_mp4a(cls, data: bytes) -> dict[str, int]:
# this atom also contains the esds atom:
# https://ffmpeg.org/doxygen/0.6/mov_8c-source.html
# http://xhelmboyx.tripod.com/formats/mp4-layout.txt
# http://sasperger.tistory.com/103
datafh = io.BytesIO(data)
datafh.seek(16, os.SEEK_CUR) # jump over version and flags
channels = struct.unpack('>H', datafh.read(2))[0]
datafh.seek(2, os.SEEK_CUR) # jump over bit_depth
datafh.seek(2, os.SEEK_CUR) # jump over QT compr id & pkt size
sr = struct.unpack('>I', datafh.read(4))[0]
# ES Description Atom
esds_atom_size = struct.unpack('>I', data[28:32])[0]
esds_atom = io.BytesIO(data[36:36 + esds_atom_size])
esds_atom.seek(5, os.SEEK_CUR) # jump over version, flags and tag
# ES Descriptor
cls._read_extended_descriptor(esds_atom)
esds_atom.seek(4, os.SEEK_CUR) # jump over ES id, flags and tag
# Decoder Config Descriptor
cls._read_extended_descriptor(esds_atom)
esds_atom.seek(9, os.SEEK_CUR)
avg_br = struct.unpack('>I', esds_atom.read(4))[0] / 1000 # kbit/s
return {'channels': channels, 'samplerate': sr, 'bitrate': avg_br}
@classmethod
def _parse_audio_sample_entry_alac(cls, data: bytes) -> dict[str, int]:
# https://github.com/macosforge/alac/blob/master/ALACMagicCookieDescription.txt
alac_atom_size = struct.unpack('>I', data[28:32])[0]
alac_atom = io.BytesIO(data[36:36 + alac_atom_size])
alac_atom.seek(9, os.SEEK_CUR)
bitdepth = struct.unpack('b', alac_atom.read(1))[0]
alac_atom.seek(3, os.SEEK_CUR)
channels = struct.unpack('b', alac_atom.read(1))[0]
alac_atom.seek(6, os.SEEK_CUR)
avg_br = struct.unpack('>I', alac_atom.read(4))[0] / 1000 # kbit/s
sr = struct.unpack('>I', alac_atom.read(4))[0]
return {'channels': channels, 'samplerate': sr, 'bitrate': avg_br, 'bitdepth': bitdepth}
@classmethod
def _parse_mvhd(cls, data: bytes) -> dict[str, float]:
# http://stackoverflow.com/a/3639993/1191373
walker = io.BytesIO(data)
version = struct.unpack('b', walker.read(1))[0]
walker.seek(3, os.SEEK_CUR) # jump over flags
if version == 0: # uses 32 bit integers for timestamps
walker.seek(8, os.SEEK_CUR) # jump over create & mod times
time_scale = struct.unpack('>I', walker.read(4))[0]
duration = struct.unpack('>I', walker.read(4))[0]
else: # version == 1: # uses 64 bit integers for timestamps
walker.seek(16, os.SEEK_CUR) # jump over create & mod times
time_scale = struct.unpack('>I', walker.read(4))[0]
duration = struct.unpack('>q', walker.read(8))[0]
return {'duration': duration / time_scale}
# The parser tree: Each key is an atom name which is traversed if existing.
# Leaves of the parser tree are callables which receive the atom data.
# callables return {fieldname: value} which is updates the TinyTag.
_META_DATA_TREE = {b'moov': {b'udta': {b'meta': {b'ilst': {
# see: http://atomicparsley.sourceforge.net/mpeg-4files.html
# and: https://metacpan.org/dist/Image-ExifTool/source/lib/Image/ExifTool/QuickTime.pm#L3093
b'\xa9ART': {b'data': _Parser._make_data_atom_parser('artist')},
b'\xa9alb': {b'data': _Parser._make_data_atom_parser('album')},
b'\xa9cmt': {b'data': _Parser._make_data_atom_parser('comment')},
b'\xa9con': {b'data': _Parser._make_data_atom_parser('extra.conductor')},
# need test-data for this
# b'cpil': {b'data': _Parser._make_data_atom_parser('extra.compilation')},
b'\xa9day': {b'data': _Parser._make_data_atom_parser('year')},
b'\xa9des': {b'data': _Parser._make_data_atom_parser('extra.description')},
b'\xa9dir': {b'data': _Parser._make_data_atom_parser('extra.director')},
b'\xa9gen': {b'data': _Parser._make_data_atom_parser('genre')},
b'\xa9lyr': {b'data': _Parser._make_data_atom_parser('extra.lyrics')},
b'\xa9mvn': {b'data': _Parser._make_data_atom_parser('movement')},
b'\xa9nam': {b'data': _Parser._make_data_atom_parser('title')},
b'\xa9pub': {b'data': _Parser._make_data_atom_parser('extra.publisher')},
b'\xa9too': {b'data': _Parser._make_data_atom_parser('extra.encoded_by')},
b'\xa9wrt': {b'data': _Parser._make_data_atom_parser('composer')},
b'aART': {b'data': _Parser._make_data_atom_parser('albumartist')},
b'cprt': {b'data': _Parser._make_data_atom_parser('extra.copyright')},
b'desc': {b'data': _Parser._make_data_atom_parser('extra.description')},
b'disk': {b'data': _Parser._make_number_parser('disc', 'disc_total')},
b'gnre': {b'data': _Parser._parse_id3v1_genre},
b'trkn': {b'data': _Parser._make_number_parser('track', 'track_total')},
b'tmpo': {b'data': _Parser._make_data_atom_parser('extra.bpm')},
b'covr': {b'data': _Parser._make_data_atom_parser('images.front_cover')},
b'----': _Parser._parse_custom_field,
}}}}}
# see: https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap3/qtff3.html
_AUDIO_DATA_TREE = {
b'moov': {
b'mvhd': _Parser._parse_mvhd,
b'trak': {b'mdia': {b"minf": {b"stbl": {b"stsd": {
b'mp4a': _Parser._parse_audio_sample_entry_mp4a,
b'alac': _Parser._parse_audio_sample_entry_alac
}}}}}
}
}
_VERSIONED_ATOMS = {b'meta', b'stsd'} # those have an extra 4 byte header
_FLAGGED_ATOMS = {b'stsd'} # these also have an extra 4 byte header
def _determine_duration(self, fh: BinaryIO) -> None:
self._traverse_atoms(fh, path=self._AUDIO_DATA_TREE)
def _parse_tag(self, fh: BinaryIO) -> None:
self._traverse_atoms(fh, path=self._META_DATA_TREE)
def _traverse_atoms(self, fh: BinaryIO, path: dict[bytes, Any],
stop_pos: int | None = None,
curr_path: list[bytes] | None = None) -> None:
header_size = 8
atom_header = fh.read(header_size)
while len(atom_header) == header_size:
atom_size = struct.unpack('>I', atom_header[:4])[0] - header_size
atom_type = atom_header[4:]
if curr_path is None: # keep track how we traversed in the tree
curr_path = [atom_type]
if atom_size <= 0: # empty atom, jump to next one
atom_header = fh.read(header_size)
continue
if DEBUG:
print(f'{" " * 4 * len(curr_path)} pos: {fh.tell() - header_size} '
f'atom: {atom_type!r} len: {atom_size + header_size}')
if atom_type in self._VERSIONED_ATOMS: # jump atom version for now
fh.seek(4, os.SEEK_CUR)
if atom_type in self._FLAGGED_ATOMS: # jump atom flags for now
fh.seek(4, os.SEEK_CUR)
sub_path = path.get(atom_type, None)
# if the path leaf is a dict, traverse deeper into the tree:
if isinstance(sub_path, dict):
atom_end_pos = fh.tell() + atom_size
self._traverse_atoms(fh, path=sub_path, stop_pos=atom_end_pos,
curr_path=curr_path + [atom_type])
# if the path-leaf is a callable, call it on the atom data
elif callable(sub_path):
for fieldname, value in sub_path(fh.read(atom_size)).items():
if DEBUG:
print(' ' * 4 * len(curr_path), 'FIELD: ', fieldname)
if fieldname.startswith('images.'):
if self._load_image:
self._set_image_field(fieldname[len('images.'):], value)
elif fieldname:
self._set_field(fieldname, value)
# if no action was specified using dict or callable, jump over atom
else:
fh.seek(atom_size, os.SEEK_CUR)
# check if we have reached the end of this branch:
if stop_pos and fh.tell() >= stop_pos:
return # return to parent (next parent node in tree)
atom_header = fh.read(header_size) # read next atom
class _ID3(TinyTag):
_ID3_MAPPING = {
# Mapping from Frame ID to a field of the TinyTag
# https://exiftool.org/TagNames/ID3.html
'COMM': 'comment', 'COM': 'comment',
'TRCK': 'track', 'TRK': 'track',
'TYER': 'year', 'TYE': 'year', 'TDRC': 'year',
'TALB': 'album', 'TAL': 'album',
'TPE1': 'artist', 'TP1': 'artist',
'TIT2': 'title', 'TT2': 'title',
'TCON': 'genre', 'TCO': 'genre',
'TPOS': 'disc', 'TPA': 'disc',
'TPE2': 'albumartist', 'TP2': 'albumartist',
'TCOM': 'composer', 'TCM': 'composer',
'WOAR': 'extra.url', 'WAR': 'extra.url',
'TSRC': 'extra.isrc', 'TRC': 'extra.isrc',
'TCOP': 'extra.copyright', 'TCR': 'extra.copyright',
'TBPM': 'extra.bpm', 'TBP': 'extra.bpm',
'TKEY': 'extra.initial_key', 'TKE': 'extra.initial_key',
'TLAN': 'extra.language', 'TLA': 'extra.language',
'TPUB': 'extra.publisher', 'TPB': 'extra.publisher',
'USLT': 'extra.lyrics', 'ULT': 'extra.lyrics',
'TPE3': 'extra.conductor', 'TP3': 'extra.conductor',
'TEXT': 'extra.lyricist', 'TXT': 'extra.lyricist',
'TSST': 'extra.set_subtitle',
'TENC': 'extra.encoded_by', 'TEN': 'extra.encoded_by',
'TSSE': 'extra.encoder_settings', 'TSS': 'extra.encoder_settings',
'TMED': 'extra.media', 'TMT': 'extra.media',
'TDOR': 'extra.original_date',
'TORY': 'extra.original_year', 'TOR': 'extra.original_year',
'WCOP': 'extra.license',
}
_ID3_MAPPING_CUSTOM = {
'artists': 'artist',
'director': 'extra.director',
'license': 'extra.license',
'originalyear': 'extra.original_year',
'barcode': 'extra.barcode',
'catalognumber': 'extra.catalog_number',
}
_IMAGE_FRAME_IDS = {'APIC', 'PIC'}
_CUSTOM_FRAME_IDS = {'TXXX', 'TXX'}
_DISALLOWED_FRAME_IDS = {'PRIV', 'RGAD', 'GEOB', 'GEO', 'ÿû°d'}
_MAX_ESTIMATION_SEC = 30.0
_CBR_DETECTION_FRAME_COUNT = 5
_USE_XING_HEADER = True # much faster, but can be deactivated for testing
_ID3V1_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', 'AlternRock', '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 American', 'Cabaret', 'New Wave', 'Psychadelic', 'Rave',
'Showtunes', 'Trailer', 'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz',
'Polka', 'Retro', 'Musical', 'Rock & Roll', 'Hard Rock',
# Wimamp Extended Genres
'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', 'A capella', 'Euro-House',
'Dance Hall', 'Goa', 'Drum & Bass',
# according to https://de.wikipedia.org/wiki/Liste_der_ID3v1-Genres:
'Club-House', 'Hardcore Techno', 'Terror', 'Indie', 'BritPop',
'', # don't use ethnic slur ("Negerpunk", WTF!)
'Polsk Punk', 'Beat', 'Christian Gangsta Rap', 'Heavy Metal',
'Black Metal', 'Contemporary Christian', 'Christian Rock',
# WinAmp 1.91
'Merengue', 'Salsa', 'Thrash Metal', 'Anime', 'Jpop', 'Synthpop',
# WinAmp 5.6
'Abstract', 'Art Rock', 'Baroque', 'Bhangra', 'Big Beat', 'Breakbeat',
'Chillout', 'Downtempo', 'Dub', 'EBM', 'Eclectic', 'Electro',
'Electroclash', 'Emo', 'Experimental', 'Garage', 'Illbient',
'Industro-Goth', 'Jam Band', 'Krautrock', 'Leftfield', 'Lounge',
'Math Rock', 'New Romantic', 'Nu-Breakz', 'Post-Punk', 'Post-Rock',
'Psytrance', 'Shoegaze', 'Space Rock', 'Trop Rock', 'World Music',
'Neoclassical', 'Audiobook', 'Audio Theatre', 'Neue Deutsche Welle',
'Podcast', 'Indie Rock', 'G-Funk', 'Dubstep', 'Garage Rock', 'Psybient',
)
_ID3V2_2_IMAGE_FORMATS = {
'bmp': 'image/bmp',
'jpg': 'image/jpeg',
'png': 'image/png',
}
_IMAGE_TYPES = (
'other',
'extra.icon',
'extra.other_icon',
'front_cover',
'back_cover',
'leaflet',
'media',
'extra.lead_artist',
'extra.artist',
'extra.conductor',
'extra.band',
'extra.composer',
'extra.lyricist',
'extra.recording_location',
'extra.during_recording',
'extra.during_performance',
'extra.video',
'extra.bright_colored_fish',
'extra.illustration',
'extra.band_logo',
'extra.publisher_logo',
)
_UNKNOWN_IMAGE_TYPE = 'extra.unknown'
# see this page for the magic values used in mp3:
# http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
_SAMPLE_RATES = (
(11025, 12000, 8000), # MPEG 2.5
(0, 0, 0), # reserved
(22050, 24000, 16000), # MPEG 2
(44100, 48000, 32000), # MPEG 1
)
_V1L1 = (0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0)
_V1L2 = (0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0)
_V1L3 = (0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0)
_V2L1 = (0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0)
_V2L2 = (0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0)
_V2L3 = _V2L2
_NONE = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
_BITRATE_BY_VERSION_BY_LAYER = (
(_NONE, _V2L3, _V2L2, _V2L1), # MPEG Version 2.5 # note that the layers go
(_NONE, _NONE, _NONE, _NONE), # reserved # from 3 to 1 by design.
(_NONE, _V2L3, _V2L2, _V2L1), # MPEG Version 2 # the first layer id is
(_NONE, _V1L3, _V1L2, _V1L1), # MPEG Version 1 # reserved
)
_SAMPLES_PER_FRAME = 1152 # the default frame size for mp3
_CHANNELS_PER_CHANNEL_MODE = (
2, # 00 Stereo
2, # 01 Joint stereo (Stereo)
2, # 10 Dual channel (2 mono channels)
1, # 11 Single channel (Mono)
)
def __init__(self) -> None:
super().__init__()
# save position after the ID3 tag for duration measurement speedup
self._bytepos_after_id3v2 = -1
@staticmethod
def _parse_xing_header(fh: BinaryIO) -> tuple[int, int]:
# see: http://www.mp3-tech.org/programmer/sources/vbrheadersdk.zip
fh.seek(4, os.SEEK_CUR) # read over Xing header
header_flags = struct.unpack('>i', fh.read(4))[0]
frames = byte_count = 0
if header_flags & 1: # FRAMES FLAG
frames = struct.unpack('>i', fh.read(4))[0]
if header_flags & 2: # BYTES FLAG
byte_count = struct.unpack('>i', fh.read(4))[0]
if header_flags & 4: # TOC FLAG
fh.seek(100, os.SEEK_CUR)
if header_flags & 8: # VBR SCALE FLAG
fh.seek(4, os.SEEK_CUR)
return frames, byte_count
def _determine_duration(self, fh: BinaryIO) -> None:
# if tag reading was disabled, find start position of audio data
if self._bytepos_after_id3v2 == -1:
self._parse_id3v2_header(fh)
max_estimation_frames = (_ID3._MAX_ESTIMATION_SEC * 44100) // _ID3._SAMPLES_PER_FRAME
frame_size_accu = 0
audio_offset = 0
frames = 0 # count frames for determining mp3 duration
bitrate_accu = 0 # add up bitrates to find average bitrate to detect
last_bitrates = set() # CBR mp3s (multiple frames with same bitrates)
# seek to first position after id3 tag (speedup for large header)
first_mpeg_id = None
fh.seek(self._bytepos_after_id3v2)
file_offset = fh.tell()
walker = io.BytesIO(fh.read())
while True:
# reading through garbage until 11 '1' sync-bits are found
header = walker.read(4)
header_len = len(header)
walker.seek(-header_len, os.SEEK_CUR)
if header_len < 4:
if frames:
self.bitrate = bitrate_accu / frames
break # EOF
_sync, conf, bitrate_freq, rest = struct.unpack('BBBB', header)
br_id = (bitrate_freq >> 4) & 0x0F # biterate id
sr_id = (bitrate_freq >> 2) & 0x03 # sample rate id
padding = 1 if bitrate_freq & 0x02 > 0 else 0
mpeg_id = (conf >> 3) & 0x03
layer_id = (conf >> 1) & 0x03
channel_mode = (rest >> 6) & 0x03
# check for eleven 1s, validate bitrate and sample rate
if (not header[:2] > b'\xFF\xE0'
or (first_mpeg_id is not None and first_mpeg_id != mpeg_id)
or br_id > 14 or br_id == 0 or sr_id == 3 or layer_id == 0 or mpeg_id == 1):
idx = header.find(b'\xFF', 1) # invalid frame, find next sync header
if idx == -1:
idx = header_len # not found: jump over the current peek buffer
walker.seek(max(idx, 1), os.SEEK_CUR)
continue
if first_mpeg_id is None:
first_mpeg_id = mpeg_id
self.channels = self._CHANNELS_PER_CHANNEL_MODE[channel_mode]
frame_bitrate = self._BITRATE_BY_VERSION_BY_LAYER[mpeg_id][layer_id][br_id]
self.samplerate = samplerate = self._SAMPLE_RATES[mpeg_id][sr_id]
frame_length = (144000 * frame_bitrate) // samplerate + padding
# There might be a xing header in the first frame that contains
# all the info we need, otherwise parse multiple frames to find the
# accurate average bitrate
if frames == 0 and self._USE_XING_HEADER:
walker_offset = walker.tell()
frame_content = walker.read(frame_length)
xing_header_offset = frame_content.find(b'Xing')
if xing_header_offset != -1:
walker.seek(walker_offset + xing_header_offset)
xframes, byte_count = self._parse_xing_header(walker)
if xframes > 0 and byte_count > 0:
# MPEG-2 Audio Layer III uses 576 samples per frame
samples_per_frame = 576 if mpeg_id <= 2 else self._SAMPLES_PER_FRAME
self.duration = duration = xframes * samples_per_frame / samplerate
self.bitrate = byte_count * 8 / duration / 1000
return
walker.seek(walker_offset)
frames += 1 # it's most probably an mp3 frame
bitrate_accu += frame_bitrate
if frames == 1:
audio_offset = file_offset + walker.tell()
if frames <= self._CBR_DETECTION_FRAME_COUNT:
last_bitrates.add(frame_bitrate)
frame_size_accu += frame_length
# if bitrate does not change over time its probably CBR
is_cbr = (frames == self._CBR_DETECTION_FRAME_COUNT and len(last_bitrates) == 1)
if frames == max_estimation_frames or is_cbr:
# try to estimate duration
fh.seek(-128, 2) # jump to last byte (leaving out id3v1 tag)
audio_stream_size = fh.tell() - audio_offset
est_frame_count = audio_stream_size / (frame_size_accu / frames)
samples = est_frame_count * self._SAMPLES_PER_FRAME
self.duration = samples / samplerate
self.bitrate = bitrate_accu / frames
return
if frame_length > 1: # jump over current frame body
walker.seek(frame_length, os.SEEK_CUR)
if self.samplerate:
self.duration = frames * self._SAMPLES_PER_FRAME / self.samplerate
def _parse_tag(self, fh: BinaryIO) -> None:
self._parse_id3v2(fh)
if self.filesize > 128:
fh.seek(-128, os.SEEK_END) # try parsing id3v1 in last 128 bytes
self._parse_id3v1(fh)
def _parse_id3v2_header(self, fh: BinaryIO) -> tuple[int, bool, int]:
size = major = 0
extended = False
# for info on the specs, see: http://id3.org/Developer%20Information
header = struct.unpack('3sBBB4B', fh.read(10))
tag = header[0].decode('ISO-8859-1', 'replace')
# check if there is an ID3v2 tag at the beginning of the file
if tag == 'ID3':
major, _rev = header[1:3]
if DEBUG:
print(f'Found id3 v2.{major}')
# unsync = (header[3] & 0x80) > 0
extended = (header[3] & 0x40) > 0
# experimental = (header[3] & 0x20) > 0
# footer = (header[3] & 0x10) > 0
size = self._calc_size(header[4:8], 7)
self._bytepos_after_id3v2 = size
return size, extended, major
def _parse_id3v2(self, fh: BinaryIO) -> None:
size, extended, major = self._parse_id3v2_header(fh)
if size:
end_pos = fh.tell() + size
parsed_size = 0
if extended: # just read over the extended header.
size_bytes = struct.unpack('4B', fh.read(6)[0:4])
extd_size = self._calc_size(size_bytes, 7)
fh.seek(extd_size - 6, os.SEEK_CUR) # jump over extended_header
while parsed_size < size:
frame_size = self._parse_frame(fh, id3version=major)
if frame_size == 0:
break
parsed_size += frame_size
fh.seek(end_pos, os.SEEK_SET)
def _parse_id3v1(self, fh: BinaryIO) -> None:
if fh.read(3) != b'TAG': # check if this is an ID3 v1 tag
return
def asciidecode(x: bytes) -> str:
return self._unpad(x.decode(self._default_encoding or 'latin1', 'replace'))
# Only set fields that were not set by ID3v2 tags, as ID3v1
# tags are more likely to be outdated or have encoding issues
fields = fh.read(30 + 30 + 30 + 4 + 30 + 1)
if not self.title:
self._set_field('title', asciidecode(fields[:30]))
if not self.artist:
self._set_field('artist', asciidecode(fields[30:60]))
if not self.album:
self._set_field('album', asciidecode(fields[60:90]))
if not self.year:
self._set_field('year', asciidecode(fields[90:94]))
comment = fields[94:124]
if b'\x00\x00' < comment[-2:] < b'\x01\x00':
if self.track is None:
self._set_field('track', ord(comment[-1:]))
comment = comment[:-2]
if not self.comment:
self._set_field('comment', asciidecode(comment))
if not self.genre:
genre_id = ord(fields[124:125])