#!/usr/bin/env python3
"""
cutout_pro.py - cut a person out of normal phone footage, with clean hair and no see-through.

What it does
------------
1. Reads your video with ffmpeg, one frame at a time (it never loads the whole video into RAM).
2. Finds the person in every frame with BiRefNet_HR-matting (free, MIT licence).
3. Smooths the matte over time, so the edges don't flicker.
4. Re-solves the colour of the hair edges with pymatting (free, MIT licence),
   so the old wall colour does not stay stuck in your hair.
5. Fills the solid middle of the person, so the new background never shows through your head.
6. Writes a transparent cutout: ProRes 4444 .mov with an alpha channel (opens in Premiere,
   Resolve, Final Cut, After Effects, CapCut desktop).
7. Optional: --bg puts you straight onto a background image or video and writes an .mp4.

Quick start
-----------
    python cutout_pro.py my_video.mp4
    python cutout_pro.py my_video.mp4 --bg studio.jpg
    python cutout_pro.py my_video.mp4 --bg studio.jpg --start 10 --duration 3     (test a 3 second piece first)

Needs: Python 3.12, ffmpeg + ffprobe on PATH, an NVIDIA GPU with CUDA. See SETUP.md.
Speed: about 1.5 to 3 s per frame on an RTX 3060 12 GB at 1080x1920. Uses about 5.4 GB of GPU memory.
"""

import argparse
import json
import math
import shutil
import subprocess
import sys
import time
from pathlib import Path

MODEL_ID = "ZhengPeng7/BiRefNet_HR-matting"  # MIT licence, downloaded from Hugging Face on first run (~450 MB)
MODEL_SIZE = 2048                            # the HR model is trained at 2048 x 2048

# HDR (iPhone "HDR video", Dolby Vision / HLG) -> normal SDR BT.709, so colours don't look washed out
TONEMAP = ("zscale=t=linear:npl=203,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,"
           "zscale=t=bt709:m=bt709:r=tv,format=yuv420p,")


def die(msg):
    print(f"\nERROR: {msg}\n", file=sys.stderr)
    sys.exit(1)


# ----------------------------------------------------------------------------------------- video helpers
def ffprobe_json(path, *args):
    r = subprocess.run(["ffprobe", "-v", "error", *args, "-of", "json", str(path)], capture_output=True, text=True)
    if r.returncode != 0:
        die(f"ffprobe could not read {path}:\n{r.stderr.strip()}")
    return json.loads(r.stdout)


def upright_size(path):
    """Width and height as the video is SEEN, after the phone's rotation flag.
    Phones often store a portrait video as landscape pixels plus 'rotate 90'. ffmpeg turns it upright for us
    (autorotate is on by default), so we only need to know the upright size here."""
    s = ffprobe_json(path, "-select_streams", "v:0", "-show_entries",
                     "stream=width,height:stream_tags=rotate:stream_side_data=rotation")["streams"]
    if not s:
        die(f"no video stream in {path}")
    s = s[0]
    w, h = int(s["width"]), int(s["height"])
    rot = 0
    for d in s.get("side_data_list", []) or []:
        if "rotation" in d:
            rot = int(float(d["rotation"]))
    if not rot and "rotate" in (s.get("tags") or {}):
        rot = int(s["tags"]["rotate"])
    if abs(rot) % 180 == 90:
        w, h = h, w
    return w, h


def duration_of(path):
    d = ffprobe_json(path, "-show_entries", "format=duration")
    try:
        return float(d["format"]["duration"])
    except (KeyError, ValueError):
        return None


def is_hdr(path):
    s = ffprobe_json(path, "-select_streams", "v:0", "-show_entries", "stream=color_transfer,color_primaries")["streams"]
    txt = json.dumps(s)
    return any(k in txt for k in ("arib-std-b67", "smpte2084", "bt2020"))


def audio_index(path):
    """First audio track ffmpeg can decode, or None. (New iPhones put a spatial-audio track first that ffmpeg
    can't decode; the normal AAC track comes after it.)"""
    s = ffprobe_json(path, "-select_streams", "a", "-show_entries", "stream=codec_name")["streams"]
    for k, st in enumerate(s):
        if st.get("codec_name") not in (None, "", "none", "unknown"):
            return k
    return None


def even(x):
    return max(2, int(round(x / 2)) * 2)


# ----------------------------------------------------------------------------------------- the matting engine
class Matter:
    """BiRefNet_HR-matting + motion-adaptive temporal blend + pymatting foreground colour + solid-core fill."""

    def __init__(self, device):
        import torch
        from transformers import AutoModelForImageSegmentation
        from pymatting import estimate_foreground_ml
        self.torch, self.estimate_fg, self.dev = torch, estimate_foreground_ml, device
        self.dtype = torch.float16 if device == "cuda" else torch.float32  # fp16 halves memory on the GPU
        print(f"Loading {MODEL_ID} (first run downloads it, ~450 MB) ...", flush=True)
        net = AutoModelForImageSegmentation.from_pretrained(MODEL_ID, trust_remote_code=True)
        self.net = net.to(device).eval().to(self.dtype)
        # ImageNet normalisation, the same the model was trained with
        self.mean = torch.tensor([0.485, 0.456, 0.406], device=device).view(1, 3, 1, 1)
        self.std = torch.tensor([0.229, 0.224, 0.225], device=device).view(1, 3, 1, 1)
        self.prev = None  # last frame's matte, for the temporal blend

    def alpha(self, rgb):
        """rgb uint8 HxWx3 -> matte float32 HxW in 0..1 (temporally smoothed)."""
        t = self.torch
        h, w = rgb.shape[:2]
        with t.inference_mode():
            x = t.from_numpy(rgb.copy()).to(self.dev).permute(2, 0, 1).float().div_(255).unsqueeze(0)
            x = t.nn.functional.interpolate(x, size=(MODEL_SIZE, MODEL_SIZE), mode="bilinear", align_corners=False)
            p = self.net(((x - self.mean) / self.std).to(self.dtype))[-1].sigmoid().float()  # last output = finest
            p = t.nn.functional.interpolate(p, size=(h, w), mode="bilinear", align_corners=False)[0, 0]
            # Motion-adaptive temporal blend: where the matte barely changed since the last frame, mix 60% new +
            # 40% old (kills edge flicker). Where it changed a lot (> 0.2) you moved: take the new value as-is,
            # so there is no ghost trail behind a moving hand.
            if self.prev is not None:
                k = t.where((p - self.prev).abs() > 0.2, t.ones_like(p), t.full_like(p, 0.6))
                p = k * p + (1 - k) * self.prev
            self.prev = p
            a = p.clamp(0, 1).cpu().numpy()
        return a

    def __call__(self, rgb, solid_core=True):
        """rgb uint8 HxWx3 -> rgba uint8 HxWx4 (straight, not premultiplied, alpha)."""
        import numpy as np
        import cv2
        h, w = rgb.shape[:2]
        a = self.alpha(rgb)
        a = np.where(a < 0.02, 0.0, np.where(a > 0.98, 1.0, a)).astype(np.float32)  # snap near-0 / near-1 noise

        # Foreground colour: pymatting solves what colour each half-see-through hair pixel really is, without the
        # old wall mixed in. This is what removes the white/grey fringe.
        fg = self.estimate_fg(rgb.astype(np.float64) / 255, a.astype(np.float64))

        # Solid core (stops see-through): models leave curly hair part-transparent, so the new background shows
        # through your head. Take the confident core (alpha > 0.55), close the small gaps between curls, pull it
        # in from the outline, feather it, and never let alpha drop below it. Only the outer few pixels stay soft.
        # Sizes are a fraction of the frame's short side (1080 on a vertical phone video).
        if solid_core:
            s = min(w, h)
            core = (a > 0.55).astype(np.uint8)
            kc = max(5, int(0.022 * s) | 1)   # close: ~2.2% of frame width
            core = cv2.morphologyEx(core, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kc, kc)))
            ke = max(3, int(0.006 * s) | 1)   # erode: ~0.6%
            core = cv2.erode(core, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ke, ke)))
            core = cv2.GaussianBlur(core.astype(np.float32), (0, 0), 0.003 * s)  # feather: ~0.3%
            core = np.clip(core * 1.25, 0, 1)
            a = np.maximum(a, core)

        out = np.empty((h, w, 4), np.uint8)
        out[:, :, :3] = (np.clip(fg, 0, 1) * 255 + 0.5).astype(np.uint8)
        out[:, :, 3] = (a * 255 + 0.5).astype(np.uint8)
        return out


# ----------------------------------------------------------------------------------------- main
def main():
    ap = argparse.ArgumentParser(description="Pro-grade person cutout from normal phone footage (free, open source).")
    ap.add_argument("input", help="your video (mp4 / mov)")
    ap.add_argument("--out", help="output folder (default: next to the input)")
    ap.add_argument("--bg", help="optional background image or video: also writes <name>_on_bg.mp4")
    ap.add_argument("--start", type=float, default=0.0, help="start at this many seconds (default 0)")
    ap.add_argument("--duration", type=float, help="only do this many seconds (great for a quick test)")
    ap.add_argument("--fps", type=float, default=30, help="output frame rate (default 30)")
    ap.add_argument("--max-size", type=int, default=1920,
                    help="cap the long edge in pixels (default 1920; 4K is much slower)")
    ap.add_argument("--no-solid-core", action="store_true", help="skip the solid-core fill (not recommended)")
    ap.add_argument("--cpu", action="store_true", help="run without an NVIDIA GPU (works, but VERY slow)")
    args = ap.parse_args()

    # ---- checks, with plain-English errors
    for tool in ("ffmpeg", "ffprobe"):
        if not shutil.which(tool):
            die(f"{tool} not found. Install ffmpeg and make sure '{tool}' works in a new terminal (see SETUP.md).")
    src = Path(args.input)
    if not src.exists():
        die(f"input not found: {src}")
    try:
        import torch
    except ImportError:
        die("PyTorch is not installed in this Python. Activate the venv and follow SETUP.md step 4.")
    if args.cpu:
        device = "cpu"
        print("Running on the CPU. Expect minutes per frame, not seconds.")
    else:
        if not torch.cuda.is_available():
            die("No CUDA GPU found.\n"
                "  - This needs an NVIDIA graphics card (we use an RTX 3060 12 GB).\n"
                "  - If you have one: install the latest NVIDIA driver, and install PyTorch with the CUDA line\n"
                "    from SETUP.md (a plain 'pip install torch' gives the CPU-only version).\n"
                "  - No NVIDIA card (e.g. a Mac)? Add --cpu to run it anyway, very slowly.")
        device = "cuda"
        free, total = torch.cuda.mem_get_info()
        print(f"GPU: {torch.cuda.get_device_name(0)}, {free / 2**30:.1f} of {total / 2**30:.1f} GB free")
        if free < 5.5 * 2**30:
            print("  Warning: this needs about 5.4 GB of GPU memory. Close games, other AI apps or video editors "
                  "if it runs out of memory.")

    # ---- what we are cutting
    full = duration_of(src)
    start = max(0.0, args.start)
    end = full if args.duration is None else start + args.duration
    if full is not None:
        end = min(end, full) if end is not None else full
    if end is None or end <= start:
        die(f"nothing to cut: start {start}s is past the end of the video ({full}s)")
    uw, uh = upright_size(src)
    k = min(1.0, args.max_size / max(uw, uh))
    W, H = even(uw * k), even(uh * k)
    n_est = int(math.floor((end - start) * args.fps + 1e-6))
    out_dir = Path(args.out) if args.out else src.parent
    out_dir.mkdir(parents=True, exist_ok=True)
    stem = src.stem + (f"_{start:g}-{end:g}s" if (args.start or args.duration) else "")
    mov = out_dir / f"{stem}_cutout.mov"
    a_idx = audio_index(src)
    print(f"Input: {src.name}  upright {uw}x{uh} -> working size {W}x{H} @ {args.fps:g} fps, "
          f"{start:g}s to {end:g}s (~{n_est} frames), audio: {'yes' if a_idx is not None else 'no'}")

    # ---- decoder: ffmpeg autorotates, tonemaps HDR, scales, fixes the frame rate, streams raw RGB frames to us
    vf = (TONEMAP if is_hdr(src) else "") + f"scale={W}:{H}:flags=lanczos,fps={args.fps:g},format=rgb24"
    dec = subprocess.Popen(["ffmpeg", "-v", "error", "-ss", f"{start:.3f}", "-to", f"{end:.3f}", "-i", str(src),
                            "-map", "0:v:0", "-vf", vf, "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"],
                           stdout=subprocess.PIPE, bufsize=W * H * 3 * 2)

    # ---- encoder: raw RGBA frames in -> ProRes 4444 with alpha (+ the original audio as PCM)
    enc_cmd = ["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgba", "-s", f"{W}x{H}",
               "-r", f"{args.fps:g}", "-i", "pipe:0"]
    if a_idx is not None:
        enc_cmd += ["-ss", f"{start:.3f}", "-to", f"{end:.3f}", "-i", str(src), "-map", "0:v", "-map", f"1:a:{a_idx}",
                    "-c:a", "pcm_s16le", "-shortest"]
    # RGB -> YUV with the BT.709 matrix (ffmpeg's default is BT.601, which shifts skin tones)
    enc_cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv,format=yuva444p10le",
                "-c:v", "prores_ks", "-profile:v", "4444", "-pix_fmt", "yuva444p10le", "-alpha_bits", "16",
                "-vendor", "apl0", "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709",
                str(mov)]
    enc = subprocess.Popen(enc_cmd, stdin=subprocess.PIPE)

    matter = Matter(device)
    import numpy as np
    frame_bytes = W * H * 3
    i, t0 = 0, time.time()
    tty = sys.stdout.isatty()
    try:
        while True:
            buf = dec.stdout.read(frame_bytes)
            if len(buf) < frame_bytes:
                break
            rgb = np.frombuffer(buf, np.uint8).reshape(H, W, 3)
            try:
                enc.stdin.write(matter(rgb, solid_core=not args.no_solid_core).tobytes())
            except (BrokenPipeError, OSError):
                # the encoder already stopped: it ends with the audio, and the decoder can hand over one extra frame
                break
            i += 1
            spf = (time.time() - t0) / i
            if tty or i == 1 or i % 10 == 0:
                left = max(0, n_est - i) * spf
                print(f"frame {i}/{n_est}  {spf:.2f} s/frame  ~{left / 60:.1f} min left", end="\r" if tty else "\n",
                      flush=True)
    except torch.cuda.OutOfMemoryError:
        enc.kill()
        die("the GPU ran out of memory. Close other GPU apps, or try --max-size 1280.")
    finally:
        dec.stdout.close()
        dec.wait()
        if enc.stdin and not enc.stdin.closed:
            try:
                enc.stdin.close()
            except OSError:  # already closed by the encoder
                pass
        enc.wait()
    total = time.time() - t0
    if i == 0 or enc.returncode != 0:
        die("no frames were written. Check the input plays, and that --start is inside the video.")
    print(f"\nDone: {i} frames in {total / 60:.1f} min ({total / i:.2f} s/frame)")
    print(f"Transparent cutout: {mov}")

    # free the GPU before compositing
    del matter
    if device == "cuda":
        torch.cuda.empty_cache()

    # ---- optional: you on a new background (image or looping video), cover-fit to the frame
    if args.bg:
        bg = Path(args.bg)
        if not bg.exists():
            die(f"background not found: {bg}")
        is_video = bg.suffix.lower() in (".mp4", ".mov", ".webm", ".mkv", ".m4v")
        mp4 = out_dir / f"{stem}_on_bg.mp4"
        bg_in = (["-stream_loop", "-1"] if is_video else ["-loop", "1"]) + ["-i", str(bg)]
        # mix in RGB (straight alpha), then back to BT.709 YUV for the mp4
        fc = (f"[0:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},fps={args.fps:g},format=rgba[b];"
              f"[1:v]scale=in_color_matrix=bt709:in_range=tv,format=rgba[f];"
              f"[b][f]overlay=0:0:format=rgb:shortest=1,"
              f"scale=out_color_matrix=bt709:out_range=tv,format=yuv420p[v]")
        cmd = ["ffmpeg", "-v", "error", "-y", *bg_in, "-i", str(mov), "-filter_complex", fc, "-map", "[v]"]
        if a_idx is not None:
            cmd += ["-map", "1:a", "-c:a", "aac", "-b:a", "192k"]
        cmd += ["-c:v", "libx264", "-crf", "16", "-preset", "medium", "-color_primaries", "bt709",
                "-color_trc", "bt709", "-colorspace", "bt709", "-movflags", "+faststart", "-shortest", str(mp4)]
        r = subprocess.run(cmd)
        if r.returncode != 0:
            die("compositing onto the background failed (see the ffmpeg message above).")
        print(f"On the background: {mp4}")


if __name__ == "__main__":
    main()
