- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage) - hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench) - android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive - protocol: architecture, MCP schema, and WebSocket protocol specs
331 lines
12 KiB
Python
331 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
import struct
|
|
from typing import Iterable
|
|
|
|
|
|
def _mp4_box(box_type: bytes, payload: bytes) -> bytes:
|
|
return struct.pack(">I", 8 + len(payload)) + box_type + payload
|
|
|
|
|
|
def _mp4_full_box(box_type: bytes, version: int, flags: int, payload: bytes) -> bytes:
|
|
vf = ((version & 0xFF) << 24) | (flags & 0xFFFFFF)
|
|
return _mp4_box(box_type, struct.pack(">I", vf) + payload)
|
|
|
|
|
|
_IDENTITY_MATRIX = struct.pack(
|
|
">9I",
|
|
0x00010000, 0, 0,
|
|
0, 0x00010000, 0,
|
|
0, 0, 0x40000000,
|
|
)
|
|
|
|
|
|
def _find_start_codes(buf: bytes | bytearray) -> list[tuple[int, int]]:
|
|
"""Returns list of (start_code_offset, nal_payload_offset) for every Annex-B start code in buf."""
|
|
res: list[tuple[int, int]] = []
|
|
n = len(buf)
|
|
i = 0
|
|
while i < n - 3:
|
|
pos = buf.find(b"\x00\x00\x01", i)
|
|
if pos < 0:
|
|
break
|
|
if pos > 0 and buf[pos - 1] == 0:
|
|
sc_start = pos - 1
|
|
else:
|
|
sc_start = pos
|
|
nal_start = pos + 3
|
|
if res and sc_start < res[-1][1]:
|
|
sc_start = pos
|
|
res.append((sc_start, nal_start))
|
|
i = nal_start
|
|
return res
|
|
|
|
|
|
class AnnexBAccessUnitFramer:
|
|
"""Zero-hold Annex-B H.264 Access Unit framer.
|
|
|
|
Unlike FFmpeg's av_parser_parse2 (which permanently traps the newest frame
|
|
until the NEXT frame's start code arrives), this framer emits each Access Unit
|
|
immediately on the next frame boundary AND supports `flush_idle()` after a
|
|
brief read timeout (~45ms) so the final frame of a burst or initial static
|
|
screen IDR is delivered immediately.
|
|
"""
|
|
|
|
def __init__(self) -> None:
|
|
self._buf = bytearray()
|
|
self._cur_nals: list[bytes] = []
|
|
self._cur_has_vcl = False
|
|
self._cur_is_idr = False
|
|
|
|
def reset(self) -> None:
|
|
self._buf.clear()
|
|
self._cur_nals.clear()
|
|
self._cur_has_vcl = False
|
|
self._cur_is_idr = False
|
|
|
|
def _emit_current(self) -> tuple[list[bytes], bool] | None:
|
|
if not self._cur_has_vcl or not self._cur_nals:
|
|
return None
|
|
out = (list(self._cur_nals), self._cur_is_idr)
|
|
self._cur_nals.clear()
|
|
self._cur_has_vcl = False
|
|
self._cur_is_idr = False
|
|
return out
|
|
|
|
def _ingest_nal(self, nal: bytes, ready: list[tuple[list[bytes], bool]]) -> None:
|
|
if not nal:
|
|
return
|
|
ntype = nal[0] & 0x1F
|
|
if ntype == 9: # AUD starts a new access unit
|
|
emitted = self._emit_current()
|
|
if emitted:
|
|
ready.append(emitted)
|
|
return
|
|
|
|
# If we already have a VCL slice in the current AU, check if this NAL begins the next AU
|
|
if self._cur_has_vcl:
|
|
if ntype in (6, 7, 8):
|
|
emitted = self._emit_current()
|
|
if emitted:
|
|
ready.append(emitted)
|
|
elif ntype in (1, 5):
|
|
# first_mb_in_slice == 0 in Exp-Golomb iff MSB of byte 1 is 1
|
|
is_new_pic = len(nal) > 1 and (nal[1] & 0x80) != 0
|
|
if is_new_pic:
|
|
emitted = self._emit_current()
|
|
if emitted:
|
|
ready.append(emitted)
|
|
|
|
self._cur_nals.append(nal)
|
|
if ntype == 5:
|
|
self._cur_has_vcl = True
|
|
self._cur_is_idr = True
|
|
elif ntype == 1:
|
|
self._cur_has_vcl = True
|
|
|
|
def feed(self, chunk: bytes) -> list[tuple[list[bytes], bool]]:
|
|
"""Feeds incoming raw Annex-B bytes and returns all immediately complete Access Units."""
|
|
if not chunk:
|
|
return []
|
|
self._buf.extend(chunk)
|
|
# Guard against corrupted runaway buffer
|
|
if len(self._buf) > 4 * 1024 * 1024:
|
|
self.reset()
|
|
return []
|
|
|
|
codes = _find_start_codes(self._buf)
|
|
if len(codes) < 2:
|
|
return []
|
|
|
|
ready: list[tuple[list[bytes], bool]] = []
|
|
# Every NAL between code[k] and code[k+1] is guaranteed complete
|
|
for k in range(len(codes) - 1):
|
|
_, nal_start = codes[k]
|
|
next_sc, _ = codes[k + 1]
|
|
if next_sc > nal_start:
|
|
nal = bytes(self._buf[nal_start:next_sc])
|
|
self._ingest_nal(nal, ready)
|
|
|
|
# Keep only from the last start code onward
|
|
last_sc, _ = codes[-1]
|
|
del self._buf[:last_sc]
|
|
return ready
|
|
|
|
def flush_idle(self) -> list[tuple[list[bytes], bool]]:
|
|
"""Flushes the trailing NAL/AU once the input pipe goes idle (e.g. 45ms timeout)."""
|
|
ready: list[tuple[list[bytes], bool]] = []
|
|
if self._buf:
|
|
codes = _find_start_codes(self._buf)
|
|
if codes:
|
|
_, nal_start = codes[-1]
|
|
# Only flush if we have a real VCL NAL in progress or already buffered
|
|
if nal_start < len(self._buf):
|
|
trailing = bytes(self._buf[nal_start:])
|
|
ntype = trailing[0] & 0x1F
|
|
# Don't flush if trailing is only SPS/PPS without VCL yet
|
|
if ntype in (1, 5) or self._cur_has_vcl:
|
|
self._buf.clear()
|
|
self._ingest_nal(trailing, ready)
|
|
emitted = self._emit_current()
|
|
if emitted:
|
|
ready.append(emitted)
|
|
return ready
|
|
|
|
|
|
class ZeroLatencyFmp4Muxer:
|
|
"""Pure-Python ISO BMFF fMP4 muxer for H.264 with ZERO frame buffering.
|
|
|
|
Emits `ftyp+moov` init segment once SPS+PPS are observed, and emits a standalone
|
|
`moof+mdat` fragment for every single Access Unit in <0.1ms with monotonic
|
|
sequence_number and decode_time across seamless source restarts.
|
|
"""
|
|
|
|
def __init__(self, timescale: int = 90000, frame_duration: int = 3600) -> None:
|
|
self.timescale = timescale
|
|
self.frame_duration = frame_duration
|
|
self.sps: bytes | None = None
|
|
self.pps: bytes | None = None
|
|
self.width: int = 960
|
|
self.height: int = 540
|
|
self.mime: str = 'video/mp4; codecs="avc1.42c029"'
|
|
self.init_segment: bytes | None = None
|
|
self._seq_num: int = 0
|
|
self._decode_time: int = 0
|
|
|
|
def update_dimensions(self, width: int, height: int) -> None:
|
|
if width != self.width or height != self.height:
|
|
self.width = width
|
|
self.height = height
|
|
self.init_segment = None
|
|
|
|
def _build_init_segment(self, sps: bytes, pps: bytes) -> bytes:
|
|
w, h = self.width, self.height
|
|
ts = self.timescale
|
|
|
|
ftyp = _mp4_box(b"ftyp", b"isom" + struct.pack(">I", 512) + b"isomiso2avc1mp41")
|
|
|
|
mvhd_payload = (
|
|
struct.pack(">IIII", 0, 0, ts, 0)
|
|
+ struct.pack(">IH", 0x00010000, 0x0100)
|
|
+ b"\x00" * 10
|
|
+ _IDENTITY_MATRIX
|
|
+ b"\x00" * 24
|
|
+ struct.pack(">I", 2)
|
|
)
|
|
mvhd = _mp4_full_box(b"mvhd", 0, 0, mvhd_payload)
|
|
|
|
tkhd_payload = (
|
|
struct.pack(">IIIII", 0, 0, 1, 0, 0)
|
|
+ b"\x00" * 8
|
|
+ struct.pack(">HHHH", 0, 0, 0, 0)
|
|
+ _IDENTITY_MATRIX
|
|
+ struct.pack(">II", w << 16, h << 16)
|
|
)
|
|
tkhd = _mp4_full_box(b"tkhd", 0, 3, tkhd_payload)
|
|
|
|
mdhd = _mp4_full_box(b"mdhd", 0, 0, struct.pack(">IIIIHH", 0, 0, ts, 0, 0x55C4, 0))
|
|
hdlr = _mp4_full_box(b"hdlr", 0, 0, struct.pack(">I", 0) + b"vide" + b"\x00" * 12 + b"VideoHandler\x00")
|
|
vmhd = _mp4_full_box(b"vmhd", 0, 1, struct.pack(">HHHH", 0, 0, 0, 0))
|
|
url_box = _mp4_full_box(b"url ", 0, 1, b"")
|
|
dref = _mp4_full_box(b"dref", 0, 0, struct.pack(">I", 1) + url_box)
|
|
dinf = _mp4_box(b"dinf", dref)
|
|
|
|
profile = sps[1] if len(sps) > 1 else 0x42
|
|
compat = sps[2] if len(sps) > 2 else 0xC0
|
|
level = sps[3] if len(sps) > 3 else 0x29
|
|
self.mime = f'video/mp4; codecs="avc1.{profile:02x}{compat:02x}{level:02x}"'
|
|
|
|
avcc_payload = (
|
|
bytes([1, profile, compat, level, 0xFF, 0xE1])
|
|
+ struct.pack(">H", len(sps))
|
|
+ sps
|
|
+ bytes([1])
|
|
+ struct.pack(">H", len(pps))
|
|
+ pps
|
|
)
|
|
avcc = _mp4_box(b"avcC", avcc_payload)
|
|
|
|
avc1_payload = (
|
|
b"\x00" * 6
|
|
+ struct.pack(">H", 1)
|
|
+ b"\x00" * 16
|
|
+ struct.pack(">HH", w, h)
|
|
+ struct.pack(">II", 0x00480000, 0x00480000)
|
|
+ struct.pack(">I", 0)
|
|
+ struct.pack(">H", 1)
|
|
+ b"\x00" * 32
|
|
+ struct.pack(">HH", 0x0018, 0xFFFF)
|
|
+ avcc
|
|
)
|
|
avc1 = _mp4_box(b"avc1", avc1_payload)
|
|
stsd = _mp4_full_box(b"stsd", 0, 0, struct.pack(">I", 1) + avc1)
|
|
stts = _mp4_full_box(b"stts", 0, 0, struct.pack(">I", 0))
|
|
stsc = _mp4_full_box(b"stsc", 0, 0, struct.pack(">I", 0))
|
|
stsz = _mp4_full_box(b"stsz", 0, 0, struct.pack(">II", 0, 0))
|
|
stco = _mp4_full_box(b"stco", 0, 0, struct.pack(">I", 0))
|
|
stbl = _mp4_box(b"stbl", stsd + stts + stsc + stsz + stco)
|
|
minf = _mp4_box(b"minf", vmhd + dinf + stbl)
|
|
mdia = _mp4_box(b"mdia", mdhd + hdlr + minf)
|
|
trak = _mp4_box(b"trak", tkhd + mdia)
|
|
|
|
trex = _mp4_full_box(
|
|
b"trex",
|
|
0,
|
|
0,
|
|
struct.pack(">IIIII", 1, 1, self.frame_duration, 0, 0x01010000),
|
|
)
|
|
mvex = _mp4_box(b"mvex", trex)
|
|
moov = _mp4_box(b"moov", mvhd + trak + mvex)
|
|
return ftyp + moov
|
|
|
|
def mux_access_unit(
|
|
self,
|
|
nals: Iterable[bytes],
|
|
is_idr: bool,
|
|
) -> tuple[bytes | None, bytes | None]:
|
|
"""Returns (new_init_segment_or_None, media_fragment_or_None).
|
|
|
|
`new_init_segment` is returned ONLY when SPS/PPS first appear or change,
|
|
so seamless restarts at identical resolution never tear down browser MSE!
|
|
"""
|
|
nal_list = [n for n in nals if n]
|
|
if not nal_list:
|
|
return None, None
|
|
|
|
sps_changed = False
|
|
avcc_parts: list[bytes] = []
|
|
for nal in nal_list:
|
|
ntype = nal[0] & 0x1F
|
|
if ntype == 7:
|
|
if self.sps != nal:
|
|
self.sps = nal
|
|
sps_changed = True
|
|
elif ntype == 8:
|
|
if self.pps != nal:
|
|
self.pps = nal
|
|
sps_changed = True
|
|
if ntype != 9:
|
|
avcc_parts.append(struct.pack(">I", len(nal)) + nal)
|
|
|
|
new_init: bytes | None = None
|
|
if self.sps and self.pps and (self.init_segment is None or sps_changed):
|
|
self.init_segment = self._build_init_segment(self.sps, self.pps)
|
|
new_init = self.init_segment
|
|
|
|
if self.init_segment is None or not avcc_parts:
|
|
return new_init, None
|
|
|
|
mdat_payload = b"".join(avcc_parts)
|
|
self._seq_num += 1
|
|
decode_time = self._decode_time
|
|
self._decode_time += self.frame_duration
|
|
|
|
sample_flags = 0x02000000 if is_idr else 0x01010000
|
|
mfhd = _mp4_full_box(b"mfhd", 0, 0, struct.pack(">I", self._seq_num))
|
|
tfhd = _mp4_full_box(b"tfhd", 0, 0x020000, struct.pack(">I", 1))
|
|
tfdt = _mp4_full_box(b"tfdt", 1, 0, struct.pack(">Q", decode_time))
|
|
|
|
def _make_moof(data_offset: int) -> bytes:
|
|
# flags 0x000701: data-offset | sample-duration | sample-size | sample-flags
|
|
trun = _mp4_full_box(
|
|
b"trun",
|
|
0,
|
|
0x000701,
|
|
struct.pack(
|
|
">IiIII",
|
|
1,
|
|
data_offset,
|
|
self.frame_duration,
|
|
len(mdat_payload),
|
|
sample_flags,
|
|
),
|
|
)
|
|
traf = _mp4_box(b"traf", tfhd + tfdt + trun)
|
|
return _mp4_box(b"moof", mfhd + traf)
|
|
|
|
probe_moof = _make_moof(0)
|
|
moof = _make_moof(len(probe_moof) + 8)
|
|
mdat = _mp4_box(b"mdat", mdat_payload)
|
|
return new_init, moof + mdat
|