#!/usr/bin/env python3
"""Koldflux: the same cadence test as test-run.py, on live-action footage: one source file converted to 24, 30 and 60 fps
with ffmpeg's fps filter. Usage: test-live.py <source> <start_s> <dur_s>. Control: the conversion to the source's own rate."""
import subprocess, sys, collections
src, ss, dur = sys.argv[1], sys.argv[2], sys.argv[3]
def hashes(vf):
    out = subprocess.run(['ffmpeg', '-v', 'error', '-ss', ss, '-t', dur, '-i', src, '-an', '-vf', vf, '-f', 'framemd5', '-'], capture_output=True, text=True, check=True).stdout
    return [l.split(',')[-1].strip() for l in out.splitlines() if l and not l.startswith('#')]
rate = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', '-of', 'csv=p=0', src], capture_output=True, text=True).stdout.strip()
base = hashes('scale=160:90,format=gray')
print(f'source {src.split("/")[-1]} at {rate} fps, excerpt start {ss} s, {dur} s: {len(base)} frames, all hashes distinct: {len(set(base)) == len(base)}')
if len(set(base)) != len(base): sys.exit('CONTROL FAILED: duplicate source frames')
idx = {h: i for i, h in enumerate(base)}
for T in ['source', 24, 30, 60]:
    vf = 'scale=160:90,format=gray' if T == 'source' else f'fps={T},scale=160:90,format=gray'
    out = hashes(vf); mapped = [idx.get(h, -1) for h in out]; holds = collections.Counter(mapped)
    kept = len([k for k in holds if k >= 0]); seq = [holds[i] for i in range(len(base))]
    print(f'-> {T}: out frames {len(out)}, unmapped {mapped.count(-1)}, source frames kept {kept} of {len(base)}, dropped {len(base) - kept} ({100 * (len(base) - kept) / len(base):.2f}%), '
          f'repeated output frames {len(out) - kept} ({100 * (len(out) - kept) / len(out):.2f}%), distinct hold lengths {sorted(set(seq))}, first 12 holds {",".join(map(str, seq[:12]))}')
