#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 Short 1 拼片：12 静帧场景 -> 30fps 视频；s42 旁白 + 正片 BGM 混音；
loudnorm 两遍法到 -14 LUFS；AAC twoloop 真峰逐档扫值；烧字幕后 mux 成 ep03_short1.mp4。
"""
import json, os, re, subprocess, sys

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")
FR = os.path.join(BASE, "ep03_short1_frames")
TMP = os.path.join(BASE, "ep03_short1_tmp")
os.makedirs(TMP, exist_ok=True)
NARR = os.path.join(BASE, "ep03_short1_vox", "ep03_short1_s42.wav")
BGM = os.path.join(PKG, "bgm", "bed_b_pad.wav")
ASS = os.path.join(BASE, "ep03_short1_subs.ass")
OUT = os.path.join(BASE, "ep03_short1.mp4")
REP = json.load(open(os.path.join(BASE, "ep03_short1_frames_report.json"), encoding="utf-8"))
TOTAL = REP["total_s"]           # 40.8
OFFSET = REP["intro_offset_s"]   # 0.8
BED_GAIN = -1.3                  # 实测 s42 mean -22.9 / BGM mean -40.6 -> -22.9-19-(-40.6)
FONTS = os.path.join(PKG, "fonts")


def run(args, capture=False, cwd=None):
    r = subprocess.run(args, capture_output=True, text=True,
                       encoding="utf-8", errors="replace", cwd=cwd)
    if r.returncode != 0 and capture:
        print("FFMPEG FAIL", " ".join(args)[:300], (r.stderr or "")[-1000:], flush=True)
    return r


def meas(path):
    """EBU R128 实测：input_i / input_tp / input_lra。"""
    r = run(["ffmpeg", "-v", "info", "-i", path,
             "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], True)
    assert r.returncode == 0
    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 build_video():
    segs = []
    for i, sc in enumerate(REP["scenes"]):
        dur = round(sc["end"] - sc["start"], 3)
        p = os.path.join(TMP, "seg%02d.mp4" % i)
        r = run(["ffmpeg", "-v", "error", "-y", "-loop", "1", "-framerate", "30",
                 "-t", "%.3f" % dur, "-i", sc["file"], "-c:v", "libx264",
                 "-pix_fmt", "yuv420p", "-crf", "17", "-r", "30", "-an", p])
        assert r.returncode == 0, (sc["name"], r.stderr[-500:])
        segs.append(p)
        print("SEG %-14s %.3fs" % (sc["name"], dur), flush=True)
    lst = os.path.join(TMP, "concat.txt")
    with open(lst, "w", encoding="utf-8") as f:
        for p in segs:
            f.write("file '%s'\n" % p.replace("\\", "/"))
    raw = os.path.join(TMP, "video_raw.mp4")
    r = run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0",
             "-i", lst, "-c", "copy", raw])
    assert r.returncode == 0, r.stderr[-800:]
    sub = os.path.join(TMP, "video_sub.mp4")
    # ffmpeg 的 ass 滤镜会把 Windows 绝对路径里的冒号当选项分隔符，改用包内相对路径
    import shutil
    shutil.copyfile(ASS, os.path.join(PKG, "ep03_short1_subs.ass"))
    r = run(["ffmpeg", "-v", "error", "-y", "-i", raw,
             "-vf", "ass=ep03_short1_subs.ass:fontsdir=fonts",
             "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "17", "-r", "30", "-an", sub],
            cwd=PKG)
    assert r.returncode == 0, (r.stderr or "")[-800:]
    return sub


def filt(loud_extra=""):
    return (f"[0:a]adelay={int(OFFSET*1000)},apad,atrim=0:{TOTAL:.2f},highpass=f=80[narr];"
            f"[1:a]aloop=loop=-1:size=2e+09,atrim=0:{TOTAL:.2f},volume={BED_GAIN:.1f}dB,"
            f"afade=t=in:st=0:d=1.5,afade=t=out:st={TOTAL-3:.2f}:d=3.0[bed];"
            f"[narr][bed]amix=inputs=2:normalize=0,aformat=channel_layouts=stereo,"
            f"loudnorm=I=-14:TP=-1.5:LRA=11{loud_extra}")


def build_audio():
    # pass1 测量
    r = run(["ffmpeg", "-v", "info", "-i", NARR, "-i", BGM,
             "-filter_complex", filt(":print_format=json"), "-f", "null", "-"], True)
    assert r.returncode == 0, r.stderr[-1500:]
    def g(k):
        m = re.search(r'"%s"\s*:\s*"([-\d.]+)"' % k, r.stderr)
        return float(m.group(1)) if m else None
    # ffmpeg 8.x 的 loudnorm 动态模式 JSON 只给 output_*，两遍法要把它回填到 measured_*
    p1 = {k: g(k) for k in ("input_i", "input_tp", "input_lra", "output_i",
                            "output_tp", "output_lra", "output_thresh", "target_offset")}
    print("LOUDNORM PASS1", p1, flush=True)
    assert all(v is not None for v in p1.values()), p1
    ext = (":linear=true:measured_I=%.2f:measured_TP=%.2f:measured_LRA=%.2f"
           ":measured_thresh=%.2f:offset=%.2f" %
           (p1["output_i"], p1["output_tp"], p1["output_lra"],
            p1["output_thresh"], p1["target_offset"]))
    wav = os.path.join(TMP, "master_short1.wav")
    r = run(["ffmpeg", "-v", "error", "-y", "-i", NARR, "-i", BGM,
             "-filter_complex", filt(ext), "-ar", "48000", "-ac", "2",
             "-c:a", "pcm_s16le", wav])
    assert r.returncode == 0, r.stderr[-800:]
    mw = meas(wav)
    print("PCM MASTER", mw, flush=True)
    # AAC 真峰扫值（twoloop 非单调，逐档实测）
    rows = []
    for gain in (0.0, -0.3, -0.6, -0.9):
        m4a = os.path.join(TMP, "aac%s.m4a" % str(gain).replace("-", "m").replace(".", "p"))
        r = run(["ffmpeg", "-v", "error", "-y", "-i", wav,
                 "-af", "volume=%.2fdB" % gain,
                 "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", m4a])
        assert r.returncode == 0, r.stderr[-800:]
        m = meas(m4a)
        rows.append({"gain_db": gain, "meas": m, "bytes": os.path.getsize(m4a),
                     "pass": m["tp"] is not None and m["tp"] <= -1.0})
        print("AAC SWEEP %+.1fdB -> I=%s TP=%s LRA=%s %s" %
              (gain, m["lufs"], m["tp"], m["lra"], "PASS" if rows[-1]["pass"] else "FAIL"),
              flush=True)
    ok = [x for x in rows if x["pass"]]
    assert ok, "四档 AAC 真峰全部超线，需改扫值"
    # 取过线档里响度最接近 -14 的
    best = min(ok, key=lambda x: abs(x["meas"]["lufs"] + 14.0))
    chosen = os.path.join(TMP, "aac%s.m4a" % str(best["gain_db"]).replace("-", "m").replace(".", "p"))
    print("CHOSEN", best["gain_db"], best["meas"], flush=True)
    return wav, chosen, p1, mw, rows, best


def main():
    video = build_video()
    wav, aac, p1, mw, rows, best = build_audio()
    r = run(["ffmpeg", "-v", "error", "-y", "-i", video, "-i", aac,
             "-map", "0:v:0", "-map", "1:a:0", "-c", "copy", "-shortest", OUT])
    assert r.returncode == 0, r.stderr[-800:]
    rep = {"out": OUT, "total_s": TOTAL, "narr": NARR, "narr_offset_s": OFFSET,
           "bgm": BGM, "bed_gain_db": BED_GAIN, "pcm_master": mw,
           "loudnorm_pass1": p1, "aac_sweep": rows, "chosen": best,
           "video": video, "note": "画面静帧拼接+字幕烧录；音频两遍 loudnorm -14 LUFS；AAC 192k 双声道逐档实测真峰"}
    json.dump(rep, open(os.path.join(BASE, "ep03_short1_assemble_report.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("ASSEMBLED", OUT, os.path.getsize(OUT), "B", flush=True)

if __name__ == "__main__":
    main()
