-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessing.py
More file actions
3075 lines (2565 loc) · 104 KB
/
Copy pathprocessing.py
File metadata and controls
3075 lines (2565 loc) · 104 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
"""
DropGain processing, metadata, and output verification.
This module contains the rendering path, metadata copy/verify helpers, and
post-render validation. Shared configuration and analysis helpers live in
analysis.py.
"""
from __future__ import annotations
import copy
import hashlib
import logging
import math
import os
import queue
import struct
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any, Callable, Iterable, TypeVar
logger = logging.getLogger("dropgain")
try:
import numpy as np
import pyloudnorm as pyln
from mutagen import File as MutagenFile
from mutagen.aiff import AIFF
from mutagen.flac import FLAC
from mutagen.id3 import (
APIC,
COMM,
ID3,
ID3NoHeaderError,
TALB,
TBPM,
TCOM,
TCON,
TDRC,
TIT2,
TKEY,
TPE1,
TPE2,
TRCK,
)
from mutagen.wave import WAVE
except ImportError as exc:
raise RuntimeError(
"Required Python packages were not found.\n\n"
"Install numpy, pyloudnorm, and mutagen, then try again."
) from exc
from analysis import (
DEFAULT_OUTPUT_FORMAT_MODE,
EFFECTIVE_ZERO_GAIN_DB,
OUTPUT_FORMAT_ALL_TO_AIFF,
OUTPUT_FORMAT_PRESERVE,
METER_SAMPLE_RATE,
MIN_OUTPUT_FILE_BYTES,
MP3_ENCODE_TRUE_PEAK_LIFT_DB,
NORMALIZATION_MODE_LIMITER_ASSISTED,
MP3_ID3_VERSION,
MP3_OUTPUT_BITRATE,
PIONEER_COMPATIBLE_AIFF_CODECS,
PIONEER_COMPATIBLE_AIFF_SAMPLE_RATES,
POST_VERIFY_LUFS_TOLERANCE,
POST_VERIFY_PEAK_TOLERANCE_DB,
POST_VERIFY_PROCESSED_AUDIO,
PROCESS_OVERWRITE_EXISTING,
PROCESSING_ENGINE_CLEAN_GAIN,
PROCESSING_ENGINE_PROL2,
PROL2_DEFAULT_OUTPUT_LEVEL_DBFS,
PROL2_DEFAULT_OVERSAMPLING,
PROL2_DEFAULT_PLUGIN_PATH,
PROL2_DEFAULT_STYLE,
PROL2_DEFAULT_TRUE_PEAK,
PROL2_PROCESS_BUFFER_SIZE,
STRICT_VERIFY_LOSSLESS_OUTPUT,
SUPPORTED_EXTENSIONS,
TrackRow,
aiff_codec_to_use,
audio_for_loudness_meter,
benchmark_timer,
append_note,
dbfs,
decode_audio_ffmpeg,
ffprobe_audio_info,
flac_sample_fmt_to_use,
hidden_subprocess_kwargs,
infer_bit_depth,
loudest_section_lufs,
min_abs_gain_for_extension,
measure_lufs,
measure_lufs_input,
normalize_output_format_mode,
measure_section_and_whole_true_peak_oversampled,
parse_float_or_default,
parse_int_or_default,
pioneer_compatible_aiff_codec,
pioneer_compatible_aiff_sample_rate,
is_aiff_output,
requires_pioneer_compatible_aiff,
round_or_blank,
wav_codec_to_use,
)
# =============================================================================
# METADATA COPY / VERIFY
# =============================================================================
LOUDNESS_METADATA_KEY_PREFIXES = (
"REPLAYGAIN_",
"R128_",
"EBU_R128",
)
# Exact or compact names for player-side loudness/normalization metadata.
# These tags should not be copied to baked-gain output files because a player
# could apply them on top of the audio gain DropGain just rendered.
LOUDNESS_METADATA_KEYS_EXACT = (
"ITUNNORM", # Apple/iTunes Sound Check, often stored as COMM:iTunNORM.
"ITUNES_NORMALIZATION",
"SOUND_CHECK",
"SOUNDCHECK",
)
LOUDNESS_METADATA_COMPACT_PREFIXES = (
"REPLAYGAIN",
"R128",
"EBUR128",
"ITUNNORM",
"ITUNESNORMALIZATION",
"SOUNDCHECK",
)
LOUDNESS_METADATA_ID3_PREFIXES = (
"RVA2", # ID3 relative volume adjustment
"RVAD", # obsolete ID3 relative volume adjustment
"RGAD", # ReplayGain adjustment frame used by some tools
)
def compact_metadata_key(value: object) -> str:
"""Return a normalized metadata key suitable for loose loudness-tag matching."""
return "".join(ch for ch in str(value or "").upper() if ch.isalnum())
def is_loudness_metadata_key(key: object) -> bool:
"""Return True for tags that describe previous playback loudness normalization."""
text = str(key or "").strip().upper()
if not text:
return False
# ID3 TXXX/COMM keys are often represented as TXXX:<description> or
# COMM:<description>:<language>. Test every segment plus the whole key.
parts = [text, *(part.strip() for part in text.split(":") if part.strip())]
for part in parts:
if part in LOUDNESS_METADATA_KEYS_EXACT:
return True
if part.startswith(LOUDNESS_METADATA_KEY_PREFIXES):
return True
compact = compact_metadata_key(part)
if any(compact.startswith(prefix) for prefix in LOUDNESS_METADATA_COMPACT_PREFIXES):
return True
return False
def is_loudness_metadata_id3_frame(key: object, frame: object | None = None) -> bool:
"""Return True for ID3 frames that can apply stale playback gain/volume adjustment."""
text = str(key or "").strip().upper()
if is_loudness_metadata_key(text) or text.startswith(LOUDNESS_METADATA_ID3_PREFIXES):
return True
desc = str(getattr(frame, "desc", "") or "").strip().upper()
return is_loudness_metadata_key(desc) or desc.startswith(LOUDNESS_METADATA_ID3_PREFIXES)
def strip_loudness_id3_frames(tags: ID3) -> None:
"""Remove ReplayGain/R128/relative-volume frames from copied ID3 tags."""
for key in list(tags.keys()):
frame = tags.get(key)
if is_loudness_metadata_id3_frame(key, frame):
del tags[key]
def normalized_id3_frame_value(frame: object) -> object:
"""Return a stable comparable representation of a Mutagen ID3 frame.
Mutagen frame objects include implementation details such as text encoding,
which can legitimately change when tags are saved as ID3v2.3. This helper
compares the meaningful public frame data instead. Binary payloads, such as
cover art, are represented by length and SHA-256 digest so large images are
not copied into warning messages.
"""
def normalize(value: object) -> object:
if isinstance(value, bytes):
return ("bytes", len(value), hashlib.sha256(value).hexdigest())
if isinstance(value, bytearray):
raw = bytes(value)
return ("bytes", len(raw), hashlib.sha256(raw).hexdigest())
if isinstance(value, (str, int, float, bool)) or value is None:
return value
if isinstance(value, (list, tuple)):
return tuple(normalize(item) for item in value)
if isinstance(value, dict):
return tuple(
sorted(
(str(key), normalize(item))
for key, item in value.items()
)
)
if isinstance(value, set):
return tuple(sorted((normalize(item) for item in value), key=repr))
try:
attrs = vars(value)
except TypeError:
attrs = None
if attrs is not None:
return (
value.__class__.__name__,
tuple(
sorted(
(str(key), normalize(item))
for key, item in attrs.items()
if not str(key).startswith("_") and str(key) != "encoding"
)
),
)
return str(value)
try:
attrs = vars(frame)
except TypeError:
return str(frame)
return (
frame.__class__.__name__,
tuple(
sorted(
(str(key), normalize(value))
for key, value in attrs.items()
if not str(key).startswith("_") and str(key) != "encoding"
)
),
)
def append_changed_id3_frame_warnings(
problems: list[str],
source_tags: ID3,
output_tags: ID3,
source_keys: set[str],
output_keys: set[str],
label: str,
) -> None:
"""Append warnings for matching ID3 frame keys whose meaningful values changed."""
changed = sorted(
key for key in (source_keys & output_keys)
if normalized_id3_frame_value(source_tags.get(key))
!= normalized_id3_frame_value(output_tags.get(key))
)
for key in changed[:20]:
problems.append(f"changed {label} frame {key}")
if len(changed) > 20:
problems.append(f"{len(changed) - 20} more {label} frames changed")
def normalized_vorbis_comments(flac: FLAC) -> dict[str, list[str]]:
"""Return uppercase-sorted Vorbis comments, excluding stale loudness metadata."""
if not flac.tags:
return {}
result: dict[str, list[str]] = {}
for key, values in flac.tags.items():
if is_loudness_metadata_key(key):
continue
result[key.upper()] = sorted(str(v) for v in values)
return result
def copy_flac_metadata_exact(source_path: str, output_path: str) -> None:
"""Copy FLAC tags and pictures, excluding stale loudness-normalization tags."""
source = FLAC(source_path)
output = FLAC(output_path)
output.clear()
if source.tags:
for key, values in source.tags.items():
if is_loudness_metadata_key(key):
continue
output[key] = [str(v) for v in values]
output.clear_pictures()
for picture in source.pictures:
output.add_picture(picture)
output.save()
def verify_flac_metadata(source_path: str, output_path: str) -> list[str]:
"""Compare tags and pictures between source and output FLAC."""
source = FLAC(source_path)
output = FLAC(output_path)
problems: list[str] = []
source_tags = normalized_vorbis_comments(source)
output_tags = normalized_vorbis_comments(output)
if output.tags:
stale = sorted(str(key).upper() for key in output.tags.keys() if is_loudness_metadata_key(key))
for key in stale[:20]:
problems.append(f"stale loudness FLAC tag {key}")
if len(stale) > 20:
problems.append(f"{len(stale) - 20} more stale loudness FLAC tags")
for key, values in source_tags.items():
if key not in output_tags:
problems.append(f"missing FLAC tag {key}")
elif output_tags[key] != values:
problems.append(f"changed FLAC tag {key}")
if len(source.pictures) != len(output.pictures):
problems.append(f"picture count changed {len(source.pictures)} -> {len(output.pictures)}")
return problems
def copy_mp3_metadata_exact(source_path: str, output_path: str) -> None:
"""Copy ID3 tags from source MP3, excluding stale loudness-normalization frames."""
try:
source_tags = copy.deepcopy(ID3(source_path))
except ID3NoHeaderError:
return
strip_loudness_id3_frames(source_tags)
source_tags.save(output_path, v2_version=MP3_ID3_VERSION)
def verify_mp3_metadata(source_path: str, output_path: str) -> list[str]:
"""Compare ID3 frames between source and output MP3."""
problems: list[str] = []
try:
source_tags = ID3(source_path)
except ID3NoHeaderError:
return problems
try:
output_tags = ID3(output_path)
except ID3NoHeaderError:
return ["missing ID3 tag"]
source_keys = {
key for key in source_tags.keys()
if not is_loudness_metadata_id3_frame(key, source_tags.get(key))
}
output_keys = {
key for key in output_tags.keys()
if not is_loudness_metadata_id3_frame(key, output_tags.get(key))
}
stale = sorted(
key for key in output_tags.keys()
if is_loudness_metadata_id3_frame(key, output_tags.get(key))
)
for key in stale[:20]:
problems.append(f"stale loudness ID3 frame {key}")
if len(stale) > 20:
problems.append(f"{len(stale) - 20} more stale loudness ID3 frames")
missing = sorted(source_keys - output_keys)
for key in missing[:20]:
problems.append(f"missing ID3 frame {key}")
if len(missing) > 20:
problems.append(f"{len(missing) - 20} more ID3 frames missing")
append_changed_id3_frame_warnings(
problems,
source_tags,
output_tags,
source_keys,
output_keys,
"ID3",
)
return problems
def copy_wav_metadata_best_effort(source_path: str, output_path: str) -> None:
"""Copy WAV ID3 tags from source to output, if present."""
try:
source = WAVE(source_path)
except Exception as exc:
logger.warning(
"Could not read source WAV tags from %s: %s",
source_path,
exc,
exc_info=True,
)
return
if not source.tags:
return
try:
output = WAVE(output_path)
if output.tags is None:
output.add_tags()
output.tags.clear()
for key, frame in source.tags.items():
if is_loudness_metadata_id3_frame(key, frame):
continue
output.tags.add(copy.deepcopy(frame))
output.save()
except Exception as exc:
logger.warning(
"Could not copy WAV tags from %s to %s: %s",
source_path,
output_path,
exc,
exc_info=True,
)
raise
def verify_wav_metadata(source_path: str, output_path: str) -> list[str]:
"""Compare ID3 frames between source and output WAV."""
problems: list[str] = []
try:
source = WAVE(source_path)
except Exception as exc:
logger.warning(
"Could not read source WAV tags from %s during verification: %s",
source_path,
exc,
exc_info=True,
)
return [f"could not read source WAV tags: {exc}"]
if not source.tags:
return problems
try:
output = WAVE(output_path)
except Exception as exc:
logger.warning(
"Could not read output WAV tags from %s during verification: %s",
output_path,
exc,
exc_info=True,
)
return [f"could not read output WAV tags: {exc}"]
if output.tags is None:
return ["missing WAV ID3 tag"]
source_keys = {
key for key in source.tags.keys()
if not is_loudness_metadata_id3_frame(key, source.tags.get(key))
}
output_keys = {
key for key in output.tags.keys()
if not is_loudness_metadata_id3_frame(key, output.tags.get(key))
}
stale = sorted(
key for key in output.tags.keys()
if is_loudness_metadata_id3_frame(key, output.tags.get(key))
)
for key in stale[:20]:
problems.append(f"stale loudness WAV ID3 frame {key}")
if len(stale) > 20:
problems.append(f"{len(stale) - 20} more stale loudness WAV ID3 frames")
missing = sorted(source_keys - output_keys)
for key in missing[:20]:
problems.append(f"missing WAV ID3 frame {key}")
if len(missing) > 20:
problems.append(f"{len(missing) - 20} more WAV ID3 frames missing")
append_changed_id3_frame_warnings(
problems,
source.tags,
output.tags,
source_keys,
output_keys,
"WAV ID3",
)
return problems
def copy_aiff_metadata_best_effort(source_path: str, output_path: str) -> None:
"""Copy AIFF ID3 tags from source to output, if present."""
try:
source = AIFF(source_path)
except Exception as exc:
logger.warning(
"Could not read source AIFF tags from %s: %s",
source_path,
exc,
exc_info=True,
)
return
if not source.tags:
return
try:
output = AIFF(output_path)
if output.tags is None:
output.add_tags()
output.tags.clear()
for key, frame in source.tags.items():
if is_loudness_metadata_id3_frame(key, frame):
continue
output.tags.add(copy.deepcopy(frame))
output.save()
except Exception as exc:
logger.warning(
"Could not copy AIFF tags from %s to %s: %s",
source_path,
output_path,
exc,
exc_info=True,
)
raise
def verify_aiff_metadata(source_path: str, output_path: str) -> list[str]:
"""Compare ID3 frames between source and output AIFF."""
problems: list[str] = []
try:
source = AIFF(source_path)
except Exception as exc:
logger.warning(
"Could not read source AIFF tags from %s during verification: %s",
source_path,
exc,
exc_info=True,
)
return [f"could not read source AIFF tags: {exc}"]
if not source.tags:
return problems
try:
output = AIFF(output_path)
except Exception as exc:
logger.warning(
"Could not read output AIFF tags from %s during verification: %s",
output_path,
exc,
exc_info=True,
)
return [f"could not read output AIFF tags: {exc}"]
if output.tags is None:
return ["missing AIFF ID3 tag"]
source_keys = {
key for key in source.tags.keys()
if not is_loudness_metadata_id3_frame(key, source.tags.get(key))
}
output_keys = {
key for key in output.tags.keys()
if not is_loudness_metadata_id3_frame(key, output.tags.get(key))
}
stale = sorted(
key for key in output.tags.keys()
if is_loudness_metadata_id3_frame(key, output.tags.get(key))
)
for key in stale[:20]:
problems.append(f"stale loudness AIFF ID3 frame {key}")
if len(stale) > 20:
problems.append(f"{len(stale) - 20} more stale loudness AIFF ID3 frames")
missing = sorted(source_keys - output_keys)
for key in missing[:20]:
problems.append(f"missing AIFF ID3 frame {key}")
if len(missing) > 20:
problems.append(f"{len(missing) - 20} more AIFF ID3 frames missing")
append_changed_id3_frame_warnings(
problems,
source.tags,
output.tags,
source_keys,
output_keys,
"AIFF ID3",
)
return problems
def strip_loudness_tags_from_mp3(output_path: str) -> None:
"""Remove loudness-normalization ID3 frames that ffmpeg mapped into the output MP3."""
try:
tags = ID3(output_path)
except ID3NoHeaderError:
return
strip_loudness_id3_frames(tags)
tags.save(output_path, v2_version=MP3_ID3_VERSION)
def strip_loudness_tags_from_id3_container(output_path: str, audio_cls: Any) -> None:
"""Remove loudness-normalization ID3 frames from WAV/AIFF containers."""
try:
audio = audio_cls(output_path)
except Exception as exc:
logger.warning(
"Could not read tags from %s for loudness strip: %s",
output_path,
exc,
exc_info=True,
)
return
tags = getattr(audio, "tags", None)
if tags is None:
return
changed = False
for key in list(tags.keys()):
frame = tags.get(key)
if is_loudness_metadata_id3_frame(key, frame):
del tags[key]
changed = True
if changed:
try:
audio.save()
except Exception as exc:
logger.warning(
"Could not save loudness-stripped tags to %s: %s",
output_path,
exc,
exc_info=True,
)
def strip_loudness_tags_from_aiff(output_path: str) -> None:
"""Remove stale loudness-normalization ID3 frames from an AIFF output."""
strip_loudness_tags_from_id3_container(output_path, AIFF)
def strip_loudness_tags_from_wav(output_path: str) -> None:
"""Remove stale loudness-normalization ID3 frames from a WAV output."""
strip_loudness_tags_from_id3_container(output_path, WAVE)
DJ_METADATA_GROUPS: dict[str, tuple[str, ...]] = {
"title": ("title",),
"artist": ("artist", "albumartist", "performer"),
"album": ("album",),
"genre": ("genre",),
"comment": ("comment", "comments", "description"),
"composer": ("composer",),
"date/year": ("date", "year"),
"track number": ("tracknumber",),
"BPM": ("bpm",),
"musical key": ("initialkey", "key"),
}
ID3_TEXT_FRAME_TO_EASY_KEY: dict[str, str] = {
"tit2": "title",
"tpe1": "artist",
"tpe2": "albumartist",
"tpe3": "performer",
"talb": "album",
"tcon": "genre",
"tcom": "composer",
"tdrc": "date",
"tyer": "date",
"trck": "tracknumber",
"tbpm": "bpm",
"tkey": "initialkey",
}
def easy_metadata_tags(path: str) -> dict[str, list[str]]:
"""Read easy, cross-format metadata tags for DJ-critical field checks."""
try:
audio = MutagenFile(path, easy=True)
except Exception as exc:
logger.warning(
"Could not read easy metadata from %s: %s",
path,
exc,
exc_info=True,
)
return {}
tags = getattr(audio, "tags", None)
if not tags:
return {}
result: dict[str, list[str]] = {}
try:
items = tags.items()
except Exception as exc:
logger.warning(
"Could not enumerate easy metadata tags from %s: %s",
path,
exc,
exc_info=True,
)
return result
for key, values in items:
key_text = str(key or "").strip().lower()
if not key_text or is_loudness_metadata_key(key_text):
continue
key_text = ID3_TEXT_FRAME_TO_EASY_KEY.get(key_text, key_text)
if isinstance(values, (list, tuple)):
normalized_values = [str(value).strip() for value in values if str(value).strip()]
else:
normalized_values = [str(values).strip()] if str(values).strip() else []
if normalized_values:
result[key_text] = normalized_values
# Some containers expose ID3 text frames directly rather than through
# Mutagen's easy-key aliases. MP3 EasyID3 also omits useful DJ fields such
# as TKEY, so merge raw ID3 text frames as a fallback.
raw_tags = source_id3_tags_for_copy(path)
if raw_tags is not None:
for raw_key in list(raw_tags.keys()):
frame = raw_tags.get(raw_key)
raw_key_text = str(raw_key or "").split(":", 1)[0].strip().lower()
if raw_key_text == "comm":
key_text = "comment"
else:
key_text = ID3_TEXT_FRAME_TO_EASY_KEY.get(raw_key_text, "")
if not key_text or key_text in result or is_loudness_metadata_id3_frame(raw_key, frame):
continue
values = getattr(frame, "text", None)
if values is None:
continue
if isinstance(values, (list, tuple)):
normalized_values = [str(value).strip() for value in values if str(value).strip()]
else:
normalized_values = [str(values).strip()] if str(values).strip() else []
if normalized_values:
result[key_text] = normalized_values
return result
def first_metadata_group_value(tags: dict[str, list[str]], aliases: tuple[str, ...]) -> list[str]:
for alias in aliases:
values = tags.get(alias)
if values:
return values
return []
def has_embedded_art(path: str) -> bool:
"""Return True when common embedded artwork is present."""
ext = Path(path).suffix.lower()
try:
if ext == ".flac":
return bool(FLAC(path).pictures)
if ext == ".mp3":
try:
tags = ID3(path)
except ID3NoHeaderError:
return False
return any(str(key).upper().startswith("APIC") for key in tags.keys())
if ext == ".wav":
tags = WAVE(path).tags
return bool(tags and any(str(key).upper().startswith("APIC") for key in tags.keys()))
if ext == ".aiff":
tags = AIFF(path).tags
return bool(tags and any(str(key).upper().startswith("APIC") for key in tags.keys()))
except Exception as exc:
logger.warning(
"Could not check embedded artwork in %s: %s",
path,
exc,
exc_info=True,
)
return False
return False
def source_id3_tags_for_copy(source_path: str) -> ID3 | None:
"""Return ID3-style tags from MP3/WAV/AIFF sources, excluding unsupported files."""
ext = Path(source_path).suffix.lower()
try:
if ext == ".mp3":
try:
return ID3(source_path)
except ID3NoHeaderError:
return None
if ext == ".wav":
return WAVE(source_path).tags
if ext == ".aiff":
return AIFF(source_path).tags
except Exception as exc:
logger.warning(
"Could not read source ID3 tags from %s: %s",
source_path,
exc,
exc_info=True,
)
return None
return None
def add_non_loudness_id3_frames(target_tags: ID3, source_tags: ID3 | None) -> None:
"""Copy all source ID3 frames except stale playback loudness frames."""
if source_tags is None:
return
for key in list(source_tags.keys()):
frame = source_tags.get(key)
if is_loudness_metadata_id3_frame(key, frame):
continue
try:
target_tags.add(copy.deepcopy(frame))
except Exception as exc:
logger.warning(
"Skipped copying ID3 frame %s: %s",
key,
exc,
exc_info=True,
)
continue
def first_nonempty_metadata_values(
tags: dict[str, list[str]],
aliases: tuple[str, ...],
) -> list[str]:
"""Return cleaned values for the first present metadata alias."""
for alias in aliases:
values = tags.get(alias.lower())
if values:
cleaned = [str(value).strip() for value in values if str(value).strip()]
if cleaned:
return cleaned
return []
def add_text_frame_if_present(
tags: ID3,
frame_cls: Any,
values: list[str],
) -> None:
"""Add one ID3 text frame when source metadata contains usable values."""
if not values:
return
frame_name = getattr(frame_cls, "__name__", str(frame_cls))
try:
tags.add(frame_cls(encoding=3, text=values))
except Exception:
try:
tags.add(frame_cls(encoding=3, text=[str(values[0])]))
except Exception as retry_exc:
logger.warning(
"Could not add ID3 frame %s with values %r: %s",
frame_name,
values,
retry_exc,
exc_info=True,
)
def add_comm_frame_if_present(tags: ID3, values: list[str]) -> None:
"""Add one ID3 comment frame when source metadata contains usable values."""
if not values:
return
try:
tags.add(COMM(encoding=3, lang="eng", desc="", text=values))
except Exception:
try:
tags.add(COMM(encoding=3, lang="eng", desc="", text=[str(values[0])]))
except Exception as retry_exc:
logger.warning(
"Could not add ID3 COMM frame with values %r: %s",
values,
retry_exc,
exc_info=True,
)
def add_easy_metadata_as_id3_frames(target_tags: ID3, source_path: str) -> None:
"""Map common easy metadata fields to portable ID3 frames."""
source_tags = easy_metadata_tags(source_path)
if not source_tags:
return
field_map: tuple[tuple[Any, tuple[str, ...]], ...] = (
(TIT2, ("title",)),
(TPE1, ("artist", "performer", "albumartist")),
(TPE2, ("albumartist",)),
(TALB, ("album",)),
(TCON, ("genre",)),
(TCOM, ("composer",)),
(TDRC, ("date", "year")),
(TRCK, ("tracknumber",)),
(TBPM, ("bpm",)),
(TKEY, ("initialkey", "key")),
)
for frame_cls, aliases in field_map:
values = first_nonempty_metadata_values(source_tags, aliases)
add_text_frame_if_present(target_tags, frame_cls, values)
comment_values = first_nonempty_metadata_values(
source_tags,
("comment", "comments", "description"),
)
add_comm_frame_if_present(target_tags, comment_values)
def add_flac_pictures_as_apic_frames(target_tags: ID3, source_path: str) -> None:
"""Convert FLAC embedded pictures to ID3 APIC frames."""
try:
source = FLAC(source_path)
except Exception as exc:
logger.warning(
"Could not read FLAC pictures from %s: %s",
source_path,
exc,
exc_info=True,
)
return
for index, picture in enumerate(source.pictures):
data = getattr(picture, "data", b"") or b""
if not data:
continue
mime = str(getattr(picture, "mime", "") or "image/jpeg")
desc = str(getattr(picture, "desc", "") or "")
pic_type = getattr(picture, "type", 3)
try:
pic_type = int(pic_type)
except Exception:
pic_type = 3
try:
target_tags.add(
APIC(
encoding=3,
mime=mime,
type=pic_type,
desc=desc or f"Cover {index + 1}",
data=data,
)
)
except Exception as exc:
logger.warning(
"Could not add APIC frame %s from %s: %s",
index + 1,
source_path,
exc,
exc_info=True,
)
continue