-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmaster.py
More file actions
2163 lines (1829 loc) · 84.8 KB
/
Copy pathmaster.py
File metadata and controls
2163 lines (1829 loc) · 84.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
deshimmer6.py
Anti-shimmer + smart repair + optional delivery mastering:
Core (STFT domain):
- Target-band "birdie/shimmer" suppression via local-median residuals.
- Smart spectral denoise (noise-floor management) using a minimum-statistics-ish noise PSD tracker
and Wiener-like gain with time/frequency smoothing.
- Smart de-resonator (dynamic EQ / dynamic notch) that attenuates persistent narrow peaks across a band.
Optional post ("deliver"):
- Loudness normalization toward a target LUFS (ITU-R BS.1770 via pyloudnorm when available).
- True-peak-ish limiting via oversampling + lookahead peak limiter.
Debug mode:
- Writes a debug folder with .json summary, .npz internals, and .png visualizations
(attenuation maps + spectrogram before/after/diff).
Notes:
- This is designed to be subtractive and conservative. It "fixes" more than it "flavors".
- Still: auto-repair can be wrong on some material. Use --debug to see what it's doing.
"""
from __future__ import annotations
import argparse
import json
import math
import os
from dataclasses import asdict, dataclass
from typing import Optional, Tuple, Dict, Any, List
import numpy as np
import soundfile as sf
from scipy.ndimage import median_filter, minimum_filter1d, uniform_filter1d, maximum_filter1d
from scipy.signal import butter, sosfiltfilt, sosfilt, resample_poly, lfilter, lfilter_zi, stft, istft
# -----------------------------
# Utility conversions
# -----------------------------
def _db_to_lin(db: float | np.ndarray) -> float | np.ndarray:
return 10.0 ** (np.asarray(db) / 20.0)
def _lin_to_db(x: float | np.ndarray, eps: float = 1e-12) -> float | np.ndarray:
return 20.0 * np.log10(np.asarray(x) + eps)
def _as_2d(x: np.ndarray) -> np.ndarray:
return x[:, None] if x.ndim == 1 else x
def band_from_center(center_hz: float, width_cents: float) -> Tuple[float, float]:
half = width_cents * 0.5
ratio = 2.0 ** (half / 1200.0)
return center_hz / ratio, center_hz * ratio
def _edge_taper(freqs: np.ndarray, band_idx: np.ndarray, start_hz: float, end_hz: float, edge_hz: float) -> np.ndarray:
"""Cosine taper inside edge_hz of the band edges."""
w = np.ones(band_idx.size, dtype=np.float32)
edge = float(max(0.0, edge_hz))
if edge <= 0.0 or band_idx.size == 0:
return w
fb = freqs[band_idx].astype(np.float32)
lo, hi = float(start_hz), float(end_hz)
m = fb < lo + edge
if np.any(m):
rel = (fb[m] - lo) / edge
w[m] = 0.5 - 0.5 * np.cos(np.pi * np.clip(rel, 0, 1))
m2 = fb > hi - edge
if np.any(m2):
rel = (hi - fb[m2]) / edge
w[m2] = np.minimum(w[m2], 0.5 - 0.5 * np.cos(np.pi * np.clip(rel, 0, 1)))
return w
def _frame_coeff(hop: int, sr: int, ms: float) -> float:
"""Per-frame EMA coefficient for time constant ms."""
tau = max(1e-4, float(ms) / 1000.0)
return float(math.exp(-float(hop) / (float(sr) * tau)))
def _butter_sos(sr: int, kind: str, cutoff_hz, order: int = 2):
nyq = 0.5 * sr
if kind in ("lowpass", "highpass"):
wn = float(cutoff_hz) / nyq
wn = float(np.clip(wn, 1e-6, 0.999999))
return butter(int(order), wn, btype=kind, output="sos")
if kind == "bandpass":
lo, hi = cutoff_hz
lo = float(np.clip(lo / nyq, 1e-6, 0.999999))
hi = float(np.clip(hi / nyq, 1e-6, 0.999999))
if hi <= lo:
raise ValueError("Invalid bandpass cutoffs")
return butter(int(order), [lo, hi], btype="bandpass", output="sos")
raise ValueError("Unknown filter kind")
def _onepole_lp(x: np.ndarray, a: float) -> np.ndarray:
"""One-pole low-pass: y[n] = (1-a)*x[n] + a*y[n-1] (0<a<1)."""
x = np.asarray(x, dtype=np.float32)
if x.size == 0:
return x
a = float(np.clip(a, 0.0, 0.999999))
b = np.array([1.0 - a], dtype=np.float32)
A = np.array([1.0, -a], dtype=np.float32)
zi = lfilter_zi(b, A) * float(x[0])
y, _ = lfilter(b, A, x, zi=zi)
return y.astype(np.float32, copy=False)
# -----------------------------
# Parameters
# -----------------------------
@dataclass
class Params:
# --- Original shimmer band ---
start_hz: float = 5100.0
end_hz: float = 7200.0
edge_hz: float = 200.0
n_fft: int = 2048
hop: int = 512
# Noise-likeness gate via spectral flatness (geo/arith of power spectrum).
flat_start: float = 0.25
flat_end: float = 0.70
# Birdie suppression (within start_hz..end_hz)
freq_med_bins: int = 9
thr_db: float = 8.0
slope: float = 0.6
# If MANY bins exceed threshold, treat as real broadband event; do less
density_lo: float = 0.02
density_hi: float = 0.15
# Transient protect (based on band energy jump)
flux_thr_db: float = 6.0
flux_range_db: float = 8.0
# Optional random-phase blend (only in noise-like frames)
noise_resynth: float = 0.0 # 0..1
# Wet/dry
mix: float = 1.0
# Padding & fade
pad: bool = True
fade_ms: float = 5.0
seed: int = 0
# ----------------------------------------------------------------------
# Smart noise-floor management: spectral denoise (taste-neutral)
# ----------------------------------------------------------------------
denoise: float = 0.0 # 0..1 overall strength
dn_start_hz: float = 120.0
dn_end_hz: float = 16000.0
dn_edge_hz: float = 200.0
dn_floor_db: float = -18.0 # minimum gain floor (dB), avoids dead-silent artifacts
dn_psd_smooth_ms: float = 50.0 # smooth PSD before min-tracking
dn_minwin_ms: float = 400.0 # minimum-statistics window for tracking minima
dn_up_db_per_s: float = 3.0 # how fast noise estimate can rise (dB/s, power-domain approx)
dn_attack_ms: float = 5.0
dn_release_ms: float = 120.0
dn_freq_smooth_bins: int = 3 # smooth gain across frequency (reduce musical noise)
# ----------------------------------------------------------------------
# Smart dynamic EQ: de-resonator (taste-neutral, subtractive only)
# ----------------------------------------------------------------------
deres: float = 0.0 # 0..1 strength
deq_start_hz: float = 180.0
deq_end_hz: float = 12000.0
deq_edge_hz: float = 150.0
deq_freq_med_bins: int = 31 # median width across frequency for baseline
deq_thr_db: float = 6.0 # residual threshold above local median
deq_slope: float = 0.7 # how hard to push down peaks above threshold
deq_max_att_db: float = 8.0 # cap reduction (safety)
# If too many bins exceed threshold, assume it's legit broadband/tonal content -> back off
deq_density_lo: float = 0.03
deq_density_hi: float = 0.20
# persistence favors stationary resonances over moving harmonics
deq_persist_ms: float = 600.0
deq_persist_thr_db: float = 2.5
deq_freq_smooth_bins: int = 5
deq_tonal_boost_db: float = 6.0 # raises threshold when frame is tonal (based on flatness)
# ----------------------------------------------------------------------
# Optional: time-stabilized baseline for stationary ringing ("whine" lines)
# ----------------------------------------------------------------------
deq_time_floor: bool = False
deq_floor_smooth_ms: float = 80.0 # smooth PSD before floor tracking (ms)
deq_floor_rise_db_per_s: float = 1.0 # how fast the floor can rise (dB/s, power-domain approx)
deq_floor_thr_db: float = 3.0 # threshold for "high stationary floor" vs local floor baseline
# Listen to removed only (useful for dialing in)
delta_listen: bool = False
# ----------------------------------------------------------------------
# Optional: downward expander in an artifact band (targets grit in tails)
# ----------------------------------------------------------------------
expander: bool = False
exp_start_hz: float = 3000.0
exp_end_hz: float = 8000.0
exp_threshold_db: float = -45.0 # band level in dB (power)
exp_ratio: float = 2.0 # 2:1 downward expander
exp_attack_ms: float = 10.0
exp_release_ms: float = 150.0
# ----------------------------------------------------------------------
# Optional: HPSS-ish harmonic mask inside a band (protect percussive transients)
# ----------------------------------------------------------------------
hpss: bool = False
hpss_start_hz: float = 3000.0
hpss_end_hz: float = 8000.0
hpss_time_frames: int = 21 # median over time (odd recommended)
hpss_freq_bins: int = 17 # median over freq (odd recommended)
hpss_harmonic_only: bool = True # apply processing only to harmonic (horizontal) component
hpss_protect_percussive: float = 0.0 # 0..1 reduce repair depth on percussive bins
# ----------------------------------------------------------------------
# Repair philosophy: magnitude inpainting vs pure attenuation
# ----------------------------------------------------------------------
magnitude_inpaint: bool = True # cap spikes to local median instead of only cutting gain
deq_inpaint: bool = True # de-resonator uses inpaint when magnitude_inpaint is on
# Combined-stage safety cap (per bin, product of stage gains)
total_att_cap_db: float = 12.0
nuclear_mode: bool = False # disables combined attenuation cap
# Mid/Side: run detectors on mono; apply scaled repair on Side channel
ms_process: bool = False
ms_side_scale: float = 0.35
# ----------------------------------------------------------------------
# Optional: phase blur (random-phase blend) in a selected band (texture masking)
# ----------------------------------------------------------------------
phase_blur: float = 0.0
pb_start_hz: float = 3000.0
pb_end_hz: float = 8000.0
pb_harmonic_only: bool = True
# ----------------------------------------------------------------------
# Swish repair: adaptive inter-frame / inter-bin phase coherence smoothing
# Targets moving "swish" from neural decoders (phase incoherence, not birdies).
# ----------------------------------------------------------------------
swish_repair: float = 0.0
swish_start_hz: float = 3500.0
swish_end_hz: float = 14000.0
swish_time_amt: float = 0.55 # inter-frame phase smoothing blend
swish_freq_amt: float = 0.30 # inter-bin phase smoothing blend
swish_time_win: int = 7 # STFT frames (odd)
swish_freq_win: int = 5 # frequency bins (odd)
swish_transient_protect: float = 0.85
swish_harmonic_protect: float = 0.45
# HF stereo decorrelation (break synthetic L/R phase lock in upper band)
hf_decorrelate: float = 0.0
hf_dec_start_hz: float = 4500.0
hf_dec_end_hz: float = 16000.0
# ----------------------------------------------------------------------
# Optional: "Nuclear" HF resynthesis (remove HF and re-create from low band)
# ----------------------------------------------------------------------
hf_resynth: bool = False
hf_lp_hz: float = 3000.0 # low-pass cutoff for "clean" base
hf_src_lo_hz: float = 1000.0 # source band to excite
hf_src_hi_hz: float = 2000.0
hf_drive: float = 2.0 # tanh drive
hf_hp_hz: float = 3000.0 # high-pass for generated harmonics
hf_mix: float = 0.35 # mix generated HF back in
hf_tilt_lp_hz: float = 12000.0 # soften buzz: low-pass on generated HF
hf_zero_phase: bool = True # offline nicety; set False for realtime-ish chunk processing
hf_confidence_blend: bool = True # blend resynth only where artifact confidence is high
# Last STFT-frame artifact confidence (F_band, T) for HF resynth blending
_LAST_ARTIFACT_CONF_FRAMES: Optional[np.ndarray] = None
@dataclass
class MasterParams:
enabled: bool = False
dc_remove: bool = True
hp_hz: float = 20.0
hp_order: int = 2
# Loudness normalization
target_lufs: Optional[float] = -14.0 # None disables
target_rms_dbfs: Optional[float] = -16.0 # fallback if pyloudnorm not available
norm_max_gain_db: float = 12.0
norm_max_atten_db: float = 24.0
# Limiter / true-peak-ish
ceiling_dbtp: float = -1.0
lookahead_ms: float = 5.0
release_ms: float = 100.0
os_factor: int = 4 # ITU/BS.1770 commonly uses 4x for true-peak estimation
@dataclass
class DebugParams:
enabled: bool = False
debug_dir: Optional[str] = None
stride: int = 8
# Spectrogram visuals
spec_n_fft: int = 2048
spec_hop: int = 512
spec_max_frames: int = 2200
spec_max_hz: float = 20000.0
save_npz: bool = True
save_png: bool = True
# -----------------------------
# Debug collector
# -----------------------------
class DebugCollector:
def __init__(
self,
sr: int,
freqs: np.ndarray,
dn_idx: np.ndarray,
deq_idx: np.ndarray,
sh_idx: np.ndarray,
stride: int,
pad_offset: int,
duration_s: float,
):
self.sr = int(sr)
self.freqs = freqs
self.dn_idx = dn_idx
self.deq_idx = deq_idx
self.sh_idx = sh_idx
self.stride = int(max(1, stride))
self.pad_offset = int(pad_offset)
self.duration_s = float(duration_s)
self.frame_i = 0
self.t: List[float] = []
self.w_noise: List[float] = []
self.w_trans: List[float] = []
self.flux_db: List[float] = []
self.band_db: List[float] = []
self.dn_depth: List[float] = []
self.deq_depth: List[float] = []
self.sh_depth: List[float] = []
self.att_dn_db: List[np.ndarray] = []
self.att_deq_db: List[np.ndarray] = []
self.att_sh_db: List[np.ndarray] = []
self.noise_psd_dn_db: List[np.ndarray] = [] # estimated noise PSD in denoise band (dB)
def want(self) -> bool:
return (self.frame_i % self.stride) == 0
def push_meta(self, s: int, n_fft: int, w_noise: float, w_trans: float, flux_db: float, band_db: float,
dn_depth: float, deq_depth: float, sh_depth: float):
# frame center time relative to *original* (unpadded) signal
t_center = (float(s) + 0.5 * float(n_fft) - float(self.pad_offset)) / float(self.sr)
if t_center < 0.0:
t_center = 0.0
if t_center > self.duration_s:
t_center = self.duration_s
self.t.append(float(t_center))
self.w_noise.append(float(w_noise))
self.w_trans.append(float(w_trans))
self.flux_db.append(float(flux_db))
self.band_db.append(float(band_db))
self.dn_depth.append(float(dn_depth))
self.deq_depth.append(float(deq_depth))
self.sh_depth.append(float(sh_depth))
def push_att(self, att_dn_db: Optional[np.ndarray], att_deq_db: Optional[np.ndarray], att_sh_db: Optional[np.ndarray]):
if att_dn_db is not None:
self.att_dn_db.append(att_dn_db.astype(np.float32, copy=False))
if att_deq_db is not None:
self.att_deq_db.append(att_deq_db.astype(np.float32, copy=False))
if att_sh_db is not None:
self.att_sh_db.append(att_sh_db.astype(np.float32, copy=False))
def push_noise_psd_dn(self, noise_psd_dn_db: Optional[np.ndarray]):
if noise_psd_dn_db is not None:
self.noise_psd_dn_db.append(noise_psd_dn_db.astype(np.float32, copy=False))
def step(self):
self.frame_i += 1
def finalize(self) -> Dict[str, Any]:
out: Dict[str, Any] = {}
out["t"] = np.array(self.t, dtype=np.float32)
out["w_noise"] = np.array(self.w_noise, dtype=np.float32)
out["w_trans"] = np.array(self.w_trans, dtype=np.float32)
out["flux_db"] = np.array(self.flux_db, dtype=np.float32)
out["band_db"] = np.array(self.band_db, dtype=np.float32)
out["dn_depth"] = np.array(self.dn_depth, dtype=np.float32)
out["deq_depth"] = np.array(self.deq_depth, dtype=np.float32)
out["sh_depth"] = np.array(self.sh_depth, dtype=np.float32)
if len(self.att_dn_db) > 0:
out["f_dn"] = self.freqs[self.dn_idx].astype(np.float32)
out["att_dn_db"] = np.stack(self.att_dn_db, axis=1) # (F, T)
if len(self.att_deq_db) > 0:
out["f_deq"] = self.freqs[self.deq_idx].astype(np.float32)
out["att_deq_db"] = np.stack(self.att_deq_db, axis=1)
if len(self.att_sh_db) > 0:
out["f_sh"] = self.freqs[self.sh_idx].astype(np.float32)
out["att_sh_db"] = np.stack(self.att_sh_db, axis=1)
if len(self.noise_psd_dn_db) > 0:
out["noise_psd_dn_db"] = np.stack(self.noise_psd_dn_db, axis=1)
return out
# -----------------------------
# Measurements (for debug)
# -----------------------------
def measure_true_peak_db(x: np.ndarray, os_factor: int = 4) -> float:
"""Approx true-peak via oversampling + sample peak on oversampled signal."""
x2 = _as_2d(np.asarray(x, dtype=np.float32))
osf = int(max(1, os_factor))
if osf > 1:
x_os = resample_poly(x2, osf, 1, axis=0).astype(np.float32, copy=False)
else:
x_os = x2
peak = float(np.max(np.abs(x_os))) if x_os.size else 0.0
return float(_lin_to_db(peak))
def measure_rms_dbfs(x: np.ndarray) -> float:
x2 = _as_2d(np.asarray(x, dtype=np.float32))
rms = float(np.sqrt(np.mean(x2 * x2) + 1e-12))
return float(_lin_to_db(rms))
def measure_lufs(x: np.ndarray, sr: int) -> Optional[float]:
try:
import pyloudnorm as pyln
meter = pyln.Meter(int(sr))
return float(meter.integrated_loudness(_as_2d(x)))
except Exception:
return None
# -----------------------------
# Post: loudness normalize + limiter
# -----------------------------
def _peak_limiter(x: np.ndarray, sr: int, ceiling_db: float, lookahead_ms: float, release_ms: float) -> np.ndarray:
"""
Lookahead peak limiter:
- Compute forward-looking local max over lookahead window.
- Compute required gain to keep peaks under ceiling.
- Apply "attack instant / release slow" smoothing via low-pass+min trick.
"""
eps = 1e-12
x2 = _as_2d(x).astype(np.float32, copy=False)
ceiling = float(_db_to_lin(float(ceiling_db)))
ceiling = float(np.clip(ceiling, 1e-6, 1.0))
sc = np.max(np.abs(x2), axis=1).astype(np.float32)
la = int(float(sr) * (float(lookahead_ms) / 1000.0))
la = max(0, la)
size = la + 1
if size <= 1:
peak = sc
else:
# Forward window: [n, n+la]
origin = la // 2 # shifts window to the right
peak = maximum_filter1d(sc, size=size, origin=origin, mode="nearest").astype(np.float32)
req = np.minimum(1.0, ceiling / (peak + eps)).astype(np.float32)
rel = max(1.0, float(release_ms)) / 1000.0
a_rel = math.exp(-1.0 / (float(sr) * rel))
req_lp = _onepole_lp(req, a_rel)
g = np.minimum(req, req_lp).astype(np.float32)
return (x2 * g[:, None]).astype(np.float32, copy=False)
def loudness_normalize(x: np.ndarray, sr: int, mp: MasterParams, debug: bool = False) -> Tuple[np.ndarray, Dict[str, Any]]:
"""
Loudness normalization:
- Prefer pyloudnorm (BS.1770) if available.
- Otherwise fallback to RMS.
- Clamp gain.
"""
info: Dict[str, Any] = {}
x2 = _as_2d(np.asarray(x, dtype=np.float32))
max_up = float(max(0.0, mp.norm_max_gain_db))
max_dn = float(max(0.0, mp.norm_max_atten_db))
gain_db: Optional[float] = None
lufs = None
if mp.target_lufs is not None:
lufs = measure_lufs(x2, sr)
if lufs is not None and math.isfinite(lufs):
gain_db = float(mp.target_lufs) - float(lufs)
info["lufs_in"] = float(lufs)
info["target_lufs"] = float(mp.target_lufs)
if gain_db is None:
# RMS fallback (not perceptual, but better than nothing)
if mp.target_rms_dbfs is None:
info["norm"] = "disabled"
return x2, info
rms_db = measure_rms_dbfs(x2)
gain_db = float(mp.target_rms_dbfs) - float(rms_db)
info["rms_dbfs_in"] = float(rms_db)
info["target_rms_dbfs"] = float(mp.target_rms_dbfs)
gain_db = float(np.clip(gain_db, -max_dn, +max_up))
info["gain_db_applied"] = float(gain_db)
g = float(_db_to_lin(gain_db))
y = (x2 * g).astype(np.float32, copy=False)
if debug:
info["peak_after_norm_dbfs"] = float(_lin_to_db(np.max(np.abs(y)) + 1e-12))
return y, info
def master_post(x: np.ndarray, sr: int, mp: MasterParams, debug: bool = False) -> Tuple[np.ndarray, Dict[str, Any]]:
info: Dict[str, Any] = {"enabled": bool(mp.enabled)}
if not mp.enabled:
return x, info
y = _as_2d(np.asarray(x, dtype=np.float32))
# DC remove
if mp.dc_remove:
y = (y - np.mean(y, axis=0, keepdims=True)).astype(np.float32, copy=False)
info["dc_remove"] = bool(mp.dc_remove)
# Subsonic high-pass
if mp.hp_hz and mp.hp_hz > 0.0:
nyq = 0.5 * sr
if mp.hp_hz < nyq - 10.0:
sos = _butter_sos(sr, "highpass", float(mp.hp_hz), order=int(max(1, mp.hp_order)))
y = sosfiltfilt(sos, y, axis=0).astype(np.float32, copy=False)
info["hp_hz"] = float(mp.hp_hz)
info["hp_order"] = int(mp.hp_order)
# Loudness normalization
y, norm_info = loudness_normalize(y, sr, mp, debug=debug)
info["normalize"] = norm_info
# Limiter (oversampled for true-peak-ish)
osf = int(max(1, mp.os_factor))
info["limiter_os_factor"] = osf
if osf > 1:
y_os = resample_poly(y, osf, 1, axis=0).astype(np.float32, copy=False)
y_os = _peak_limiter(y_os, sr * osf, mp.ceiling_dbtp, mp.lookahead_ms, mp.release_ms)
y2 = resample_poly(y_os, 1, osf, axis=0).astype(np.float32, copy=False)
# Align length
if y2.shape[0] > y.shape[0]:
y2 = y2[: y.shape[0], :]
elif y2.shape[0] < y.shape[0]:
y2 = np.pad(y2, ((0, y.shape[0] - y2.shape[0]), (0, 0)), mode="constant")
y = y2
else:
y = _peak_limiter(y, sr, mp.ceiling_dbtp, mp.lookahead_ms, mp.release_ms)
info["ceiling_dbtp"] = float(mp.ceiling_dbtp)
info["lookahead_ms"] = float(mp.lookahead_ms)
info["release_ms"] = float(mp.release_ms)
# Safety: prevent sample peak > 0 dBFS
peak = float(np.max(np.abs(y))) if y.size else 0.0
if peak > 0.999999:
y = (y / peak * 0.999999).astype(np.float32)
info["post_scale_db"] = float(_lin_to_db(0.999999 / peak))
return y.squeeze(), info
# -----------------------------
# Core STFT repair
# -----------------------------
try:
from numba import jit
HAS_NUMBA = True
except ImportError:
HAS_NUMBA = False
# Dummy decorator if numba missing (though we installed it)
def jit(*args, **kwargs):
def decorator(func):
return func
return decorator
@jit(nopython=True)
def _numba_exp_env(g_target, n_cols, att, rel):
# g_target: (T,)
g_env = np.ones_like(g_target)
g_sm = 1.0
# Cast scalars to match array precision (likely float32)
att_f = float(att)
rel_f = float(rel)
for i in range(n_cols):
curr = g_target[i]
if curr < g_sm:
g_sm = att_f * g_sm + (1.0 - att_f) * curr
else:
g_sm = rel_f * g_sm + (1.0 - rel_f) * curr
g_env[i] = g_sm
return g_env
@jit(nopython=True)
def _numba_dn_noise_est(curr_min, n_blocks, curr_noise_vec, rise):
# curr_min: (F, n_blocks)
# curr_noise_vec: (F,) initialized
output = np.zeros_like(curr_min)
# Cast rise to float32 to match curr_noise_vec precision
rise_f = np.float32(rise)
for b in range(n_blocks):
M = curr_min[:, b]
# Ensure operation result is cast or compatible
# curr_noise_vec * rise_f should be float32 if both are float32
curr_noise_vec = np.minimum(M, curr_noise_vec * rise_f)
output[:, b] = curr_noise_vec
return output
@jit(nopython=True)
def _numba_dn_gain_smooth(target_grid, n_cols, att, rel):
# target_grid: (F, T)
output = np.empty_like(target_grid)
F = target_grid.shape[0]
s_val = np.ones(F, dtype=np.float32)
att_f = np.float32(att)
rel_f = np.float32(rel)
for i in range(n_cols):
t_col = target_grid[:, i]
# Explicit inner loop for Numba efficiency
for f in range(F):
t = t_col[f]
s = s_val[f]
if t < s:
s_val[f] = att_f * s + (1.0 - att_f) * t
else:
s_val[f] = rel_f * s + (1.0 - rel_f) * t
output[:, i] = s_val
return output
@jit(nopython=True)
def _numba_deq_persist(pos, n_cols, a_p):
# pos: (F, T)
output = np.zeros_like(pos)
F = pos.shape[0]
state_p = np.zeros(F, dtype=np.float32)
a_p_f = np.float32(a_p)
for i in range(n_cols):
col = pos[:, i]
for f in range(F):
state_p[f] = a_p_f * state_p[f] + (1.0 - a_p_f) * col[f]
output[f, i] = state_p[f]
return output
def _hpss_harmonic_mask(log_mag: np.ndarray, time_frames: int, freq_bins: int, eps: float = 1e-12) -> np.ndarray:
"""Median-filter HPSS harmonic mask in [0, 1] with shape matching log_mag."""
tf = int(max(1, time_frames))
ff = int(max(1, freq_bins))
H = median_filter(log_mag, size=(1, tf), mode="nearest")
P = median_filter(log_mag, size=(ff, 1), mode="nearest")
Hlin = np.exp(H)
Plin = np.exp(P)
return (Hlin * Hlin) / (Hlin * Hlin + Plin * Plin + eps)
def _hpss_depth_scale(
Mh: np.ndarray,
*,
harmonic_only: bool,
protect_percussive: float,
) -> np.ndarray:
"""Scale repair depth maps; returns multiplier in [0, 1]."""
scale = np.ones_like(Mh, dtype=np.float32)
if harmonic_only:
scale *= Mh.astype(np.float32, copy=False)
prot = float(np.clip(protect_percussive, 0.0, 1.0))
if prot > 0.0:
Mp = (1.0 - Mh).astype(np.float32, copy=False)
scale *= (1.0 - prot * Mp)
return np.clip(scale, 0.0, 1.0).astype(np.float32, copy=False)
def _hpss_mask_for_band(
Mag_mono: np.ndarray,
band_idx: np.ndarray,
*,
time_frames: int,
freq_bins: int,
eps: float,
) -> np.ndarray:
if band_idx.size == 0:
return np.ones((0, Mag_mono.shape[1]), dtype=np.float32)
log_mag = np.log(Mag_mono[band_idx, :] + eps)
return _hpss_harmonic_mask(log_mag, time_frames, freq_bins, eps=eps)
def _apply_magnitude_inpaint(
Z_band: np.ndarray,
*,
target_mag: np.ndarray,
repair_depth: np.ndarray,
confidence: np.ndarray,
eps: float,
ch_scales: Optional[np.ndarray] = None,
) -> tuple[np.ndarray, np.ndarray]:
"""
Blend toward target magnitude keeping phase. Returns (Z_new, g_eff mono).
repair_depth/confidence: (F, T); ch_scales optional (n_ch,) per-channel depth scale.
"""
orig = Z_band
orig_mag = np.abs(orig).astype(np.float32, copy=False)
orig_phase = orig / (orig_mag + eps)
tm = np.minimum(orig_mag[..., 0] if orig_mag.ndim == 3 else orig_mag, target_mag).astype(np.float32)
if orig_mag.ndim == 3:
tm = tm[:, :, None]
rd = (repair_depth * confidence).astype(np.float32)
if rd.ndim == 2 and orig_mag.ndim == 3:
rd = rd[:, :, None]
if ch_scales is not None and orig_mag.ndim == 3:
rd = rd * ch_scales.astype(np.float32)[None, None, :]
new_mag = (1.0 - rd) * orig_mag + rd * tm
g_eff = (new_mag[..., 0] / (orig_mag[..., 0] + eps)).astype(np.float32)
return (new_mag * orig_phase).astype(np.complex64, copy=False), g_eff
def _phasor_smooth_complex(
Z: np.ndarray,
weights: np.ndarray,
size: int,
axis: int,
eps: float,
) -> np.ndarray:
"""Weighted circular-mean smoothing of unit phasors along one axis."""
mag = np.abs(Z).astype(np.float32)
w = (weights.astype(np.float32) * mag).astype(np.float32)
unit = Z / (mag + eps)
k = max(3, int(size) | 1)
def _filt(a: np.ndarray) -> np.ndarray:
return uniform_filter1d(a.astype(np.float64), size=k, axis=axis, mode="nearest").astype(np.float32)
wr = _filt(w * np.real(unit))
wi = _filt(w * np.imag(unit))
ww = _filt(w) + eps
u = (wr + 1j * wi) / ww
u /= (np.abs(u) + eps)
return u.astype(np.complex64, copy=False)
def _phase_instability_map(Z_mono: np.ndarray, eps: float) -> np.ndarray:
"""
(F, T) map in [0, 1]: high where inter-frame / inter-bin phase jumps are erratic.
Used to target moving 'swish' without dulling stable harmonics.
"""
unit = Z_mono / (np.abs(Z_mono) + eps)
n_f, n_t = unit.shape
instab_t = np.zeros((n_f, n_t), dtype=np.float32)
if n_t >= 2:
dt = unit[:, 1:] * np.conj(unit[:, :-1])
dphi_t = np.abs(np.angle(dt)).astype(np.float32)
instab_t[:, 0] = dphi_t[:, 0]
if n_t >= 3:
instab_t[:, 1:-1] = 0.5 * (dphi_t[:, :-1] + dphi_t[:, 1:])
instab_t[:, -1] = dphi_t[:, -1]
instab_f = np.zeros((n_f, n_t), dtype=np.float32)
if n_f >= 2:
df = unit[1:, :] * np.conj(unit[:-1, :])
dphi_f = np.abs(np.angle(df)).astype(np.float32)
instab_f[0, :] = dphi_f[0, :]
if n_f >= 3:
instab_f[1:-1, :] = 0.5 * (dphi_f[:-1, :] + dphi_f[1:, :])
instab_f[-1, :] = dphi_f[-1, :]
raw = instab_t + 0.65 * instab_f
p25 = float(np.percentile(raw, 25.0))
p75 = float(np.percentile(raw, 75.0))
span = max(p75 - p25, 0.04)
return np.clip((raw - p25) / span, 0.0, 1.0).astype(np.float32, copy=False)
def measure_phase_instability(
x: np.ndarray,
sr: int,
lo_hz: float,
hi_hz: float,
*,
n_fft: int = 2048,
hop: int = 512,
) -> float:
"""
Magnitude-weighted mean phase instability in [0, 1] for a frequency band.
Higher values indicate more moving 'swish' / erratic phase texture.
"""
xm = np.asarray(x, dtype=np.float32)
if xm.ndim == 2:
xm = np.mean(xm, axis=1).astype(np.float32, copy=False)
elif xm.ndim != 1:
raise ValueError("audio must be 1D or 2D")
if xm.size < n_fft:
return 0.0
eps = 1e-12
_, _, Z = stft(
xm[None, :],
fs=int(sr),
window="hann",
nperseg=n_fft,
noverlap=n_fft - hop,
nfft=n_fft,
boundary="zeros",
padded=True,
axis=-1,
)
freqs = np.fft.rfftfreq(n_fft, d=1.0 / float(sr)).astype(np.float32)
lo = float(max(0.0, lo_hz))
hi = float(min(float(freqs[-1]), hi_hz))
if hi <= lo:
return 0.0
idx = np.where((freqs >= lo) & (freqs <= hi))[0]
if idx.size < 4:
return 0.0
zm = Z[0, idx, :].astype(np.complex64, copy=False)
instab = _phase_instability_map(zm, eps=eps)
mag = np.abs(zm).astype(np.float32, copy=False)
return float(np.sum(instab * mag) / (np.sum(mag) + eps))
def _apply_swish_phase_repair(
Z: np.ndarray,
band_idx: np.ndarray,
*,
strength: float,
time_amt: float,
freq_amt: float,
time_win: int,
freq_win: int,
w_nontrans: np.ndarray,
transient_protect: float,
harmonic_protect: float,
Mag_mono: np.ndarray,
hpss_time_frames: int,
hpss_freq_bins: int,
eps: float,
) -> None:
"""In-place adaptive phase smoothing for moving swish texture."""
if band_idx.size == 0 or strength <= 1e-6:
return
zm = np.mean(Z[band_idx, :, :], axis=2)
instab = _phase_instability_map(zm, eps=eps)
log_mag = np.log(Mag_mono[band_idx, :] + eps)
t_win = max(3, int(hpss_time_frames) | 1)
f_win = max(3, int(hpss_freq_bins) | 1)
h_lin = np.exp(median_filter(log_mag, size=(1, t_win), mode="nearest"))
p_lin = np.exp(median_filter(log_mag, size=(f_win, 1), mode="nearest"))
mh = (h_lin ** 2 / (h_lin ** 2 + p_lin ** 2 + eps)).astype(np.float32, copy=False)
w_trans = 1.0 - w_nontrans.astype(np.float32, copy=False)
w_prot = (1.0 - float(np.clip(transient_protect, 0.0, 1.0)) * w_trans).astype(np.float32, copy=False)
depth = (
float(np.clip(strength, 0.0, 1.0))
* instab
* w_prot[None, :]
* (1.0 - float(np.clip(harmonic_protect, 0.0, 1.0)) * mh)
).astype(np.float32, copy=False)
weights = Mag_mono[band_idx, :].astype(np.float32, copy=False)
t_amt = float(np.clip(time_amt, 0.0, 1.0))
f_amt = float(np.clip(freq_amt, 0.0, 1.0))
for ch in range(Z.shape[2]):
zc = Z[band_idx, :, ch]
mag = np.abs(zc).astype(np.float32, copy=False)
unit = zc / (mag + eps)
if t_amt > 1e-6:
unit_t = _phasor_smooth_complex(zc, weights, time_win, axis=1, eps=eps)
blend = (t_amt * depth).astype(np.float32, copy=False)
unit = (1.0 - blend) * unit + blend * unit_t
if f_amt > 1e-6:
unit_f = _phasor_smooth_complex(unit * mag, weights, freq_win, axis=0, eps=eps)
blend = (f_amt * depth).astype(np.float32, copy=False)
unit = (1.0 - blend) * unit + blend * unit_f
unit /= (np.abs(unit) + eps)
Z[band_idx, :, ch] = (mag * unit).astype(np.complex64, copy=False)
def _apply_hf_decorrelation(
Z: np.ndarray,
band_idx: np.ndarray,
*,
amount: float,
rng: np.random.Generator,
eps: float,
) -> None:
"""Break synthetic L/R phase lock in HF by partial Side-channel phase scatter."""
if band_idx.size == 0 or amount <= 1e-6 or Z.shape[2] < 2:
return
left = Z[band_idx, :, 0]
right = Z[band_idx, :, 1]
mid = 0.5 * (left + right)
side = 0.5 * (left - right)
coh = np.real(left * np.conj(right)) / (np.abs(left) * np.abs(right) + eps)
coh = np.clip(coh, -1.0, 1.0).astype(np.float32, copy=False)
coh_excess = np.clip((coh - 0.25) / 0.65, 0.0, 1.0).astype(np.float32, copy=False)
side_mag = np.abs(side)
side_phi = np.angle(side)
mid_phi = np.angle(mid + eps)
phi_rand = rng.uniform(0.0, 2.0 * np.pi, size=side_phi.shape).astype(np.float32)
phi_target = 0.55 * phi_rand + 0.45 * mid_phi
side_new = side_mag * np.exp(1j * phi_target).astype(np.complex64)
depth = (float(np.clip(amount, 0.0, 1.0)) * coh_excess).astype(np.float32, copy=False)
side_blend = (1.0 - depth) * side + depth * side_new
Z[band_idx, :, 0] = (mid + side_blend).astype(np.complex64, copy=False)
Z[band_idx, :, 1] = (mid - side_blend).astype(np.complex64, copy=False)
def _artifact_confidence_map(
Mag_mono: np.ndarray,
band_idx: np.ndarray,
*,
freq_med_bins: int,
thr_db: float,
eps: float,
) -> np.ndarray:
"""High where narrow log-magnitude residual exceeds threshold."""
if band_idx.size == 0:
return np.zeros((0, Mag_mono.shape[1]), dtype=np.float32)
mag = Mag_mono[band_idx, :]
L = np.log(mag + eps)
L_med = median_filter(L, size=(int(max(3, freq_med_bins)), 1), mode="nearest")
resid = (L - L_med) * (20.0 / np.log(10.0))
conf = np.clip((resid - float(thr_db)) / max(1e-6, float(thr_db)), 0.0, 1.0)
return conf.astype(np.float32, copy=False)
def process_stft(x: np.ndarray, sr: int, p: Params, dbg: Optional[DebugCollector] = None) -> np.ndarray:
if x.ndim == 1:
x = x[:, None]
# Transpose to (n_ch, n_samples) for scipy.signal
x_t = x.T
n_ch, n_samples = x_t.shape
n_fft = int(p.n_fft)
hop = int(p.hop)
# Get STFT (scipy style: input (ch, time) -> output (ch, freq, time) with axis=-1)
f, t_sec, Z = stft(x_t, fs=sr, window='hann', nperseg=n_fft, noverlap=n_fft-hop, nfft=n_fft, boundary='zeros', padded=True, axis=-1)
# Transpose to (n_freq, n_time, n_ch) for convenient processing
Z = Z.transpose(1, 2, 0).astype(np.complex64)
freqs = f.astype(np.float32)
nyq = f[-1] if len(f) > 0 else 0.0
n_cols = Z.shape[1]
eps = 1e-12
rng = np.random.default_rng(int(getattr(p, "seed", 0)))
# --- Indices helper ---
def _idx(lo_hz: float, hi_hz: float) -> np.ndarray:
lo = float(max(0.0, lo_hz))