"""Render the opening from chair-native.mp4 and crt-face.mp4. Requires FFmpeg and Pillow."""
import subprocess
import tempfile
from pathlib import Path

from PIL import Image, ImageDraw, ImageFilter

ROOT = Path(__file__).resolve().parent
CAMERA = ROOT / 'chair-native.mp4'
DISPLAY = ROOT / 'crt-face.mp4'
FRAMES = 80
# The original locked projection is a 184 × 180 crop at x=468,y=418.
# Its reference edge stays on the outside of the front bezel; the tube, its
# reflections, lettering and power switch are one photographed object.
SIZE = (184,180)
RIM = [(12,21),(163,9),(169,152),(14,176)]


def render():
    with tempfile.TemporaryDirectory(dir=ROOT) as folder:
        temp = Path(folder)
        alpha = Image.new('L',SIZE)
        ImageDraw.Draw(alpha).polygon(RIM,fill=255)
        alpha.filter(ImageFilter.GaussianBlur(2.2)).save(temp/'rim.png')
        # Use 80 consecutive camera exposures. The two-pixel extension brings
        # the 1918-wide source to delivery size without resampling the actor.
        # The photographed screen wakes 13 frames earlier for this performance.
        graph = ('[0:v]trim=end_frame=80,pad=1920:1080:0:0,fillborders=right=2:mode=smear[wide];'
                 '[1:v]trim=start_frame=13:end_frame=80,setpts=PTS-STARTPTS,'
                 'tpad=stop_mode=clone:stop=13[screen];'
                 '[2:v]format=gray[mask];[screen][mask]alphamerge[face];'
                 '[wide][face]overlay=468:418:format=yuv420,setsar=1[v]')
        subprocess.run(['ffmpeg','-v','error','-nostdin','-y','-i',str(CAMERA),'-i',str(DISPLAY),
                        '-loop','1','-framerate','24','-i',str(temp/'rim.png'),'-filter_complex',graph,
                        '-map','[v]','-frames:v',str(FRAMES),'-an','-c:v','libx264','-profile:v','high',
                        '-crf','10','-threads','2','-preset','medium','-pix_fmt','yuv420p','-color_primaries','bt709',
                        '-color_trc','bt709','-colorspace','bt709','-color_range','tv','-video_track_timescale',
                        '12288','-movflags','+faststart',str(temp/'chair.mp4')],check=True)
        (temp/'chair.mp4').replace(ROOT/'chair.mp4')


if __name__=='__main__':
    render()
