"""Finish the provider take’s generated reach, power cue and incidental light in the locked reveal.

Requires ffmpeg, Pillow and NumPy. Run here, or pass the directory containing
sofa-reveal.mp4. Frame numbers refer to the native 864 × 496, 24 fps take.
"""
from pathlib import Path
import subprocess
import sys

import numpy as np
from PIL import Image, ImageDraw, ImageFilter

HERE = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
WIDTH, HEIGHT = 864, 496
CONTACT = 14
X = np.arange(WIDTH)
Y = np.arange(HEIGHT)[:, None]


def unit(value):
    return np.clip(value, 0, 1)


def smooth(value):
    value = unit(value)
    return value * value * (3 - 2 * value)


def feather(points, radius):
    matte = Image.new("L", (WIDTH, HEIGHT))
    ImageDraw.Draw(matte).polygon(points, fill=255)
    return np.asarray(matte.filter(ImageFilter.GaussianBlur(radius))) / 255.


def mix(under, over, mask):
    return under + (over - under) * mask[:, :, None]


def plate_mask(frame, clear, n):
    """Use the professor's actual changing outline. Neutral grey sleeve gives way to warm skin."""
    delta = np.max(abs(frame - clear), axis=2)
    red = frame[:, :, 0] - frame[:, :, 1]
    clean_red = clear[:, :, 0] - clear[:, :, 1]
    skin = unit((red - clean_red - 3) / 8) * unit((red - 12) / 7)
    # An elliptical search area follows the real hand's withdrawal behind the desk.
    end = np.interp(n, [0, 4, 14, 18, 19, 20, 21, 22, 23, 24, 25, 26],
                    [719, 723, 731, 731, 727, 713, 697, 673, 644, 615, 574, 537])
    fall = max(n - 18, 0)
    centre = np.interp(X, [398, 460, 565, 635, 731], [164, 210, 272, 302, 300])
    centre += np.interp(X, [398, 490, 635, 731], [4, 8, 9, 9]) * fall
    bounds = (abs(Y - centre) < 58) & (X < end + 2)
    sleeve = unit((delta - 7) / 13)
    skin_weight = smooth((X - 477) / 20)
    key = ((1 - skin_weight) * sleeve + skin_weight * skin) * bounds * (X >= 385)
    # Join small creases inside the sleeve/knuckles before feathering its real silhouette.
    key = Image.fromarray(np.uint8(key * 255)).filter(ImageFilter.MedianFilter(3))
    key = key.filter(ImageFilter.MaxFilter(7)).filter(ImageFilter.MinFilter(7))
    key = key.filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.GaussianBlur(.5))
    return np.asarray(key) / 255.


def reach(frame, clear, n):
    amount = smooth(n / CONTACT) if n <= CONTACT else 1 - smooth((n - 18) / 8)
    if amount <= 0:
        return frame
    mask = plate_mask(frame, clear, n)
    # Keep the shoulder attached, progressively straighten the forearm and
    # translate the wrist and hand together. The finger lengths stay intact.
    weight = smooth((X - 386) / 211)
    dx, dy = 76 * amount, 15 * amount
    src_x = np.interp(X, X + dx * weight, X)
    src_y = np.clip(Y - dy * np.interp(src_x, X, weight), 0, HEIGHT - 1)
    x0 = src_x.astype(int)
    y0 = src_y.astype(int)
    x1 = np.minimum(x0 + 1, WIDTH - 1)
    y1 = np.minimum(y0 + 1, HEIGHT - 1)
    fx, fy = (src_x - x0)[None, :], src_y - y0

    def translate(value):
        if value.ndim == 3:
            ax, ay = fx[:, :, None], fy[:, :, None]
        else:
            ax, ay = fx, fy
        upper = value[y0, x0] * (1 - ax) + value[y0, x1] * ax
        lower = value[y1, x0] * (1 - ax) + value[y1, x1] * ax
        return upper * (1 - ay) + lower * ay

    # The fill plate comes from this take after the same arm clears the desk.
    restored = mix(frame, clear, mask)
    result = mix(restored, translate(frame), translate(mask))
    return mix(frame, result, np.broadcast_to(smooth((X - 390) / 47), mask.shape))


def light_field():
    # Follow the two lobes of the stray light. Assessed independently at near
    # and far focus; the frame of the winter print crosses this area.
    y, x = np.mgrid[169:255, 389:495]
    diagonal = (abs(y - (231 - .72 * (x - 410))) < 27) & (y < 246) & (x > 396)
    lower = ((x - 467) / 25) ** 2 + ((y - 246) / 16) ** 2 < 1
    mask = Image.fromarray(np.uint8((diagonal | lower) * 255))
    return np.asarray(mask.filter(ImageFilter.GaussianBlur(2.5))) / 255.


def remove_stray_light(frame, clear, mask, n):
    area = np.s_[169:255, 389:495]
    patch = frame[area]
    # The neighbouring strip of this same wall includes the lower rail of
    # the frame and top edge of sofa. Its detail tracks the real lens pull.
    baseline = np.median(frame[169:255, 500:518], axis=1)[:, None, :]
    gradient = np.interp(np.arange(389, 495), [389, 420, 485, 518], [7, 9, 4, 0])
    target = baseline + gradient[None, :, None]
    # Interpolate the undisturbed frame rail from the same image row, without
    # imposing the gradient of the plaster onto the darker wooden rail.
    target[:23] = baseline[:23] + 2
    excess = np.maximum(patch - target, 0)
    if n < 34:
        diff = np.max(abs(patch - clear[area]), axis=2)
        mask = mask * (1 - smooth((diff - 9) / 20))
    patch -= excess * mask[:, :, None]


def finish():
    source = HERE / "sofa-reveal.mp4"
    outputs = subprocess.check_output(["ffmpeg", "-v", "error", "-i", str(source), "-an",
                                       "-fps_mode", "passthrough", "-pix_fmt", "rgb24",
                                       "-f", "rawvideo", "pipe:1"])
    frames = np.frombuffer(outputs, np.uint8).reshape(-1, HEIGHT, WIDTH, 3)
    assert len(frames) == 217
    clear = frames[40].astype(np.float32)
    lit = frames[0].astype(np.float32)
    # Hold only glass and rocker across the provider's premature blackout.
    glass = feather([(701, 16), (826, 16), (823, 292), (701, 286)], 2)
    rocker = feather([(790, 299), (818, 301), (816, 336), (788, 329)], 2)
    power = np.maximum(glass, rocker)
    wall_mask = light_field()
    target = HERE / "sofa-reveal-finish.mp4"
    command = ["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
               "-s", f"{WIDTH}x{HEIGHT}", "-r", "24", "-i", "pipe:0", "-an", "-c:v",
               "libx264", "-threads", "1", "-crf", "12", "-preset", "medium", "-pix_fmt",
               "yuv420p", "-movflags", "+faststart", str(target)]
    with subprocess.Popen(command, stdin=subprocess.PIPE) as writer:
        for n, image in enumerate(frames):
            frame = image.astype(np.float32)
            if n < CONTACT:
                frame = mix(frame, lit, power)
            if 0 < n < 26:
                frame = reach(frame, clear, n)
            remove_stray_light(frame, clear, wall_mask, n)
            writer.stdin.write(np.uint8(np.clip(frame, 0, 255) + .49).tobytes())
        writer.stdin.close()
        if writer.wait():
            raise RuntimeError("The reveal encoder failed.")


if __name__ == "__main__":
    finish()
