#!/usr/bin/env python3
# MP3 frame copy (what the Koldflux Cut audio tool runs) vs an exact WAV cut, plus the fade command on the tool output.
import wave, array, subprocess, random, math, statistics, os, filecmp
W = "work"; SR = 44100
LOG = open("commands-mp3.log", "w"); RES = open("test-results-mp3.txt", "w")
def out(s=""):
    print(s); RES.write(s + "\n"); RES.flush()
def run(published, args, note, shell=False):
    r = subprocess.run(args, capture_output=True, text=True, shell=shell)
    LOG.write(f"published: {published}\ncommand as run: {args if shell else ' '.join(args)}  ({note})\nexit={r.returncode}\n"); LOG.flush()
    if r.returncode: print(r.stderr[-300:])
    return r
def load(p):
    w = wave.open(p); n = w.getnframes(); a = array.array("h"); a.frombytes(w.readframes(n)); return a
def db(x): return -999.0 if x == 0 else 20 * math.log10(abs(x) / 32768)
run("ffmpeg -i source.mp3 -c:a pcm_s16le full.wav", ["ffmpeg","-y","-v","error","-i","source.mp3","-c:a","pcm_s16le",f"{W}/full.wav"], "reference decode of the whole MP3")
full = load(f"{W}/full.wav")
out(f"source.mp3: FLEURS en_us clips 01-04 (CC BY 4.0) joined, 44.1 kHz mono, libmp3lame 128 kbps; decoded {len(full)/SR:.3f} s")
random.seed(11)
starts = sorted(round(random.uniform(1.0, 27.0), 3) for _ in range(12))
rows = []
for i, s in enumerate(starts):
    e = round(s + 2.0, 3)
    mp3 = f"{W}/m-{i}.mp3"; wav = f"{W}/m-{i}.wav"; ex = f"{W}/x-{i}.wav"
    run("ffmpeg -i in.mp3 -ss START -to END -c copy cut.mp3", ["ffmpeg","-y","-v","error","-i","source.mp3","-ss",str(s),"-to",str(e),"-c","copy",mp3], f"copy cut {i}")
    run("ffmpeg -i cut.mp3 cut.wav", ["ffmpeg","-y","-v","error","-i",mp3,"-c:a","pcm_s16le",wav], f"decode copy {i}")
    run("ffmpeg -ss START -t 2 -i in.wav cut.wav", ["ffmpeg","-y","-v","error","-i",f"{W}/full.wav","-ss",str(s),"-t","2","-c:a","pcm_s16le",ex], f"exact cut of the decoded source {i}")
    a = load(wav); x = load(ex)
    # locate the copy inside the full decode using a stretch 200 ms in (frames there decode normally)
    centre = int(s*SR); best = None
    for lag in range(max(0, centre-4000), min(len(full)-12000, centre+4000)):
        d = sum(abs(a[8800+k]-full[lag+8800+k]) for k in range(0, 2000, 2))
        if best is None or d < best[0]: best = (d, lag)
    lag = best[1]; off_ms = (lag-centre)/SR*1000
    rmsfull = math.sqrt(sum(v*v for v in full[lag+9000:lag+11000])/2000)
    lead0 = next((k for k, v in enumerate(a) if v != 0), len(a))
    muted = None
    for blk in range(0, 8000, 64):
        dd = sum(abs(a[blk+k]-full[lag+blk+k]) for k in range(64))/64
        if dd < 0.05*rmsfull:
            muted = blk; break
    mad = best[0]/1000
    rows.append((s, len(a)/SR, abs(a[0]), abs(a[-1]), abs(x[0]), abs(x[-1]), off_ms, mad, lead0, muted))
    out(f"cut {i:>2}: {s:.3f}-{e:.3f} s | copy {len(a)/SR:.3f} s, first {abs(a[0])} ({db(a[0]):.1f} dBFS), last {abs(a[-1])} ({db(a[-1]):.1f}) | exact cut first {abs(x[0])} ({db(x[0]):.1f}), last {abs(x[-1])} ({db(x[-1]):.1f}) | copy starts {off_ms:+.1f} ms from the requested start, mean abs difference of the matching stretch {mad:.1f}, leading zero samples {lead0} ({lead0/SR*1000:.1f} ms), first 64-sample block that matches the full decode {muted} (None = within 8000 samples none)")
out(f"median first sample of the copies {statistics.median(r[2] for r in rows):.0f}, max {max(r[2] for r in rows)} ({db(max(r[2] for r in rows)):.1f} dBFS); exact cuts median {statistics.median(r[4] for r in rows):.0f}, max {max(r[4] for r in rows)}")
out(f"start offset of the copies: min {min(r[6] for r in rows):+.1f} ms, max {max(r[6] for r in rows):+.1f} ms (one MP3 frame is 26.1 ms)")
out(f"first 64-sample block that matches the full decode (copies): min {min(r[9] for r in rows if r[9] is not None)}, max {max(r[9] for r in rows if r[9] is not None)} samples ({min(r[9] for r in rows if r[9] is not None)/SR*1000:.1f} to {max(r[9] for r in rows if r[9] is not None)/SR*1000:.1f} ms)")
out(f"leading exact-zero samples in the copies: median {statistics.median(r[8] for r in rows):.0f}, max {max(r[8] for r in rows)}")
out(f"median length of the 2 s copies {statistics.median(r[1] for r in rows):.3f} s")
out()
# tool vs native copy
out("Koldflux Cut audio tool (live, headless Chromium) vs the native ffmpeg copy, same times")
for i in (0, 4, 8, 11):
    s = starts[i]; e = round(s + 2.0, 3)
    r = subprocess.run(["node","tool-run.cjs","source.mp3",str(s),str(e),f"{W}/t-{i}.mp3"], capture_output=True, text=True,
                       env={**os.environ, "PATH": os.environ["PATH"]})
    LOG.write(f"published: Koldflux Cut audio tool, Start {s}, End {e}\ncommand as run: node tool-run.cjs source.mp3 {s} {e} work/t-{i}.mp3\nexit={r.returncode}\n")
    md5 = lambda p: subprocess.run(["ffmpeg","-v","error","-i",p,"-map","0:a","-c","copy","-f","md5","-"],capture_output=True,text=True).stdout.strip()
    same = md5(f"{W}/t-{i}.mp3") == md5(f"{W}/m-{i}.mp3")
    ds = lambda p: subprocess.run(["ffprobe","-v","error","-show_entries","format=duration","-of","csv=p=0",p],capture_output=True,text=True).stdout.strip()
    out(f"cut {i}: tool output {os.path.getsize(f'{W}/t-{i}.mp3')} bytes, {ds(f'{W}/t-{i}.mp3')} s; native copy {os.path.getsize(f'{W}/m-{i}.mp3')} bytes, {ds(f'{W}/m-{i}.mp3')} s; audio packets identical (ffmpeg -c copy -f md5): {same}")
out()
# fade command on the tool output (reader's command), plus an edge input
FADE = 'ffmpeg -y -v error -i @IN@ -af "afade=t=in:d=0.01,areverse,afade=t=in:d=0.01,areverse" @OUT@'
OLDFADE = 'D=$(ffprobe -v error -show_entries format=duration -of csv=p=0 @IN@); ffmpeg -y -v error -i @IN@ -af "afade=t=in:d=0.01,afade=t=out:st=$(awk -v d=$D \'BEGIN{printf "%.4f", d-0.01}\'):d=0.01" @OUT@'
out("Fade command on tool output and an edge input")
out(f"ffprobe duration of t-0.mp3 {subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',f'{W}/t-0.mp3'],capture_output=True,text=True).stdout.strip()} s; decoded length {len(load(f'{W}/t-0-dec.wav'))/SR:.4f} s" if subprocess.run(['ffmpeg','-y','-v','error','-i',f'{W}/t-0.mp3','-c:a','pcm_s16le',f'{W}/t-0-dec.wav']).returncode==0 else "decode failed")
r = run("fade with a start time taken from the ffprobe duration (the first version, NOT published)", ["bash","-c",OLDFADE.replace("@IN@",f"{W}/t-0.mp3").replace("@OUT@",f"{W}/t-0-oldfade.mp3")], "old fade-out by start time on the MP3")
subprocess.run(["ffmpeg","-y","-v","error","-i",f"{W}/t-0-oldfade.mp3","-c:a","pcm_s16le",f"{W}/chk.wav"]); a_=load(f"{W}/chk.wav")
out(f"start-time fade-out on the MP3 tool output: last decoded sample {abs(a_[-1])} ({db(a_[-1]):.1f} dBFS) - the fade-out missed the end")
for name, inp, o in (("tool output t-0.mp3", f"{W}/t-0.mp3", f"{W}/t-0-faded.mp3"), ("tool output t-8.mp3", f"{W}/t-8.mp3", f"{W}/t-8-faded.mp3"),
                     ("edge: 0.5 s WAV clip", f"{W}/s-plain-3.wav", f"{W}/edge-faded.wav"), ("edge: 0.03 s WAV (longer than the two 10 ms fades, 0.02 s; the shorter 5 ms edge is in test-results-edge.txt)", f"{W}/short.wav", f"{W}/short-faded.wav")):
    if name.startswith("edge: 0.03"):
        run("ffmpeg -ss 1 -t 0.03 -i clip.wav short.wav", ["ffmpeg","-y","-v","error","-ss","1","-t","0.03","-i","clip03.wav",inp], "build 0.03 s edge input")
    cmd = FADE.replace("@IN@", inp).replace("@OUT@", o)
    r = run("fade command (see page)", ["bash","-c",cmd], name)
    dec = f"{W}/chk.wav"
    subprocess.run(["ffmpeg","-y","-v","error","-i",o,"-c:a","pcm_s16le",dec])
    a = load(dec)
    out(f"{name}: exit={r.returncode}, output first {abs(a[0])} ({db(a[0]):.1f} dBFS), last {abs(a[-1])} ({db(a[-1]):.1f} dBFS), {len(a)} samples")
LOG.close(); RES.close()
