feat(video): recover camera previews and reduce encoding and playout cost
Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
"""Original transfer bounds, idempotency and camera-control exclusion; fake SDK."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from runtime import archive # noqa: E402
|
||||
|
||||
ID = "file_" + "a" * 32
|
||||
SOURCE = "/DCIM/Camera01/VID_20261014_120000_00_001.insv"
|
||||
|
||||
|
||||
class ArchiveTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory(dir=ROOT / "build")
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
self.gate = threading.Lock()
|
||||
self.camera = Mock()
|
||||
self.manager = archive.Archive(self.camera, Path(self.folder.name), self.gate)
|
||||
self.life = patch.object(archive, "acquisition", return_value=nullcontext())
|
||||
self.space = patch.object(
|
||||
archive.shutil, "disk_usage", return_value=Mock(free=16 * 1024**3)
|
||||
)
|
||||
self.life.start()
|
||||
self.space.start()
|
||||
self.addCleanup(patch.stopall)
|
||||
|
||||
def wait(self):
|
||||
deadline = time.monotonic() + 3
|
||||
while self.manager.busy() and time.monotonic() < deadline:
|
||||
time.sleep(0.005)
|
||||
self.assertFalse(self.manager.busy())
|
||||
return self.manager.status(ID)
|
||||
|
||||
def complete(self, source, destination, progress):
|
||||
# SDK transports may announce (0, 0) before receiving Content-Length.
|
||||
progress(0, 0)
|
||||
destination.write_bytes(b"original")
|
||||
progress(8, 8)
|
||||
return True
|
||||
|
||||
def test_verified_original_chunks_and_same_identity_do_not_repeat_sdk(self):
|
||||
self.camera.download.side_effect = self.complete
|
||||
self.manager.start(ID, SOURCE)
|
||||
status = self.wait()
|
||||
self.assertEqual(status["state"], "complete")
|
||||
self.assertEqual(status["sha256"], hashlib.sha256(b"original").hexdigest())
|
||||
self.assertEqual(self.manager.read(ID, 2), b"iginal")
|
||||
self.assertEqual(self.manager.start(ID, SOURCE), status)
|
||||
self.camera.download.assert_called_once()
|
||||
self.assertTrue(self.gate.acquire(blocking=False))
|
||||
self.gate.release()
|
||||
with self.assertRaises(ValueError):
|
||||
self.manager.start(ID, SOURCE.replace("001", "002"))
|
||||
with self.assertRaises(ValueError):
|
||||
self.manager.read(ID, 8)
|
||||
|
||||
def test_busy_transfer_owns_gate_until_sdk_really_returns(self):
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def slow(*args):
|
||||
entered.set()
|
||||
release.wait(2)
|
||||
return self.complete(*args)
|
||||
|
||||
self.camera.download.side_effect = slow
|
||||
try:
|
||||
self.manager.start(ID, SOURCE)
|
||||
self.assertTrue(entered.wait(1))
|
||||
self.assertFalse(self.gate.acquire(blocking=False))
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.manager.start("file_" + "b" * 32, SOURCE)
|
||||
with self.assertRaises(ValueError):
|
||||
self.manager.read(ID, 0)
|
||||
finally:
|
||||
release.set()
|
||||
self.wait()
|
||||
|
||||
def test_failed_and_interrupted_files_are_retained_and_not_restarted(self):
|
||||
def failed(source, destination, progress):
|
||||
destination.write_bytes(b"part")
|
||||
progress(4, 8)
|
||||
return False
|
||||
|
||||
self.camera.download.side_effect = failed
|
||||
self.manager.start(ID, SOURCE)
|
||||
self.assertEqual(self.wait()["state"], "error")
|
||||
path = self.manager.folder(ID)
|
||||
self.assertEqual((path / "original.insv").read_bytes(), b"part")
|
||||
value = json.loads((path / "receipt.json").read_text())
|
||||
value["state"] = "running"
|
||||
(path / "receipt.json").write_text(json.dumps(value))
|
||||
self.assertEqual(self.manager.start(ID, SOURCE)["state"], "interrupted")
|
||||
self.camera.download.assert_called_once()
|
||||
|
||||
def test_timeout_requests_cancel_without_releasing_live_sdk_ownership(self):
|
||||
def slow(source, destination, progress):
|
||||
time.sleep(0.15)
|
||||
self.assertTrue(self.manager.busy())
|
||||
return self.complete(source, destination, progress)
|
||||
|
||||
self.camera.download.side_effect = slow
|
||||
with patch.object(archive, "TIMEOUT", 0):
|
||||
self.manager.start(ID, SOURCE)
|
||||
self.assertEqual(self.wait()["state"], "error")
|
||||
self.camera.cancel_download.assert_called_once()
|
||||
|
||||
def test_oversized_or_inconsistent_progress_cannot_mark_file_complete(self):
|
||||
for downloaded, total in ((8, archive.MAX_BYTES + 1), (8, 0), (7, 8)):
|
||||
ident = "file_" + f"{total + 1:032x}"
|
||||
|
||||
def invalid(source, destination, progress, downloaded=downloaded, total=total):
|
||||
destination.write_bytes(b"original")
|
||||
progress(downloaded, total)
|
||||
return True
|
||||
|
||||
self.camera.download.side_effect = invalid
|
||||
self.manager.start(ident, SOURCE)
|
||||
deadline = time.monotonic() + 2
|
||||
while self.manager.busy() and time.monotonic() < deadline:
|
||||
time.sleep(0.005)
|
||||
self.assertEqual(self.manager.status(ident)["state"], "error")
|
||||
|
||||
def test_paths_and_space_reject_before_sdk_or_file_creation(self):
|
||||
for source in (
|
||||
"/etc/passwd",
|
||||
"http://camera/file.insv",
|
||||
"/DCIM/../x.insv",
|
||||
"/DCIM/a\\b.insv",
|
||||
):
|
||||
with self.assertRaises(ValueError):
|
||||
self.manager.start(ID, source)
|
||||
with (
|
||||
patch.object(archive.shutil, "disk_usage", return_value=Mock(free=0)),
|
||||
self.assertRaises(RuntimeError),
|
||||
):
|
||||
self.manager.start(ID, SOURCE)
|
||||
self.assertFalse(self.manager.folder(ID).exists())
|
||||
self.camera.download.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Synthetic tests of the privileged reader boundary; no camera or SDK use."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "packaging"))
|
||||
import media_live_source as source
|
||||
from media_live_qualification import calibration_bytes
|
||||
|
||||
DEVICE = "instax4_" + "0" * 32
|
||||
SESSION = "x4_" + "1" * 32
|
||||
|
||||
|
||||
class LiveReader(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.calibration = {
|
||||
"revision": 5,
|
||||
"camera_name": "X4",
|
||||
"offsets": ["factory", ""],
|
||||
"encode_type": 0,
|
||||
"crop": dict(source_width=8000, source_height=6000, width=5760, height=5760, x=0, y=0),
|
||||
}
|
||||
self.header = dict(
|
||||
cursor=1,
|
||||
generation=3,
|
||||
timestamp=100,
|
||||
stream_index=0,
|
||||
stream_type=0x20,
|
||||
codec=0,
|
||||
calibration_revision=5,
|
||||
bytes=5,
|
||||
gap=False,
|
||||
)
|
||||
self.details = {
|
||||
"state": "complete",
|
||||
"result": {"preview": 1, "recording": 0, "preview_calibration": self.calibration},
|
||||
}
|
||||
self.calls = []
|
||||
|
||||
def request(self, path, camera, *, cursor=None):
|
||||
self.calls.append((str(path), camera, cursor))
|
||||
if camera is None:
|
||||
return {"id": DEVICE, "session_id": SESSION, "online": True}
|
||||
if cursor is None:
|
||||
return self.details
|
||||
h = json.dumps(dict(self.header, cursor=cursor + 1)).encode()
|
||||
return struct.pack("!I", len(h)) + h + b"\0\0\1\x65x"
|
||||
|
||||
def run_source(self, warmup=0):
|
||||
messages = []
|
||||
# readiness deadline, start, loop, loop end, receipt duration
|
||||
ticks = (
|
||||
[0, 0] + [0] * 8 + [21, 21]
|
||||
if not warmup
|
||||
else [0, 0, 0, 1, 1, 2.1] + [2.1] * 7 + [21, 21]
|
||||
)
|
||||
with (
|
||||
patch.object(source, "request", side_effect=self.request),
|
||||
patch.object(source, "read_exact", return_value=b"START\n"),
|
||||
patch.object(source.time, "monotonic", side_effect=ticks),
|
||||
patch.object(source, "WARMUP", warmup),
|
||||
patch.object(source, "independent_packet", return_value=True),
|
||||
patch.object(source, "emit_message", side_effect=lambda _, raw: messages.append(raw)),
|
||||
):
|
||||
result = source.source(DEVICE, SESSION, io.BytesIO(), io.BytesIO())
|
||||
return result, messages
|
||||
|
||||
def test_exact_original_bytes_and_calibration_forwarded_without_camera_mutation(self):
|
||||
result, messages = self.run_source()
|
||||
self.assertEqual(result["packets"], 8)
|
||||
self.assertTrue(result["preview_preserved"])
|
||||
self.assertEqual(json.loads(messages[0])["calibration"], self.calibration)
|
||||
self.assertTrue(messages[1].endswith(b"\0\0\1\x65x"))
|
||||
self.assertEqual(messages[-1], b"")
|
||||
self.assertEqual([c[2] for c in self.calls], [None, None, *range(8), None])
|
||||
self.assertTrue(all(c[0].endswith(DEVICE + "/driver.sock") for c in self.calls))
|
||||
|
||||
def test_startup_backlog_is_discarded_without_modifying_forwarded_bytes(self):
|
||||
result, messages = self.run_source(warmup=2)
|
||||
self.assertEqual(result["startup_discarded_packets"], 1)
|
||||
self.assertEqual(result["forwarded_packets"], 8)
|
||||
size = struct.unpack("!I", messages[1][8:12])[0]
|
||||
self.assertEqual(json.loads(messages[1][12 : 12 + size])["cursor"], 2)
|
||||
self.assertTrue(messages[1].endswith(b"\0\0\1\x65x"))
|
||||
|
||||
def test_keyframe_requires_original_parameter_sets_for_its_codec(self):
|
||||
def nal(kind):
|
||||
return b"\0\0\1" + bytes([kind]) + b"x"
|
||||
|
||||
self.assertTrue(source.independent_packet(nal(7) + nal(8) + nal(5), 0))
|
||||
self.assertFalse(source.independent_packet(nal(5), 0))
|
||||
self.assertFalse(source.independent_packet(nal(7) + nal(8) + nal(1), 0))
|
||||
self.assertTrue(
|
||||
source.independent_packet(b"".join(nal(n << 1) for n in [32, 33, 34, 19]), 1)
|
||||
)
|
||||
self.assertFalse(source.independent_packet(nal(19 << 1), 1))
|
||||
|
||||
def test_recording_or_inactive_preview_is_rejected_without_start_stop(self):
|
||||
for key, value in [("recording", 1), ("recording", None), ("preview", 0)]:
|
||||
with self.subTest(key=key, value=value):
|
||||
old = self.details["result"][key]
|
||||
self.details["result"][key] = value
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.run_source()
|
||||
self.details["result"][key] = old
|
||||
|
||||
def test_gap_revision_and_codec_changes_stop_the_sample(self):
|
||||
for key, value in [("gap", True), ("calibration_revision", 6), ("codec", 1)]:
|
||||
old = self.header[key]
|
||||
self.header[key] = value
|
||||
with self.subTest(key=key), self.assertRaises(ValueError):
|
||||
self.run_source()
|
||||
self.header[key] = old
|
||||
|
||||
def test_byte_limit_stops_before_sending_oversized_payload(self):
|
||||
with patch.object(source, "MAX_BYTES", 4), self.assertRaises(ValueError):
|
||||
self.run_source()
|
||||
|
||||
def test_no_identity_path_traversal(self):
|
||||
with self.assertRaises(ValueError):
|
||||
source.source("../../other", SESSION, io.BytesIO(), io.BytesIO())
|
||||
|
||||
def test_missing_calibration_and_invalid_geometry_rejected(self):
|
||||
valid = calibration_bytes(self.calibration)
|
||||
self.assertTrue(valid.startswith(b"MCX4L001"))
|
||||
self.calibration["crop"]["width"] = 99999
|
||||
with self.assertRaises(ValueError):
|
||||
calibration_bytes(self.calibration)
|
||||
self.calibration["crop"]["width"] = 5760
|
||||
self.calibration["offsets"] = ["", ""]
|
||||
with self.assertRaises(ValueError):
|
||||
calibration_bytes(self.calibration)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,6 +8,7 @@ import threading
|
||||
import unittest
|
||||
from fractions import Fraction
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription
|
||||
@@ -27,6 +28,194 @@ def packet(number, data=b"synthetic", generation=1):
|
||||
|
||||
|
||||
class FrameTests(unittest.TestCase):
|
||||
def test_encoder_recovers_above_an_already_applied_sustained_floor(self):
|
||||
from aiortc.rtcrtpparameters import RTCRtpCodecParameters
|
||||
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
|
||||
from aiortc import VideoStreamTrack
|
||||
now = [10.0]
|
||||
class Track(VideoStreamTrack):
|
||||
index = 0
|
||||
async def recv(self):
|
||||
import av
|
||||
frame = av.VideoFrame(64, 32, "yuv420p")
|
||||
for plane in frame.planes:
|
||||
plane.update(bytes(plane.buffer_size))
|
||||
self.index += 1
|
||||
frame.pts, frame.time_base = self.index * 6000, Fraction(1, 90000)
|
||||
return frame
|
||||
async def run():
|
||||
pc = RTCPeerConnection()
|
||||
budget = MediaBudget("video", clock=lambda: now[0])
|
||||
sender = pc.addTrack(Track())
|
||||
cap_video_sender(sender, budget)
|
||||
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
|
||||
try:
|
||||
for at, requested, expected in [(10, 100000, 100000), (10.1, 225000, 100000),
|
||||
(11, 365544, 100000), (12.2, 365544, 225000),
|
||||
(12.3, 365544, 225000), (14.4, 365544, 365000),
|
||||
(14.5, 160000, 160000)]:
|
||||
now[0] = at
|
||||
budget.target, budget.valid_until = requested, at + 3
|
||||
budget.profile = (640, 15)
|
||||
await sender._next_encoded_frame(codec)
|
||||
# libx264 reports its applied rate in whole kbit/s.
|
||||
self.assertEqual(sender._RTCRtpSender__encoder.codec.bit_rate, expected)
|
||||
self.assertEqual(sender._RTCRtpSender__encoder.codec.thread_count, 2)
|
||||
self.assertFalse(sender._RTCRtpSender__encoder.codec.has_b_frames)
|
||||
finally:
|
||||
await pc.close()
|
||||
budget.connection.close()
|
||||
asyncio.run(run())
|
||||
|
||||
def test_preview_priority_is_typed_and_legacy_offer_remains_valid(self):
|
||||
from runtime.native import parameters
|
||||
offer = {"sdp":"v=0", "layer":"preview"}
|
||||
self.assertEqual(parameters("offer",offer), (0,"",0.))
|
||||
self.assertEqual(parameters("offer",{**offer,"primary":True}), (0,"",0.))
|
||||
with self.assertRaises(ValueError):parameters("offer",{**offer,"primary":1})
|
||||
with self.assertRaises(ValueError):parameters("offer",{**offer,"bypass":True})
|
||||
|
||||
def test_adaptive_encoder_is_capped_below_stock_codec_floor(self):
|
||||
import av
|
||||
from aiortc import VideoStreamTrack
|
||||
from aiortc.rtcrtpparameters import RTCRtpCodecParameters
|
||||
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
|
||||
class Track(VideoStreamTrack):
|
||||
async def recv(self):
|
||||
frame = av.VideoFrame(64, 32, "yuv420p")
|
||||
for plane in frame.planes:
|
||||
plane.update(bytes(plane.buffer_size))
|
||||
frame.pts, frame.time_base = 0, Fraction(1, 90000)
|
||||
return frame
|
||||
async def run(codec):
|
||||
pc = RTCPeerConnection()
|
||||
budget = MediaBudget("video")
|
||||
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": 80000, "ttl_ms": 3000})
|
||||
try:
|
||||
sender = pc.addTrack(Track())
|
||||
cap_video_sender(sender, budget)
|
||||
result = await sender._next_encoded_frame(RTCRtpCodecParameters(
|
||||
mimeType="video/"+codec, clockRate=90000, payloadType=96))
|
||||
self.assertTrue(result)
|
||||
encoder = sender._RTCRtpSender__encoder
|
||||
self.assertEqual(encoder.codec.bit_rate, 52000)
|
||||
encoder.target_bitrate = 32000
|
||||
self.assertEqual(encoder.target_bitrate, 52000)
|
||||
budget.target = 2600000
|
||||
self.assertEqual(budget.video(), (1280, 15))
|
||||
self.assertGreaterEqual(encoder.target_bitrate, 250000)
|
||||
encoder.target_bitrate = 600000
|
||||
self.assertEqual(encoder.target_bitrate, 600000)
|
||||
self.assertEqual(budget.video(), (1280, 15))
|
||||
finally:
|
||||
await pc.close()
|
||||
budget.connection.close()
|
||||
for codec in ("H264", "VP8"):
|
||||
asyncio.run(run(codec))
|
||||
|
||||
def test_source_recovers_at_keyframe_after_gap_between_separate_nals(self):
|
||||
import av
|
||||
|
||||
encoder = av.CodecContext.create("libx264", "w")
|
||||
encoder.width, encoder.height, encoder.pix_fmt = 32, 16, "yuv420p"
|
||||
encoder.time_base = Fraction(1, 30)
|
||||
encoder.options = {
|
||||
"preset": "ultrafast", "tune": "zerolatency",
|
||||
"x264-params": "keyint=30:min-keyint=30:scenecut=0:repeat-headers=1",
|
||||
}
|
||||
feed, wire = frames.Feed(None), []
|
||||
for number in range(150):
|
||||
frame = av.VideoFrame(32, 16, "yuv420p")
|
||||
frame.pts = number
|
||||
for plane in frame.planes:
|
||||
plane.update(bytes([64 + number % 100]) * plane.buffer_size)
|
||||
for encoded in encoder.encode(frame):
|
||||
for unit in re.split(b"\x00\x00(?:\x00)?\x01", bytes(encoded)):
|
||||
if not unit or (number and unit[0] & 31 in (7, 8)):
|
||||
continue
|
||||
# Separate SDK callbacks, with SPS/PPS sent only at startup.
|
||||
feed.append(packet(number, b"\x00\x00\x00\x01" + unit))
|
||||
header, data, _, _ = feed.queue[-1]
|
||||
wire.append((dict(header, gap=False), data))
|
||||
|
||||
source = media.Source("synthetic.sock", "synthetic")
|
||||
clock, cursor, before_gap = source.started, 0, None
|
||||
|
||||
def request(path, route, value, **kwargs):
|
||||
nonlocal clock, cursor, before_gap
|
||||
if cursor == 55:
|
||||
before_gap = source.sequence
|
||||
cursor += 5
|
||||
wire[cursor][0]["gap"] = True
|
||||
if cursor >= len(wire):
|
||||
source.close()
|
||||
return b""
|
||||
clock += 0.1
|
||||
value = frames.encode(wire[cursor])
|
||||
cursor += 1
|
||||
return value
|
||||
|
||||
with patch.object(media, "request", request), patch.object(
|
||||
media, "time", SimpleNamespace(monotonic=lambda: clock)
|
||||
):
|
||||
source.pump()
|
||||
self.assertGreater(before_gap, 20)
|
||||
self.assertGreater(source.sequence - before_gap, 60)
|
||||
self.assertEqual(source.health()["gaps"], 1)
|
||||
self.assertLessEqual(source.health()["decode_errors"], 1)
|
||||
|
||||
def test_source_health_distinguishes_input_loss_from_decode_loss(self):
|
||||
source = media.Source("synthetic.sock", "synthetic")
|
||||
payloads = synthetic_video(12)
|
||||
feed = frames.Feed(None)
|
||||
for number, data in enumerate(payloads):
|
||||
feed.append(packet(number, data))
|
||||
|
||||
def request(path, route, value, **kwargs):
|
||||
value = feed.read(value["cursor"], 0)
|
||||
if value is None:
|
||||
source.close()
|
||||
return frames.encode(value)
|
||||
|
||||
with patch.object(media, "request", request):
|
||||
source.pump()
|
||||
health = source.health()
|
||||
self.assertEqual(health["packets"], len(payloads))
|
||||
self.assertGreater(health["frames"], 0)
|
||||
self.assertGreater(health["keyframes"], 0)
|
||||
self.assertEqual(health["gaps"], 0)
|
||||
self.assertEqual(health["decode_errors"], 0)
|
||||
self.assertTrue(health["closed"])
|
||||
self.assertIsNone(health["failure"])
|
||||
self.assertIsInstance(health["packet_age_ms"], int)
|
||||
self.assertTrue(all(not isinstance(value, (bytes, list, dict)) for value in health.values()))
|
||||
|
||||
def test_sdk_reader_keeps_exact_packets_while_browser_gets_parameter_replay(self):
|
||||
config = b"\x00\x00\x01\x67sps\x00\x00\x01\x68pps"
|
||||
keyframe = b"\x00\x00\x01\x65frame"
|
||||
feed = frames.Feed(None)
|
||||
sdk, browser = feed.reader(original=True), feed.reader()
|
||||
header, data = packet(1, config)
|
||||
header.update(stream_type=0x20, calibration_revision=9)
|
||||
feed.append((header, data))
|
||||
self.assertEqual(sdk()[1], config)
|
||||
self.assertEqual(browser()[1], config)
|
||||
header, data = packet(2, keyframe)
|
||||
header.update(stream_type=0x22, calibration_revision=9)
|
||||
feed.append((header, data))
|
||||
original, display = sdk(), browser()
|
||||
self.assertEqual(original[1], keyframe)
|
||||
self.assertEqual(display[1], config + keyframe)
|
||||
for value in (original, display):
|
||||
self.assertEqual(value[0]["stream_type"], 0x22)
|
||||
self.assertEqual(value[0]["calibration_revision"], 9)
|
||||
self.assertEqual(value[0]["bytes"], len(value[1]))
|
||||
self.assertEqual(frames.decode(frames.encode(value)), value)
|
||||
feed.clear()
|
||||
feed.append(packet(3, keyframe, generation=2))
|
||||
self.assertEqual(sdk()[1], keyframe)
|
||||
self.assertEqual(browser()[1], keyframe)
|
||||
|
||||
def test_repeated_preview_commands_preserve_generation_and_readers(self):
|
||||
feed = frames.Feed(None)
|
||||
camera = VideoCamera([], preview=1)
|
||||
@@ -202,6 +391,21 @@ class FrameTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
feed.read(True, 0)
|
||||
|
||||
def test_capacity_has_a_definite_public_error_not_an_unknown_camera_write(self):
|
||||
from concurrent.futures import Future
|
||||
from runtime.errors import MESSAGES
|
||||
engine = media.Engine.__new__(media.Engine)
|
||||
engine.peers, engine.loop = media.Peers(), object()
|
||||
def schedule(coroutine, loop):
|
||||
coroutine.close()
|
||||
future = Future()
|
||||
future.set_exception(media.PreviewCapacityError("preview_capacity"))
|
||||
return future
|
||||
with patch.object(media.asyncio, "run_coroutine_threadsafe", side_effect=schedule):
|
||||
result = engine.call(("synthetic", "synthetic"), None, "offer", {"sdp": "v=0\r\n"})
|
||||
self.assertEqual(result, {"state": "error", "error": "preview_capacity"})
|
||||
self.assertIn("два просмотра", MESSAGES[result["error"]])
|
||||
|
||||
def test_public_ice_candidates_are_rejected_before_network_work(self):
|
||||
with self.assertRaises(ValueError):
|
||||
media.admit_sdp("v=0\r\na=candidate:1 1 udp 1 203.0.113.6 1234 typ host\r\n")
|
||||
@@ -209,6 +413,28 @@ class FrameTests(unittest.TestCase):
|
||||
|
||||
|
||||
class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
# Package qualification has no live Node. Keep the real queue/transport,
|
||||
# grant synthetic permits; aggregate allocation has independent tests.
|
||||
from missioncore_plugin_sdk.link_budget import BudgetClient
|
||||
guard = patch.object(BudgetClient, "_permit", return_value=True)
|
||||
guard.start()
|
||||
self.addCleanup(guard.stop)
|
||||
from missioncore_plugin_sdk.media_budget import MediaBudget
|
||||
allocation = patch.object(MediaBudget, "exchange", return_value={
|
||||
"schema": "missioncore.media-budget/v1", "allocation_bps": 4_000_000, "ttl_ms": 3000})
|
||||
allocation.start()
|
||||
self.addCleanup(allocation.stop)
|
||||
|
||||
async def test_capacity_rejection_admits_no_peer_and_never_touches_capture(self):
|
||||
peers = media.Peers()
|
||||
key = ("synthetic-camera", "synthetic")
|
||||
peers.items = {"one": {"key": key}, "two": {"key": key}}
|
||||
with patch.object(peers, "source", side_effect=AssertionError("capture must not be touched")):
|
||||
with self.assertRaises(media.PreviewCapacityError):
|
||||
await peers.offer(key, None, {"sdp": "v=0\r\n"})
|
||||
self.assertEqual(set(peers.items), {"one", "two"})
|
||||
|
||||
async def test_primed_decoder_survives_late_viewer_and_peer_close(self):
|
||||
with tempfile.TemporaryDirectory(dir=ROOT / "build") as temporary:
|
||||
descriptor = os.open(temporary, os.O_RDONLY)
|
||||
@@ -304,6 +530,9 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
class Retained:
|
||||
closed = threading.Event()
|
||||
|
||||
def health(self):
|
||||
return {"frames": 50}
|
||||
|
||||
def current(self):
|
||||
return 50, object(), media.time.monotonic()
|
||||
|
||||
@@ -349,7 +578,7 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
producer.start()
|
||||
peers = media.Peers()
|
||||
receiver = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
||||
received = asyncio.get_running_loop().create_future()
|
||||
received = asyncio.Queue(maxsize=4)
|
||||
tasks = []
|
||||
identifier = None
|
||||
key = ("synthetic-camera", "synthetic")
|
||||
@@ -357,10 +586,11 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
@receiver.on("track")
|
||||
def track(value):
|
||||
async def observe():
|
||||
first = await value.recv()
|
||||
second = await value.recv()
|
||||
if not received.done():
|
||||
received.set_result((first, second))
|
||||
while True:
|
||||
frame = await value.recv()
|
||||
if received.full():
|
||||
received.get_nowait()
|
||||
received.put_nowait(frame)
|
||||
|
||||
tasks.append(asyncio.create_task(observe()))
|
||||
|
||||
@@ -383,9 +613,41 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
await receiver.setRemoteDescription(
|
||||
RTCSessionDescription(sdp=answer["sdp"], type="answer")
|
||||
)
|
||||
first, second = await asyncio.wait_for(received, 12)
|
||||
first = await asyncio.wait_for(received.get(), 12)
|
||||
second = await asyncio.wait_for(received.get(), 4)
|
||||
self.assertEqual((first.width, first.height), (32, 16))
|
||||
self.assertGreater(second.pts, first.pts)
|
||||
# Control pressure pauses admission for >=1s. Keep this same
|
||||
# actual ICE/DTLS/SCTP peer and decoder across the shorter media
|
||||
# deadline; no stale encoded backlog may be replayed afterward.
|
||||
from missioncore_plugin_sdk.link_budget import BudgetClient
|
||||
sender = peers.items[identifier]["pc"]
|
||||
with patch.object(BudgetClient, "_permit", return_value=False):
|
||||
await asyncio.sleep(1.3)
|
||||
self.assertEqual(sender.connectionState, "connected")
|
||||
self.assertEqual(receiver.connectionState, "connected")
|
||||
stats = sender._missioncore_egress_metrics
|
||||
self.assertGreater(stats["expired_frames"] + stats["expired_datagrams"], 0)
|
||||
while not received.empty():
|
||||
received.get_nowait()
|
||||
# aiortc's synthetic receiver has a 128-packet jitter buffer
|
||||
# with no time-based eviction. Tiny 32x16 frames use one RTP
|
||||
# packet, so a deliberately lost packet can hold decoding for
|
||||
# ~9s at 15fps. This is not the browser's jitter-buffer policy.
|
||||
# Keep the real receiver unmodified and bound that drain too.
|
||||
try:
|
||||
resumed = await asyncio.wait_for(received.get(), 12)
|
||||
except TimeoutError:
|
||||
self.fail(repr({
|
||||
"sender": sender.connectionState,
|
||||
"receiver": receiver.connectionState,
|
||||
"egress": sender._missioncore_egress_metrics,
|
||||
"source": peers.sources[key].health(),
|
||||
"budget": peers.items[identifier]["budget"].snapshot(),
|
||||
"stats": await receiver.getStats(),
|
||||
}))
|
||||
self.assertGreater(resumed.pts, second.pts)
|
||||
self.assertIs(peers.items[identifier]["pc"], sender)
|
||||
with self.assertRaises(ValueError):
|
||||
await peers.close(("another-camera", "synthetic"), identifier)
|
||||
self.assertIn(identifier, peers.items)
|
||||
@@ -409,5 +671,105 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertFalse(producer.is_alive())
|
||||
|
||||
|
||||
class ImpairedUDPTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_actual_h264_dtls_udp_survives_delay_loss_and_send_expiry(self):
|
||||
# The impairment is confined to this test's loopback media transport.
|
||||
# No tc rules, real Node socket, camera SDK, control or host route.
|
||||
import av
|
||||
import random
|
||||
import time
|
||||
from missioncore_plugin_sdk.link_budget import budget_peer, _essential
|
||||
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
|
||||
|
||||
class Pixels(media.VideoStreamTrack):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.origin = time.monotonic()
|
||||
self.random = random.Random(17)
|
||||
async def recv(self):
|
||||
await asyncio.sleep(.067)
|
||||
frame = av.VideoFrame(320,160,"yuv420p")
|
||||
for plane in frame.planes:plane.update(self.random.randbytes(plane.buffer_size))
|
||||
frame.pts = int((time.monotonic()-self.origin)*90000)
|
||||
frame.time_base = Fraction(1,90000)
|
||||
return frame
|
||||
|
||||
class Permit:
|
||||
async def acquire(self, size, *, deadline=None):
|
||||
if not 0 < size <= 2048:raise ValueError("oversized fixture packet")
|
||||
def close(self):pass
|
||||
|
||||
sender = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
||||
receiver = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
||||
budget = MediaBudget("video", clock=lambda:100.)
|
||||
budget.update({"schema":"missioncore.media-budget/v1","allocation_bps":4_000_000,"ttl_ms":3000})
|
||||
received = asyncio.Queue(maxsize=4)
|
||||
tasks = []
|
||||
state = {"delay":0.,"loss":False,"packets":0,"dropped":0,"cancelled":0,"max_udp_payload":0}
|
||||
@receiver.on("track")
|
||||
def track(value):
|
||||
async def consume():
|
||||
while True:
|
||||
frame = await value.recv()
|
||||
if received.full():received.get_nowait()
|
||||
received.put_nowait(frame)
|
||||
tasks.append(asyncio.create_task(consume()))
|
||||
try:
|
||||
video = sender.addTrack(Pixels())
|
||||
cap_video_sender(video,budget)
|
||||
transceiver = sender.getTransceivers()[0]
|
||||
transceiver.setCodecPreferences([c for c in media.RTCRtpSender.getCapabilities("video").codecs if c.mimeType.lower() in ("video/h264", "video/rtx")])
|
||||
receiver.addTransceiver("video",direction="recvonly")
|
||||
receiver.createDataChannel("sensor")
|
||||
with patch.object(media,"_host_addresses",return_value=["127.0.0.1"]):
|
||||
await receiver.setLocalDescription(await receiver.createOffer())
|
||||
await sender.setRemoteDescription(receiver.localDescription)
|
||||
transports = {t.sender.transport.transport for t in sender.getTransceivers()}
|
||||
transports.add(sender.sctp.transport.transport)
|
||||
for transport in transports:
|
||||
original = transport._send
|
||||
async def impaired(data, original=original):
|
||||
if 128 <= data[0] <= 191 and not _essential(data):
|
||||
state["packets"] += 1
|
||||
state["max_udp_payload"] = max(state["max_udp_payload"],len(data))
|
||||
try:await asyncio.sleep(state["delay"])
|
||||
except asyncio.CancelledError:
|
||||
state["cancelled"] += 1
|
||||
raise
|
||||
if state["loss"] and state["packets"]%113==0:
|
||||
state["dropped"] += 1
|
||||
return
|
||||
await original(data)
|
||||
transport._send = impaired
|
||||
budget_peer(sender,"video",client=Permit())
|
||||
await sender.setLocalDescription(await sender.createAnswer())
|
||||
self.assertIn("rtx/90000", sender.localDescription.sdp)
|
||||
await receiver.setRemoteDescription(sender.localDescription)
|
||||
first = await asyncio.wait_for(received.get(),12)
|
||||
state.update(delay=.003,loss=True)
|
||||
await asyncio.sleep(2)
|
||||
state.update(delay=.65,loss=False)
|
||||
await asyncio.sleep(1.3)
|
||||
self.assertEqual(sender.connectionState,"connected")
|
||||
self.assertEqual(receiver.connectionState,"connected")
|
||||
self.assertGreater(state["cancelled"],0)
|
||||
self.assertGreater(sender._missioncore_egress_metrics["expired_frames"],0)
|
||||
self.assertLessEqual(sender._missioncore_pending_media(),65536)
|
||||
state["delay"] = 0
|
||||
while not received.empty():received.get_nowait()
|
||||
resumed = await asyncio.wait_for(received.get(),12)
|
||||
self.assertGreater(resumed.pts,first.pts)
|
||||
self.assertLessEqual(state["max_udp_payload"]+28,1280)
|
||||
self.assertGreater(state["dropped"],0)
|
||||
self.assertGreater(sender._missioncore_egress_metrics["retransmitted_packets"],0)
|
||||
self.assertLessEqual(sender._missioncore_egress_metrics["retained_frame_deadlines"],256)
|
||||
self.assertIsNone(sender._missioncore_egress_metrics["close_reason"])
|
||||
finally:
|
||||
state["delay"] = 0
|
||||
for task in tasks:task.cancel()
|
||||
await asyncio.gather(*tasks,return_exceptions=True)
|
||||
await sender.close();await receiver.close();await budget.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
"""Synthetic admission tests; never load a vendor SDK or contact the camera."""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
FILE = Path(__file__).resolve().parents[1] / "packaging/media_qualification.py"
|
||||
spec = importlib.util.spec_from_file_location("media_qualification", FILE)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
def archive(path, entries):
|
||||
data = io.BytesIO()
|
||||
with tarfile.open(fileobj=data, mode="w:gz") as tar:
|
||||
for name, kind, value in entries:
|
||||
item = tarfile.TarInfo("./" + module.PREFIX + name)
|
||||
if kind == "file":
|
||||
item.size = len(value)
|
||||
tar.addfile(item, io.BytesIO(value))
|
||||
else:
|
||||
item.type = tarfile.SYMTYPE
|
||||
item.linkname = value
|
||||
tar.addfile(item)
|
||||
payload = data.getvalue()
|
||||
header = f"{'data.tar.gz/':<16}{0:<12}{0:<6}{0:<6}{'100644':<8}{len(payload):<10}`\n".encode()
|
||||
deb = b"!<arch>\n" + header + payload + (b"\n" if len(payload) % 2 else b"")
|
||||
outer = io.BytesIO()
|
||||
with tarfile.open(fileobj=outer, mode="w:gz") as tar:
|
||||
item = tarfile.TarInfo("MediaSDK-3.1.5-20260819-linux64/MediaSDK-3.1.5-linux-amd64.deb")
|
||||
item.size = len(deb)
|
||||
tar.addfile(item, io.BytesIO(deb))
|
||||
with zipfile.ZipFile(path, "w") as z:
|
||||
z.writestr(module.MEMBER, outer.getvalue())
|
||||
|
||||
|
||||
class Qualification(unittest.TestCase):
|
||||
def test_network_filter_denies_socket_io_uring_and_foreign_abis(self):
|
||||
code = list(struct.iter_unpack("HBBI", module.network_filter()))
|
||||
|
||||
def verdict(number, arch=0xC000003E):
|
||||
registers, pc, value = {0: number, 4: arch}, 0, 0
|
||||
while pc < len(code):
|
||||
op, yes, no, operand = code[pc]
|
||||
if op == 0x20:
|
||||
value = registers[operand]
|
||||
elif op == 0x06:
|
||||
return operand
|
||||
elif op == 0x15:
|
||||
pc += yes if value == operand else no
|
||||
elif op == 0x35:
|
||||
pc += yes if value >= operand else no
|
||||
else:
|
||||
raise AssertionError("Unknown instruction")
|
||||
pc += 1
|
||||
raise AssertionError("No verdict")
|
||||
|
||||
for number in [41, 42, 44, 46, 53, 288, 299, 307, 425, 426, 427]:
|
||||
self.assertEqual(verdict(number), 0x00050001)
|
||||
for number in [0, 1, 2, 3, 9, 16, 60, 202]:
|
||||
self.assertEqual(verdict(number), 0x7FFF0000)
|
||||
self.assertEqual(verdict(0, 0x40000003), 0x80000000)
|
||||
self.assertEqual(verdict(0x40000029), 0x80000000)
|
||||
|
||||
def test_ranged_download_reassembles_and_verifies_preserved_prefix(self):
|
||||
data = b"synthetic vendor archive"
|
||||
|
||||
class Response(io.BytesIO):
|
||||
url = module.ARCHIVE_URL
|
||||
status = 206
|
||||
headers = {"Content-Range": f"bytes 4-{len(data) - 1}/{len(data)}"}
|
||||
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as temp,
|
||||
patch.object(module, "ARCHIVE_BYTES", len(data)),
|
||||
patch.object(module, "ARCHIVE_SHA", hashlib.sha256(data).hexdigest()),
|
||||
):
|
||||
root = Path(temp)
|
||||
prefix = root / "prefix"
|
||||
prefix.write_bytes(data[:4])
|
||||
with patch.object(
|
||||
module.urllib.request, "urlopen", return_value=Response(data[4:])
|
||||
) as request:
|
||||
result = module.source_archive(root, prefix)
|
||||
self.assertEqual(result.read_bytes(), data)
|
||||
self.assertEqual(
|
||||
request.call_args.args[0].get_header("Range"), f"bytes=4-{len(data) - 1}"
|
||||
)
|
||||
self.assertEqual(prefix.read_bytes(), data[:4])
|
||||
self.assertFalse((root / "download").exists())
|
||||
|
||||
def test_download_rejects_server_ignoring_the_range(self):
|
||||
class Response(io.BytesIO):
|
||||
url = module.ARCHIVE_URL
|
||||
status = 200
|
||||
headers = {}
|
||||
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as temp,
|
||||
patch.object(module.urllib.request, "urlopen", return_value=Response(b"bad")),
|
||||
self.assertRaises(ValueError),
|
||||
):
|
||||
module.download_range(Path(temp), 0, 2)
|
||||
|
||||
def test_download_rejects_changed_completed_part(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
(root / "0-2.part").write_bytes(b"bad")
|
||||
(root / "0-2.json").write_text(json.dumps({"sha256": "wrong"}))
|
||||
with self.assertRaises(ValueError):
|
||||
module.download_range(root, 0, 2)
|
||||
|
||||
def test_vendor_path_rejects_host_escape_and_unexpected_prefix(self):
|
||||
for value in [
|
||||
"/etc/passwd",
|
||||
"./opt/MediaSDK-3.1.5-linux/lib/../../x",
|
||||
"opt/other/lib/a",
|
||||
"opt/MediaSDK-3.1.5-linux/lib\\x",
|
||||
"opt/MediaSDK-3.1.5-linux/../../x",
|
||||
]:
|
||||
with self.assertRaises(ValueError):
|
||||
module.relative(value)
|
||||
|
||||
def test_packaged_aliases_resolve_to_verified_regular_files(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
archive(
|
||||
root / "input.zip", [("lib/a.so", "link", "b.so"), ("lib/b.so", "file", b"fixture")]
|
||||
)
|
||||
rows = module.extract_runtime(root / "input.zip", root / "sdk")
|
||||
(root / "runtime.json").write_text(
|
||||
json.dumps({"archive_sha256": module.ARCHIVE_SHA, "files": rows})
|
||||
)
|
||||
module.verify_runtime(root)
|
||||
self.assertTrue((root / "sdk/lib/a.so").samefile(root / "sdk/lib/b.so"))
|
||||
(root / "sdk/lib/b.so").write_bytes(b"changed")
|
||||
with self.assertRaises(ValueError):
|
||||
module.verify_runtime(root)
|
||||
|
||||
def test_escaping_alias_is_never_created(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
archive(root / "input.zip", [("lib/a.so", "link", "/etc/passwd")])
|
||||
with self.assertRaises(ValueError):
|
||||
module.extract_runtime(root / "input.zip", root / "sdk")
|
||||
self.assertFalse((root / "sdk/lib/a.so").exists())
|
||||
|
||||
def test_vendor_alias_cycle_fails(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
archive(
|
||||
root / "input.zip", [("lib/a.so", "link", "b.so"), ("lib/b.so", "link", "a.so")]
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
module.extract_runtime(root / "input.zip", root / "sdk")
|
||||
|
||||
|
||||
class RecordedInput(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import base64
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"media_builder", FILE.with_name("build_media_qualification.py")
|
||||
)
|
||||
self.builder = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(self.builder)
|
||||
self.sample = {
|
||||
"schema": "missioncore.insta360.stitch-input/v1",
|
||||
"generation": 3,
|
||||
"calibration": {
|
||||
"revision": 5,
|
||||
"camera_name": "X4",
|
||||
"encode_type": 0,
|
||||
"offsets": ["factory-a", "factory-b", "factory-c", ""],
|
||||
"crop": dict(
|
||||
source_width=8000, source_height=6000, width=5760, height=5760, x=0, y=0
|
||||
),
|
||||
},
|
||||
"packets": [
|
||||
{
|
||||
"header": dict(
|
||||
cursor=i + 1,
|
||||
generation=3,
|
||||
calibration_revision=5,
|
||||
stream_index=i % 2,
|
||||
stream_type=0x21 + i % 2,
|
||||
codec=0,
|
||||
timestamp=1000000 + i * 1000,
|
||||
bytes=5,
|
||||
gap=False,
|
||||
),
|
||||
"data": base64.b64encode(b"\0\0\1\x65x").decode(),
|
||||
}
|
||||
for i in range(8)
|
||||
],
|
||||
}
|
||||
|
||||
def serialize(self):
|
||||
return self.builder.recorded_input(json.dumps(self.sample).encode())
|
||||
|
||||
def test_callback_order_markers_timestamps_and_bytes_are_not_rewritten(self):
|
||||
source = io.BytesIO(self.serialize())
|
||||
self.assertEqual(source.read(8), b"MCX4P002")
|
||||
|
||||
def number(fmt="I"):
|
||||
return struct.unpack("<" + fmt, source.read(struct.calcsize("<" + fmt)))[0]
|
||||
|
||||
def text():
|
||||
return source.read(number())
|
||||
|
||||
self.assertEqual(text(), b"X4")
|
||||
self.assertEqual(
|
||||
[text() for _ in range(number())], [b"factory-a", b"factory-b", b"factory-c", b""]
|
||||
)
|
||||
self.assertEqual([number() for _ in range(6)], [8000, 6000, 5760, 5760, 0, 0])
|
||||
self.assertEqual(number(), 0)
|
||||
self.assertEqual(number(), 8)
|
||||
for i in range(8):
|
||||
self.assertEqual(number("q"), 1000000 + i * 1000)
|
||||
self.assertEqual(number(), 0x21 + i % 2)
|
||||
self.assertEqual(number(), i % 2)
|
||||
self.assertEqual(text(), b"\0\0\1\x65x")
|
||||
self.assertEqual(source.read(), b"")
|
||||
|
||||
def test_mixed_calibration_or_generation_and_gaps_fail(self):
|
||||
for key, value in [
|
||||
("calibration_revision", 6),
|
||||
("generation", 4),
|
||||
("gap", True),
|
||||
("cursor", 99),
|
||||
("codec", 1),
|
||||
("bytes", 6),
|
||||
("stream_type", 256),
|
||||
("timestamp", 1),
|
||||
]:
|
||||
previous = self.sample["packets"][3]["header"][key]
|
||||
self.sample["packets"][3]["header"][key] = value
|
||||
with self.assertRaises(ValueError):
|
||||
self.serialize()
|
||||
self.sample["packets"][3]["header"][key] = previous
|
||||
|
||||
def test_missing_offsets_and_invalid_base64_fail(self):
|
||||
self.sample["calibration"]["offsets"] = ["", "", "", ""]
|
||||
with self.assertRaises(ValueError):
|
||||
self.serialize()
|
||||
self.sample["calibration"]["offsets"] = ["factory"]
|
||||
self.sample["packets"][0]["data"] = "???"
|
||||
with self.assertRaises(ValueError):
|
||||
self.serialize()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -32,13 +32,23 @@ class OwnerModelUpdateTests(unittest.TestCase):
|
||||
self.assertEqual(owner.update_installed_x4(run)["state"], "current")
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
def test_newer_installed_model_is_preserved_without_profile_restart(self):
|
||||
run = Mock(return_value="0.1.3-15")
|
||||
with (
|
||||
patch.object(owner.subprocess, "run", side_effect=[Mock(returncode=0, stdout="install ok installed"), Mock(returncode=0)]) as commands,
|
||||
patch.object(owner.Path, "read_text", return_value=json.dumps(PROFILE)),
|
||||
):
|
||||
self.assertEqual(owner.update_installed_x4(run), {"state": "newer-installed-preserved", "version": "0.1.3-15"})
|
||||
self.assertEqual(run.call_count, 1)
|
||||
self.assertEqual(commands.call_args.args[0], ["/usr/bin/dpkg", "--compare-versions", "0.1.3-15", "gt", PROFILE["version"]])
|
||||
|
||||
def test_offline_model_update_uses_only_fixed_profile_and_checks_result(self):
|
||||
run = Mock(side_effect=["0.1.3-7", "", PROFILE["version"]])
|
||||
with (
|
||||
patch.object(
|
||||
owner.subprocess,
|
||||
"run",
|
||||
return_value=Mock(returncode=0, stdout="install ok installed"),
|
||||
side_effect=[Mock(returncode=0, stdout="install ok installed"), Mock(returncode=1)],
|
||||
),
|
||||
patch.object(
|
||||
owner.Path,
|
||||
@@ -70,7 +80,7 @@ class OwnerModelUpdateTests(unittest.TestCase):
|
||||
patch.object(
|
||||
owner.subprocess,
|
||||
"run",
|
||||
return_value=Mock(returncode=0, stdout="install ok installed"),
|
||||
side_effect=[Mock(returncode=0, stdout="install ok installed"), Mock(returncode=1)],
|
||||
),
|
||||
patch.object(
|
||||
owner.Path,
|
||||
|
||||
@@ -61,6 +61,15 @@ class RecoveryTests(unittest.TestCase):
|
||||
self.assertEqual(self.value.observe([], 8), [(A, "wake")])
|
||||
self.assertFalse(self.value.view(B)["enabled"])
|
||||
|
||||
def test_original_transfer_suppresses_wake_without_faking_fresh_camera_status(self):
|
||||
self.enable()
|
||||
value = snapshot()
|
||||
value.update(online=False, status={}, file_transfer={"active": True})
|
||||
self.assertEqual(self.value.observe([value], 0), [])
|
||||
self.assertEqual(self.value.observe([value], 1000), [])
|
||||
self.assertFalse(self.value.current[A]["online"])
|
||||
self.assertEqual(self.value.current[A]["status"], {})
|
||||
|
||||
def test_grace_three_attempts_and_restart_do_not_reset_budget(self):
|
||||
self.enable()
|
||||
self.value.observe([], 0)
|
||||
|
||||
@@ -21,7 +21,7 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "packaging")]
|
||||
import prepare # noqa: E402
|
||||
from runtime import broker, http, identity, operations, worker # noqa: E402
|
||||
from runtime import broker, frames, http, identity, operations, worker # noqa: E402
|
||||
from runtime.verification import Control # noqa: E402
|
||||
|
||||
|
||||
@@ -112,6 +112,38 @@ class RuntimeTests(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
self.temporary.cleanup()
|
||||
|
||||
def test_sdk_packet_route_is_session_scoped_and_does_not_control_camera(self):
|
||||
binding = identity.Binding(identity.device_id("SYNTHETIC"), "1-2", 1, 2, "SYNTHETIC")
|
||||
instance = worker.Worker(binding, self.root, self.root)
|
||||
instance.feed = frames.Feed(None)
|
||||
header = {
|
||||
"generation": 1,
|
||||
"stream_index": 0,
|
||||
"codec": 0,
|
||||
"stream_type": 0x20,
|
||||
"calibration_revision": 4,
|
||||
}
|
||||
config, image = b"\x00\x00\x01\x67sps\x00\x00\x01\x68pps", b"\x00\x00\x01\x65frame"
|
||||
instance.feed.append((header, config))
|
||||
instance.feed.append((header, image))
|
||||
request = {"session_id": instance.session, "cursor": 1}
|
||||
with self.assertRaises(ValueError):
|
||||
instance.dispatch("POST", "/sdk-video", request, {})
|
||||
instance.ready = True
|
||||
for route, expected in (("/sdk-video", image), ("/video", config + image)):
|
||||
result = instance.dispatch("POST", route, request, {})
|
||||
packet, data = frames.decode(result.data)
|
||||
self.assertEqual(data, expected)
|
||||
self.assertEqual(packet["calibration_revision"], 4)
|
||||
for invalid in (
|
||||
{**request, "session_id": "previous"},
|
||||
{**request, "action": "preview.start"},
|
||||
{**request, "cursor": -1},
|
||||
):
|
||||
with self.assertRaises(ValueError):
|
||||
instance.dispatch("POST", route, invalid, {})
|
||||
self.assertIsNone(instance.camera)
|
||||
|
||||
def test_verification_uses_live_source_and_deduplicates_across_preview_states(self):
|
||||
value = broker.Broker()
|
||||
ident, session = identity.device_id("SYNTHETIC-A"), "session_one"
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Hot-unplug races must not terminate supervision of unrelated cameras."""
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
SPEC = importlib.util.spec_from_file_location("x4_supervisor", ROOT / "packaging/supervisor.py")
|
||||
supervisor = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(supervisor)
|
||||
from runtime.identity import Binding, device_id # noqa: E402
|
||||
|
||||
|
||||
class SupervisorTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
root = Path(temporary.name)
|
||||
self.units, self.control = root / "units", root / "control"
|
||||
self.units.mkdir()
|
||||
self.control.mkdir()
|
||||
self.camera = Binding(device_id("SYNTHETIC-A"), "1-2", 1, 2, "SYNTHETIC-A")
|
||||
self.other = Binding(device_id("SYNTHETIC-B"), "1-3", 1, 3, "SYNTHETIC-B")
|
||||
self.present = {}
|
||||
self.known = {}
|
||||
self.calls = []
|
||||
self.start_failure = None
|
||||
self.patch("UNITS", self.units)
|
||||
self.patch("CONTROL", self.control)
|
||||
self.patch("active", lambda: Path("revision"))
|
||||
self.patch("trusted", lambda path, *args: path)
|
||||
self.patch("write", lambda path, data: path.write_bytes(data))
|
||||
self.patch("unit", lambda binding: binding.device_path.encode())
|
||||
self.patch("bindings", lambda: dict(self.present))
|
||||
self.patch("read_binding", self.read_binding)
|
||||
self.patch("systemctl", self.systemctl)
|
||||
self.stderr = io.StringIO()
|
||||
self.patch("sys", type("Streams", (), {"stderr": self.stderr}))
|
||||
|
||||
def patch(self, name, value):
|
||||
replacement = patch.object(supervisor, name, value)
|
||||
replacement.start()
|
||||
self.addCleanup(replacement.stop)
|
||||
|
||||
def read_binding(self, port):
|
||||
return next(value for value in self.present.values() if value.port == port)
|
||||
|
||||
def systemctl(self, *args):
|
||||
self.calls.append(args)
|
||||
if (
|
||||
args == ("start", supervisor.PREFIX + self.camera.device_id + ".service")
|
||||
and self.start_failure
|
||||
):
|
||||
raise self.start_failure
|
||||
|
||||
def test_failed_start_preserves_other_camera_and_recovers_on_new_binding(self):
|
||||
self.present = {self.camera.device_id: self.camera, self.other.device_id: self.other}
|
||||
self.start_failure = subprocess.CalledProcessError(1, ["systemctl", "start"])
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertIn(("start", supervisor.PREFIX + self.other.device_id + ".service"), self.calls)
|
||||
self.assertIn("CalledProcessError", self.stderr.getvalue())
|
||||
self.calls.clear()
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertEqual(self.calls, []) # No repeated SDK launches for the same binding.
|
||||
|
||||
del self.present[self.camera.device_id]
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertNotIn(self.camera.device_id, self.known)
|
||||
self.assertFalse(
|
||||
(self.units / (supervisor.PREFIX + self.camera.device_id + ".service")).exists()
|
||||
)
|
||||
self.assertIn(
|
||||
self.other.device_id, json.loads((self.control / "bindings.json").read_text())
|
||||
)
|
||||
|
||||
self.camera = Binding(self.camera.device_id, "1-2", 1, 8, "SYNTHETIC-A")
|
||||
self.present[self.camera.device_id] = self.camera
|
||||
self.start_failure = None
|
||||
self.calls.clear()
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertEqual(self.known[self.camera.device_id]["address"], 8)
|
||||
self.assertEqual(
|
||||
[call for call in self.calls if call[0] == "start"],
|
||||
[("start", supervisor.PREFIX + self.camera.device_id + ".service")],
|
||||
)
|
||||
|
||||
def test_revalidation_disappearance_does_not_publish_a_stale_unit(self):
|
||||
self.present = {self.camera.device_id: self.camera}
|
||||
for error in (FileNotFoundError(), ValueError("device replaced")):
|
||||
with patch.object(supervisor, "read_binding", side_effect=error):
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertEqual(self.known, {})
|
||||
self.assertEqual(list(self.units.iterdir()), [])
|
||||
self.assertEqual(self.calls, [])
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertIn(self.camera.device_id, self.known)
|
||||
|
||||
def test_timeout_has_no_automatic_replay_for_an_unchanged_binding(self):
|
||||
self.present = {self.camera.device_id: self.camera}
|
||||
self.start_failure = subprocess.TimeoutExpired(["systemctl", "start"], 20)
|
||||
supervisor.reconcile(self.known, startup=True)
|
||||
self.calls.clear()
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertEqual(self.calls, [])
|
||||
self.assertIn("TimeoutExpired", self.stderr.getvalue())
|
||||
|
||||
def test_untrusted_installation_still_fails_closed(self):
|
||||
self.present = {self.camera.device_id: self.camera}
|
||||
with (
|
||||
patch.object(supervisor, "unit", side_effect=RuntimeError("untrusted")),
|
||||
self.assertRaisesRegex(RuntimeError, "untrusted"),
|
||||
):
|
||||
supervisor.reconcile(self.known)
|
||||
self.assertEqual(self.known, {})
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user