# Measures bytes per minute of the files in out/ and compares with the size formula. Control first.
import json, subprocess, sys, glob, os
W = sys.argv[1]
MIB = 1048576; GIB = 1073741824
def probe(p):
    j = json.loads(subprocess.check_output(['ffprobe','-v','error','-print_format','json','-show_format','-show_streams',p]))
    v = [s for s in j['streams'] if s['codec_type']=='video'][0]; a = [s for s in j['streams'] if s['codec_type']=='audio'][0]
    return dict(size=os.path.getsize(p), dur=float(j['format']['duration']), vk=int(v['bit_rate'])/1000, ak=int(a['bit_rate'])/1000, w=v['width'], h=v['height'], fps=v['avg_frame_rate'], codec=v['codec_name'])
def formula_bytes(vk, ak, s): return (vk+ak)*1000*s/8
# control: 1000 kbps for 60 s is exactly 7,500,000 bytes = 7.15 MiB
c = formula_bytes(1000, 0, 60); print(f'CONTROL formula 1000 kbps x 60 s = {c:.0f} bytes = {c/MIB:.2f} MiB ->', 'PASS' if c==7500000 and f'{c/MIB:.2f}'=='7.15' else 'FAIL')
tg = {'p1-1080p30-h264':10000,'p2-1080p60-h264':15000,'p3-4k30-h264':23000,'p4-4k60-h264':40000,'p5-4k30-hevc':23000}
print('file | WxH fps codec | target v kbps | measured v kbps | a kbps | bytes | dur s | MiB/min | MB(1e6)/min | GiB/h | GB(1e9)/h | formula(target+128) MiB | err% | formula(measured) MiB | err%')
for f in sorted(glob.glob(W+'/out/*.mp4')):
    n = os.path.basename(f)[:-4]; r = probe(f); per = 60/r['dur']
    mib = r['size']*per/MIB; mb = r['size']*per/1e6; gib = r['size']*3600/r['dur']/GIB; gb = r['size']*3600/r['dur']/1e9
    if n in tg:
        ft = formula_bytes(tg[n],128,r['dur']); e1 = (r['size']-ft)/ft*100
    else: ft=None; e1=None
    fm = formula_bytes(r['vk'],r['ak'],r['dur']); e2 = (r['size']-fm)/fm*100
    print(f"{n} | {r['w']}x{r['h']} {r['fps']} {r['codec']} | {tg.get(n,'CRF23')} | {r['vk']:.0f} | {r['ak']:.0f} | {r['size']} | {r['dur']:.3f} | {mib:.2f} | {mb:.2f} | {gib:.2f} | {gb:.2f} | " + (f"{ft/MIB:.2f} | {e1:+.2f}" if ft else "- | -") + f" | {fm/MIB:.2f} | {e2:+.2f}")
