"""Crop the recorded 2x viewport to the tested environment row; hide unrelated rows.
The error state makes the row 32 CSS pixels taller. Preserve its red diagnosis.
"""
import subprocess, sys
from PIL import Image, ImageDraw
src, dest = sys.argv[1:]
width, height, fps = 846, 88, 10
reader = subprocess.Popen(['ffmpeg','-v','error','-i',src,'-vf','crop=1692:176:674:304,scale=846:88,fps=10','-f','rawvideo','-pix_fmt','rgb24','-'], stdout=subprocess.PIPE)
writer = subprocess.Popen(['ffmpeg','-v','error','-f','rawvideo','-pix_fmt','rgb24','-s','846x88','-r','10','-i','-','-an','-c:v','libx264','-crf','18','-pix_fmt','yuv420p',dest], stdin=subprocess.PIPE)
while True:
    data=reader.stdout.read(width*height*3)
    if not data:break
    if len(data)!=width*height*3:raise RuntimeError('Incomplete video frame')
    frame=Image.frombytes('RGB',(width,height),data)
    diagnosis=frame.crop((40,44,700,70))
    red=sum(1 for r,g,b in diagnosis.getdata() if r>150 and r>g*1.35 and r>b*1.2)
    if red<10:ImageDraw.Draw(frame).rectangle((0,56,width,height),fill=(255,255,255))
    writer.stdin.write(frame.tobytes())
writer.stdin.close()
if reader.wait() or writer.wait():raise RuntimeError('ffmpeg failed')
