#!/usr/bin/env python3
"""split-video-into-parts test. Usage: python3 test-run.py <workdir>   Needs ffmpeg 6.x + ffprobe. Writes test-results.txt lines to stdout."""
import json, math, os, subprocess, sys
W = sys.argv[1]; os.makedirs(W, exist_ok=True); os.chdir(W)
def sh(cmd):
    r = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if r.returncode: print("CMD FAIL", cmd, r.stderr[-400:]); sys.exit(1)
    return r.stdout
def probe(f):
    """video/audio stream start, end (last pts+dur), frames from packets"""
    out = {}
    for t, s in (("v", "v:0"), ("a", "a:0")):
        j = json.loads(sh(f'ffprobe -v error -select_streams {s} -show_entries packet=pts_time,duration_time,flags -of json "{f}"'))
        pk = [p for p in j["packets"] if "pts_time" in p]
        if not pk: out[t] = dict(start=0, end=0, dur=0, n=0, key=[]); continue
        ts = [float(p["pts_time"]) for p in pk]
        end = max(float(p["pts_time"]) + float(p.get("duration_time", 0)) for p in pk)
        out[t] = dict(start=min(ts), end=end, dur=end - min(ts), n=len(pk), key=[float(p["pts_time"]) for p in pk if "K" in p["flags"]])
    out["size"] = os.path.getsize(f)
    return out
def line(*a): print(*a, flush=True)
FPS = 25; TOTAL = 148; N = 4; PART = TOTAL / N
line(f"# split-video-into-parts test, ffmpeg: {sh('ffmpeg -version').splitlines()[0]}")
# sources
sh(f'ffmpeg -y -v error -f lavfi -i testsrc2=size=640x360:rate={FPS}:duration={TOTAL} -f lavfi -i sine=frequency=440:sample_rate=44100:duration={TOTAL} -c:v libx264 -preset veryfast -b:v 1200k -pix_fmt yuv420p -c:a aac -b:a 96k -shortest srcA.mp4')
pa = probe("srcA.mp4")
line(f"srcA: video {pa['v']['n']} frames, {pa['v']['dur']:.3f} s, audio {pa['a']['dur']:.3f} s, size {pa['size']} B, keyframes at {[round(k,2) for k in pa['v']['key']]}")
line(f"control 1: expected frames {TOTAL*FPS}, got {pa['v']['n']} -> {'OK' if pa['v']['n']==TOTAL*FPS else 'FAILED'}")
# Method A: stream copy, segment muxer
def parts(prefix): return sorted(f for f in os.listdir('.') if f.startswith(prefix) and f.endswith('.mp4'))
def report(label, files, want, skip_last=False):
    line(f"## {label} (requested {want:g} s parts)")
    line("part | video s | audio s | frames | video start s")
    tot = 0; maxerr = 0
    for i, f in enumerate(files):
        p = probe(f); tot += p['v']['n']
        if not (skip_last and i == len(files) - 1): maxerr = max(maxerr, abs(p['v']['dur'] - want))
        line(f"{i+1} | {p['v']['dur']:.3f} | {p['a']['dur']:.3f} | {p['v']['n']} | {p['v']['start']:.3f}")
    line(f"parts {len(files)}, frames in all parts {tot} (source {pa['v']['n']}), worst video-length error {maxerr:.3f} s{' (last part is the 28 s remainder, not counted)' if skip_last else ''}")
    return maxerr
# control 2: 40 s parts sit on keyframes (10 s GOP), copy must be exact
sh('ffmpeg -y -v error -i srcA.mp4 -c copy -f segment -segment_time 40 -reset_timestamps 1 ctlA_%02d.mp4')
e = report("control: stream copy at 40 s (a multiple of the 10 s keyframe spacing)", parts('ctlA_'), 40, True)
line(f"control 2: worst error {e:.3f} s -> {'OK (<0.1 s)' if e<0.1 else 'FAILED'}")
sh(f'ffmpeg -y -v error -i srcA.mp4 -c copy -f segment -segment_time {PART:g} -reset_timestamps 1 cpA_%02d.mp4')
report(f"A stream copy, segment_time {PART:g}", parts('cpA_'), PART)
sh(f'ffmpeg -y -v error -i srcA.mp4 -c:v libx264 -preset veryfast -b:v 1200k -pix_fmt yuv420p -force_key_frames "expr:gte(t,n_forced*{PART:g})" -c:a aac -b:a 96k -f segment -segment_time {PART:g} -reset_timestamps 1 reA_%02d.mp4')
report(f"B re-encode with forced keyframes, segment_time {PART:g}", parts('reA_'), PART)
for i in range(N):
    sh(f'ffmpeg -y -v error -i srcA.mp4 -ss {i*PART:g} -to {(i+1)*PART:g} -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p -c:a aac -b:a 96k tmA_{i+1:02d}.mp4')
report("C one trim per part (-ss/-to after -i, re-encode, same command shape as the Koldflux Trim tool)", parts('tmA_'), PART)
# size cap on a source whose complexity changes: 74 s test pattern + 74 s mandelbrot, CRF 23
sh(f'ffmpeg -y -v error -f lavfi -i testsrc2=size=640x360:rate={FPS}:duration=74 -f lavfi -i mandelbrot=size=640x360:rate={FPS} -t 74 -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -f lavfi -i sine=frequency=440:sample_rate=44100:duration=148 -map 2:a -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p -g 25 -c:a aac -b:a 96k -shortest srcB.mp4' ) if False else None
sh(f'ffmpeg -y -v error -f lavfi -i testsrc2=size=640x360:rate={FPS}:duration=74 -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p -g 25 -an b1.mp4')
sh(f'ffmpeg -y -v error -f lavfi -i mandelbrot=size=640x360:rate={FPS} -t 74 -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p -g 25 -an b2.mp4')
open('l.txt','w').write("file 'b1.mp4'\nfile 'b2.mp4'\n")
sh('ffmpeg -y -v error -f concat -i l.txt -c copy bv.mp4')
sh(f'ffmpeg -y -v error -i bv.mp4 -f lavfi -i sine=frequency=440:sample_rate=44100:duration={TOTAL} -map 0:v -map 1:a -c:v copy -c:a aac -b:a 96k -shortest srcB.mp4')
pb = probe("srcB.mp4")
dur = pb['v']['dur']; avg = pb['size']*8/dur
LIM = 10_000_000  # bytes, a stand-in for an upload cap
line(f"## size cap on srcB (CRF 23, 1 s keyframes: 74 s test pattern then 74 s mandelbrot)")
line(f"srcB: {dur:.3f} s, {pb['size']} B, average {avg/1000:.1f} kbit/s; cap {LIM} B")
sec_avg = math.floor(LIM*0.9*8/avg)
line(f"naive length from the average with 10% margin: floor({LIM}*0.9*8/{avg:.0f}) = {sec_avg} s")
sh(f'ffmpeg -y -v error -i srcB.mp4 -c copy -f segment -segment_time {sec_avg} -reset_timestamps 1 szB_%02d.mp4')
fs = parts('szB_'); sizes = [os.path.getsize(f) for f in fs]
line("part | size B | over cap?")
for i, s in enumerate(sizes): line(f"{i+1} | {s} | {'OVER' if s>LIM else 'ok'}")
line(f"{len(fs)} parts, largest {max(sizes)} B = {max(sizes)/LIM*100:.0f}% of cap, smallest {min(sizes)} B; {sum(1 for s in sizes if s>LIM)} over the cap")
# bitrate per half, to explain
for name, f in (("first half (test pattern)", "b1.mp4"), ("second half (mandelbrot)", "b2.mp4")):
    p = probe(f); line(f"{name}: {p['size']*8/p['v']['dur']/1000:.1f} kbit/s")
# fix: length from the busiest stretch instead of the average
peak = max(probe("b1.mp4")['size']*8/74, probe("b2.mp4")['size']*8/74)
sec_peak = math.floor(LIM*0.9*8/peak)
line(f"length from the busiest half ({peak/1000:.1f} kbit/s) with 10% margin: floor({LIM}*0.9*8/{peak:.0f}) = {sec_peak} s")
sh(f'ffmpeg -y -v error -i srcB.mp4 -c copy -f segment -segment_time {sec_peak} -reset_timestamps 1 pkB_%02d.mp4')
fs = parts('pkB_'); sizes = [os.path.getsize(f) for f in fs]
line(f"{len(fs)} parts, largest {max(sizes)} B = {max(sizes)/LIM*100:.0f}% of cap, smallest {min(sizes)} B; {sum(1 for s in sizes if s>LIM)} over the cap")
# fix 2: cut by bytes. Add one keyframe-to-keyframe stretch at a time until the next one would pass 97% of the cap
j = json.loads(sh('ffprobe -v error -show_entries packet=stream_index,pts_time,size,flags -of json srcB.mp4'))
pk = sorted((float(p["pts_time"]), int(p["size"]), "K" in p["flags"] and p["stream_index"] == 0) for p in j["packets"] if "pts_time" in p)
keys = [t for t, sz, k in pk if k]
def bytes_between(a, b): return sum(sz for t, sz, k in pk if a <= t < b)
cuts = []; start = 0.0
for i in range(1, len(keys)):
    if bytes_between(start, keys[i] + (keys[i+1] - keys[i] if i + 1 < len(keys) else 1)) > LIM * 0.97 and keys[i] > start:
        cuts.append(keys[i]); start = keys[i]
line(f"byte-based cut points (keyframes): {[round(c,2) for c in cuts]}")
sh(f'ffmpeg -y -v error -i srcB.mp4 -c copy -f segment -segment_times {",".join(str(c) for c in cuts)} -reset_timestamps 1 byB_%02d.mp4')
fs = parts('byB_'); sizes = [os.path.getsize(f) for f in fs]
line(f"{len(fs)} parts, largest {max(sizes)} B = {max(sizes)/LIM*100:.0f}% of cap, smallest {min(sizes)} B; {sum(1 for s in sizes if s>LIM)} over the cap")
line("part | size B")
for i, s in enumerate(sizes): line(f"{i+1} | {s}")
line("done")
