#!/usr/bin/env python3
# Boundary-step test for cut audio. Stdlib only. Writes commands.log and test-results.txt
import wave, array, subprocess, random, math, statistics
SR = 16000
W = "work"
LOG = open("commands.log", "w")
RES = open("test-results.txt", "w")
def out(s=""):
    print(s); RES.write(s + "\n"); RES.flush()
def run(published, args, note):
    r = subprocess.run(args, capture_output=True, text=True)
    LOG.write(f"published: {published}\ncommand as run: {' '.join(args)}  ({note})\nexit={r.returncode}\n"); LOG.flush()
    if r.returncode: print(r.stderr[-400:])
    return r.returncode
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)
def maxstep(a, lo=0, hi=None):
    hi = len(a) if hi is None else hi
    return max(abs(a[i] - a[i - 1]) for i in range(max(lo, 1), min(hi, len(a))))
def rms(a): return math.sqrt(sum(x*x for x in a)/len(a))
# ---------- A. control: 400 Hz sine, amplitude 0.5, one period = 40 samples exactly
run("ffmpeg -f lavfi -i sine=f=400:d=1:r=16000 -af volume=4 sine.wav", ["ffmpeg","-y","-v","error","-f","lavfi","-i","sine=f=400:d=1:r=16000","-af","volume=4","-c:a","pcm_s16le",f"{W}/sine.wav"], "control source: sine default amplitude 0.125 x4 = 0.5")
sine = load(f"{W}/sine.wav")
out("A. CONTROL: 400 Hz sine, amplitude 0.5 (period 40 samples at 16 kHz)")
out(f"source sample 10 = {sine[10]} (expected about 16384 = 0.5 of full scale), sample 0 = {sine[0]}, sample 20 = {sine[20]}")
for name, n0 in (("cut at wave peak (sample 10)", 10), ("cut at zero crossing (sample 20)", 20)):
    p = f"{W}/ctl-{n0}.wav"
    run("ffmpeg -ss START -t 0.1 -i in.wav out.wav", ["ffmpeg","-y","-v","error","-ss",f"{n0/SR:.7f}","-t","0.1","-i",f"{W}/sine.wav",p], name)
    a = load(p)
    out(f"{name}: first sample {a[0]} ({db(a[0]):.1f} dBFS), source sample there {sine[n0]}, match={a[0]==sine[n0]}")
a = load(f"{W}/ctl-10.wav")
run("ffmpeg -i in.wav -af afade=t=in:d=0.01 out.wav", ["ffmpeg","-y","-v","error","-i",f"{W}/ctl-10.wav","-af","afade=t=in:d=0.01",f"{W}/ctl-10f.wav"], "control with 10 ms fade-in")
f = load(f"{W}/ctl-10f.wav")
out(f"peak cut + 10 ms fade-in: first sample {f[0]}, largest step in the first 20 ms {maxstep(f,0,320)} (plain peak cut: largest step in the first 20 ms {maxstep(a,0,320)}, jump from silence {abs(a[0])})")
out()
# ---------- B. speech
src = load("clip03.wav")
smax = maxstep(src); steps = sorted(abs(src[i]-src[i-1]) for i in range(1,len(src)))
p99 = steps[int(len(steps)*0.99)]
peak = max(abs(x) for x in src)
out(f"B. SPEECH: clip03.wav FLEURS en_us (CC BY 4.0), {len(src)/SR:.3f} s, 16 kHz mono")
out(f"source: largest sample-to-sample step {smax} ({db(smax):.1f} dBFS), 99th percentile step {p99} ({db(p99):.1f} dBFS), peak {peak} ({db(peak):.1f} dBFS)")
random.seed(7)
D = 0.5; NS = int(D*SR)
starts = sorted(random.randrange(int(0.3*SR), len(src)-NS-int(0.3*SR)) for _ in range(50))
def zc(n):
    for k in range(0, 400):
        for m in (n-k, n+k):
            if 1 <= m < len(src) and ((src[m-1] < 0) != (src[m] < 0) or src[m] == 0):
                return m
    return n
FADE = "afade=t=in:d=0.01,areverse,afade=t=in:d=0.01,areverse"
res = {"plain":[], "zerocross":[], "fade10":[]}
for i, n in enumerate(starts):
    for v in res:
        nn = zc(n) if v == "zerocross" else n
        ne = zc(n+NS) if v == "zerocross" else n+NS
        p = f"{W}/s-{v}-{i}.wav"
        args = ["ffmpeg","-y","-v","error","-ss",f"{nn/SR:.7f}","-t",f"{(ne-nn)/SR:.7f}" if v == "zerocross" else str(D),"-i","clip03.wav"]
        if v == "fade10": args += ["-af", FADE]
        run("ffmpeg -ss START -t 0.5 -i clip.wav [-af \"%s\"] cut.wav" % FADE, args+[p], f"speech cut {i} {v}")
        a = load(p)
        ok = (a[0] == src[nn]) if v != "fade10" else (a[0] == 0)
        ok = ok and (v != "zerocross" or a[-1] == src[ne-1])
        res[v].append((abs(a[0]), abs(a[-1]), len(a), ok))
out("50 seeded start points, 0.5 s cuts. 'Step from silence' = |first sample| and |last sample|. Control (first sample equals the source sample, or 0 when faded) true for: " + ", ".join(f"{v} {sum(1 for r in res[v] if r[3])}/50" for v in res))
for v, rr in res.items():
    f_ = [r[0] for r in rr]; l_ = [r[1] for r in rr]
    over = sum(1 for r in rr if max(r[0], r[1]) > smax)
    over99 = sum(1 for r in rr if max(r[0], r[1]) > p99)
    out(f"{v:<9} median first {statistics.median(f_):.0f} ({db(statistics.median(f_)):.1f} dBFS), max first {max(f_)} ({db(max(f_)):.1f}); median last {statistics.median(l_):.0f} ({db(statistics.median(l_)):.1f}), max last {max(l_)} ({db(max(l_)):.1f}); cuts with a boundary step above the source's largest step {over}/50, above its 99th percentile {over99}/50")
out(f"cut lengths in samples: {sorted(set(r[2] for rr in res.values() for r in rr))} (expected {NS}; zero-crossing cuts differ by up to a few ms because both ends moved)")
out()
# ---------- C. fade length sweep
out("C. FADE LENGTH: same 50 cuts, fade in and out of equal length; energy change = RMS of faded cut vs plain cut, median")
plain = [load(f"{W}/s-plain-{i}.wav") for i in range(50)]
for ms in (1, 2, 5, 10, 20, 50, 100):
    d = ms/1000; fs = []; firsts = []; loss = []
    for i, n in enumerate(starts):
        p = f"{W}/f-{ms}-{i}.wav"
        run("ffmpeg -ss START -t 0.5 -i clip.wav -af \"afade=t=in:d=D,areverse,afade=t=in:d=D,areverse\" cut.wav",
            ["ffmpeg","-y","-v","error","-ss",f"{n/SR:.7f}","-t",str(D),"-i","clip03.wav","-af",f"afade=t=in:d={d},areverse,afade=t=in:d={d},areverse",p], f"fade {ms} ms cut {i}")
        a = load(p); firsts.append(abs(a[0]))
        fs.append(max(max(abs(x) for x in a[:16]), max(abs(x) for x in a[-16:])))
        loss.append(20*math.log10(rms(a)/rms(plain[i])))
    out(f"fade {ms:>3} ms: median first sample {statistics.median(firsts):.0f}, median of the peak level within the first and last 1 ms {statistics.median(fs):.0f} (max {max(fs)}), energy change {statistics.median(loss):.2f} dB")
pf = [max(max(abs(x) for x in a[:16]), max(abs(x) for x in a[-16:])) for a in plain]
out(f"no fade    : median of the peak level within the first and last 1 ms {statistics.median(pf):.0f} (max {max(pf)})")
out()
# ---------- D. splice
out("D. SPLICE: join cut i to cut i+25 with ffmpeg concat; step at the join = |first sample of B - last sample of A|, read from the joined file")
for v in ("plain", "fade10"):
    st = []
    for i in range(25):
        a, b = starts[i], starts[i+25]
        pa = f"{W}/j-{v}-{i}.wav"
        if v == "plain":
            fc = "[0:a]atrim=0:%s[a];[1:a]atrim=0:%s[b];[a][b]concat=n=2:v=0:a=1" % (D, D)
        else:
            fc = "[0:a]atrim=0:%s,areverse,afade=t=in:d=0.01,areverse[a];[1:a]atrim=0:%s,afade=t=in:d=0.01[b];[a][b]concat=n=2:v=0:a=1" % (D, D)
        run("ffmpeg -ss A -t 0.5 -i clip.wav -ss B -t 0.5 -i clip.wav -filter_complex \"concat\" joined.wav",
            ["ffmpeg","-y","-v","error","-ss",f"{a/SR:.7f}","-t",str(D),"-i","clip03.wav","-ss",f"{b/SR:.7f}","-t",str(D),"-i","clip03.wav","-filter_complex",fc,pa], f"splice {v} {i}")
        j = load(pa)
        st.append(abs(j[NS]-j[NS-1]))
    out(f"{v:<7}: median step at the join {statistics.median(st):.0f} ({db(statistics.median(st)):.1f} dBFS), max {max(st)} ({db(max(st)):.1f}), joins above the source's largest step ({smax}): {sum(1 for x in st if x>smax)}/25")
LOG.close(); RES.close()
