#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fix10 真峰修正：从 -0.5dB 混音母带扫多档增益，逐档编码 AAC 后实测真峰/响度。
AAC twoloop 非单调，必须逐档实测。输出扫值表 ep03_fix10_tp_sweep.json。
"""
import json, os, re, subprocess, sys, hashlib

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

BASE = r"D:/Download/muse_exchange"
PKG = os.path.join(BASE, "ep03_package", "ep03_package")
SRC = os.path.join(PKG, "ep03_master_v6.wav")   # -0.5dB 混音母带 (PCM s16le 48k mono)
TMP = os.path.join(BASE, "ep03_fix10_tp_sweep_tmp")
os.makedirs(TMP, exist_ok=True)

# 目标总增益（相对 loudnorm 输出），源已是 -0.5dB，delta = g - (-0.5)
TARGETS = [-0.9, -1.0, -1.1, -1.2]


def run(args):
    return subprocess.run(args, capture_output=True, text=True,
                          encoding="utf-8", errors="replace")


def meas(path):
    r = run(["ffmpeg", "-v", "info", "-i", path,
             "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"])
    def g(k):
        m = re.search(r'"%s"\s*:\s*"([-\d.]+)"' % k, r.stderr)
        return float(m.group(1)) if m else None
    return {"lufs": g("input_i"), "tp": g("input_tp"), "lra": g("input_lra")}


def main():
    assert os.path.exists(SRC), SRC
    print("SRC", SRC, "base gain -0.5dB", flush=True)
    print("base meas (PCM母带):", meas(SRC), flush=True)
    rows = []
    for g in TARGETS:
        delta = round(g - (-0.5), 2)
        m4a = os.path.join(TMP, "g%s.m4a" % str(g).replace("-", "m").replace(".", "p"))
        rc = run(["ffmpeg", "-v", "error", "-y", "-i", SRC,
                  "-af", "volume=%.2fdB" % delta,
                  "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "1", m4a])
        assert rc.returncode == 0, (g, rc.stderr[-800:])
        m = meas(m4a)
        row = {"target_gain_db": g, "delta_from_base_db": delta,
               "aac_bytes": os.path.getsize(m4a), "measured_aac": m,
               "pass_tp_minus1": (m["tp"] is not None and m["tp"] <= -1.0)}
        rows.append(row)
        print("SWEEP g=%.1f delta=%.1f -> I=%s TP=%s LRA=%s %s" %
              (g, delta, m["lufs"], m["tp"], m["lra"],
               "PASS" if row["pass_tp_minus1"] else "FAIL"), flush=True)
    out = {"source": SRC, "source_base_gain_db": -0.5,
           "source_meas": meas(SRC), "sweep": rows,
           "note": "AAC twoloop 非单调，逐档实测；-0.7dB 历史给 -0.20 异常，未纳入扫值。达标线 TP<=-1.0 dBTP。"}
    json.dump(out, open(os.path.join(BASE, "ep03_fix10_tp_sweep.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("SWEEP DONE", flush=True)


if __name__ == "__main__":
    main()
