# -*- coding: utf-8 -*-
"""Green-artifact cleanup per shot, then concat."""
import subprocess, sys, os
import numpy as np
from green_fix import fix

SHOTS=['s1','s2','s3','s4','s5','s6']
W,H=1440,800

def clean(src,dst):
    vf=f"scale={W}:{H},format=rgb24"
    p_in=subprocess.Popen(['ffmpeg','-v','error','-i',src,'-vf',vf,'-f','rawvideo','-pix_fmt','rgb24','-'],
                          stdout=subprocess.PIPE)
    p_out=subprocess.Popen(['ffmpeg','-y','-v','error','-f','rawvideo','-pix_fmt','rgb24','-s',f'{W}x{H}','-r','24','-i','-',
                            '-i',src,'-map','0:v','-map','1:a','-c:v','libx264','-crf','16','-preset','medium',
                            '-pix_fmt','yuv420p','-r','24','-c:a','aac','-b:a','192k','-shortest',dst],
                           stdin=subprocess.PIPE)
    n=0
    while True:
        buf=p_in.stdout.read(W*H*3)
        if len(buf)<W*H*3: break
        arr=np.frombuffer(buf,dtype=np.uint8).reshape(H,W,3)
        out=fix(arr)
        p_out.stdin.write(out.tobytes())
        n+=1
    p_in.stdout.close(); p_in.wait()
    p_out.stdin.close(); p_out.wait()
    print(f"  {src} -> {dst} frames={n}", flush=True)

if __name__=='__main__':
    for s in SHOTS:
        if os.path.exists(f'shot_{s}.mp4'):
            clean(f'shot_{s}.mp4', f'clean_{s}.mp4')
