#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fix10 真峰修正成片：视频流 copy 零改动，音频换成已实测 -1.83dBTP 的 -0.9dB AAC。
校验：视频流 sha 新旧一致 / 成片三项 / PCM 削波 / 黑帧 0。通过后覆盖 ep03_final_fix10.mp4。
"""
import hashlib, json, math, os, re, subprocess, sys, wave

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

BASE = r"D:/Download/muse_exchange"
OLD = os.path.join(BASE, "ep03_final_fix10.mp4")            # -0.5dB 版（-1.41 超线）
AAC = os.path.join(BASE, "ep03_fix10_tp_sweep_tmp", "gm0p9.m4a")  # -0.9dB 版，扫值实测 -1.83
NEW = os.path.join(BASE, "ep03_final_fix10_tp09.mp4")
FINAL = OLD
WAV = os.path.join(BASE, "ep03_fix10_tp09_check.wav")
TOTAL = 1524.48


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


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def vstream_sha(p):
    """提取裸 H.264 视频流算 sha（不含容器），验证画面逐字节零改动。"""
    h = hashlib.sha256()
    proc = subprocess.Popen(["ffmpeg", "-v", "error", "-i", p, "-map", "0:v:0",
                             "-c", "copy", "-bsf:v", "h264_mp4toannexb",
                             "-f", "h264", "-"], stdout=subprocess.PIPE)
    for c in iter(lambda: proc.stdout.read(1 << 20), b""):
        h.update(c)
    proc.stdout.close()
    rc = proc.wait()
    assert rc == 0, ("vstream extract failed", p, rc)
    return h.hexdigest()


def main():
    assert os.path.exists(OLD) and os.path.exists(AAC)
    old_vsha = vstream_sha(OLD)
    print("OLD video stream sha256", old_vsha, flush=True)

    # 只换音频，视频 copy；音频流直接 copy 扫值实测的 m4a（无二次编码）
    rc = run(["ffmpeg", "-hide_banner", "-nostdin", "-y", "-i", OLD, "-i", AAC,
              "-map", "0:v:0", "-map", "1:a:0", "-c", "copy",
              "-movflags", "+faststart", NEW])
    assert rc.returncode == 0, ("mux failed", rc.stderr[-2000:])
    print("MUX done", os.path.getsize(NEW), "B", flush=True)

    new_vsha = vstream_sha(NEW)
    print("NEW video stream sha256", new_vsha, flush=True)
    assert new_vsha == old_vsha, "视频流变了！画面非逐字节一致，停止交付"

    # 成片三项实测
    r = run(["ffmpeg", "-v", "info", "-i", NEW,
             "-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
    meas = {"lufs": g("input_i"), "tp": g("input_tp"), "lra": g("input_lra")}
    print("MEAS", meas, flush=True)

    # PCM 峰与削波
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", NEW, "-vn",
                    "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "1", WAV], check=True)
    import numpy as np
    w = wave.open(WAV)
    a = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2")
    w.close()
    peak = int(np.abs(a.astype(np.int32)).max())
    fullscale = int(np.count_nonzero((a == -32768) | (a == 32767)))
    peak_db = round(20 * math.log10(peak / 32768.0), 3) if peak else None
    print("PCM peak", peak, peak_db, "dBFS fullscale", fullscale, flush=True)

    # 黑帧扫描
    b = run(["ffmpeg", "-hide_banner", "-nostdin", "-v", "info", "-i", NEW,
             "-vf", "blackdetect=d=0.05:pix_th=0.10", "-an", "-f", "null", "-"])
    blacks = re.findall(r"black_start:([0-9.]+)", b.stderr)
    print("BLACK", len(blacks), blacks[:20], flush=True)

    # 流参数
    probe = json.loads(run(["ffprobe", "-v", "error", "-show_entries",
                            "stream=codec_name,codec_type,duration,sample_rate,channels,bit_rate",
                            "-of", "json", NEW]).stdout)
    vst = next(s for s in probe["streams"] if s["codec_type"] == "video")
    ast = next(s for s in probe["streams"] if s["codec_type"] == "audio")
    vdur, adur = float(vst["duration"]), float(ast["duration"])
    print("STREAM v %.2fs a %.2fs" % (vdur, adur), flush=True)

    tp_ok = meas["tp"] is not None and meas["tp"] <= -1.0
    assert tp_ok, ("真峰仍超线，不覆盖成片", meas)
    assert fullscale == 0, "满刻度削波非0"
    assert len(blacks) == 0, "黑帧非0"
    assert abs(adur - TOTAL) < 0.05, ("音频时长异常", adur)

    # 通过才覆盖正式成片（ffmpeg 不做 in-place，先 temp 再 os.replace）
    os.replace(NEW, FINAL)
    print("OVERWROTE", FINAL, flush=True)

    rep = {
        "file": os.path.basename(FINAL), "bytes": os.path.getsize(FINAL),
        "sha256": sha(FINAL),
        "video_duration_s": round(vdur, 3), "audio_duration_s": round(adur, 3),
        "measured": meas, "pcm_peak_dbfs": peak_db, "fullscale_samples": fullscale,
        "black_starts": blacks,
        "video_stream_sha256_old": old_vsha, "video_stream_sha256_new": new_vsha,
        "video_stream_identical": True,
        "audio_source": "ep03_fix10_tp_sweep_tmp/gm0p9.m4a",
        "total_gain_db": -0.9, "delta_from_base_db": -0.4,
        "tp_ok": tp_ok,
        "note": "按 wb id=379：只动音频，视频流 copy 逐字节不变；成片混音总增益 -0.5→-0.9dB（再降0.4），AAC 重编码192k。AAC twoloop 非单调，逐档实测：-0.9→-1.83(过)/-1.0→-2.0(过)/-1.1→-2.08(过)/-1.2→-0.64(炸)。取 -0.9。字幕烧死在画面，未动；s7_2 未重渲、12 镜未动。",
    }
    json.dump(rep, open(os.path.join(BASE, "ep03_fix10_tp09_report.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE", json.dumps(rep, ensure_ascii=False), flush=True)


if __name__ == "__main__":
    main()
