#!/usr/bin/env python3
"""settle time per key mark from a .mov: frame differences at 10 fps."""
import json,subprocess,sys,os
import numpy as np
name=sys.argv[1]; HERE=os.path.dirname(os.path.abspath(__file__))
mov=HERE+'/perf/%s.mov'%name; marks=json.load(open(HERE+'/perf/%s.json'%name))
W,H=160,90
p=subprocess.run(['ffmpeg','-v','error','-i',mov,'-vf','fps=20,scale=%d:%d,format=gray'%(W,H),'-f','rawvideo','-'],capture_output=True)
f=np.frombuffer(p.stdout,dtype=np.uint8).reshape(-1,H,W).astype(np.int16)
mask=np.ones((H,W),bool); mask[:12,130:]=False  # clock
d=np.abs(f[1:]-f[:-1])*mask
act=(d>6).mean(axis=(1,2))
print('frames',len(f))
for i,m in enumerate(marks):
    a=int(m*20); e=int((marks[i+1] if i+1<len(marks) else m+6)*20); seg=act[a:min(e,len(act))]
    idx=np.nonzero(seg>0.002)[0]
    first=idx[0]/20 if len(idx) else None; last=idx[-1]/20 if len(idx) else None
    print('key %d: first change %s s, settled %s s'%(i,first,last))
