# -*- coding: utf-8 -*-
"""验证 v2 母带是否用 loudnorm 两遍法（measured_* 喂入 dynamic）：raw->pass1->pass2->比对。"""
import os, subprocess, re, json, wave, numpy as np

BASE = r"D:/Download/muse_exchange"
RAW = os.path.join(BASE, "ep03_raw_v2_concat.wav")
MASTER = os.path.join(BASE, "ep03_package/ep03_package/ep03_narration_master_v2.wav")
TMP = os.path.join(BASE, "ep03_diag_twopass.wav")
BR = "bandreject=f=120:w=50"

def meas_json(signal_af):
    r = subprocess.run(["ffmpeg","-v","info","-i",RAW,
        "-af",signal_af+",loudnorm=I=-14:TP=-1:LRA=11:print_format=json","-f","null","-"],
        capture_output=True,text=True)
    js = re.findall(r"\{[\s\S]*?\}", r.stderr)
    for blk in reversed(js):
        try:
            d = json.loads(blk)
            if "measured_I" in d: return d
        except Exception: pass
    return None

m = meas_json(BR)
print("pass1 measured:", m, flush=True)
if not m: raise SystemExit("pass1 failed")
ln = ("loudnorm=I=-14:TP=-1:LRA=11:measured_I=%s:measured_TP=%s:measured_LRA=%s:"
      "measured_thresh=%s:offset=%s" % (m["measured_I"],m["measured_TP"],
      m["measured_LRA"],m["measured_thresh"],m["offset"]))
for linear in [False, True]:
    af = BR+","+ln+(":linear=true" if linear else "")+",aresample=48000," \
         "afade=t=in:st=0:d=0.05,afade=t=out:st=1520.27:d=0.05,volume=-0.25dB"
    subprocess.run(["ffmpeg","-y","-v","error","-i",RAW,"-af",af,
                    "-c:a","pcm_s16le",TMP],check=True,cwd=BASE)
    w1=wave.open(MASTER); w2=wave.open(TMP)
    n=min(w1.getnframes(),w2.getnframes())
    a=np.frombuffer(w1.readframes(n),dtype="<i2").astype(np.float64)
    b=np.frombuffer(w2.readframes(n),dtype="<i2").astype(np.float64)
    print("linear=%s corr=%.6f scale=%.5f" % (linear,np.corrcoef(a,b)[0,1],(a@b)/(a@a)),flush=True)
