# Overlay each QR PNG on the clip at several widths, encode with x264 at two bitrates, decode every 5th frame.
import json, subprocess, sys, os, time
PY = os.environ.get('PY', 'python3')           # python with opencv-python-headless
JSQRLIB = os.environ.get('JSQRLIB', 'jsqr')    # path or name of the jsqr package
D = sys.argv[1]            # work dir with hoverfly.webm and qr/
QR = json.load(open(f'{D}/qr/qr-index.json'))
SIZES = [60, 90, 120, 180, 240, 360]
BR = {'1.5M': '1500k', '6M': '6000k'}
cells = []
for g, prefix in (('A-short', 'short-'), ('B-long', 'long-')):
    for e in 'LMQH':
        for w in SIZES:
            for b in BR: cells.append((g, f'{prefix}{e}', w, b))
for n in ['c-dkgray', 'c-midgray', 'c-ltgray', 'c-blue', 'c-yellow', 'c-inverted', 'short-M']:
    for b in BR: cells.append(('C-colors', n, 180, b))
for w in (120, 180, 240):
    for b in BR: cells.append(('D-margin', 'short-M-margin0', w, b))
for b in BR: cells.append(('X-control-nooverlay', None, 0, b))
os.makedirs(f'{D}/enc', exist_ok=True)
outf = open(f'{D}/results.tsv', 'w')
outf.write('group\tqr\tuser_width_px\tbitrate\tchars\tecc\tversion\tmodules\tmargin\tpx_per_module\tbytes\tcv_classic\tcv_aruco\tjsqr\tframes\n')
cmdlog = open(f'{D}/cmd-run.log', 'w')
for g, qn, w, b in cells:
    name = f'{g}_{qn}_{w}_{b}'
    out = f'{D}/enc/{name}.mp4'
    if qn:
        q = QR[qn]; exp = q['text']
        fc = f'[1:v]scale={w}:{w}:flags=bicubic[q];[0:v][q]overlay=main_w-w-60:main_h-h-60,format=yuv420p'
        cmd = ['ffmpeg', '-y', '-v', 'error', '-ss', '3', '-t', '5', '-i', f'{D}/hoverfly.webm', '-i', f'{D}/qr/{qn}.png', '-filter_complex', fc, '-an', '-c:v', 'libx264', '-preset', 'medium', '-b:v', BR[b], '-pix_fmt', 'yuv420p', out]
        ppm = w / (q['modules'] + 2 * q['margin'])
    else:
        exp = QR['short-M']['text']
        cmd = ['ffmpeg', '-y', '-v', 'error', '-ss', '3', '-t', '5', '-i', f'{D}/hoverfly.webm', '-an', '-c:v', 'libx264', '-preset', 'medium', '-b:v', BR[b], '-pix_fmt', 'yuv420p', out]
        q = {'chars': 0, 'ecc': '-', 'version': 0, 'modules': 0, 'margin': 0}; ppm = 0
    r = subprocess.run(cmd, capture_output=True, text=True)
    cmdlog.write(' '.join(cmd) + f' exit={r.returncode}\n')
    cv = subprocess.run([PY, 'decode-cv.py', out, '5', exp], capture_output=True, text=True, cwd=D).stdout.split()
    js = subprocess.run(['node', 'decode-jsqr.cjs', out, '5', exp], capture_output=True, text=True, cwd=D, env={**os.environ, 'JSQRLIB': JSQRLIB}).stdout.split()
    row = [g, qn or 'none', w, b, q['chars'], q['ecc'], q['version'], q['modules'], q['margin'], f'{ppm:.2f}', os.path.getsize(out), cv[0], cv[1], js[0], cv[2]]
    outf.write('\t'.join(map(str, row)) + '\n'); outf.flush()
    print(time.strftime('%H:%M:%S'), name, row[11:], flush=True)
