-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.py
More file actions
2561 lines (2165 loc) · 87.9 KB
/
Copy pathanalysis.py
File metadata and controls
2561 lines (2165 loc) · 87.9 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 analysis and shared helpers.
This module contains configuration, path helpers, file discovery, ffprobe
helpers, loudness analysis, and summary reporting.
"""
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
import json
import logging
import math
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Literal, TypeAlias, TypedDict
try:
import numpy as np
import pyloudnorm as pyln
from scipy.signal import resample_poly
except ImportError as exc:
raise RuntimeError(
"Required Python packages were not found.\n\n"
"Install numpy, scipy, and pyloudnorm, then try again."
) from exc
# =============================================================================
# CONFIGURATION CONSTANTS
# =============================================================================
APP_TITLE = "DropGain"
APP_VERSION = "0.1.1"
APP_WINDOW_TITLE = f"{APP_TITLE} v{APP_VERSION}"
METER_SAMPLE_RATE = 48_000 # ITU-R BS.1770-4 specifies 48 kHz for loudness measurement.
DEFAULT_OUTPUT_CSV_NAME = "dropgain_report.csv"
ENABLE_BENCHMARK_TIMING_LOGS = str(os.environ.get("DROPGAIN_BENCHMARK_TIMING", "")).strip().lower() in {
"1",
"true",
"yes",
"on",
}
@contextmanager
def benchmark_timer(label: str, logger: logging.Logger | None = None):
"""Log elapsed time for a phase when benchmark timing is enabled."""
if not ENABLE_BENCHMARK_TIMING_LOGS:
yield
return
started_at = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - started_at
(logger or logging.getLogger("dropgain")).info("Timing %-28s %.3fs", label, elapsed)
PROCESSED_SUFFIX = "_DG"
OUTPUT_FORMAT_PRESERVE = "Preserve source format"
OUTPUT_FORMAT_MP3_TO_AIFF = "MP3 sources to AIFF"
OUTPUT_FORMAT_ALL_TO_AIFF = "All outputs as AIFF"
OUTPUT_FORMAT_ALL_TO_MP3 = "All outputs as MP3"
OUTPUT_FORMAT_MODE_CHOICES = (
OUTPUT_FORMAT_PRESERVE,
OUTPUT_FORMAT_MP3_TO_AIFF,
OUTPUT_FORMAT_ALL_TO_AIFF,
OUTPUT_FORMAT_ALL_TO_MP3,
)
DEFAULT_OUTPUT_FORMAT_MODE = OUTPUT_FORMAT_ALL_TO_AIFF
SUPPORTED_EXTENSIONS = {".flac", ".mp3", ".wav", ".aiff"}
SKIP_ALREADY_PROCESSED_FILES_IN_SCAN = True
PROCESS_OVERWRITE_EXISTING = False
# Treat tiny outputs as corrupt/truncated ffmpeg writes.
MIN_OUTPUT_FILE_BYTES = 10_000
LOSSLESS_MIN_ABS_GAIN_DB = 0.10
MP3_MIN_ABS_GAIN_DB = 0.10
EFFECTIVE_ZERO_GAIN_DB = 0.01
DEFAULT_APPLY_RENDER_GAIN_THRESHOLD = False
CPU_COUNT = max(1, os.cpu_count() or 1)
DEFAULT_RENDER_WORKER_THREADS = CPU_COUNT
MIN_RENDER_WORKER_THREADS = 1
MAX_RENDER_WORKER_THREADS = CPU_COUNT
DEFAULT_ANALYSIS_WORKER_THREADS = min(2, CPU_COUNT)
MIN_ANALYSIS_WORKER_THREADS = 1
MAX_ANALYSIS_WORKER_THREADS = CPU_COUNT
MAX_TRUE_PEAK_SUBPROCESSES = min(4, max(2, os.cpu_count() or 2))
TRUE_PEAK_OVERSAMPLE_FACTOR = 4
TRUE_PEAK_WINDOW_PADDING_SECONDS = 0.05
DEFAULT_LOUD_SECTION_WINDOW_SECONDS = 20.0
DEFAULT_LOUD_SECTION_HOP_SECONDS = 5.0
MIN_LOUD_SECTION_WINDOW_SECONDS = 10.0
MAX_LOUD_SECTION_WINDOW_SECONDS = 120.0
MIN_LOUD_SECTION_HOP_SECONDS = 5.0
MAX_LOUD_SECTION_HOP_SECONDS = 60.0
DEFAULT_TARGET_LOW_LUFS = -7.8
DEFAULT_TARGET_HIGH_LUFS = -7.5
DEFAULT_MAX_REDUCTION_DB = 3.0
DEFAULT_BASS_MAX_BOOST_REDUCTION_DB = 0.80
MIN_BASS_MAX_BOOST_REDUCTION_DB = 0.0
MAX_BASS_MAX_BOOST_REDUCTION_DB = 3.0
NORMALIZATION_MODE_LIMITER_ASSISTED = "Limiter-assisted"
NORMALIZATION_MODE_CLEAN_GAIN = "Clean gain"
NORMALIZATION_MODE_CHOICES = (
NORMALIZATION_MODE_LIMITER_ASSISTED,
NORMALIZATION_MODE_CLEAN_GAIN,
)
DEFAULT_NORMALIZATION_MODE = NORMALIZATION_MODE_LIMITER_ASSISTED
PEAK_CONTROL_SEVERITY_NONE = "none"
PEAK_CONTROL_SEVERITY_LIGHT = "light"
PEAK_CONTROL_SEVERITY_MODERATE = "moderate"
PEAK_CONTROL_SEVERITY_HEAVY = "heavy"
# True-peak ceiling for analysis, reporting, and Pro-L output level (-1.0 dBTP).
DEFAULT_BOOST_PEAK_CEILING_DBFS = -1.0
PROCESSING_ENGINE_PROL2 = "FabFilter Pro-L 2 Gain"
PROCESSING_ENGINE_LOUDMAX = "LoudMax Gain"
PROCESSING_ENGINE_CLEAN_GAIN = "Clean gain (no limiter)"
DEFAULT_PROCESSING_ENGINE = PROCESSING_ENGINE_PROL2
LIMITER_PROCESSING_ENGINES = {
PROCESSING_ENGINE_PROL2,
PROCESSING_ENGINE_LOUDMAX,
}
LIMITER_ENGINE_PROL2 = "FabFilter Pro-L 2"
LIMITER_ENGINE_LOUDMAX = "LoudMax"
LIMITER_ENGINE_CHOICES = (
LIMITER_ENGINE_PROL2,
LIMITER_ENGINE_LOUDMAX,
)
DEFAULT_LIMITER_ENGINE = LIMITER_ENGINE_PROL2
PROL2_DEFAULT_OUTPUT_LEVEL_DBFS = -1.0
PROL2_DEFAULT_TRUE_PEAK = True
PROL2_DEFAULT_OVERSAMPLING = "4x"
PROL2_STYLE_MODERN = "Modern"
PROL2_STYLE_TRANSPARENT = "Transparent"
PROL2_STYLE_SAFE = "Safe"
PROL2_STYLE_CHOICES = (
PROL2_STYLE_MODERN,
PROL2_STYLE_TRANSPARENT,
PROL2_STYLE_SAFE,
)
# Transparent stays closest to the source instead of coloring hot EDM masters further.
PROL2_DEFAULT_STYLE = PROL2_STYLE_TRANSPARENT
PROL2_DEFAULT_PLUGIN_PATH = ""
PROL2_PROCESS_BUFFER_SIZE = 8192
LOUDMAX_DEFAULT_PLUGIN_PATH = ""
LOUDMAX_PROCESS_BUFFER_SIZE = 8192
# Empirical offset vs Pro-L 2 on limiter-assisted renders; LoudMax's simpler
# brickwall path tends to land slightly quieter at the same nominal settings.
LOUDMAX_LIMITER_CALIBRATION_DB = 0.10
MP3_OUTPUT_BITRATE = "320k"
MP3_ID3_VERSION = 3
# Extra true-peak headroom budget for forced MP3 encodes; skipped for preserve-format MP3.
MP3_ENCODE_TRUE_PEAK_LIFT_DB = 0.80
WAV_CODECS_TO_KEEP = {
"pcm_u8",
"pcm_s8",
"pcm_s16le",
"pcm_s24le",
"pcm_s32le",
"pcm_f32le",
"pcm_f64le",
}
AIFF_CODECS_TO_KEEP = {
"pcm_s16be",
"pcm_s24be",
"pcm_s32be",
}
STRICT_VERIFY_LOSSLESS_OUTPUT = True
POST_VERIFY_PROCESSED_AUDIO = True
POST_VERIFY_LUFS_TOLERANCE = 0.40
POST_VERIFY_PEAK_TOLERANCE_DB = 0.20
BASS_ANALYSIS_LOW_HZ = 45.0
BASS_ANALYSIS_HIGH_HZ = 115.0
BASS_REFERENCE_LOW_HZ = 115.0
BASS_REFERENCE_HIGH_HZ = 1000.0
DEFAULT_BASS_PENALTY_START_DB = 5.0
DEFAULT_BASS_PENALTY_FULL_DB = 17.0
BASS_ANALYSIS_FFT_SIZE = 16_384
SUB_ANALYSIS_LOW_HZ = 20.0
SUB_ANALYSIS_HIGH_HZ = 45.0
DEFAULT_SUB_PENALTY_START_DB = 8.0
DEFAULT_SUB_PENALTY_FULL_DB = 17.0
MIN_BASS_PENALTY_THRESHOLD_DB = 0.0
MAX_BASS_PENALTY_THRESHOLD_DB = 30.0
TrackRowValue: TypeAlias = str | int | float
TrackRowNumber: TypeAlias = float | str
TrackRowInt: TypeAlias = int | str
TrackRowKey: TypeAlias = Literal[
"path",
"output_path",
"filename",
"source_folder_name",
"extension",
"output_format_mode",
"duration_sec",
"original_sample_rate",
"output_sample_rate",
"channels",
"output_channels",
"audio_codec",
"output_audio_codec",
"audio_sample_fmt",
"output_audio_sample_fmt",
"original_bit_depth",
"output_bit_depth",
"original_bit_rate",
"output_bit_rate",
"file_size_mb",
"output_file_size_mb",
"integrated_lufs",
"loudest_section_lufs",
"loudest_section_start_sec",
"loudest_section_end_sec",
"sample_peak_dbfs",
"true_peak_dbtp",
"section_true_peak_dbtp",
"peak_headroom_to_0_db",
"true_peak_headroom_db",
"target_low_lufs",
"target_high_lufs",
"normalization_mode",
"bass_strength_db",
"sub_strength_db",
"bass_adjustment_db",
"limiter_budget_db",
"limiter_budget_adjustment_db",
"raw_gain_db",
"suggested_gain_db",
"projected_loudest_section_lufs",
"projected_sample_peak_dbfs",
"projected_true_peak_dbtp",
"estimated_peak_control_db",
"peak_control_severity",
"processing_engine",
"output_integrated_lufs",
"output_same_section_lufs",
"output_sample_peak_dbfs",
"output_true_peak_dbtp",
"actual_same_section_gain_db",
"actual_peak_gain_db",
"actual_true_peak_gain_db",
"audio_verification",
"metadata_verification",
"action",
"processing_status",
"processing_error",
"warnings",
"decision_notes",
"true_peak_unreliable",
"manual_check_required",
]
class TrackRow(TypedDict):
"""TypedDict representing all fields for one audio file in the CSV report."""
path: str
output_path: str
filename: str
source_folder_name: str
extension: str
output_format_mode: str
duration_sec: TrackRowNumber
original_sample_rate: int
output_sample_rate: TrackRowInt
channels: int
output_channels: TrackRowInt
audio_codec: str
output_audio_codec: str
audio_sample_fmt: str
output_audio_sample_fmt: str
original_bit_depth: TrackRowInt
output_bit_depth: TrackRowInt
original_bit_rate: str
output_bit_rate: str
file_size_mb: TrackRowNumber
output_file_size_mb: TrackRowNumber
integrated_lufs: TrackRowNumber
loudest_section_lufs: TrackRowNumber
loudest_section_start_sec: TrackRowNumber
loudest_section_end_sec: TrackRowNumber
sample_peak_dbfs: TrackRowNumber
true_peak_dbtp: TrackRowNumber
section_true_peak_dbtp: TrackRowNumber
peak_headroom_to_0_db: TrackRowNumber
true_peak_headroom_db: TrackRowNumber
target_low_lufs: float
target_high_lufs: float
normalization_mode: str
bass_strength_db: TrackRowNumber
sub_strength_db: TrackRowNumber
bass_adjustment_db: TrackRowNumber
limiter_budget_db: TrackRowNumber
limiter_budget_adjustment_db: TrackRowNumber
raw_gain_db: TrackRowNumber
suggested_gain_db: TrackRowNumber
projected_loudest_section_lufs: TrackRowNumber
projected_sample_peak_dbfs: TrackRowNumber
projected_true_peak_dbtp: TrackRowNumber
estimated_peak_control_db: TrackRowNumber
peak_control_severity: str
processing_engine: str
output_integrated_lufs: TrackRowNumber
output_same_section_lufs: TrackRowNumber
output_sample_peak_dbfs: TrackRowNumber
output_true_peak_dbtp: TrackRowNumber
actual_same_section_gain_db: TrackRowNumber
actual_peak_gain_db: TrackRowNumber
actual_true_peak_gain_db: TrackRowNumber
audio_verification: str
metadata_verification: str
action: str
processing_status: str
processing_error: str
warnings: str
decision_notes: str
true_peak_unreliable: str
manual_check_required: str
CSV_FIELDNAMES: tuple[TrackRowKey, ...] = (
"path",
"output_path",
"filename",
"source_folder_name",
"extension",
"output_format_mode",
"duration_sec",
"original_sample_rate",
"output_sample_rate",
"channels",
"output_channels",
"audio_codec",
"output_audio_codec",
"audio_sample_fmt",
"output_audio_sample_fmt",
"original_bit_depth",
"output_bit_depth",
"original_bit_rate",
"output_bit_rate",
"file_size_mb",
"output_file_size_mb",
"integrated_lufs",
"loudest_section_lufs",
"loudest_section_start_sec",
"loudest_section_end_sec",
"sample_peak_dbfs",
"true_peak_dbtp",
"section_true_peak_dbtp",
"peak_headroom_to_0_db",
"true_peak_headroom_db",
"target_low_lufs",
"target_high_lufs",
"normalization_mode",
"bass_strength_db",
"sub_strength_db",
"bass_adjustment_db",
"limiter_budget_db",
"limiter_budget_adjustment_db",
"raw_gain_db",
"suggested_gain_db",
"projected_loudest_section_lufs",
"projected_sample_peak_dbfs",
"projected_true_peak_dbtp",
"estimated_peak_control_db",
"peak_control_severity",
"processing_engine",
"output_integrated_lufs",
"output_same_section_lufs",
"output_sample_peak_dbfs",
"output_true_peak_dbtp",
"actual_same_section_gain_db",
"actual_peak_gain_db",
"actual_true_peak_gain_db",
"audio_verification",
"metadata_verification",
"action",
"processing_status",
"processing_error",
"warnings",
"decision_notes",
"true_peak_unreliable",
"manual_check_required",
)
def row_to_csv_dict(row: TrackRow) -> dict[TrackRowKey, TrackRowValue]:
return {field: row[field] for field in CSV_FIELDNAMES}
# =============================================================================
# PATHS / GENERAL HELPERS
# =============================================================================
def script_folder() -> Path:
"""Return the folder containing the script or the frozen executable."""
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
def bundled_bin_dir() -> Path:
"""Return the app-local bin folder (ffmpeg/ffprobe for packaged builds)."""
return script_folder() / "bin"
def ensure_bundled_bin_on_path() -> None:
"""Prepend script_folder()/bin to PATH so bundled ffmpeg/ffprobe resolve."""
bin_dir = bundled_bin_dir()
if not bin_dir.is_dir():
return
bin_str = str(bin_dir.resolve())
current = os.environ.get("PATH", "")
parts = [p for p in current.split(os.pathsep) if p]
if parts and parts[0] == bin_str:
return
parts = [p for p in parts if p != bin_str]
os.environ["PATH"] = os.pathsep.join([bin_str, *parts])
def default_csv_path(folder: str | None = None) -> str:
"""Return the default path for the CSV report next to the executable/script.
When a source folder is provided, the folder name is appended to the report
filename so reports from different libraries are easy to distinguish.
"""
path = script_folder() / DEFAULT_OUTPUT_CSV_NAME
if folder:
folder_name = os.path.basename(os.path.normpath(folder))
if folder_name:
path = path.with_name(f"{path.stem}_{folder_name}{path.suffix}")
return str(path)
def normalize_output_format_mode(value: object) -> str:
"""Return a valid output-format mode string, falling back to the default mode."""
text = str(value or "").strip()
if text in OUTPUT_FORMAT_MODE_CHOICES:
return text
return DEFAULT_OUTPUT_FORMAT_MODE
def output_extension_for_source(source_ext: str, output_format_mode: object = DEFAULT_OUTPUT_FORMAT_MODE) -> str:
"""Return the output suffix for a source suffix under the selected output mode."""
ext = str(source_ext or "").lower()
mode = normalize_output_format_mode(output_format_mode)
if mode == OUTPUT_FORMAT_ALL_TO_MP3:
return ".mp3"
if mode == OUTPUT_FORMAT_ALL_TO_AIFF:
return ".aiff"
if mode == OUTPUT_FORMAT_MP3_TO_AIFF and ext == ".mp3":
return ".aiff"
return ext
def output_format_mode_description(output_format_mode: object) -> str:
"""Return a concise log-friendly description of an output format mode."""
mode = normalize_output_format_mode(output_format_mode)
if mode == OUTPUT_FORMAT_MP3_TO_AIFF:
return "MP3 sources render as AIFF; lossless sources preserve their format"
if mode == OUTPUT_FORMAT_ALL_TO_AIFF:
return "all outputs render as CDJ/XDJ-compatible AIFF (44.1/48 kHz, 16/24-bit PCM)"
if mode == OUTPUT_FORMAT_ALL_TO_MP3:
return f"all outputs render as {MP3_OUTPUT_BITRATE} MP3"
return "preserve source format"
def output_format_mode_tooltip() -> str:
"""Return hover tooltip text for the output format setting."""
return (
"Recommended mode avoids encoding MP3 twice. "
"Preserve source format and All outputs as MP3 can push or approximate true peak above your ceiling; "
"AIFF output stays closer to the limiter result."
)
def output_format_mode_ui_hint(output_format_mode: object) -> tuple[str, bool]:
"""Return a short under-control note and whether it should use warning styling."""
mode = normalize_output_format_mode(output_format_mode)
if mode == OUTPUT_FORMAT_PRESERVE:
return (
"MP3 sources stay MP3: re-encoding can push true peak above your ceiling. "
"Use MP3 sources to AIFF for safer true peak.",
True,
)
if mode == OUTPUT_FORMAT_ALL_TO_MP3:
return (
f"Lossless sources become {MP3_OUTPUT_BITRATE} MP3 (destructive). "
"True peak on MP3 outputs is approximate.",
True,
)
if mode == OUTPUT_FORMAT_ALL_TO_AIFF:
return (
"Every rendered file becomes CDJ/XDJ-compatible AIFF (44.1/48 kHz, 16/24-bit PCM) "
"for rekordbox import.",
False,
)
return "", False
def processed_output_path(
input_path: str,
output_root: str | None = None,
source_root: str | None = None,
output_format_mode: object = DEFAULT_OUTPUT_FORMAT_MODE,
) -> str:
"""Build the output path by adding PROCESSED_SUFFIX, preserving subfolders.
When the selected output mode changes the file extension, the source
extension is added to the filename to avoid collisions such as Track.flac
and Track.wav both rendering to Track_flac_DG.aiff and Track_wav_DG.aiff.
"""
p = Path(input_path)
mode = normalize_output_format_mode(output_format_mode)
suffix = output_extension_for_source(p.suffix, mode)
source_ext = p.suffix.lower()
source_ext_marker = f"_{source_ext.lstrip('.')}" if suffix.lower() != source_ext else ""
output_name = f"{p.stem}{source_ext_marker}{PROCESSED_SUFFIX}{suffix}"
if output_root:
root = Path(output_root)
if source_root:
try:
relative_parent = p.resolve().parent.relative_to(Path(source_root).resolve())
except ValueError:
relative_parent = Path()
return str(root / relative_parent / output_name)
return str(root / output_name)
return str(p.with_name(output_name))
def hidden_subprocess_kwargs() -> dict[str, int]:
"""Return subprocess kwargs that hide the console window on Windows."""
if os.name == "nt" and hasattr(subprocess, "CREATE_NO_WINDOW"):
return {"creationflags": subprocess.CREATE_NO_WINDOW}
return {}
def check_ffmpeg_available() -> None:
"""Raise RuntimeError if ffmpeg or ffprobe is not found in PATH."""
ensure_bundled_bin_on_path()
bin_hint = bundled_bin_dir()
for tool in ("ffmpeg", "ffprobe"):
try:
subprocess.run(
[tool, "-version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
**hidden_subprocess_kwargs(),
)
except Exception as exc:
raise RuntimeError(
f"{tool} was not found. Install FFmpeg on PATH, or place "
f"{tool}.exe in:\n{bin_hint}"
) from exc
def normalized_path(path: str) -> str:
"""Return a case-normalized absolute path for deterministic sorting."""
return os.path.normcase(os.path.abspath(path))
def make_error_track_row(
path: str,
error_message: str,
*,
source_root: str | None = None,
source_folder_name: str = "",
output_format_mode: object = DEFAULT_OUTPUT_FORMAT_MODE,
) -> TrackRow:
"""Build a minimal TrackRow for a file that failed before analysis completed."""
row = {field: "" for field in CSV_FIELDNAMES}
source_path = Path(path)
ext = source_path.suffix.lower()
row.update(
{
"path": path,
"output_path": processed_output_path(
path,
source_root=source_root,
output_format_mode=output_format_mode,
),
"filename": source_path.name,
"source_folder_name": source_folder_name,
"extension": ext,
"output_format_mode": normalize_output_format_mode(output_format_mode),
"processing_status": "error",
"processing_error": error_message,
"audio_verification": "not_applicable",
"metadata_verification": "not_applicable",
}
)
return row # type: ignore[return-value]
def sort_track_rows_by_path(rows: list[TrackRow]) -> list[TrackRow]:
"""Return rows sorted by normalized source path for stable library order."""
return sorted(rows, key=lambda row: normalized_path(str(row.get("path", ""))))
def dbfs(value: float) -> float:
"""Convert a linear amplitude to dBFS. Non-positive values return -999.0."""
if value <= 0.0 or not math.isfinite(value):
return -999.0
return 20.0 * math.log10(value)
_TRUE_PEAK_SUBPROCESS_SEMAPHORE = threading.BoundedSemaphore(MAX_TRUE_PEAK_SUBPROCESSES)
def decode_audio_ffmpeg_for_true_peak(
path: str,
channels: int,
start_sec: float | None = None,
end_sec: float | None = None,
) -> np.ndarray:
"""Decode native-rate float PCM for oversampled true-peak measurement."""
cmd = [
"ffmpeg",
"-hide_banner",
"-nostdin",
"-v",
"error",
]
if start_sec is not None:
cmd.extend(["-ss", f"{max(0.0, float(start_sec)):.6f}"])
if start_sec is not None and end_sec is not None:
duration = max(0.001, float(end_sec) - float(start_sec))
cmd.extend(["-t", f"{duration:.6f}"])
cmd.extend([
"-i",
path,
"-map",
"0:a:0",
"-vn",
"-f",
"f32le",
"-acodec",
"pcm_f32le",
"pipe:1",
])
with _TRUE_PEAK_SUBPROCESS_SEMAPHORE:
result = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**hidden_subprocess_kwargs(),
)
if result.returncode != 0:
err = result.stderr.decode("utf-8", errors="replace").strip()
if not err:
err = "ffmpeg true-peak decode failed"
raise RuntimeError(err)
audio = np.frombuffer(result.stdout, dtype=np.float32)
if audio.size == 0:
raise RuntimeError("decoded true-peak audio is empty")
remainder = audio.size % channels
if remainder:
audio = audio[: audio.size - remainder]
if audio.size == 0:
raise RuntimeError("decoded true-peak audio has invalid channel layout")
return audio.reshape(-1, channels)
def _section_sample_bounds(
start_sec: float,
end_sec: float,
sample_rate: int,
) -> tuple[int, int]:
"""Return native-rate [start, end) sample indices for an analyzed section."""
start = max(0.0, float(start_sec))
end = max(start + 0.001, float(end_sec))
padding = TRUE_PEAK_WINDOW_PADDING_SECONDS
padded_start = max(0.0, start - padding)
trim_start_samples = max(0, int(round((start - padded_start) * sample_rate)))
window_samples = max(1, int(round((end - start) * sample_rate)))
decode_base = int(round(padded_start * sample_rate))
section_start = decode_base + trim_start_samples
section_end = section_start + window_samples
return section_start, section_end
def _oversample_audio_for_true_peak(
audio: np.ndarray,
oversample_factor: int = TRUE_PEAK_OVERSAMPLE_FACTOR,
) -> tuple[np.ndarray, int]:
"""Oversample decoded native-rate audio for true-peak measurement."""
oversample = max(1, int(oversample_factor))
if oversample > 1:
return resample_poly(audio, oversample, 1, axis=0), oversample
return audio, oversample
def _true_peak_db_from_audio(measured: np.ndarray) -> float:
"""Return the true peak in dBTP from an oversampled audio array."""
if measured.size == 0:
raise RuntimeError("trimmed true-peak audio is empty")
peak = float(np.max(np.abs(measured), initial=0.0))
true_peak = dbfs(peak)
if not math.isfinite(true_peak):
raise RuntimeError("true peak measurement was not finite")
return true_peak
def _resolve_true_peak_channels_and_rate(
path: str,
channels: int | None,
sample_rate: int | None,
) -> tuple[int, int]:
if channels is None or sample_rate is None:
info = ffprobe_audio_info(path)
if channels is None:
channels = int(info["channels"])
if sample_rate is None:
sample_rate = int(info["sample_rate"])
channels = int(channels)
sample_rate = int(sample_rate)
if channels <= 0 or sample_rate <= 0:
raise RuntimeError("invalid channel count or sample rate for true-peak measurement")
return channels, sample_rate
def measure_true_peak_oversampled(
path: str,
start_sec: float | None = None,
end_sec: float | None = None,
*,
channels: int | None = None,
sample_rate: int | None = None,
oversample_factor: int = TRUE_PEAK_OVERSAMPLE_FACTOR,
) -> float:
"""Measure true peak in dBTP with native-rate polyphase oversampling."""
channels, sample_rate = _resolve_true_peak_channels_and_rate(path, channels, sample_rate)
decode_start = start_sec
decode_end = end_sec
trim_start_samples = 0
trim_end_samples: int | None = None
if start_sec is not None and end_sec is not None:
section_start, section_end = _section_sample_bounds(start_sec, end_sec, sample_rate)
start = max(0.0, float(start_sec))
end = max(start + 0.001, float(end_sec))
padding = TRUE_PEAK_WINDOW_PADDING_SECONDS
padded_start = max(0.0, start - padding)
padded_end = end + padding
decode_start = padded_start
decode_end = padded_end
decode_base = int(round(padded_start * sample_rate))
trim_start_samples = section_start - decode_base
trim_end_samples = section_end - decode_base
audio = decode_audio_ffmpeg_for_true_peak(
path,
channels,
start_sec=decode_start,
end_sec=decode_end,
)
measured, oversample = _oversample_audio_for_true_peak(audio, oversample_factor)
trim_start = trim_start_samples * oversample
trim_end = None if trim_end_samples is None else trim_end_samples * oversample
if trim_start or trim_end is not None:
measured = measured[trim_start:trim_end]
return _true_peak_db_from_audio(measured)
def measure_section_and_whole_true_peak_oversampled(
path: str,
start_sec: float,
end_sec: float,
*,
channels: int | None = None,
sample_rate: int | None = None,
section_failure_label: str = "section true peak measurement failed",
whole_failure_label: str = "whole-track true peak measurement failed",
) -> tuple[float | None, float | None, str]:
"""Measure section and whole-track true peaks from one decode and oversample pass."""
section_true_peak: float | None = None
whole_true_peak: float | None = None
notes = ""
try:
channels, sample_rate = _resolve_true_peak_channels_and_rate(path, channels, sample_rate)
audio = decode_audio_ffmpeg_for_true_peak(path, channels)
oversampled, oversample_factor = _oversample_audio_for_true_peak(audio)
except Exception as exc:
notes = append_note(notes, f"{whole_failure_label}: {exc}")
notes = append_note(notes, f"{section_failure_label}: {exc}")
return section_true_peak, whole_true_peak, notes
try:
whole_true_peak = _true_peak_db_from_audio(oversampled)
except Exception as exc:
notes = append_note(notes, f"{whole_failure_label}: {exc}")
try:
section_start, section_end = _section_sample_bounds(start_sec, end_sec, sample_rate)
section_start *= oversample_factor
section_end *= oversample_factor
section_end = min(section_end, oversampled.shape[0])
section_audio = oversampled[section_start:section_end]
section_true_peak = _true_peak_db_from_audio(section_audio)
except Exception as exc:
notes = append_note(notes, f"{section_failure_label}: {exc}")
return section_true_peak, whole_true_peak, notes
def round_or_blank(value: float | None, digits: int = 2) -> float | str:
"""Round a number for CSV output. Return blank string for None or non-finite."""
if value is None:
return ""
if not math.isfinite(float(value)):
return ""
return round(float(value), digits)
def parse_optional_float(value: object) -> float | None:
"""Safely parse a value to float, returning None on failure or non-finite."""
try:
f = float(value)
except Exception:
return None
if not math.isfinite(f):
return None
return f
def parse_float_or_default(value: object, default: float = 0.0) -> float:
"""Parse a value to float, falling back to default on failure."""
parsed = parse_optional_float(value)
if parsed is None:
return default
return parsed
def parse_int_or_default(value: object, default: int = 0) -> int:
"""Parse a value to int via float(), falling back to default on failure."""
try:
if value is None:
return default
text = str(value).strip()
if text == "":
return default
return int(float(text))
except Exception:
return default
def append_note(existing: object, note: str) -> str:
"""Append a semicolon-separated note to an existing string."""
old = str(existing or "").strip()
if not old:
return note
return old + "; " + note
def mp3_encode_peak_allowance_db(output_ext: str) -> float:
"""Return extra true-peak headroom to budget for any final MP3 encode."""
if str(output_ext or "").lower() == ".mp3":
return MP3_ENCODE_TRUE_PEAK_LIFT_DB
return 0.0
def normalize_normalization_mode(value: object) -> str:
"""Return a valid normalization mode string, falling back to the default."""
text = str(value or "").strip()
if text in NORMALIZATION_MODE_CHOICES:
return text
return DEFAULT_NORMALIZATION_MODE
def normalize_limiter_engine(value: object) -> str:
"""Return a valid limiter engine string, falling back to the default."""
text = str(value or "").strip()
if text in LIMITER_ENGINE_CHOICES:
return text
return DEFAULT_LIMITER_ENGINE
def processing_engine_for_limiter(limiter_engine: object) -> str:
"""Return the processing-engine label a limiter-assisted row should record."""
if normalize_limiter_engine(limiter_engine) == LIMITER_ENGINE_LOUDMAX:
return PROCESSING_ENGINE_LOUDMAX
return PROCESSING_ENGINE_PROL2
def is_limiter_processing_engine(value: object) -> bool:
"""Return True when a row's processing_engine used a limiter (any engine)."""
return str(value or "") in LIMITER_PROCESSING_ENGINES
def peak_control_severity_label(estimated_peak_control_db: float) -> str:
"""Classify estimated peak limiting into none/light/moderate/heavy."""
estimated = max(0.0, float(estimated_peak_control_db))
if estimated <= 0.01:
return PEAK_CONTROL_SEVERITY_NONE
if estimated <= 1.0:
return PEAK_CONTROL_SEVERITY_LIGHT
if estimated <= 3.0:
return PEAK_CONTROL_SEVERITY_MODERATE
return PEAK_CONTROL_SEVERITY_HEAVY
def peak_control_reduction_percent(peak_control_db: float) -> int | None:
"""Return peak amplitude reduction as a linear percent from the limit depth in dB."""
peak = max(0.0, float(peak_control_db))
if peak <= 0.01:
return None
return min(100, round((1.0 - 10.0 ** (-peak / 20.0)) * 100.0))
def format_peak_control_display(
estimated_peak_control_db: object,
processing_engine: object = None,
*,
include_percent: bool = True,
) -> str:
"""Format estimated limiter peak control as dB and optional linear peak-reduction percent."""
peak = parse_optional_float(estimated_peak_control_db)
if peak is None or peak <= 0.01:
return "-"
uses_limiter = is_limiter_processing_engine(processing_engine)
text = f"{peak:.2f} dB"
if not uses_limiter:
text = f"{text} (clean)"
elif include_percent:
pct = peak_control_reduction_percent(peak)
if pct is not None:
text = f"{text} ({pct}%)"
return text