"""Rebuild the two localized performance finishes and their decoded comparison.

Run with Python 3, NumPy, Pillow and OpenCV. FFmpeg and ffprobe must be on PATH.
The plan stores all landmark positions relative to their corresponding crop.
"""
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parent
PLAN = json.loads((ROOT / 'performance-plan.json').read_text())
BASE = ROOT / PLAN['baseline']
SIZE = tuple(PLAN['nativeSize'])
FPS = PLAN['fps']


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def decoded(path, first, count, box=None):
    vf = []
    w, h = SIZE
    if box:
        x, y, right, bottom = box
        w, h = right - x, bottom - y
        vf = ['-vf', f'crop={w}:{h}:{x}:{y}']
    cmd = ['ffmpeg', '-nostdin', '-v', 'error', '-ss', f'{first/FPS:.9f}', '-i', path,
           '-frames:v', str(count), *vf, '-an', '-pix_fmt', 'rgb24', '-f', 'rawvideo', 'pipe:1']
    with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
        for _ in range(count):
            data = proc.stdout.read(w*h*3)
            if len(data) != w*h*3:
                raise ValueError(f'Truncated frame in {path.name}')
            yield np.frombuffer(data, np.uint8).reshape(h, w, 3)
        if proc.wait():
            raise RuntimeError(f'Could not decode {path.name}')


def encode(path, frames, size=SIZE, crf=12):
    cmd = ['ffmpeg', '-v', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s',
           f'{size[0]}x{size[1]}', '-framerate', str(FPS), '-i', 'pipe:0', '-an',
           '-vf', 'scale=out_color_matrix=bt709:out_range=tv,format=yuv420p,setsar=1,'
           'setparams=range=limited:color_primaries=bt709:color_trc=bt709:colorspace=bt709',
           '-c:v', 'libx264', '-crf', str(crf), '-preset', 'medium', '-threads', '2',
           '-color_range', 'tv', '-color_primaries', 'bt709', '-color_trc', 'bt709',
           '-colorspace', 'bt709', '-bsf:v', 'h264_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1',
           '-video_track_timescale', '12288', '-movflags', '+faststart', path]
    with subprocess.Popen(cmd, stdin=subprocess.PIPE) as proc:
        for frame in frames:
            proc.stdin.write(frame.tobytes())
        proc.stdin.close()
        if proc.wait():
            raise RuntimeError(f'Could not encode {path.name}')


def photo(path, box):
    with Image.open(ROOT / path) as src:
        return np.asarray(src.convert('RGB').resize(SIZE, Image.Resampling.LANCZOS).crop(box)).copy()


def grid(frame):
    y, x = np.mgrid[:frame.shape[0], :frame.shape[1]].astype('f4')
    return np.dstack((x, y))


def sample(frame, points):
    return cv2.remap(frame, points.astype('f4'), None, cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)


def flow(a, b, level=0):
    solver = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)
    solver.setFinestScale(level)
    return solver.calc(cv2.cvtColor(a, cv2.COLOR_RGB2GRAY), cv2.cvtColor(b, cv2.COLOR_RGB2GRAY), None)


def ease(t):
    t = np.clip(t, 0, 1)
    return t*t*(3-2*t)


def mix(under, over, alpha):
    return np.uint8(np.clip(under.astype('f4') + (over.astype('f4') - under)*alpha, 0, 255) + .5)


def borrowed_detail(base, source, landmarks, target):
    align = cv2.estimateAffinePartial2D(np.float32(landmarks), np.float32(target), method=cv2.LMEDS)[0]
    coarse = cv2.warpAffine(source, align, (base.shape[1], base.shape[0]), borderMode=cv2.BORDER_REPLICATE)
    movement = cv2.GaussianBlur(flow(base, coarse), (0, 0), 2.4)
    fine = sample(coarse, grid(base) + movement).astype('f4')
    detail = np.clip(fine - cv2.GaussianBlur(fine, (0, 0), 2.4), -17, 17)
    disagreement = np.abs(cv2.GaussianBlur(coarse, (0, 0), 3).astype('f4') - base).mean(2)
    strength = (.75 - .35*ease((disagreement-12)/28))[:, :, None]
    tone = cv2.GaussianBlur(base.astype('f4'), (0, 0), 1.2)
    return np.uint8(np.clip(tone + strength*detail, 0, 255) + .5)


def chair_patches(shot):
    original = list(decoded(BASE, shot['masterStart'], shot['frames'], shot['box']))
    pts = grid(original[0])
    matte = ease((1.01 - ((pts[:,:,0]-129)/77)**2 - ((pts[:,:,1]-127)/91)**2) / .32)[:, :, None]
    photos = [photo(path, shot['box']) for path in shot['photos']]
    poses = shot['poseFrames']
    resolved = []
    for n, target in zip(poses, shot['poseLandmarks']):
        down, up = [borrowed_detail(original[n], plate, landmarks, target)
                    for plate, landmarks in zip(photos, shot['photoLandmarks'])]
        resolved.append(mix(down, up, ease((n-56)/23)))
    output = []
    for i, (start, end) in enumerate(zip(poses, poses[1:])):
        forward = flow(original[start], original[end])
        back = flow(original[end], original[start])
        for n in range(start, end):
            t = (n-start)/(end-start)
            a, b = pts-t*forward, pts-(1-t)*back
            # Invert the source-to-output displacements at the output pixel.
            for _ in range(2):
                a, b = pts-t*sample(forward, a), pts-(1-t)*sample(back, b)
            pose = mix(sample(resolved[i], a), sample(resolved[i+1], b), t)
            output.append(mix(original[n], pose, matte))
    output.append(mix(original[-1], resolved[-1], matte))
    return output


def hand_matte(source, shot):
    boundary = np.rint(np.array(shot['silhouette'])/shot['inspectionScale']).astype('i4')
    drawn = cv2.fillPoly(np.zeros(source.shape[:2], np.uint8), [boundary], 255)
    hints = np.full(source.shape[:2], cv2.GC_BGD, np.uint8)
    edge = np.ones((15, 15), np.uint8)
    hints[cv2.dilate(drawn, edge)>0] = cv2.GC_PR_BGD
    hints[drawn>0] = cv2.GC_PR_FGD
    hints[cv2.erode(drawn, edge)>0] = cv2.GC_FGD
    cv2.setRNGSeed(451)
    cv2.grabCut(source, hints, None, np.zeros((1,65),'f8'), np.zeros((1,65),'f8'), 3, cv2.GC_INIT_WITH_MASK)
    return cv2.GaussianBlur(np.float32((hints==cv2.GC_FGD)|(hints==cv2.GC_PR_FGD)), (0,0), .62)


def sofa_patches(shot):
    scale = shot['inspectionScale']
    original = list(decoded(BASE, shot['masterStart'], 25, shot['box']))
    clear = next(decoded(BASE, shot['masterStart'] + shot['clearLocalFrame'], 1, shot['box']))
    source = photo(shot['photo'], shot['box'])
    matte = hand_matte(source, shot)
    # Match the fine skin detail to the near forearm in this lens plane.
    source = cv2.GaussianBlur(source, (0,0), .72)
    pts = grid(source)
    landmarks = np.float32(shot['photoLandmarks'])/scale
    times = [row[0] for row in shot['path']]
    track = np.float32([row[1:] for row in shot['path']])/scale

    def coordinates(time):
        target = np.float32([[np.interp(time, times, track[:, k, axis]) for axis in range(2)] for k in range(3)])
        transform = cv2.getAffineTransform(landmarks, target)
        return cv2.transform(pts, cv2.invertAffineTransform(transform))

    output = []
    for n, base in enumerate(original):
        center = coordinates(n)
        # Average three points in a short shutter, in premultiplied colour.
        # The hand stops on the rocker and acquires blur again as the wrist withdraws.
        coverage = np.zeros(matte.shape, 'f4')
        ink = np.zeros(source.shape, 'f4')
        for dt, weight in ((-.16,.25),(0,.5),(.16,.25)):
            coords = center if dt == 0 else coordinates(n+dt)
            alpha = np.clip(sample(matte, coords),0,1)*weight
            ink += sample(source, coords).astype('f4')*alpha[:,:,None]
            coverage += alpha
        projected = np.uint8(np.clip(ink/np.maximum(coverage[:,:,None], 1e-5), 0, 255) + .5)
        wrist = ease((center[:,:,0]*scale-156)/69)
        neighborhood = cv2.dilate(np.uint8(coverage>.05), cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(69,69)))
        neighborhood = cv2.GaussianBlur(neighborhood.astype('f4'), (0,0), 5)
        difference = np.abs(base.astype('f4')-clear).max(2)
        remove = ease((difference-3)/13)*neighborhood*wrist
        remove *= 1-ease((pts[:,:,0]*scale-475)/35)*(1-ease((pts[:,:,1]*scale-98)/36))
        under = mix(base, clear, remove[:,:,None])
        if n >= 20:
            projected = cv2.GaussianBlur(projected, (0,0), .8+.48*(n-20))
        corrected = mix(under, projected, (wrist*coverage)[:,:,None])
        if n >= 19:
            live_flow = cv2.GaussianBlur(flow(base, corrected, 1), (0,0), 1.8)
            aligned = sample(corrected, pts + live_flow*ease((n-18)/3))
            if n >= 20:
                high = aligned.astype('f4')-cv2.GaussianBlur(aligned,(0,0),2).astype('f4')
                live = np.uint8(np.clip(base.astype('f4')+np.clip(high,-8,8)*.5, 0, 255))
                aligned = mix(aligned, live, ease((n-19)/2))
            corrected = mix(base, aligned, 1-ease((n-20)/4))
        output.append(corrected)
    return output


def render_shot(name, patches, destination):
    shot = PLAN[name]
    x, y, right, bottom = shot['box']
    def frames():
        for n, base in enumerate(decoded(BASE, shot['masterStart'], shot['frames'])):
            if n < len(patches):
                base = base.copy()
                base[y:bottom, x:right] = patches[n]
            yield base
    encode(destination, frames())


def compare(folder):
    font = ImageFont.load_default(size=18)
    stills = []
    def views():
        for name, first, end, size, label in [('chair',38,80,(366,344),'Head lift'),
                                               ('sofa-reveal',0,32,(496,230),'Switch and release')]:
            shot = PLAN[name]
            original = decoded(BASE, shot['masterStart']+first, end-first, shot['box'])
            revised = decoded(folder/(name+'.mp4'), first, end-first, shot['box'])
            for n, (a,b) in enumerate(zip(original,revised), first):
                page = Image.new('RGB',(1024,408),'#171815')
                draw = ImageDraw.Draw(page)
                for i,(data,title) in enumerate(((a,'V9'),(b,'V10'))):
                    tile = Image.fromarray(data).resize(size, Image.Resampling.LANCZOS)
                    x = i*512+(512-size[0])//2
                    page.paste(tile,(x,27+(344-size[1])//2))
                    draw.text((x,4),title,font=font,fill='white')
                draw.text((18,379),f'{label}   /   film frame {shot["masterStart"]+n}',font=font,fill='#e8e6dd')
                if shot['masterStart']+n in (74,1018):
                    stills.append(page.copy())
                yield np.asarray(page)
    encode(folder/'performance-comparison.mp4', views(), (1024,408), 14)
    sheet = Image.new('RGB',(1024,816))
    for i, row in enumerate(stills):
        sheet.paste(row,(0,i*408))
    sheet.save(folder/'performance-comparison.jpg', quality=94, subsampling=0)


def chair_tracking(path):
    # Fixed eye, brow, nose, chin and ear points in crop coordinates.
    marks = np.float32([[99,125],[102,135],[98,143],[99,156],[110,126],[106,137],[111,151],[113,162],
                        [116,172],[153,127],[158,119],[147,98],[120,105],[86,111],[90,139],[110,170]])
    frames = decoded(path, 57, 23, PLAN['chair']['box'])
    previous = cv2.cvtColor(next(frames), cv2.COLOR_RGB2GRAY)
    tracked = [marks.copy()]
    for frame in frames:
        current = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        marks, found, _ = cv2.calcOpticalFlowPyrLK(previous, current, marks, None, winSize=(19,19), maxLevel=3)
        if not np.all(found):
            raise ValueError('One of the review landmarks left the face.')
        tracked.append(marks.copy())
        previous = current
    acceleration = np.diff(np.asarray(tracked), n=2, axis=0)
    relative = acceleration - np.median(acceleration, axis=1, keepdims=True)
    return [round(float(v), 3) for v in np.percentile(np.linalg.norm(relative, axis=2), [50,75,95])]


def verify(name, target):
    shot = PLAN[name]
    info = json.loads(subprocess.check_output(['ffprobe','-v','error','-show_streams','-of','json',target]))['streams'][0]
    assert (info['width'],info['height']) == SIZE and info['color_range'] == 'tv'
    assert all(info.get(field) == 'bt709' for field in ('color_space','color_transfer','color_primaries'))
    assert int(info['nb_frames']) == shot['frames'] and info['avg_frame_rate'] == '24/1'
    old = decoded(BASE, shot['masterStart'], shot['frames'])
    new = decoded(target, 0, shot['frames'])
    left, top, right, bottom = shot['box']
    errors = []
    focus_errors = []
    for n, (a,b) in enumerate(zip(old,new)):
        difference = np.abs(a[::8,::8].astype('i2') - b[::8,::8])
        if name == 'sofa-reveal' and n >= 24:
            focus_errors.append(float(difference.mean()))
        difference[top//8:(bottom+7)//8,left//8:(right+7)//8] = 0
        errors.append(difference.sum() / (difference.size - (right-left)*(bottom-top)*3/64))
    return {'file':target.name,'sha256':digest(target),'frames':shot['frames'],'size':SIZE,'fps':FPS,
            'markedFrame':shot['noteFrame'],'editFramesExclusive':[shot['masterStart'], shot['masterStart']+shot['frames']],
            'renderedRepairBox':shot['box'],'maximumMean8BitRgbDifferenceOutsideRepair':round(max(errors),3),
            **({'maximumMean8BitRgbDifferenceAfterHandReleases':round(max(focus_errors),3)} if focus_errors else {}),
            **({'liftTracking':{'framesInclusive':[57,79], 'landmarks':16,
                 'measure':'Median, 75th and 95th percentile residual feature acceleration, in display pixels per frame squared. Subtract common translational acceleration at each frame before pooling. The measure describes the small independent movements among facial features.',
                 'v9':chair_tracking(BASE),'v10':chair_tracking(target)}} if name == 'chair' else {})}


def main():
    cv2.setNumThreads(1)
    cv2.ocl.setUseOpenCL(False)
    with tempfile.TemporaryDirectory(dir=ROOT) as tmp:
        folder = Path(tmp)
        for name, repair in [('chair',chair_patches),('sofa-reveal',sofa_patches)]:
            render_shot(name, repair(PLAN[name]), folder/(name+'.mp4'))
        compare(folder)
        inputs = [PLAN['baseline'], *PLAN['chair']['photos'], PLAN['sofa-reveal']['photo']]
        check = {'inputs':[{'file':f,'sha256':digest(ROOT/f)} for f in inputs],
                 'shots':[verify(n,folder/(n+'.mp4')) for n in ('chair','sofa-reveal')],
                 'proof':'performance-comparison.mp4','markedFrames':'performance-comparison.jpg',
                 'method':'The script replaces only a bounded crop in the decoded Rec.709 source and copies every other RGB pixel before encoding. The measured figures compare decoded RGB at every eighth pixel on every frame after H.264 compression. The same sofa take continues through the sip and focus pull. The reference stills restore selected detail at the original Mini performance timing.'}
        (folder/'performance-check.json').write_text(json.dumps(check,ensure_ascii=False,indent=2)+'\n')
        for file in folder.iterdir():
            file.replace(ROOT/file.name)


if __name__ == '__main__':
    main()
