from PIL import Image, ImageDraw, ImageFont
import subprocess, sys
from pathlib import Path
FONT=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',12)
def clean(im):
    # Detect the native error icon, so the mask follows the toast only while it exists.
    px=im.load()
    xs=[]
    for y in range(98,115):
        for x in range(880,im.width):
            r,g,b=px[x,y][:3]
            if r>150 and r-g>4 and r-b>4: xs.append(x)
    if xs:
        x=min(xs)-1
        right=min(im.width-1,x+330)
        if right>x:
            draw=ImageDraw.Draw(im)
            draw.rectangle((x,159,right,198),fill='white')
            draw.text((x+2,169),'[checkout path omitted]',font=FONT,fill='#626269')
    return im
src=Path(sys.argv[1]); dst=Path(sys.argv[2])
if src.suffix=='.png':
    clean(Image.open(src).convert('RGB')).save(dst)
else:
    dec=subprocess.Popen(['ffmpeg','-v','error','-i',str(src),'-vf','fps=10','-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE)
    enc=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1280x800','-r','5','-i','-','-an','-c:v','libx264','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(dst)],stdin=subprocess.PIPE)
    started=False
    last=None
    while True:
        frame=dec.stdout.read(1280*800*3)
        if len(frame)!=1280*800*3: break
        im=Image.frombytes('RGB',(1280,800),frame)
        if not started:
            r,g,b=im.getpixel((100,25))
            started=b>210 and r<220 and g<220
        if started:
            last=clean(im).tobytes()
            enc.stdin.write(last)
    if last:
        for _ in range(15): enc.stdin.write(last)
    enc.stdin.close(); assert enc.wait()==0; assert dec.wait()==0
