#!/usr/bin/env python3
"""Speed-up tests, 2026-11-01. ffmpeg/ffprobe 6.1.1, python3 standard library only.
Every expected value is computed here from the speed factor; every result line says PASS or FAIL against it.
Run from the folder that holds src.mp4 (Big Buck Bunny 1080p 30 fps, Blender Foundation, CC BY 3.0)."""
import array, json, math, subprocess, sys

SRC = sys.argv[1] if len(sys.argv) > 1 else "src.mp4"
FF = ["ffmpeg", "-v", "error", "-nostdin", "-y"]


def run(cmd, check=True):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if check and r.returncode != 0:
        print("COMMAND FAILED:", " ".join(cmd), r.stderr[-300:])
        sys.exit(1)
    return r


def probe(path):
    v = json.loads(run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries",
                        "stream=nb_read_frames,r_frame_rate,avg_frame_rate,duration", "-of", "json", path]).stdout)["streams"][0]
    a = json.loads(run(["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=duration", "-of", "json", path]).stdout)["streams"]
    f = json.loads(run(["ffprobe", "-v", "error", "-show_entries", "format=duration,size,bit_rate", "-of", "json", path]).stdout)["format"]
    num, den = v["r_frame_rate"].split("/")
    return {"frames": int(v["nb_read_frames"]), "fps": round(int(num) / int(den), 3), "vdur": float(v["duration"]),
            "adur": float(a[0]["duration"]) if a else None, "dur": float(f["duration"]), "size": int(f["size"]),
            "kbps": round(int(f["bit_rate"]) / 1000)}


def atempo_chain(s):
    """Single filter up to 2x, a chain of 2.0 steps and a remainder above it (the documented daisy-chain)."""
    if s <= 2:
        return f"atempo={s}"
    parts, left = [], s
    while left > 2:
        parts.append("atempo=2.0")
        left /= 2
    parts.append(f"atempo={left:g}")
    return ",".join(parts)


def speed(inp, out, s, atempo=None, extra=(), fps=None):
    atempo = atempo or atempo_chain(s)
    vf = f"setpts=PTS/{s}" + (f",fps={fps}" if fps else "")
    fc = f"[0:v]{vf}[v];[0:a]{atempo}[a]"
    run(FF + ["-i", inp, "-filter_complex", fc, "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-crf", "20", "-preset", "medium",
              "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", *extra, out])


def pcm(path, rate=44100):
    raw = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", path, "-vn", "-ac", "1", "-ar", str(rate), "-f", "s16le", "-"],
                         capture_output=True).stdout
    a = array.array("h")
    a.frombytes(raw[: len(raw) // 2 * 2])
    return a


def frequency(path, rate=44100, skip=0.3):
    """Dominant frequency of a pure tone from rising zero crossings (interpolated), skipping the first and last 0.3 s."""
    a = pcm(path, rate)
    lo, hi = int(skip * rate), len(a) - int(skip * rate)
    xs = []
    for i in range(lo, hi - 1):
        if a[i] < 0 <= a[i + 1]:
            xs.append(i + (-a[i]) / (a[i + 1] - a[i]))
    if len(xs) < 3:
        return None
    return round((len(xs) - 1) * rate / (xs[-1] - xs[0]), 1)


def verdict(ok):
    return "PASS" if ok else "FAIL"


print("== ffmpeg", run(["ffmpeg", "-version"]).stdout.splitlines()[0])
fails = 0

# --- A. source excerpt -------------------------------------------------------------------------------------------
run(FF + ["-ss", "90", "-t", "20", "-i", SRC, "-map", "0:v:0", "-map", "0:a:0", "-c:v", "libx264", "-crf", "20", "-preset", "medium",
          "-pix_fmt", "yuv420p", "-r", "30", "-c:a", "aac", "-b:a", "128k", "in.mp4"])
base = probe("in.mp4")
print("\n== A. Source excerpt in.mp4 (20 s of Big Buck Bunny from 90 s)")
print(json.dumps(base))

# --- B. duration, frame count, size by speed ---------------------------------------------------------------------
print("\n== B. Duration, frames and size by speed (setpts=PTS/s plus atempo, default frame rate handling, x264 CRF 20)")
print("speed | atempo | duration s (expected) | video s | audio s | frames (expected) | fps | size KB | kbps | check")
rows = {}
for s in [1, 1.5, 2, 4, 10]:
    out = f"b_{s}.mp4"
    speed("in.mp4", out, s)
    p = probe(out)
    rows[s] = p
    exp_d, exp_f = 20 / s, 600 / s
    ok = abs(p["dur"] - exp_d) <= 0.15 and abs(p["frames"] - exp_f) <= 2 and abs(p["adur"] - exp_d) <= 0.15
    fails += not ok
    print(f"{s}x | {atempo_chain(s)} | {p['dur']:.3f} ({exp_d:.3f}) | {p['vdur']:.3f} | {p['adur']:.3f} | {p['frames']} ({exp_f:.0f}) | {p['fps']} | {p['size']/1024:.0f} | {p['kbps']} | {verdict(ok)}")
print("CONTROL 1x: duration must equal the source, frames must equal 600 ->",
      verdict(abs(rows[1]['dur'] - base['dur']) <= 0.15 and rows[1]['frames'] == base['frames']))
print("SIZE: 1x", round(rows[1]['size'] / 1024), "KB; 2x", round(rows[2]['size'] / 1024), "KB =", f"{rows[2]['size']/rows[1]['size']*100:.0f}% of 1x for {1/2*100:.0f}% of the length;",
      "10x", round(rows[10]['size'] / 1024), "KB =", f"{rows[10]['size']/rows[1]['size']*100:.0f}% of 1x for 10% of the length")

print("\n== B2. Same speeds with an explicit fps=30 filter after setpts")
print("speed | duration s (expected) | frames (expected) | size KB | check")
for sp in [1.5, 2, 4, 10]:
    out = f"b2_{sp}.mp4"
    speed("in.mp4", out, sp, fps=30)
    p = probe(out)
    exp_d, exp_f = 20 / sp, 600 / sp
    ok = abs(p["frames"] - exp_f) <= 1 and abs(p["dur"] - exp_d) <= 0.1
    fails += not ok
    print(f"{sp}x | {p['dur']:.3f} ({exp_d:.3f}) | {p['frames']} ({exp_f:.0f}) | {p['size']/1024:.0f} | {verdict(ok)}")

# --- C. frame handling --------------------------------------------------------------------------------------------
print("\n== C. What happens to the frames at 2x and 10x")
for s in [2, 10]:
    out = f"c_pass_{s}.mp4"
    run(FF + ["-i", "in.mp4", "-vf", f"setpts=PTS/{s}", "-an", "-fps_mode", "passthrough", "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p", out])
    p = probe(out)
    avg = p["frames"] / p["vdur"]
    ok = p["frames"] == base["frames"] and abs(avg - 30 * s) <= 30 * s * 0.03
    fails += not ok
    print(f"{s}x passthrough (keep every frame): frames {p['frames']} (expected 600), average {avg:.1f} frames per second (expected {30*s} within 3%), stored rate reported by ffprobe {p['fps']} fps, duration {p['dur']:.3f} s, size {p['size']/1024:.0f} KB -> {verdict(ok)}")
    print(f"{s}x default (drop frames to 30 fps): frames {rows[s]['frames']} (expected {600//s}), stored frame rate {rows[s]['fps']} fps")

# --- D. forgetting the audio --------------------------------------------------------------------------------------
print("\n== D. Speeding up only the picture (a common mistake: -vf setpts without touching the audio)")
run(FF + ["-i", "in.mp4", "-vf", "setpts=PTS/2", "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p", "-c:a", "aac", "d_picture_only.mp4"])
p = probe("d_picture_only.mp4")
ok = abs(p["vdur"] - 10) <= 0.15 and abs(p["adur"] - 20) <= 0.3
fails += not ok
print(f"2x picture only: video stream {p['vdur']:.3f} s (expected 10), audio stream {p['adur']:.3f} s (expected 20, unchanged), container {p['dur']:.3f} s -> {verdict(ok)}")

# --- E. pitch ----------------------------------------------------------------------------------------------------
print("\n== E. Pitch of a 440 Hz test tone (zero-crossing count, tone 12 s)")
run(FF + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=12", "-c:a", "pcm_s16le", "tone.wav"])
f0 = frequency("tone.wav")
ok = f0 is not None and abs(f0 - 440) <= 2
fails += not ok
print(f"CONTROL source tone: {f0} Hz (expected 440 +-2) -> {verdict(ok)}")
tests = [("atempo=2 (2x)", "atempo=2", 440), ("atempo=2.0,atempo=2.0 (4x, chained)", "atempo=2.0,atempo=2.0", 440),
         ("atempo=4 (4x, single)", "atempo=4", 440), ("atempo=10 (10x, single)", "atempo=10", 440),
         ("asetrate=88200,aresample=44100 (2x by resampling)", "asetrate=88200,aresample=44100", 880)]
for i, (label, flt, exp) in enumerate(tests):
    run(FF + ["-i", "tone.wav", "-af", flt, f"e_{i}.wav"])
    f = frequency(f"e_{i}.wav", skip=0.2)
    ok = f is not None and abs(f - exp) <= max(2, exp * 0.005)
    fails += not ok
    print(f"{label}: {f} Hz (expected {exp}) -> {verdict(ok)}")

# --- F. atempo range in this build -------------------------------------------------------------------------------
print("\n== F. atempo range in this build (documented range [0.5, 100.0])")
for val, should_work in [("0.5", True), ("0.4", False), ("2", True), ("4", True), ("100", True), ("101", False)]:
    r = run(["ffmpeg", "-v", "error", "-nostdin", "-y", "-i", "tone.wav", "-af", f"atempo={val}", "-t", "1", "f_test.wav"], check=False)
    worked = r.returncode == 0
    ok = worked == should_work
    fails += not ok
    print(f"atempo={val}: {'accepted' if worked else 'rejected'} (expected {'accepted' if should_work else 'rejected'}) -> {verdict(ok)}")

# --- G. sync ------------------------------------------------------------------------------------------------------
print("\n== G. Picture and sound stay together (white flash and 1 kHz beep both start at 6.0 s and last 1 s; 12 s clip)")
run(FF + ["-f", "lavfi", "-i", "color=c=black:s=320x180:r=30:d=12,drawbox=x=0:y=0:w=320:h=180:color=white:t=fill:enable='between(t,6,7)'",
          "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=44100:duration=12,volume='if(between(t,6,7),1,0)':eval=frame",
          "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "sync_in.mp4"])


def flash_onset(path):
    out = run(["ffmpeg", "-v", "error", "-nostdin", "-i", path, "-vf", "format=gray,signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-",
               "-an", "-f", "null", "-"]).stdout
    t = None
    for line in out.splitlines():
        if "pts_time:" in line:
            t = float(line.split("pts_time:")[1].split()[0])
        elif "YAVG=" in line and float(line.split("=")[1]) > 128:
            return t
    return None


def beep_onset(path):
    a = pcm(path)
    for i, v in enumerate(a):
        if abs(v) > 1000:
            return i / 44100
    return None


print("variant | speed | frames (expected) | flash starts s | beep starts s | expected s | picture late by frames | check")
for variant, fps in [("setpts only", None), ("setpts + fps=30", 30)]:
    for sp in [1, 1.5, 2, 4, 10]:
        out = f"g_{sp}{'_fps' if fps else ''}.mp4"
        speed("sync_in.mp4", out, sp, fps=fps)
        fo, bo = flash_onset(out), beep_onset(out)
        nf = probe(out)["frames"]
        exp = 6 / sp
        late = (fo - exp) * 30
        if fps:
            ok = abs(fo - exp) <= 0.02 and abs(bo - exp) <= 0.1 and abs(nf - 360 / sp) <= 1
        else:  # the plain recipe: record what it does, fail only if it is worse than 3 frames
            ok = abs(fo - exp) <= 0.1 and abs(bo - exp) <= 0.1
        fails += not ok
        print(f"{variant} | {sp}x | {nf} ({360/sp:.0f}) | {fo:.3f} | {bo:.3f} | {exp:.3f} | {late:.1f} | {verdict(ok)}")

# --- H. can the picture be sped up without re-encoding? ----------------------------------------------------------------
print("\n== H. Speeding up with a filter while copying the picture (-c:v copy)")
r = run(FF + ["-i", "in.mp4", "-vf", "setpts=PTS/2", "-c:v", "copy", "-an", "h_copy.mp4"], check=False)
msg = next((l.split("] ", 1)[-1] for l in r.stderr.splitlines() if "Filtering and streamcopy" in l), r.stderr.strip()[-160:])
ok = r.returncode != 0
fails += not ok
print(f"setpts with -c:v copy: exit code {r.returncode} (expected nonzero), message: {msg[:200]} -> {verdict(ok)}")

print(f"\nSUMMARY: {fails} failed checks")
sys.exit(1 if fails else 0)
