refactor(perception): decode bounded fMP4 without source file dependencies

This commit is contained in:
DCCONSTRUCTIONS
2026-09-02 13:07:33 +03:00
parent c23e86fd39
commit 350366bae0
4 changed files with 765 additions and 341 deletions
+16 -341
View File
@@ -8,12 +8,14 @@ import re
import secrets
import stat
import threading
from collections.abc import Iterable, Iterator
from collections.abc import Iterable
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, TypeGuard
from k1link import media_fragments as _fragment_timing
from .models import RecordedMediaArtifact, ReplayCommand, SessionIntegrityError
CAMERA_ARCHIVE_SCHEMA = "missioncore.camera-recording/v1"
@@ -25,8 +27,8 @@ MAX_MEDIA_INDEX_LINE_BYTES = 64 * 1024
MAX_INIT_BYTES = 8 * 1024 * 1024
MAX_MEDIA_SEGMENT_BYTES = 64 * 1024 * 1024
MAX_SAFE_INTEGER = (1 << 53) - 1
MAX_MP4_BOXES = 100_000
MAX_MP4_SAMPLES_PER_FRAGMENT = 1_000_000
MAX_MP4_BOXES = _fragment_timing.MAX_MP4_BOXES
MAX_MP4_SAMPLES_PER_FRAGMENT = _fragment_timing.MAX_MP4_SAMPLES_PER_FRAGMENT
MAX_MP4_FRAGMENT_DURATION_SECONDS = 3_600.0
MEDIA_RECORDING_TIMELINE_TOLERANCE_SECONDS = 0.05
MAX_MEDIA_EPOCHS = 4_096
@@ -88,39 +90,9 @@ class _CachedManifest:
manifest: RecordedMediaManifest
@dataclass(frozen=True, slots=True)
class _Mp4VideoTiming:
track_id: int
timescale: int
default_sample_duration: int | None
default_sample_flags: int | None
@dataclass(frozen=True, slots=True)
class _Mp4VideoFragmentTiming:
base_decode_time: int
duration_units: int
random_access: bool
@property
def end_decode_time(self) -> int:
return self.base_decode_time + self.duration_units
@dataclass(slots=True)
class _Mp4ParseBudget:
boxes_remaining: int = MAX_MP4_BOXES
samples_remaining: int = MAX_MP4_SAMPLES_PER_FRAGMENT
def consume_box(self) -> None:
self.boxes_remaining -= 1
if self.boxes_remaining < 0:
raise SessionIntegrityError("recorded media ISO-BMFF box budget was exceeded")
def consume_samples(self, count: int) -> None:
if count < 0 or count > self.samples_remaining:
raise SessionIntegrityError("recorded media ISO-BMFF sample budget was exceeded")
self.samples_remaining -= count
_Mp4VideoTiming = _fragment_timing.VideoTiming
_Mp4VideoFragmentTiming = _fragment_timing.VideoFragmentTiming
_Mp4ParseBudget = _fragment_timing.ParseBudget
class RecordedMediaInspector:
@@ -1155,85 +1127,10 @@ def _checked_fragment_duration_seconds(duration_units: int, timescale: int) -> f
def _mp4_video_timing(payload: bytes, budget: _Mp4ParseBudget) -> _Mp4VideoTiming:
moov_payloads = [
box_payload
for box_type, box_payload in _iter_mp4_boxes(payload, budget)
if box_type == b"moov"
]
if len(moov_payloads) != 1:
raise SessionIntegrityError("recorded media init has no unique moov box")
moov = moov_payloads[0]
moov_boxes = tuple(_iter_mp4_boxes(moov, budget))
defaults: dict[int, tuple[int, int]] = {}
for box_type, box_payload in moov_boxes:
if box_type != b"mvex":
continue
for child_type, child_payload in _iter_mp4_boxes(box_payload, budget):
if child_type != b"trex":
continue
track_id, trex_default_duration, trex_default_flags = _parse_trex(child_payload)
if track_id in defaults:
raise SessionIntegrityError("recorded media init repeats a trex track")
defaults[track_id] = (trex_default_duration, trex_default_flags)
video_tracks: list[tuple[int, int]] = []
for box_type, trak_payload in moov_boxes:
if box_type != b"trak":
continue
track_id = _trak_track_id(trak_payload, budget)
media = _trak_media_timing(trak_payload, budget)
if media is not None:
video_tracks.append((track_id, media))
if len(video_tracks) != 1:
raise SessionIntegrityError("recorded media init has no unique video track")
track_id, timescale = video_tracks[0]
default_sample = defaults.get(track_id)
default_duration = None if default_sample is None else default_sample[0]
return _Mp4VideoTiming(
track_id=track_id,
timescale=timescale,
default_sample_duration=(
default_duration if default_duration is not None and default_duration > 0 else None
),
default_sample_flags=None if default_sample is None else default_sample[1],
)
def _trak_track_id(payload: bytes, budget: _Mp4ParseBudget) -> int:
track_ids = [
_parse_tkhd_track_id(box_payload)
for box_type, box_payload in _iter_mp4_boxes(payload, budget)
if box_type == b"tkhd"
]
if len(track_ids) != 1 or track_ids[0] <= 0:
raise SessionIntegrityError("recorded media track id is invalid")
return track_ids[0]
def _trak_media_timing(payload: bytes, budget: _Mp4ParseBudget) -> int | None:
media_boxes = [
box_payload
for box_type, box_payload in _iter_mp4_boxes(payload, budget)
if box_type == b"mdia"
]
if len(media_boxes) != 1:
raise SessionIntegrityError("recorded media track has no unique mdia box")
children = tuple(_iter_mp4_boxes(media_boxes[0], budget))
handlers = [
_parse_hdlr_type(box_payload) for box_type, box_payload in children if box_type == b"hdlr"
]
if len(handlers) != 1:
raise SessionIntegrityError("recorded media track handler is ambiguous")
if handlers[0] != b"vide":
return None
timescales = [
_parse_mdhd_timescale(box_payload)
for box_type, box_payload in children
if box_type == b"mdhd"
]
if len(timescales) != 1 or timescales[0] <= 0:
raise SessionIntegrityError("recorded media video timescale is invalid")
return timescales[0]
try:
return _fragment_timing.video_timing(payload, budget)
except _fragment_timing.Mp4IntegrityError as exc:
raise SessionIntegrityError(str(exc)) from exc
def _mp4_video_fragment_timing(
@@ -1241,232 +1138,10 @@ def _mp4_video_fragment_timing(
timing: _Mp4VideoTiming,
budget: _Mp4ParseBudget,
) -> _Mp4VideoFragmentTiming:
moof_payloads = [
box_payload
for box_type, box_payload in _iter_mp4_boxes(payload, budget)
if box_type == b"moof"
]
if len(moof_payloads) != 1:
raise SessionIntegrityError("recorded media fragment has no unique moof box")
matching_timings: list[_Mp4VideoFragmentTiming] = []
for box_type, traf_payload in _iter_mp4_boxes(moof_payloads[0], budget):
if box_type != b"traf":
continue
boxes = tuple(_iter_mp4_boxes(traf_payload, budget))
tfhd_payloads = [box for kind, box in boxes if kind == b"tfhd"]
if len(tfhd_payloads) != 1:
raise SessionIntegrityError("recorded media fragment tfhd is ambiguous")
track_id, fragment_default_duration, fragment_default_flags = _parse_tfhd(tfhd_payloads[0])
if track_id != timing.track_id:
continue
tfdt_payloads = [box for kind, box in boxes if kind == b"tfdt"]
if len(tfdt_payloads) != 1:
raise SessionIntegrityError("recorded media fragment tfdt is ambiguous")
base_decode_time = _parse_tfdt(tfdt_payloads[0])
trun_payloads = [box for kind, box in boxes if kind == b"trun"]
if not trun_payloads:
raise SessionIntegrityError("recorded media video fragment has no trun box")
default_duration = fragment_default_duration or timing.default_sample_duration
default_flags = (
fragment_default_flags
if fragment_default_flags is not None
else timing.default_sample_flags
)
trun_descriptors = tuple(
_parse_trun_descriptor(trun, default_duration, default_flags, budget)
for trun in trun_payloads
)
fragment_sample_count = sum(item[2] for item in trun_descriptors)
if fragment_sample_count != 1:
raise SessionIntegrityError(
"recorded media video fragment must contain exactly one sample"
)
duration = sum(item[0] for item in trun_descriptors)
if base_decode_time > MAX_SAFE_INTEGER - duration:
raise SessionIntegrityError("recorded media fragment decode time is outside bounds")
matching_timings.append(
_Mp4VideoFragmentTiming(
base_decode_time=base_decode_time,
duration_units=duration,
random_access=(trun_descriptors[0][1] & 0x00010000) == 0,
)
)
if len(matching_timings) != 1:
raise SessionIntegrityError("recorded media fragment video track is ambiguous")
return matching_timings[0]
def _iter_mp4_boxes(
payload: bytes,
budget: _Mp4ParseBudget,
) -> Iterator[tuple[bytes, bytes]]:
offset = 0
payload_length = len(payload)
while offset < payload_length:
if payload_length - offset < 8:
raise SessionIntegrityError("recorded media ISO-BMFF box is truncated")
size = int.from_bytes(payload[offset : offset + 4], "big")
box_type = payload[offset + 4 : offset + 8]
header_length = 8
if size == 1:
if payload_length - offset < 16:
raise SessionIntegrityError("recorded media ISO-BMFF box is truncated")
size = int.from_bytes(payload[offset + 8 : offset + 16], "big")
header_length = 16
elif size == 0:
size = payload_length - offset
if size < header_length or size > payload_length - offset:
raise SessionIntegrityError("recorded media ISO-BMFF box size is invalid")
budget.consume_box()
end = offset + size
yield box_type, payload[offset + header_length : end]
offset = end
def _parse_tkhd_track_id(payload: bytes) -> int:
version = _full_box_version(payload)
offset = 20 if version == 1 else 12 if version == 0 else -1
return _read_u32(payload, offset, "tkhd track id")
def _parse_mdhd_timescale(payload: bytes) -> int:
version = _full_box_version(payload)
offset = 20 if version == 1 else 12 if version == 0 else -1
return _read_u32(payload, offset, "mdhd timescale")
def _parse_hdlr_type(payload: bytes) -> bytes:
_full_box_version(payload)
if len(payload) < 12:
raise SessionIntegrityError("recorded media hdlr box is truncated")
return payload[8:12]
def _parse_trex(payload: bytes) -> tuple[int, int, int]:
_full_box_version(payload)
return (
_read_u32(payload, 4, "trex track id"),
_read_u32(payload, 12, "trex default sample duration"),
_read_u32(payload, 20, "trex default sample flags"),
)
def _parse_tfhd(payload: bytes) -> tuple[int, int | None, int | None]:
flags = _full_box_flags(payload)
track_id = _read_u32(payload, 4, "tfhd track id")
cursor = 8
for flag, width in ((0x000001, 8), (0x000002, 4)):
if flags & flag:
cursor = _advance_box_cursor(payload, cursor, width, "tfhd optional field")
default_duration: int | None = None
if flags & 0x000008:
default_duration = _read_u32(payload, cursor, "tfhd default sample duration")
cursor += 4
if flags & 0x000010:
cursor = _advance_box_cursor(payload, cursor, 4, "tfhd default sample size")
default_flags: int | None = None
if flags & 0x000020:
default_flags = _read_u32(payload, cursor, "tfhd default sample flags")
return (
track_id,
default_duration if default_duration and default_duration > 0 else None,
default_flags,
)
def _parse_tfdt(payload: bytes) -> int:
version = _full_box_version(payload)
if version == 0:
return _read_u32(payload, 4, "tfdt base decode time")
if version == 1:
if len(payload) < 12:
raise SessionIntegrityError("recorded media tfdt base decode time is truncated")
return int.from_bytes(payload[4:12], "big")
raise SessionIntegrityError("recorded media tfdt version is unsupported")
def _parse_trun_descriptor(
payload: bytes,
default_duration: int | None,
default_sample_flags: int | None,
budget: _Mp4ParseBudget,
) -> tuple[int, int, int]:
flags = _full_box_flags(payload)
sample_count = _read_u32(payload, 4, "trun sample count")
if sample_count < 1:
raise SessionIntegrityError("recorded media trun has no samples")
budget.consume_samples(sample_count)
cursor = 8
if flags & 0x000001:
cursor = _advance_box_cursor(payload, cursor, 4, "trun data offset")
first_sample_flags: int | None = None
if flags & 0x000004:
first_sample_flags = _read_u32(payload, cursor, "trun first sample flags")
cursor += 4
if first_sample_flags is not None and flags & 0x000400:
raise SessionIntegrityError("recorded media trun sample flags are ambiguous")
duration = 0
first_per_sample_flags: int | None = None
for sample_index in range(sample_count):
if flags & 0x000100:
sample_duration = _read_u32(payload, cursor, "trun sample duration")
if sample_duration <= 0:
raise SessionIntegrityError("recorded media sample duration is invalid")
duration += sample_duration
cursor += 4
elif default_duration is None or default_duration <= 0:
raise SessionIntegrityError("recorded media sample duration is unavailable")
else:
duration += default_duration
if flags & 0x000200:
cursor = _advance_box_cursor(payload, cursor, 4, "trun sample size")
if flags & 0x000400:
sample_flags = _read_u32(payload, cursor, "trun sample flags")
if sample_index == 0:
first_per_sample_flags = sample_flags
cursor += 4
if flags & 0x000800:
cursor = _advance_box_cursor(
payload,
cursor,
4,
"trun sample composition time offset",
)
effective_flags = (
first_per_sample_flags
if first_per_sample_flags is not None
else first_sample_flags
if first_sample_flags is not None
else default_sample_flags
)
if effective_flags is None:
raise SessionIntegrityError("recorded media sample flags are unavailable")
return duration, effective_flags, sample_count
def _full_box_version(payload: bytes) -> int:
if len(payload) < 4:
raise SessionIntegrityError("recorded media full box is truncated")
return payload[0]
def _full_box_flags(payload: bytes) -> int:
_full_box_version(payload)
return int.from_bytes(payload[1:4], "big")
def _read_u32(payload: bytes, offset: int, description: str) -> int:
if offset < 0 or offset + 4 > len(payload):
raise SessionIntegrityError(f"recorded media {description} is truncated")
return int.from_bytes(payload[offset : offset + 4], "big")
def _advance_box_cursor(payload: bytes, cursor: int, width: int, description: str) -> int:
if cursor < 0 or width < 0 or cursor + width > len(payload):
raise SessionIntegrityError(f"recorded media {description} is truncated")
return cursor + width
try:
return _fragment_timing.video_fragment_timing(payload, timing, budget)
except _fragment_timing.Mp4IntegrityError as exc:
raise SessionIntegrityError(str(exc)) from exc
def _mp4_media_type(init_payload: bytes) -> str: