import json, subprocess, sys
from PIL import Image, ImageDraw
source, target = sys.argv[1:]
info=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=width,height,r_frame_rate','-of','json',source]))['streams'][0]
w,h=info['width'],info['height']; fps=info['r_frame_rate']; size=w*h*3
reader=subprocess.Popen(['ffmpeg','-v','error','-i',source,'-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE)
writer=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{w}x{h}','-r',fps,'-i','-','-an','-c:v','libx264','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',target],stdin=subprocess.PIPE)
frames=masked=0
while True:
 data=reader.stdout.read(size)
 if not data: break
 if len(data)!=size: raise RuntimeError('short frame')
 im=Image.frombytes('RGB',(w,h),data)
 # Only redact the unrelated authentication notice, when its red border is present.
 pixels=im.load()
 red=sum(1 for x in range(300,min(950,w),8) if (lambda c:c[0]>200 and 65<c[1]<215 and 65<c[2]<215 and c[0]>c[1]*1.15)(pixels[x,64]))
 if red>20:
  ImageDraw.Draw(im).rectangle((271,63,987,207),fill=(250,250,250)); masked+=1
 writer.stdin.write(im.tobytes()); frames+=1
reader.stdout.close(); reader.wait(); writer.stdin.close(); writer.wait()
if reader.returncode or writer.returncode: raise RuntimeError('ffmpeg failed')
print(json.dumps({'frames':frames,'redactedAuthenticationNoticeFrames':masked,'width':w,'height':h}))
