File size: 4,707 Bytes
17d4058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
run_test_v6.py  —  S-SPADE RDFT  ·  brickwall limiter recovery
===============================================================
Usa spade_declip_v9 in mode='soft' per recuperare la dinamica
compressa da un brickwall limiter su tracce di mastering.

Novità v6 rispetto a v5
-----------------------
NEW — Progress bar (rich → tqdm → plain fallback):
    Durante il processing viene mostrata una barra di avanzamento
    per canale con ETA, % frame bypassed e contatore no_conv.
    Installare rich per la UI migliore:  pip install rich
    Alternativa:                         pip install tqdm
    Funziona anche senza nessuno dei due (plain % printout).

Come leggere delta_db da Waveform Statistics (RX / Audition / iZotope):
    Individua il livello sotto il quale il limiter NON è intervenuto,
    es. "da −∞ fino a −2.5 dB"  →  delta_db = 2.5
    In alternativa: Max RMS ≈ −1.3 dB → prova delta_db tra 1.0 e 2.5.

Output:
    Il file salvato è FLOAT32 WAV — può avere sample > 1.0 (corretto:
    sono i transienti recuperati sopra il ceiling limitato).
    Applica un gain di −20·log10(peak) dB per riportare a 0 dBFS.
"""
import numpy as np
import soundfile as sf
from spade_declip_v11 import declip, DeclipParams

# ── File da processare ────────────────────────────────────────────────────
# Formato: (filename, delta_db)
# delta_db = dB dal ceiling (0 dBFS) alla soglia del limiter
FILES_SOFT = [
    ("test.flac", 2.5),
    # ("mastering.flac", 1.5),   # prova valori più stretti se senti artefatti
    # ("mastering.flac", 3.0),   # prova valori più ampi se i transienti non cambiano
]

ALGO  = "sspade"
FRAME = "rdft"

# ─────────────────────────────────────────────────────────────────────────
print("\n" + "=" * 65)
print("MODE: SOFT  (brickwall limiter recovery)")
print("=" * 65)

for filepath, delta_db in FILES_SOFT:
    print(f"\nFile : {filepath}  |  delta_db={delta_db} dB")

    try:
        yc, sr_val = sf.read(filepath, always_2d=True)
    except Exception as e:
        print(f"  [ERRORE] {e}")
        continue

    yc = yc.astype(float)
    n_samp, n_ch = yc.shape
    labels = ["L", "R"] if n_ch == 2 else ["Ch" + str(c) for c in range(n_ch)]

    print(f"  SR={sr_val} Hz  |  dur={round(n_samp/sr_val, 2)}s  |  channels={n_ch}")
    for c, lbl in enumerate(labels):
        peak_c = float(np.max(np.abs(yc[:, c])))
        print(f"  [{lbl}] peak={round(peak_c, 4)}")

    params = DeclipParams(
        algo="sspade",
	frame="rdft",
	window_length=1024,
	hop_length=256,
	s=1, r=1, eps=0.1, max_iter=1000,
	mode="soft", 
	delta_db=delta_db,
	# --- NOVITÀ V11 ---
	sample_rate=sr_val,          # Fondamentale per il calcolo dei ms
	release_ms=250.0,             # Aiuta a ridurre il pumping post-picco
	max_gain_db=6.0,             # Evita transienti "ice-pick" innaturali
	multiband=False,             # Metti True se il limiter originale era multibanda
	macro_expand=False,          # Metti True per recuperare "corpo" (RMS)
	# ------------------
	n_jobs=-1, 
	verbose=True,
	show_progress=True,
    )


    fixed, masks = declip(yc, params)

    fixed_2d = fixed[:, None] if fixed.ndim == 1 else fixed
    peak_out = float(np.max(np.abs(fixed_2d)))

    # Costruisce nome file output
    for ext in (".flac", ".wav", ".aif", ".aiff"):
        if filepath.lower().endswith(ext):
            base = filepath[:-len(ext)]
            break
    else:
        base = filepath
    out_name = f"{base}_soft_d{str(delta_db).replace('.','p')}_{ALGO}_{FRAME}.wav"

    # ── Write as 32-bit float WAV ─────────────────────────────────────────
    # CRITICAL: subtype='FLOAT' preserves sample values > 1.0 (recovered
    # transients).  The v4 default (PCM_16) silently truncated anything
    # outside ±1.0 to exactly ±1.0, re-clipping all recovered peaks.
    sf.write(out_name, fixed_2d.astype(np.float32), sr_val, subtype='FLOAT')

    peaks = [round(float(np.max(np.abs(fixed_2d[:, c]))), 4) for c in range(n_ch)]
    print(f"  → {out_name}")
    print(f"     peak out: " + "  ".join(f"{lbl}={p}" for lbl, p in zip(labels, peaks)))
    if peak_out > 1.0:
        gain_db = round(-20 * np.log10(peak_out), 2)
        print(f"     ⚠  Peak > 1.0 — applica {gain_db} dB per riportare a 0 dBFS")
    else:
        print(f"     ✓  Peak ≤ 1.0 — nessuna normalizzazione necessaria")

print("\nDone.")