"""Perceptual sidecar transport: per-frame metadata INSIDE an H.264 stream as SEI NAL units.

THE IDEA. The video a human watches is the lossy output; the edge device knows more than the
pixels carry (detections, occupancy, illuminant, nano-model verdicts). Kilobytes of that per
frame can ride inside the same H.264 bitstream as SEI user_data_unregistered (payloadType 5:
16-byte UUID + bytes), frame-bound, with no second channel to correlate.

MEASURED (2026-09-05, 300 frames of 720p, 300-byte JSON per frame, x264 with B-frames):
  remux mp4 -> mkv -> mp4         300/300 intact, pts-aligned      325 B/frame
  `-c copy` + h264_mp4toannexb    300/300 intact
  transcode (libx264)             0/300  -- every re-encode drops it
  transcode with `-udu_sei 1`     300/300 (ffmpeg re-attaches unregistered SEI as side data)
Overhead is FIXED per frame, so it is 9% of a 0.9 Mbit/s stream and <1% above ~8 Mbit/s.

TWO THINGS THAT BIT AND ARE HANDLED HERE:
  * ffmpeg's own `h264_metadata=sei_user_data` stamps ONE payload on keyframes only (2/300).
    This module inserts a distinct SEI before the first VCL NAL of EVERY access unit.
  * Re-muxing a raw .h264 into mp4 loses B-frame timing (pts == dts). `inject_mp4` patches
    the mp4's samples in place and fixes stsz/stco, so the container's timestamps survive.

Receivers: anything that sees Annex-B NALs -- ffmpeg, a custom demuxer, or in a browser the
WebRTC Encoded Transform API, which exposes the encoded frames to JS before decode.
Payload carries its own frame index; B-frame reordering is resolved by the receiver from pts.
"""
import re, struct, subprocess, json
from pathlib import Path

SIDECAR_UUID = b"nanolab-sidecar1"          # 16 bytes; change per application if you like
assert len(SIDECAR_UUID) == 16


# ------------------------------------------------------------------ NAL / SEI primitives
def ep_insert(rbsp: bytes) -> bytes:
    """Insert emulation-prevention bytes: 00 00 {00,01,02,03} -> 00 00 03 xx."""
    out = bytearray(); zeros = 0
    for b in rbsp:
        if zeros >= 2 and b <= 3:
            out.append(3); zeros = 0
        out.append(b); zeros = zeros + 1 if b == 0 else 0
    return bytes(out)


def ep_remove(ebsp: bytes) -> bytes:
    out = bytearray(); zeros = 0
    for b in ebsp:
        if zeros >= 2 and b == 3:
            zeros = 0; continue
        out.append(b); zeros = zeros + 1 if b == 0 else 0
    return bytes(out)


def _sei_num(v):
    return b"\xff" * (v // 255) + bytes([v % 255])


def build_sei_nal(payload: bytes, uuid: bytes = SIDECAR_UUID, payload_type=5) -> bytes:
    """NAL unit (without start code): nal_ref_idc 0, type 6, one SEI message."""
    body = uuid + payload
    rbsp = _sei_num(payload_type) + _sei_num(len(body)) + body + b"\x80"
    return b"\x06" + ep_insert(rbsp)


def parse_sei(nal: bytes):
    """-> list of (payloadType, payload_bytes) for one SEI NAL (start code stripped)."""
    rbsp = ep_remove(nal[1:]); last = len(rbsp) - 1
    while last >= 0 and rbsp[last] == 0:
        last -= 1
    out, i = [], 0
    while i < last:
        pt = 0
        while rbsp[i] == 0xFF: pt += 255; i += 1
        pt += rbsp[i]; i += 1
        ps = 0
        while rbsp[i] == 0xFF: ps += 255; i += 1
        ps += rbsp[i]; i += 1
        out.append((pt, rbsp[i:i + ps])); i += ps
    return out


def split_annexb(data: bytes):
    """-> list of (start_code_len, nal_bytes)."""
    pos = [m.start() for m in re.finditer(b"\x00\x00\x01", data)]
    nals = []
    for j, p in enumerate(pos):
        sc = 4 if p > 0 and data[p - 1] == 0 else 3
        end = pos[j + 1] if j + 1 < len(pos) else len(data)
        nal = data[p + 3:end]
        while nal and nal[-1] == 0:
            nal = nal[:-1]
        nals.append((sc, nal))
    return nals


def nal_type(nal): return nal[0] & 0x1F
def is_vcl(nal): return 1 <= nal_type(nal) <= 5


def first_mb_zero(nal):
    """first_mb_in_slice is ue(v) at the slice header start; == 0 iff the first RBSP bit is 1."""
    return len(nal) > 1 and (nal[1] & 0x80) != 0


def group_aus(nals):
    """Group NAL indices into access units in decode order."""
    aus, cur, cur_has_vcl = [], [], False
    for i, (_, nal) in enumerate(nals):
        t = nal_type(nal); new_au = False
        if is_vcl(nal):
            new_au = cur_has_vcl and first_mb_zero(nal)
        elif t in (6, 7, 8, 9, 14, 15, 16, 17, 18):
            new_au = cur_has_vcl
        if new_au:
            aus.append(cur); cur, cur_has_vcl = [], False
        cur.append(i); cur_has_vcl = cur_has_vcl or is_vcl(nal)
    if cur: aus.append(cur)
    return [au for au in aus if any(is_vcl(nals[i][1]) for i in au)]


# ------------------------------------------------------------------ inject
def inject_annexb(src, dst, payload_fn, uuid: bytes = SIDECAR_UUID):
    """Insert one SEI per access unit into a raw Annex-B .h264. payload_fn(decode_index) -> bytes."""
    data = Path(src).read_bytes(); nals = split_annexb(data); aus = group_aus(nals)
    out = bytearray(); added = 0
    for d, au in enumerate(aus):
        first_vcl = next(i for i in au if is_vcl(nals[i][1]))
        for i in au:
            if i == first_vcl:
                sei = build_sei_nal(payload_fn(d), uuid); out += b"\x00\x00\x00\x01" + sei; added += 4 + len(sei)
            sc, nal = nals[i]
            out += (b"\x00\x00\x00\x01" if sc == 4 else b"\x00\x00\x01") + nal
    Path(dst).write_bytes(bytes(out))
    return {"aus": len(aus), "sei_bytes_total": added, "sei_bytes_per_frame": added / max(len(aus), 1),
            "in_bytes": len(data), "out_bytes": len(out)}


def _boxes(data, start, end):
    p = start
    while p + 8 <= end:
        sz, typ = struct.unpack(">I4s", data[p:p + 8]); hdr = 8
        if sz == 1: sz = struct.unpack(">Q", data[p + 8:p + 16])[0]; hdr = 16
        elif sz == 0: sz = end - p
        yield typ, p, sz, hdr
        p += sz


def _find(data, start, end, path):
    for typ, p, sz, hdr in _boxes(data, start, end):
        if typ == path[0]:
            if len(path) == 1: return p, sz, hdr
            r = _find(data, p + hdr, p + sz, path[1:])
            if r: return r
    return None


def _read_table(data, box, entry_fmt, n_at, first_at):
    body = box[0] + box[2]
    n = struct.unpack(">I", data[body + n_at:body + n_at + 4])[0]
    esz = struct.calcsize(">" + entry_fmt)
    ents = [struct.unpack(">" + entry_fmt, data[body + first_at + i * esz:body + first_at + (i + 1) * esz]) for i in range(n)]
    return n, ents, body + first_at


def inject_mp4(src, dst, payload_fn, uuid: bytes = SIDECAR_UUID):
    """Insert one SEI per sample into a video-only mp4 IN PLACE (stsz/stco fixed, timing kept)."""
    data = Path(src).read_bytes(); top = list(_boxes(data, 0, len(data)))
    moov = next(b for b in top if b[0] == b"moov"); mdat = next(b for b in top if b[0] == b"mdat")
    traks = [b for b in _boxes(data, moov[1] + moov[3], moov[1] + moov[2]) if b[0] == b"trak"]
    assert len(traks) == 1, "expects a video-only mp4 (use ffmpeg -an)"
    _, tp, tsz, thd = traks[0]
    stbl = _find(data, tp + thd, tp + tsz, [b"mdia", b"minf", b"stbl"]); sp, ssz, shd = stbl
    stsz = _find(data, sp + shd, sp + ssz, [b"stsz"]); stsc = _find(data, sp + shd, sp + ssz, [b"stsc"])
    stco = _find(data, sp + shd, sp + ssz, [b"stco"]); co64 = None if stco else _find(data, sp + shd, sp + ssz, [b"co64"])
    stsd = _find(data, sp + shd, sp + ssz, [b"stsd"]); avcc = data.find(b"avcC", stsd[0], stsd[0] + stsd[1])
    assert (data[avcc + 8] & 3) + 1 == 4, "expects 4-byte NAL length prefixes"
    assert struct.unpack(">I", data[stsz[0] + stsz[2] + 4:stsz[0] + stsz[2] + 8])[0] == 0
    count, sizes, sizes_at = _read_table(data, stsz, "I", 8, 12); sizes = [s[0] for s in sizes]
    if stco: n_chunks, offs, offs_at = _read_table(data, stco, "I", 4, 8)
    else: n_chunks, offs, offs_at = _read_table(data, co64, "Q", 4, 8)
    offs = [o[0] for o in offs]
    n_sc, sc, _ = _read_table(data, stsc, "III", 4, 8)
    per_chunk = []
    for i, (first, spc, _) in enumerate(sc):
        last = sc[i + 1][0] if i + 1 < n_sc else n_chunks + 1
        per_chunk += [spc] * (last - first)
    assert len(per_chunk) == n_chunks and sum(per_chunk) == count
    new_samples, new_sizes, added, d = [], [], 0, 0
    for c in range(n_chunks):
        off = offs[c]
        for _ in range(per_chunk[c]):
            s = data[off:off + sizes[d]]; off += sizes[d]
            nals, p = [], 0
            while p < len(s):
                ln = struct.unpack(">I", s[p:p + 4])[0]; nals.append(s[p + 4:p + 4 + ln]); p += 4 + ln
            fv = next(i for i, n in enumerate(nals) if is_vcl(n))
            sei = build_sei_nal(payload_fn(d), uuid); nals.insert(fv, sei)
            ns = b"".join(struct.pack(">I", len(n)) + n for n in nals)
            new_samples.append(ns); new_sizes.append(len(ns)); added += 4 + len(sei); d += 1
    body = b"".join(new_samples); assert len(body) + 8 < 2 ** 32
    new_offs, run_pos, d = [], mdat[1] + 8, 0
    for c in range(n_chunks):
        new_offs.append(run_pos)
        for _ in range(per_chunk[c]): run_pos += new_sizes[d]; d += 1
    moov_b = bytearray(data[moov[1]:moov[1] + moov[2]])
    q = sizes_at - moov[1]; moov_b[q:q + 4 * count] = struct.pack(f">{count}I", *new_sizes)
    q = offs_at - moov[1]
    if stco: assert max(new_offs) < 2 ** 32; moov_b[q:q + 4 * n_chunks] = struct.pack(f">{n_chunks}I", *new_offs)
    else: moov_b[q:q + 8 * n_chunks] = struct.pack(f">{n_chunks}Q", *new_offs)
    out = bytearray()
    for typ, p, sz, hdr in top:
        if typ == b"mdat": out += struct.pack(">I4s", 8 + len(body), b"mdat") + body
        elif typ == b"moov": out += moov_b
        else: out += data[p:p + sz]
    Path(dst).write_bytes(bytes(out))
    return {"aus": count, "sei_bytes_total": added, "sei_bytes_per_frame": added / count,
            "in_bytes": len(data), "out_bytes": len(out)}


# ------------------------------------------------------------------ extract
def extract_annexb(data: bytes, uuid: bytes = SIDECAR_UUID):
    """-> list per access unit (decode order) of the sidecar payloads found in it."""
    nals = split_annexb(data); aus = group_aus(nals); recs = []
    for d, au in enumerate(aus):
        mine = []
        for i in au:
            sc, nal = nals[i]
            if nal_type(nal) != 6: continue
            for pt, pl in parse_sei(nal):
                if pt == 5 and pl[:16] == uuid: mine.append(pl[16:])
        recs.append(mine)
    return recs


def extract(path, uuid: bytes = SIDECAR_UUID, ffmpeg="ffmpeg"):
    """Extract from .h264 directly, or from any container ffmpeg can copy to Annex-B."""
    path = Path(path)
    if path.suffix.lower() in (".h264", ".264"):
        return extract_annexb(path.read_bytes(), uuid)
    p = subprocess.run([ffmpeg, "-v", "error", "-i", str(path), "-an", "-c:v", "copy",
                        "-bsf:v", "h264_mp4toannexb", "-f", "h264", "-"], capture_output=True, check=True)
    return extract_annexb(p.stdout, uuid)


def json_payload(fn):
    """Wrap a dict-producing function into a bytes payload_fn that stamps the decode index."""
    def _p(d):
        m = fn(d); m = dict(m or {}); m.setdefault("d", d)
        return json.dumps(m, separators=(",", ":")).encode()
    return _p
