Debian Codegraph @

mediafile/__init__.py

raw
1 # This file is part of MediaFile.
2 # Copyright 2016, Adrian Sampson.
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and associated documentation files (the
6 # "Software"), to deal in the Software without restriction, including
7 # without limitation the rights to use, copy, modify, merge, publish,
8 # distribute, sublicense, and/or sell copies of the Software, and to
9 # permit persons to whom the Software is furnished to do so, subject to
10 # the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be
13 # included in all copies or substantial portions of the Software.
14
15 """Handles low-level interfacing for files' tags. Wraps Mutagen to
16 automatically detect file types and provide a unified interface for a
17 useful subset of music files' tags.
18
19 Usage:
20
21 >>> f = MediaFile('Lucy.mp3')
22 >>> f.title
23 u'Lucy in the Sky with Diamonds'
24 >>> f.artist = 'The Beatles'
25 >>> f.save()
26
27 A field will always return a reasonable value of the correct type, even
28 if no tag is present. If no value is available, the value will be false
29 (e.g., zero or the empty string).
30
31 Internally ``MediaFile`` uses ``MediaField`` descriptors to access the
32 data from the tags. In turn ``MediaField`` uses a number of
33 ``StorageStyle`` strategies to handle format specific logic.
34 """
35
36 import logging
37 import os
38 import re
39
40 import mutagen
41 import mutagen.mp3
42
43 from .constants import TYPES, ImageType
44 from .exceptions import FileTypeError, MutagenError, UnreadableFileError
45 from .fields import (
46 CoverArtField,
47 DateField,
48 DateItemField,
49 ImageListField,
50 ListMediaField,
51 MediaField,
52 QNumberField,
53 )
54 from .storage import (
55 APEv2ImageStorageStyle,
56 ASFImageStorageStyle,
57 ASFStorageStyle,
58 FlacImageStorageStyle,
59 ListStorageStyle,
60 MP3DescStorageStyle,
61 MP3ImageStorageStyle,
62 MP3ListDescStorageStyle,
63 MP3ListPeopleStorageStyle,
64 MP3ListStorageStyle,
65 MP3PeopleStorageStyle,
66 MP3SlashPackStorageStyle,
67 MP3SoundCheckStorageStyle,
68 MP3StorageStyle,
69 MP3SYLTStorageStyle,
70 MP3UFIDStorageStyle,
71 MP4BoolStorageStyle,
72 MP4ImageStorageStyle,
73 MP4ListStorageStyle,
74 MP4SoundCheckStorageStyle,
75 MP4StorageStyle,
76 MP4TupleStorageStyle,
77 SoundCheckStorageStyleMixin,
78 StorageStyle,
79 VorbisImageStorageStyle,
80 )
81 from .utils import (
82 Image,
83 image_extension,
84 image_mime_type,
85 loadfile,
86 mutagen_call,
87 update_filething,
88 )
89
90 __all__ = [
91 "TYPES",
92 "APEv2ImageStorageStyle",
93 "ASFImageStorageStyle",
94 "ASFStorageStyle",
95 "CoverArtField",
96 "DateField",
97 "DateItemField",
98 "FileTypeError",
99 "FlacImageStorageStyle",
100 "Image",
101 "ImageListField",
102 "ImageType",
103 "ListMediaField",
104 "ListStorageStyle",
105 "MP3DescStorageStyle",
106 "MP3ImageStorageStyle",
107 "MP3ListDescStorageStyle",
108 "MP3ListStorageStyle",
109 "MP3PeopleStorageStyle",
110 "MP3SlashPackStorageStyle",
111 "MP3SoundCheckStorageStyle",
112 "MP3StorageStyle",
113 "MP3UFIDStorageStyle",
114 "MP4BoolStorageStyle",
115 "MP4ImageStorageStyle",
116 "MP4ListStorageStyle",
117 "MP4SoundCheckStorageStyle",
118 "MP4StorageStyle",
119 "MP4TupleStorageStyle",
120 "MediaField",
121 "MediaFile",
122 "MutagenError",
123 "QNumberField",
124 "SoundCheckStorageStyleMixin",
125 "StorageStyle",
126 "UnreadableFileError",
127 "VorbisImageStorageStyle",
128 "image_extension",
129 "image_mime_type",
130 "loadfile",
131 "mutagen_call",
132 ]
133
134 log = logging.getLogger(__name__)
135
136
137 # MediaFile is a collection of fields.
138
139
140 class MediaFile:
141 """Represents a multimedia file on disk and provides access to its
142 metadata.
143 """
144
145 @loadfile()
146 def __init__(self, filething, id3v23=False, raise_on_unsupported_wav=False):
147 """Constructs a new `MediaFile` reflecting the provided file.
148
149 `filething` can be a path to a file (i.e., a string) or a
150 file-like object.
151
152 May throw `UnreadableFileError`.
153
154 By default, MP3 files are saved with ID3v2.4 tags. You can use
155 the older ID3v2.3 standard by specifying the `id3v23` option.
156
157 If `raise_on_unsupported_wav` is True, a `FileTypeError` is raised for WAV
158 files containing non-PCM audio streams that cannot be tagged correctly.
159 """
160 self.filething = filething
161
162 self.mgfile = mutagen_call("open", self.filename, mutagen.File, filething)
163
164 if self.mgfile is None:
165 # Mutagen couldn't guess the type
166 raise FileTypeError(self.filename)
167 elif type(self.mgfile).__name__ in ["M4A", "MP4"]:
168 info = self.mgfile.info
169 if info.codec and info.codec.startswith("alac"):
170 self.type = "alac"
171 else:
172 self.type = "aac"
173 elif type(self.mgfile).__name__ in ["ID3", "MP3"]:
174 self.type = "mp3"
175 elif type(self.mgfile).__name__ == "FLAC":
176 self.type = "flac"
177 elif type(self.mgfile).__name__ == "OggOpus":
178 self.type = "opus"
179 elif type(self.mgfile).__name__ == "OggVorbis":
180 self.type = "ogg"
181 elif type(self.mgfile).__name__ == "MonkeysAudio":
182 self.type = "ape"
183 elif type(self.mgfile).__name__ == "WavPack":
184 self.type = "wv"
185 elif type(self.mgfile).__name__ == "Musepack":
186 self.type = "mpc"
187 elif type(self.mgfile).__name__ == "ASF":
188 self.type = "asf"
189 elif type(self.mgfile).__name__ == "AIFF":
190 self.type = "aiff"
191 elif type(self.mgfile).__name__ == "DSF":
192 self.type = "dsf"
193 elif type(self.mgfile).__name__ == "WAVE":
194 # WAV files can contain non-PCM audio streams that mutagen
195 # cannot tag correctly. Rejects them with a clear error.
196 _unsupported_wav_formats = {
197 0x0002: "WAVE_FORMAT_ADPCM",
198 0x0006: "WAVE_FORMAT_ALAW",
199 0x0007: "WAVE_FORMAT_MULAW",
200 0x0055: "WAVE_FORMAT_MPEGLAYER3",
201 }
202 audio_fmt = getattr(self.mgfile.info, "audio_format", 0x0001)
203 if raise_on_unsupported_wav and audio_fmt in _unsupported_wav_formats:
204 raise FileTypeError(self.filename, _unsupported_wav_formats[audio_fmt])
205 self.type = "wav"
206 else:
207 raise FileTypeError(self.filename, type(self.mgfile).__name__)
208
209 # Add a set of tags if it's missing.
210 if self.mgfile.tags is None:
211 self.mgfile.add_tags()
212
213 # Set the ID3v2.3 flag only for MP3s.
214 self.id3v23 = id3v23 and self.type == "mp3"
215
216 @property
217 def filename(self):
218 """The name of the file.
219
220 This is the path if this object was opened from the filesystem,
221 or the name of the file-like object.
222 """
223 return self.filething.name
224
225 @filename.setter
226 def filename(self, val):
227 """Silently skips setting filename.
228 Workaround for `mutagen._util._openfile` setting instance's filename.
229 """
230 pass
231
232 @property
233 def path(self):
234 """The path to the file.
235
236 This is `None` if the data comes from a file-like object instead
237 of a filesystem path.
238 """
239 return self.filething.filename
240
241 @property
242 def filesize(self):
243 """The size (in bytes) of the underlying file."""
244 if self.filething.filename:
245 return os.path.getsize(self.filething.filename)
246 if hasattr(self.filething.fileobj, "__len__"):
247 return len(self.filething.fileobj)
248 else:
249 tell = self.filething.fileobj.tell()
250 filesize = self.filething.fileobj.seek(0, 2)
251 self.filething.fileobj.seek(tell)
252 return filesize
253
254 def save(self, **kwargs):
255 """Write the object's tags back to the file.
256
257 May throw `UnreadableFileError`. Accepts keyword arguments to be
258 passed to Mutagen's `save` function.
259 """
260 # Possibly save the tags to ID3v2.3.
261 if self.id3v23:
262 id3 = self.mgfile
263 if hasattr(id3, "tags"):
264 # In case this is an MP3 object, not an ID3 object.
265 id3 = id3.tags
266 id3.update_to_v23()
267 kwargs["v2_version"] = 3
268
269 mutagen_call(
270 "save",
271 self.filename,
272 self.mgfile.save,
273 update_filething(self.filething),
274 **kwargs,
275 )
276
277 def delete(self):
278 """Remove the current metadata tag from the file. May
279 throw `UnreadableFileError`.
280 """
281 mutagen_call(
282 "delete",
283 self.filename,
284 self.mgfile.delete,
285 update_filething(self.filething),
286 )
287
288 # Convenient access to the set of available fields.
289
290 @classmethod
291 def fields(cls):
292 """Get the names of all writable properties that reflect
293 metadata tags (i.e., those that are instances of
294 :class:`MediaField`).
295 """
296 for property, descriptor in cls.__dict__.items():
297 if isinstance(descriptor, MediaField):
298 if isinstance(property, bytes):
299 # On Python 2, class field names are bytes. This method
300 # produces text strings.
301 yield property.decode("utf8", "ignore")
302 else:
303 yield property
304
305 @classmethod
306 def _field_sort_name(cls, name):
307 """Get a sort key for a field name that determines the order
308 fields should be written in.
309
310 Fields names are kept unchanged, unless they are instances of
311 :class:`DateItemField`, in which case `year`, `month`, and `day`
312 are replaced by `date0`, `date1`, and `date2`, respectively, to
313 make them appear in that order.
314 """
315 if isinstance(cls.__dict__[name], DateItemField):
316 name = re.sub("year", "date0", name)
317 name = re.sub("month", "date1", name)
318 name = re.sub("day", "date2", name)
319 return name
320
321 @classmethod
322 def sorted_fields(cls):
323 """Get the names of all writable metadata fields, sorted in the
324 order that they should be written.
325
326 This is a lexicographic order, except for instances of
327 :class:`DateItemField`, which are sorted in year-month-day
328 order.
329 """
330 yield from sorted(cls.fields(), key=cls._field_sort_name)
331
332 @classmethod
333 def readable_fields(cls):
334 """Get all metadata fields: the writable ones from
335 :meth:`fields` and also other audio properties.
336 """
337 yield from cls.fields()
338 yield from (
339 "length",
340 "samplerate",
341 "bitdepth",
342 "bitrate",
343 "bitrate_mode",
344 "channels",
345 "encoder_info",
346 "encoder_settings",
347 "format",
348 )
349
350 @classmethod
351 def add_field(cls, name, descriptor):
352 """Add a field to store custom tags.
353
354 :param name: the name of the property the field is accessed
355 through. It must not already exist on this class.
356
357 :param descriptor: an instance of :class:`MediaField`.
358 """
359 if not isinstance(descriptor, MediaField):
360 raise ValueError(f"{descriptor} must be an instance of MediaField")
361 if name in cls.__dict__:
362 raise ValueError(f'property "{name}" already exists on MediaFile')
363 setattr(cls, name, descriptor)
364
365 def update(self, dict):
366 """Set all field values from a dictionary.
367
368 For any key in `dict` that is also a field to store tags the
369 method retrieves the corresponding value from `dict` and updates
370 the `MediaFile`. If a key has the value `None`, the
371 corresponding property is deleted from the `MediaFile`.
372 """
373 for field in self.sorted_fields():
374 if field in dict:
375 if dict[field] is None:
376 delattr(self, field)
377 else:
378 setattr(self, field, dict[field])
379
380 def as_dict(self):
381 """Get a dictionary with all writable properties that reflect
382 metadata tags (i.e., those that are instances of
383 :class:`MediaField`).
384 """
385 return {x: getattr(self, x) for x in self.fields()}
386
387 # Field definitions.
388
389 title = MediaField(
390 MP3StorageStyle("TIT2"),
391 MP4StorageStyle("\xa9nam"),
392 StorageStyle("TITLE"),
393 ASFStorageStyle("Title"),
394 )
395 artist = MediaField(
396 MP3StorageStyle("TPE1"),
397 MP4StorageStyle("\xa9ART"),
398 StorageStyle("ARTIST"),
399 ASFStorageStyle("Author"),
400 )
401 artists = ListMediaField(
402 MP3ListDescStorageStyle(desc="ARTISTS"),
403 MP4ListStorageStyle("----:com.apple.iTunes:ARTISTS"),
404 ListStorageStyle("ARTISTS"),
405 ASFStorageStyle("WM/ARTISTS"),
406 )
407 album = MediaField(
408 MP3StorageStyle("TALB"),
409 MP4StorageStyle("\xa9alb"),
410 StorageStyle("ALBUM"),
411 ASFStorageStyle("WM/AlbumTitle"),
412 )
413 genres = ListMediaField(
414 MP3ListStorageStyle("TCON"),
415 MP4ListStorageStyle("\xa9gen"),
416 ListStorageStyle("GENRE"),
417 ASFStorageStyle("WM/Genre"),
418 )
419 genre = genres.single_field()
420
421 lyricists = ListMediaField(
422 MP3ListStorageStyle("TEXT"),
423 MP4ListStorageStyle("----:com.apple.iTunes:LYRICIST"),
424 ListStorageStyle("LYRICIST"),
425 ASFStorageStyle("WM/Writer"),
426 )
427 lyricist = lyricists.single_field()
428 composers = ListMediaField(
429 MP3ListStorageStyle("TCOM"),
430 MP4ListStorageStyle("\xa9wrt"),
431 ListStorageStyle("COMPOSER"),
432 ASFStorageStyle("WM/Composer"),
433 )
434 composer = composers.single_field()
435 composer_sort = MediaField(
436 MP3StorageStyle("TSOC"),
437 MP4StorageStyle("soco"),
438 StorageStyle("COMPOSERSORT"),
439 ASFStorageStyle("WM/Composersortorder"),
440 )
441 arrangers = ListMediaField(
442 MP3ListPeopleStorageStyle("TIPL", involvement="arranger"),
443 MP4ListStorageStyle("----:com.apple.iTunes:Arranger"),
444 ListStorageStyle("ARRANGER"),
445 ASFStorageStyle("beets/Arranger"),
446 )
447 arranger = arrangers.single_field()
448
449 grouping = MediaField(
450 MP3StorageStyle("TIT1"),
451 MP4StorageStyle("\xa9grp"),
452 StorageStyle("GROUPING"),
453 ASFStorageStyle("WM/ContentGroupDescription"),
454 )
455 subtitle = MediaField(
456 MP3StorageStyle("TIT3"),
457 StorageStyle("SUBTITLE"),
458 ASFStorageStyle("Subtitle"),
459 )
460 track = MediaField(
461 MP3SlashPackStorageStyle("TRCK", pack_pos=0),
462 MP4TupleStorageStyle("trkn", index=0),
463 StorageStyle("TRACK"),
464 StorageStyle("TRACKNUMBER"),
465 ASFStorageStyle("WM/TrackNumber"),
466 out_type=int,
467 )
468 tracktotal = MediaField(
469 MP3SlashPackStorageStyle("TRCK", pack_pos=1),
470 MP4TupleStorageStyle("trkn", index=1),
471 StorageStyle("TRACKTOTAL"),
472 StorageStyle("TRACKC"),
473 StorageStyle("TOTALTRACKS"),
474 ASFStorageStyle("TotalTracks"),
475 out_type=int,
476 )
477 disc = MediaField(
478 MP3SlashPackStorageStyle("TPOS", pack_pos=0),
479 MP4TupleStorageStyle("disk", index=0),
480 StorageStyle("DISC"),
481 StorageStyle("DISCNUMBER"),
482 ASFStorageStyle("WM/PartOfSet"),
483 out_type=int,
484 )
485 disctotal = MediaField(
486 MP3SlashPackStorageStyle("TPOS", pack_pos=1),
487 MP4TupleStorageStyle("disk", index=1),
488 StorageStyle("DISCTOTAL"),
489 StorageStyle("DISCC"),
490 StorageStyle("TOTALDISCS"),
491 ASFStorageStyle("TotalDiscs"),
492 out_type=int,
493 )
494
495 url = MediaField(
496 MP3DescStorageStyle(key="WXXX", attr="url", multispec=False),
497 MP4StorageStyle("\xa9url"),
498 StorageStyle("URL"),
499 ASFStorageStyle("WM/URL"),
500 )
501 lyrics = MediaField(
502 MP3DescStorageStyle(key="USLT", multispec=False),
503 MP4StorageStyle("\xa9lyr"),
504 StorageStyle("LYRICS"),
505 ASFStorageStyle("WM/Lyrics"),
506 )
507 synced_lyrics = MediaField(
508 MP3SYLTStorageStyle(),
509 out_type=list,
510 )
511 comments = MediaField(
512 MP3DescStorageStyle(key="COMM"),
513 MP4StorageStyle("\xa9cmt"),
514 StorageStyle("DESCRIPTION"),
515 StorageStyle("COMMENT"),
516 ASFStorageStyle("WM/Comments"),
517 ASFStorageStyle("Description"),
518 )
519 copyright = MediaField(
520 MP3StorageStyle("TCOP"),
521 MP4StorageStyle("cprt"),
522 StorageStyle("COPYRIGHT"),
523 ASFStorageStyle("Copyright"),
524 )
525 bpm = MediaField(
526 MP3StorageStyle("TBPM"),
527 MP4StorageStyle("tmpo", as_type=int),
528 StorageStyle("BPM"),
529 ASFStorageStyle("WM/BeatsPerMinute"),
530 out_type=int,
531 )
532 comp = MediaField(
533 MP3StorageStyle("TCMP"),
534 MP4BoolStorageStyle("cpil"),
535 StorageStyle("COMPILATION"),
536 ASFStorageStyle("WM/IsCompilation", as_type=bool),
537 out_type=bool,
538 )
539 albumartist = MediaField(
540 MP3StorageStyle("TPE2"),
541 MP4StorageStyle("aART"),
542 StorageStyle("ALBUM ARTIST"),
543 StorageStyle("ALBUM_ARTIST"),
544 StorageStyle("ALBUMARTIST"),
545 ASFStorageStyle("WM/AlbumArtist"),
546 )
547 albumartists = ListMediaField(
548 MP3ListDescStorageStyle(desc="ALBUMARTISTS"),
549 MP3ListDescStorageStyle(desc="ALBUM_ARTISTS"),
550 MP3ListDescStorageStyle(desc="ALBUM ARTISTS", read_only=True),
551 MP4ListStorageStyle("----:com.apple.iTunes:ALBUMARTISTS"),
552 MP4ListStorageStyle("----:com.apple.iTunes:ALBUM_ARTISTS"),
553 MP4ListStorageStyle("----:com.apple.iTunes:ALBUM ARTISTS", read_only=True),
554 ListStorageStyle("ALBUMARTISTS"),
555 ListStorageStyle("ALBUM_ARTISTS"),
556 ListStorageStyle("ALBUM ARTISTS", read_only=True),
557 ASFStorageStyle("WM/AlbumArtists"),
558 )
559 albumtypes = ListMediaField(
560 MP3ListDescStorageStyle("MusicBrainz Album Type", split_v23=True),
561 MP4ListStorageStyle("----:com.apple.iTunes:MusicBrainz Album Type"),
562 ListStorageStyle("RELEASETYPE"),
563 ListStorageStyle("MUSICBRAINZ_ALBUMTYPE"),
564 ASFStorageStyle("MusicBrainz/Album Type"),
565 )
566 albumtype = albumtypes.single_field()
567
568 label = MediaField(
569 MP3StorageStyle("TPUB"),
570 MP3DescStorageStyle("LABEL"),
571 MP4StorageStyle("----:com.apple.iTunes:LABEL"),
572 MP4StorageStyle("----:com.apple.iTunes:publisher"),
573 MP4StorageStyle("----:com.apple.iTunes:Label", read_only=True),
574 StorageStyle("LABEL"),
575 StorageStyle("PUBLISHER"), # Traktor
576 ASFStorageStyle("WM/Publisher"),
577 )
578 artist_sort = MediaField(
579 MP3StorageStyle("TSOP"),
580 MP4StorageStyle("soar"),
581 StorageStyle("ARTISTSORT"),
582 ASFStorageStyle("WM/ArtistSortOrder"),
583 )
584 albumartist_sort = MediaField(
585 MP3StorageStyle("TSO2"),
586 MP3DescStorageStyle("ALBUMARTISTSORT"),
587 MP4StorageStyle("soaa"),
588 StorageStyle("ALBUMARTISTSORT"),
589 ASFStorageStyle("WM/AlbumArtistSortOrder"),
590 )
591 asin = MediaField(
592 MP3DescStorageStyle("ASIN"),
593 MP4StorageStyle("----:com.apple.iTunes:ASIN"),
594 StorageStyle("ASIN"),
595 ASFStorageStyle("MusicBrainz/ASIN"),
596 )
597 catalognums = ListMediaField(
598 MP3ListDescStorageStyle("CATALOGNUMBER", split_v23=True),
599 MP3ListDescStorageStyle("CATALOGID", read_only=True),
600 MP3ListDescStorageStyle("DISCOGS_CATALOG", read_only=True),
601 MP4ListStorageStyle("----:com.apple.iTunes:CATALOGNUMBER"),
602 MP4ListStorageStyle("----:com.apple.iTunes:CATALOGID", read_only=True),
603 MP4ListStorageStyle("----:com.apple.iTunes:DISCOGS_CATALOG", read_only=True),
604 ListStorageStyle("CATALOGNUMBER"),
605 ListStorageStyle("CATALOGID", read_only=True),
606 ListStorageStyle("DISCOGS_CATALOG", read_only=True),
607 ASFStorageStyle("WM/CatalogNo"),
608 ASFStorageStyle("CATALOGID", read_only=True),
609 ASFStorageStyle("DISCOGS_CATALOG", read_only=True),
610 )
611 catalognum = catalognums.single_field()
612
613 barcode = MediaField(
614 MP3DescStorageStyle("BARCODE"),
615 MP4StorageStyle("----:com.apple.iTunes:BARCODE"),
616 StorageStyle("BARCODE"),
617 StorageStyle("UPC", read_only=True),
618 StorageStyle("EAN/UPN", read_only=True),
619 StorageStyle("EAN", read_only=True),
620 StorageStyle("UPN", read_only=True),
621 ASFStorageStyle("WM/Barcode"),
622 )
623 isrc = MediaField(
624 MP3StorageStyle("TSRC"),
625 MP4StorageStyle("----:com.apple.iTunes:ISRC"),
626 StorageStyle("ISRC"),
627 ASFStorageStyle("WM/ISRC"),
628 )
629 disctitle = MediaField(
630 MP3StorageStyle("TSST"),
631 MP4StorageStyle("----:com.apple.iTunes:DISCSUBTITLE"),
632 StorageStyle("DISCSUBTITLE"),
633 ASFStorageStyle("WM/SetSubTitle"),
634 )
635 encoder = MediaField(
636 MP3StorageStyle("TENC"),
637 MP4StorageStyle("\xa9too"),
638 StorageStyle("ENCODEDBY"),
639 StorageStyle("ENCODER"),
640 ASFStorageStyle("WM/EncodedBy"),
641 )
642 script = MediaField(
643 MP3DescStorageStyle("Script"),
644 MP4StorageStyle("----:com.apple.iTunes:SCRIPT"),
645 StorageStyle("SCRIPT"),
646 ASFStorageStyle("WM/Script"),
647 )
648 languages = ListMediaField(
649 MP3ListStorageStyle("TLAN"),
650 MP4ListStorageStyle("----:com.apple.iTunes:LANGUAGE"),
651 ListStorageStyle("LANGUAGE"),
652 ASFStorageStyle("WM/Language"),
653 )
654 language = languages.single_field()
655
656 country = MediaField(
657 MP3DescStorageStyle("MusicBrainz Album Release Country"),
658 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Album Release Country"),
659 StorageStyle("RELEASECOUNTRY"),
660 ASFStorageStyle("MusicBrainz/Album Release Country"),
661 )
662 albumstatus = MediaField(
663 MP3DescStorageStyle("MusicBrainz Album Status"),
664 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Album Status"),
665 StorageStyle("RELEASESTATUS"),
666 StorageStyle("MUSICBRAINZ_ALBUMSTATUS"),
667 ASFStorageStyle("MusicBrainz/Album Status"),
668 )
669 media = MediaField(
670 MP3StorageStyle("TMED"),
671 MP3DescStorageStyle("MEDIA"),
672 MP4StorageStyle("----:com.apple.iTunes:MEDIA"),
673 StorageStyle("MEDIA"),
674 ASFStorageStyle("WM/Media"),
675 )
676 albumdisambig = MediaField(
677 # This tag mapping was invented for beets (not used by Picard, etc).
678 MP3DescStorageStyle("MusicBrainz Album Comment"),
679 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Album Comment"),
680 StorageStyle("MUSICBRAINZ_ALBUMCOMMENT"),
681 ASFStorageStyle("MusicBrainz/Album Comment"),
682 )
683
684 # Release date.
685 date = DateField(
686 MP3StorageStyle("TDRC"),
687 MP4StorageStyle("\xa9day"),
688 StorageStyle("DATE"),
689 ASFStorageStyle("WM/Year"),
690 year=(StorageStyle("YEAR"),),
691 )
692
693 year = date.year_field()
694 month = date.month_field()
695 day = date.day_field()
696
697 # *Original* release date.
698 original_date = DateField(
699 MP3StorageStyle("TDOR"),
700 MP4StorageStyle("----:com.apple.iTunes:ORIGINAL YEAR"),
701 MP4StorageStyle("----:com.apple.iTunes:ORIGINALDATE"),
702 StorageStyle("ORIGINALDATE"),
703 ASFStorageStyle("WM/OriginalReleaseYear"),
704 )
705
706 original_year = original_date.year_field()
707 original_month = original_date.month_field()
708 original_day = original_date.day_field()
709
710 # Nonstandard metadata.
711 artist_credit = MediaField(
712 MP3DescStorageStyle("Artist Credit"),
713 MP4StorageStyle("----:com.apple.iTunes:Artist Credit"),
714 StorageStyle("ARTIST_CREDIT"),
715 ASFStorageStyle("beets/Artist Credit"),
716 )
717 artists_credit = ListMediaField(
718 MP3ListDescStorageStyle(desc="ARTISTS_CREDIT"),
719 MP4ListStorageStyle("----:com.apple.iTunes:ARTISTS_CREDIT"),
720 ListStorageStyle("ARTISTS_CREDIT"),
721 ASFStorageStyle("beets/ArtistsCredit"),
722 )
723 artists_sort = ListMediaField(
724 MP3ListDescStorageStyle(desc="ARTISTS_SORT"),
725 MP4ListStorageStyle("----:com.apple.iTunes:ARTISTS_SORT"),
726 ListStorageStyle("ARTISTS_SORT"),
727 ASFStorageStyle("beets/ArtistsSort"),
728 )
729 albumartist_credit = MediaField(
730 MP3DescStorageStyle("Album Artist Credit"),
731 MP4StorageStyle("----:com.apple.iTunes:Album Artist Credit"),
732 StorageStyle("ALBUMARTIST_CREDIT"),
733 ASFStorageStyle("beets/Album Artist Credit"),
734 )
735 albumartists_credit = ListMediaField(
736 MP3ListDescStorageStyle(desc="ALBUMARTISTS_CREDIT"),
737 MP4ListStorageStyle("----:com.apple.iTunes:ALBUMARTISTS_CREDIT"),
738 ListStorageStyle("ALBUMARTISTS_CREDIT"),
739 ASFStorageStyle("beets/AlbumArtistsCredit"),
740 )
741 albumartists_sort = ListMediaField(
742 MP3ListDescStorageStyle(desc="ALBUMARTISTS_SORT"),
743 MP4ListStorageStyle("----:com.apple.iTunes:ALBUMARTISTS_SORT"),
744 ListStorageStyle("ALBUMARTISTS_SORT"),
745 ASFStorageStyle("beets/AlbumArtistsSort"),
746 )
747 remixers = ListMediaField(
748 MP3ListStorageStyle("TPE4"),
749 MP4ListStorageStyle("----:com.apple.iTunes:REMIXERS"),
750 ListStorageStyle("REMIXER"),
751 ASFStorageStyle("WM/REMIXERS"),
752 )
753
754 # Legacy album art field
755 art = CoverArtField()
756
757 # Image list
758 images = ImageListField()
759
760 # MusicBrainz IDs.
761 mb_trackid = MediaField(
762 MP3UFIDStorageStyle(owner="http://musicbrainz.org"),
763 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Track Id"),
764 StorageStyle("MUSICBRAINZ_TRACKID"),
765 ASFStorageStyle("MusicBrainz/Track Id"),
766 )
767 mb_releasetrackid = MediaField(
768 MP3DescStorageStyle("MusicBrainz Release Track Id"),
769 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Release Track Id"),
770 StorageStyle("MUSICBRAINZ_RELEASETRACKID"),
771 ASFStorageStyle("MusicBrainz/Release Track Id"),
772 )
773 mb_workid = MediaField(
774 MP3DescStorageStyle("MusicBrainz Work Id"),
775 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Work Id"),
776 StorageStyle("MUSICBRAINZ_WORKID"),
777 ASFStorageStyle("MusicBrainz/Work Id"),
778 )
779 mb_albumid = MediaField(
780 MP3DescStorageStyle("MusicBrainz Album Id"),
781 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Album Id"),
782 StorageStyle("MUSICBRAINZ_ALBUMID"),
783 ASFStorageStyle("MusicBrainz/Album Id"),
784 )
785 mb_artistids = ListMediaField(
786 MP3ListDescStorageStyle("MusicBrainz Artist Id", split_v23=True),
787 MP4ListStorageStyle("----:com.apple.iTunes:MusicBrainz Artist Id"),
788 ListStorageStyle("MUSICBRAINZ_ARTISTID"),
789 ASFStorageStyle("MusicBrainz/Artist Id"),
790 )
791 mb_artistid = mb_artistids.single_field()
792
793 mb_albumartistids = ListMediaField(
794 MP3ListDescStorageStyle(
795 "MusicBrainz Album Artist Id",
796 split_v23=True,
797 ),
798 MP4ListStorageStyle(
799 "----:com.apple.iTunes:MusicBrainz Album Artist Id",
800 ),
801 ListStorageStyle("MUSICBRAINZ_ALBUMARTISTID"),
802 ASFStorageStyle("MusicBrainz/Album Artist Id"),
803 )
804 mb_albumartistid = mb_albumartistids.single_field()
805
806 mb_releasegroupid = MediaField(
807 MP3DescStorageStyle("MusicBrainz Release Group Id"),
808 MP4StorageStyle("----:com.apple.iTunes:MusicBrainz Release Group Id"),
809 StorageStyle("MUSICBRAINZ_RELEASEGROUPID"),
810 ASFStorageStyle("MusicBrainz/Release Group Id"),
811 )
812
813 # Acoustid fields.
814 acoustid_fingerprint = MediaField(
815 MP3DescStorageStyle("Acoustid Fingerprint"),
816 MP4StorageStyle("----:com.apple.iTunes:Acoustid Fingerprint"),
817 StorageStyle("ACOUSTID_FINGERPRINT"),
818 ASFStorageStyle("Acoustid/Fingerprint"),
819 )
820 acoustid_id = MediaField(
821 MP3DescStorageStyle("Acoustid Id"),
822 MP4StorageStyle("----:com.apple.iTunes:Acoustid Id"),
823 StorageStyle("ACOUSTID_ID"),
824 ASFStorageStyle("Acoustid/Id"),
825 )
826
827 # ReplayGain fields.
828 rg_track_gain = MediaField(
829 MP3DescStorageStyle("REPLAYGAIN_TRACK_GAIN", float_places=2, suffix=" dB"),
830 MP3DescStorageStyle("replaygain_track_gain", float_places=2, suffix=" dB"),
831 MP3SoundCheckStorageStyle(key="COMM", index=0, desc="iTunNORM", id3_lang="eng"),
832 MP4StorageStyle(
833 "----:com.apple.iTunes:replaygain_track_gain", float_places=2, suffix=" dB"
834 ),
835 MP4SoundCheckStorageStyle("----:com.apple.iTunes:iTunNORM", index=0),
836 StorageStyle("REPLAYGAIN_TRACK_GAIN", float_places=2, suffix=" dB"),
837 ASFStorageStyle("replaygain_track_gain", float_places=2, suffix=" dB"),
838 out_type=float,
839 )
840 rg_album_gain = MediaField(
841 MP3DescStorageStyle("REPLAYGAIN_ALBUM_GAIN", float_places=2, suffix=" dB"),
842 MP3DescStorageStyle("replaygain_album_gain", float_places=2, suffix=" dB"),
843 MP4StorageStyle(
844 "----:com.apple.iTunes:replaygain_album_gain", float_places=2, suffix=" dB"
845 ),
846 StorageStyle("REPLAYGAIN_ALBUM_GAIN", float_places=2, suffix=" dB"),
847 ASFStorageStyle("replaygain_album_gain", float_places=2, suffix=" dB"),
848 out_type=float,
849 )
850 rg_track_peak = MediaField(
851 MP3DescStorageStyle("REPLAYGAIN_TRACK_PEAK", float_places=6),
852 MP3DescStorageStyle("replaygain_track_peak", float_places=6),
853 MP3SoundCheckStorageStyle(key="COMM", index=1, desc="iTunNORM", id3_lang="eng"),
854 MP4StorageStyle("----:com.apple.iTunes:replaygain_track_peak", float_places=6),
855 MP4SoundCheckStorageStyle("----:com.apple.iTunes:iTunNORM", index=1),
856 StorageStyle("REPLAYGAIN_TRACK_PEAK", float_places=6),
857 ASFStorageStyle("replaygain_track_peak", float_places=6),
858 out_type=float,
859 )
860 rg_album_peak = MediaField(
861 MP3DescStorageStyle("REPLAYGAIN_ALBUM_PEAK", float_places=6),
862 MP3DescStorageStyle("replaygain_album_peak", float_places=6),
863 MP4StorageStyle("----:com.apple.iTunes:replaygain_album_peak", float_places=6),
864 StorageStyle("REPLAYGAIN_ALBUM_PEAK", float_places=6),
865 ASFStorageStyle("replaygain_album_peak", float_places=6),
866 out_type=float,
867 )
868
869 # EBU R128 fields.
870 r128_track_gain = QNumberField(
871 8,
872 MP3DescStorageStyle("R128_TRACK_GAIN"),
873 MP4StorageStyle("----:com.apple.iTunes:R128_TRACK_GAIN"),
874 StorageStyle("R128_TRACK_GAIN"),
875 ASFStorageStyle("R128_TRACK_GAIN"),
876 )
877 r128_album_gain = QNumberField(
878 8,
879 MP3DescStorageStyle("R128_ALBUM_GAIN"),
880 MP4StorageStyle("----:com.apple.iTunes:R128_ALBUM_GAIN"),
881 StorageStyle("R128_ALBUM_GAIN"),
882 ASFStorageStyle("R128_ALBUM_GAIN"),
883 )
884
885 initial_key = MediaField(
886 MP3StorageStyle("TKEY"),
887 MP4StorageStyle("----:com.apple.iTunes:initialkey"),
888 StorageStyle("INITIALKEY"),
889 ASFStorageStyle("INITIALKEY"),
890 )
891
892 @property
893 def length(self):
894 """The duration of the audio in seconds (a float)."""
895 return self.mgfile.info.length
896
897 @property
898 def samplerate(self):
899 """The audio's sample rate (an int)."""
900 if hasattr(self.mgfile.info, "sample_rate"):
901 return self.mgfile.info.sample_rate
902 elif self.type == "opus":
903 # Opus is always 48kHz internally.
904 return 48000
905 return 0
906
907 @property
908 def bitdepth(self):
909 """The number of bits per sample in the audio encoding (an int).
910 Only available for certain file formats (zero where
911 unavailable).
912 """
913 if hasattr(self.mgfile.info, "bits_per_sample"):
914 return self.mgfile.info.bits_per_sample
915 return 0
916
917 @property
918 def channels(self):
919 """The number of channels in the audio (an int)."""
920 if hasattr(self.mgfile.info, "channels"):
921 return self.mgfile.info.channels
922 return 0
923
924 @property
925 def bitrate(self):
926 """The number of bits per seconds used in the audio coding (an
927 int). If this is provided explicitly by the compressed file
928 format, this is a precise reflection of the encoding. Otherwise,
929 it is estimated from the on-disk file size. In this case, some
930 imprecision is possible because the file header is incorporated
931 in the file size.
932 """
933 if hasattr(self.mgfile.info, "bitrate") and self.mgfile.info.bitrate:
934 # Many formats provide it explicitly.
935 return self.mgfile.info.bitrate
936 else:
937 # Otherwise, we calculate bitrate from the file size. (This
938 # is the case for all of the lossless formats.)
939 if not self.length:
940 # Avoid division by zero if length is not available.
941 return 0
942 return int(self.filesize * 8 / self.length)
943
944 @property
945 def bitrate_mode(self):
946 """The mode of the bitrate used in the audio coding
947 (a string, eg. "CBR", "VBR" or "ABR").
948 Only available for the MP3 file format (empty where unavailable).
949 """
950 if hasattr(self.mgfile.info, "bitrate_mode"):
951 return {
952 mutagen.mp3.BitrateMode.CBR: "CBR",
953 mutagen.mp3.BitrateMode.VBR: "VBR",
954 mutagen.mp3.BitrateMode.ABR: "ABR",
955 }.get(self.mgfile.info.bitrate_mode, "")
956 else:
957 return ""
958
959 @property
960 def encoder_info(self):
961 """The name and/or version of the encoder used
962 (a string, eg. "LAME 3.97.0").
963 Only available for some formats (empty where unavailable).
964 """
965 if hasattr(self.mgfile.info, "encoder_info"):
966 return self.mgfile.info.encoder_info
967 else:
968 return ""
969
970 @property
971 def encoder_settings(self):
972 """A guess of the settings used for the encoder (a string, eg. "-V2").
973 Only available for the MP3 file format (empty where unavailable).
974 """
975 if hasattr(self.mgfile.info, "encoder_settings"):
976 return self.mgfile.info.encoder_settings
977 else:
978 return ""
979
980 @property
981 def format(self):
982 """A string describing the file format/codec."""
983 return TYPES[self.type]