#!/usr/bin/env python3
"""Koldflux, 2026-11-01. File-side checks for the guide "No sound on LinkedIn videos".
Needs ffmpeg and ffprobe 6.1.1 and python3 (standard library only). Builds its own synthetic files (test pattern and a 440 Hz sine; no third-party material).
Run: python3 li_audio_test.py   (writes fixtures into ./fixtures and prints PASS or FAIL per check)."""
import json, math, os, re, subprocess, sys

FF = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"]
os.makedirs("fixtures", exist_ok=True)
os.chdir("fixtures")
fails = []

def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True)
    return r

def need(cmd):
    r = run(cmd)
    if r.returncode != 0:
        print("COMMAND FAILED:", " ".join(cmd), r.stderr[-400:]); sys.exit(1)
    return r

def verdict(ok, label=""):
    if not ok: fails.append(label)
    return "PASS" if ok else "FAIL"

def probe_audio(f):
    """The exact command printed on the page."""
    r = need(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=codec_name,channels,sample_rate", "-of", "csv=p=0", f])
    return [l for l in r.stdout.strip().splitlines() if l]

def level(f, stream=None):
    """mean and max volume (dB) of one audio stream, by volumedetect."""
    m = ["-map", f"0:a:{stream}"] if stream is not None else []
    r = run(["ffmpeg", "-hide_banner", "-i", f] + m + ["-af", "volumedetect", "-vn", "-f", "null", "-"])
    mean = re.search(r"mean_volume: (-?[\d.inf]+) dB", r.stderr); mx = re.search(r"max_volume: (-?[\d.inf]+) dB", r.stderr)
    return (float(mean.group(1)) if mean else None, float(mx.group(1)) if mx else None)

def vmd5(f):
    """md5 of the copied picture packets of the first video stream."""
    r = need(["ffmpeg", "-hide_banner", "-loglevel", "error", "-i", f, "-map", "0:v:0", "-c", "copy", "-f", "md5", "-"])
    return r.stdout.strip()

def info(f):
    r = need(["ffprobe", "-v", "error", "-show_entries", "stream=index,codec_type,codec_name,channels,sample_rate:format=duration", "-of", "json", f])
    return json.loads(r.stdout)

V = ["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=6"]
SINE = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=6"]
SIL = ["-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo"]
ENC = ["-c:v", "libx264", "-crf", "23", "-pix_fmt", "yuv420p"]

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

# ---- fixtures
need(FF + V + SINE + ENC + ["-c:a", "pcm_s16le", "-shortest", "tone_pcm.mov"])
need(FF + V + SINE + ENC + ["-c:a", "ac3", "-shortest", "tone_ac3.mp4"])
need(FF + V + SINE + ENC + ["-c:a", "aac", "-shortest", "tone_aac.mp4"])
need(FF + V + ENC + ["-an", "no_audio.mp4"])
need(FF + V + SIL + ENC + ["-c:a", "aac", "-t", "6", "silent_track.mp4"])
need(FF + V + SIL + SINE + ENC + ["-map", "0:v", "-map", "1:a", "-map", "2:a", "-c:a", "aac", "-t", "6", "two_tracks_empty_first.mp4"])

print("\n== A. Known-answer control: level of a 440 Hz sine made at amplitude 1/8")
peak = 20 * math.log10(1 / 8); rms = peak - 20 * math.log10(math.sqrt(2))
mean, mx = level("tone_aac.mp4")
print(f"expected peak {peak:.1f} dB and RMS {rms:.1f} dB; measured max {mx} dB, mean {mean} dB (AAC coding adds a little error; tolerance 0.6 dB) -> {verdict(abs(mx-peak)<0.6 and abs(mean-rms)<0.6, 'A control')}")
m2, x2 = level("silent_track.mp4")
print(f"silent track measured mean {m2} dB, max {x2} dB (expected at or below -90 dB) -> {verdict(m2 is not None and m2 <= -90 or m2 is None, 'A silent')}")

print("\n== B. The ffprobe check printed on the page: ffprobe -v error -select_streams a -show_entries stream=codec_name,channels,sample_rate -of csv=p=0 <file>")
exp = {"tone_pcm.mov": 1, "tone_ac3.mp4": 1, "tone_aac.mp4": 1, "no_audio.mp4": 0, "silent_track.mp4": 1, "two_tracks_empty_first.mp4": 2}
for f, n in exp.items():
    out = probe_audio(f)
    print(f"{f}: {len(out)} line(s) {out} (expected {n}) -> {verdict(len(out)==n, 'B '+f)}")
print("NOTE: a file with a silent audio track prints a line, so this check shows that a track exists, not that it carries sound (section C).")

print("\n== C. Level per audio track (volumedetect), the check that tells a silent track from a loud one")
for f in ["tone_pcm.mov", "tone_ac3.mp4", "silent_track.mp4"]:
    m, x = level(f, 0); print(f"{f} track 0: mean {m} dB, max {x} dB")
for i in (0, 1):
    m, x = level("two_tracks_empty_first.mp4", i); print(f"two_tracks_empty_first.mp4 track {i}: mean {m} dB, max {x} dB")
t0 = level("two_tracks_empty_first.mp4", 0)[1]; t1 = level("two_tracks_empty_first.mp4", 1)[1]
print(f"track 0 is silent and track 1 is loud -> {verdict(t0 <= -90 and t1 > -30, 'C two tracks')}")

print("\n== D. The audio-only re-encode printed on the page: -map 0:v:0 -map 0:a:0 -c:v copy -c:a aac -b:a 160k -ac 2 -ar 48000")
need(FF + V + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=6", "-ac", "2"] + ENC + ["-c:a", "pcm_s16le", "-shortest", "tone_pcm_stereo.mov"])
def fix(src, dst, atrack=0, ac="2"):
    need(FF + ["-i", src, "-map", "0:v:0", "-map", f"0:a:{atrack}", "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-ac", ac, "-ar", "48000", dst])
# the mono sources are expected to lose about 3 dB per channel when -ac 2 upmixes them; the stereo source should not change
for src, dst, expect_change in [("tone_pcm.mov", "fixed_pcm.mp4", -3.0), ("tone_ac3.mp4", "fixed_ac3.mp4", -3.0), ("tone_pcm_stereo.mov", "fixed_pcm_stereo.mp4", 0.0)]:
    fix(src, dst)
    a = [s for s in info(dst)["streams"] if s["codec_type"] == "audio"][0]
    v = [s for s in info(dst)["streams"] if s["codec_type"] == "video"][0]
    src_ch = [s for s in info(src)["streams"] if s["codec_type"] == "audio"][0]["channels"]
    same = vmd5(src) == vmd5(dst)
    ls = level(src, 0)[1]; lf = level(dst, 0)[1]
    d_src = float(info(src)["format"]["duration"]); d_dst = float(info(dst)["format"]["duration"])
    print(f"{src} ({src_ch} channel) -> {dst}: audio {a['codec_name']}, {a['channels']} channels, {a['sample_rate']} Hz; video {v['codec_name']}; picture packets identical to source: {same}; max level {ls} dB -> {lf} dB (change {lf-ls:+.1f} dB, expected about {expect_change:+.1f}); length {d_src:.3f} s -> {d_dst:.3f} s")
    ok = a["codec_name"] == "aac" and a["channels"] == 2 and a["sample_rate"] == "48000" and same and abs((lf - ls) - expect_change) < 0.8 and abs(d_src - d_dst) < 0.1
    print(f"  checks (aac, 2 ch, 48000 Hz, picture unchanged, level change as expected within 0.8 dB, length within 0.1 s) -> {verdict(ok, 'D '+src)}")
fix("tone_pcm.mov", "fixed_pcm_mono.mp4", 0, "1")
a = [s for s in info("fixed_pcm_mono.mp4")["streams"] if s["codec_type"] == "audio"][0]
ls = level("tone_pcm.mov", 0)[1]; lf = level("fixed_pcm_mono.mp4", 0)[1]
print(f"tone_pcm.mov with -ac 1 instead of -ac 2: {a['channels']} channel, max level {ls} dB -> {lf} dB (change {lf-ls:+.1f} dB) -> {verdict(a['channels'] == 1 and abs(lf - ls) < 0.8, 'D mono')}")
print("NOTE: -ac 2 on a one-channel source puts it on both channels at about 3 dB lower each (the figure above). Leave -ac 2 out to keep a mono source mono.")

print("\n== E. The same command on the file whose first audio track is empty")
fix("two_tracks_empty_first.mp4", "fixed_two_first.mp4", 0)
m, x = level("fixed_two_first.mp4", 0)
print(f"-map 0:a:0 keeps track 0: output max level {x} dB -> still silent -> {verdict(x <= -90, 'E first')}")
fix("two_tracks_empty_first.mp4", "fixed_two_second.mp4", 1)
m, x = level("fixed_two_second.mp4", 0)
print(f"-map 0:a:1 keeps track 1: output max level {x} dB -> sound present -> {verdict(x > -30, 'E second')}")
print("CONCLUSION: -map 0:a:0 does not rescue a file whose first track is empty; choose the loud track by number.")

print("\n== F. Remove an empty track and keep the other one without re-encoding the sound: -map 0:v:0 -map 0:a:1 -c copy")
need(FF + ["-i", "two_tracks_empty_first.mp4", "-map", "0:v:0", "-map", "0:a:1", "-c", "copy", "copy_second.mp4"])
n = len(probe_audio("copy_second.mp4")); x = level("copy_second.mp4", 0)[1]
print(f"output has {n} audio track, max level {x} dB -> {verdict(n == 1 and x > -30, 'F')}")

print("\nSUMMARY:", len(fails), "failed checks", fails if fails else "")
