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,184 @@
|
||||
"""Private, resumable-by-reading camera originals; never delete camera media.
|
||||
|
||||
One transfer owns the worker's control gate. CameraSDK remains inside the
|
||||
existing USB worker; no root SDK, URL fetching or caller-selected local path.
|
||||
Interrupted transfers are retained and are never automatically restarted.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from .lifecycle import acquisition
|
||||
from .operations import atomic
|
||||
|
||||
MAX_BYTES = 8 * 1024**3
|
||||
CHUNK_BYTES = 1024**2
|
||||
TIMEOUT = 300
|
||||
IDENTIFIER = re.compile(r"file_[0-9a-f]{32}")
|
||||
SOURCE = re.compile(r"/DCIM/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_.-]+\.insv")
|
||||
|
||||
|
||||
def validate_source(value):
|
||||
if (
|
||||
not isinstance(value, str)
|
||||
or len(value) > 1024
|
||||
or not SOURCE.fullmatch(value)
|
||||
or any(p in (".", "..") for p in value.split("/"))
|
||||
):
|
||||
raise ValueError("Only a listed camera original is admitted")
|
||||
return value
|
||||
|
||||
|
||||
class Archive:
|
||||
def __init__(self, camera, root, gate):
|
||||
self.camera, self.root, self.gate = camera, root, gate
|
||||
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.lock = threading.Lock()
|
||||
self.active = None
|
||||
self.progress = (0, 0)
|
||||
|
||||
def folder(self, identifier):
|
||||
if not isinstance(identifier, str) or not IDENTIFIER.fullmatch(identifier):
|
||||
raise ValueError("Invalid transfer identity")
|
||||
return self.root / identifier
|
||||
|
||||
def busy(self):
|
||||
with self.lock:
|
||||
return self.active is not None
|
||||
|
||||
def start(self, identifier, source):
|
||||
validate_source(source)
|
||||
folder = self.folder(identifier)
|
||||
with self.lock:
|
||||
if folder.exists():
|
||||
previous = json.loads((folder / "receipt.json").read_text())
|
||||
if previous["source"] != source:
|
||||
raise ValueError("Transfer identity already used")
|
||||
return self._status(identifier)
|
||||
if self.active or not self.gate.acquire(blocking=False):
|
||||
raise RuntimeError("Camera control is busy")
|
||||
try:
|
||||
if shutil.disk_usage(self.root).free < MAX_BYTES + 1024**3:
|
||||
raise RuntimeError("Insufficient space for bounded original transfer")
|
||||
folder.mkdir(mode=0o700)
|
||||
# Reserve this file without replacing any prior evidence.
|
||||
with (folder / "original.insv").open("xb"):
|
||||
pass
|
||||
receipt = {
|
||||
"schema": "missioncore.insta360.original/v1",
|
||||
"id": identifier,
|
||||
"source": source,
|
||||
"state": "running",
|
||||
"started_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
atomic(folder / "receipt.json", receipt)
|
||||
self.active, self.progress = identifier, (0, 0)
|
||||
threading.Thread(target=self._run, args=(folder, receipt), daemon=True).start()
|
||||
except BaseException:
|
||||
self.active = None
|
||||
self.gate.release()
|
||||
raise
|
||||
return {"id": identifier, "state": "running", "bytes": 0, "total": 0}
|
||||
|
||||
def _run(self, folder, receipt):
|
||||
finished, cancel = threading.Event(), threading.Event()
|
||||
started = time.monotonic()
|
||||
|
||||
def progress(downloaded, total):
|
||||
with self.lock:
|
||||
previous = self.progress[0]
|
||||
self.progress = (downloaded, total)
|
||||
if (
|
||||
not 0 <= downloaded <= MAX_BYTES
|
||||
or not 0 <= total <= MAX_BYTES
|
||||
or downloaded > total
|
||||
or downloaded < previous
|
||||
):
|
||||
cancel.set()
|
||||
|
||||
def watch():
|
||||
while not finished.wait(0.1):
|
||||
if time.monotonic() - started >= TIMEOUT:
|
||||
cancel.set()
|
||||
if cancel.is_set():
|
||||
# Never cancel reentrantly from a vendor callback and never
|
||||
# release the gate until DownloadCameraFile actually returns.
|
||||
self.camera.cancel_download()
|
||||
return
|
||||
|
||||
watcher = None
|
||||
try:
|
||||
with acquisition():
|
||||
watcher = threading.Thread(target=watch, daemon=True)
|
||||
watcher.start()
|
||||
ok = self.camera.download(receipt["source"], folder / "original.insv", progress)
|
||||
finished.set()
|
||||
watcher.join()
|
||||
size = (folder / "original.insv").stat().st_size
|
||||
with self.lock:
|
||||
downloaded, total = self.progress
|
||||
if (
|
||||
not ok
|
||||
or cancel.is_set()
|
||||
or not 0 < size <= MAX_BYTES
|
||||
or size != downloaded
|
||||
or size != total
|
||||
):
|
||||
raise RuntimeError("Original transfer was not confirmed")
|
||||
digest = hashlib.sha256()
|
||||
with (folder / "original.insv").open("rb") as stream:
|
||||
while chunk := stream.read(CHUNK_BYTES):
|
||||
digest.update(chunk)
|
||||
os.fsync(stream.fileno())
|
||||
receipt.update(state="complete", bytes=size, sha256=digest.hexdigest())
|
||||
except Exception:
|
||||
receipt.update(
|
||||
state="error", error="Original transfer was not confirmed; partial retained"
|
||||
)
|
||||
finally:
|
||||
finished.set()
|
||||
if watcher:
|
||||
watcher.join()
|
||||
receipt.update(
|
||||
finished_at=datetime.now(UTC).isoformat(),
|
||||
duration_seconds=time.monotonic() - started,
|
||||
)
|
||||
try:
|
||||
atomic(folder / "receipt.json", receipt)
|
||||
finally:
|
||||
with self.lock:
|
||||
self.active = None
|
||||
self.gate.release()
|
||||
|
||||
def _status(self, identifier):
|
||||
value = json.loads((self.folder(identifier) / "receipt.json").read_text())
|
||||
result = {key: value[key] for key in ("id", "state", "bytes", "sha256") if key in value}
|
||||
if self.active == identifier:
|
||||
result.update(bytes=self.progress[0], total=self.progress[1])
|
||||
elif result["state"] == "running":
|
||||
result["state"] = "interrupted"
|
||||
return result
|
||||
|
||||
def status(self, identifier):
|
||||
with self.lock:
|
||||
return self._status(identifier)
|
||||
|
||||
def read(self, identifier, offset):
|
||||
if type(offset) is not int or not 0 <= offset < MAX_BYTES:
|
||||
raise ValueError("Invalid original offset")
|
||||
status = self.status(identifier)
|
||||
if status["state"] != "complete" or offset >= status["bytes"]:
|
||||
raise ValueError("Original is not ready or offset is outside file")
|
||||
path = self.folder(identifier) / "original.insv"
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
with os.fdopen(fd, "rb") as stream:
|
||||
if os.fstat(stream.fileno()).st_size != status["bytes"]:
|
||||
raise RuntimeError("Original changed after transfer")
|
||||
stream.seek(offset)
|
||||
return stream.read(min(CHUNK_BYTES, status["bytes"] - offset))
|
||||
@@ -172,6 +172,7 @@ class Broker:
|
||||
"firmware": status.get("firmware"),
|
||||
"layers": [],
|
||||
"camera_status": status,
|
||||
"preview_priority_v1": True,
|
||||
"snapshot": {
|
||||
"revision": value["revision"],
|
||||
"observed_at": value["observed_at"],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Public messages are allowlisted; vendor error text never crosses the boundary."""
|
||||
|
||||
MESSAGES = {
|
||||
"preview_capacity": "У камеры уже открыто два просмотра. Закройте лишний просмотр; подключение повторится автоматически.",
|
||||
"wake_adapter_busy": "Сейчас включается другая камера. Повторите действие позже.",
|
||||
"wake_identity_missing": "Сначала подключите эту камеру по USB и подготовьте её на борту.",
|
||||
"wake_identity_conflict": "Не удалось однозначно выбрать камеру для включения.",
|
||||
|
||||
@@ -83,6 +83,10 @@ def decode(raw):
|
||||
or header["stream_index"] not in (0, 1)
|
||||
or header["codec"] not in (0, 1)
|
||||
or type(header.get("gap")) is not bool
|
||||
or (
|
||||
"stream_type" in header
|
||||
and (type(header["stream_type"]) is not int or not 0 <= header["stream_type"] <= 255)
|
||||
)
|
||||
or not 0 < len(data) <= MAX_PACKET
|
||||
):
|
||||
raise ValueError("Invalid video metadata")
|
||||
@@ -121,41 +125,49 @@ class Feed:
|
||||
self.source_generation = source["generation"]
|
||||
self.generation += 1
|
||||
self.parameters = Parameters()
|
||||
original_bytes = len(data)
|
||||
data = self.parameters.packet(source, data)
|
||||
prefix_bytes = len(data) - original_bytes
|
||||
while self.queue and (
|
||||
self.bytes + len(data) > MAX_BYTES or len(self.queue) >= MAX_ENTRIES
|
||||
):
|
||||
_, removed, _ = self.queue.popleft()
|
||||
_, removed, _, _ = self.queue.popleft()
|
||||
self.bytes -= len(removed)
|
||||
self.cursor += 1
|
||||
header = dict(source, cursor=self.cursor, generation=self.generation)
|
||||
self.queue.append((header, data, time.monotonic()))
|
||||
# Keep one bounded allocation. The SDK reader receives precisely
|
||||
# the original callback bytes; browser readers retain late-join
|
||||
# parameter replay without changing the vendor packet contract.
|
||||
self.queue.append((header, data, time.monotonic(), prefix_bytes))
|
||||
self.bytes += len(data)
|
||||
self.lock.notify_all()
|
||||
|
||||
def read(self, cursor, wait=0.1):
|
||||
def read(self, cursor, wait=0.1, *, original=False):
|
||||
if type(cursor) is not int or not 0 <= cursor < 2**64:
|
||||
raise ValueError("Invalid video cursor")
|
||||
deadline = time.monotonic() + min(max(wait, 0), 0.2)
|
||||
with self.lock:
|
||||
while True:
|
||||
for header, data, observed in self.queue:
|
||||
for header, data, observed, prefix_bytes in self.queue:
|
||||
if header["cursor"] > cursor and time.monotonic() - observed < 2:
|
||||
payload = data[prefix_bytes:] if original else data
|
||||
return dict(
|
||||
header, gap=bool(cursor and header["cursor"] != cursor + 1)
|
||||
), data
|
||||
header,
|
||||
bytes=len(payload),
|
||||
gap=bool(cursor and header["cursor"] != cursor + 1),
|
||||
), payload
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0 or self.closed.is_set():
|
||||
return None
|
||||
self.lock.wait(remaining)
|
||||
|
||||
def reader(self):
|
||||
def reader(self, *, original=False):
|
||||
with self.lock:
|
||||
cursor = self.cursor
|
||||
|
||||
def read():
|
||||
nonlocal cursor
|
||||
value = self.read(cursor, wait=0)
|
||||
value = self.read(cursor, wait=0, original=original)
|
||||
if value is not None:
|
||||
cursor = value[0]["cursor"]
|
||||
return value
|
||||
|
||||
@@ -16,6 +16,8 @@ from fractions import Fraction
|
||||
|
||||
import aioice.ice
|
||||
import av
|
||||
from missioncore_plugin_sdk.link_budget import budget_peer
|
||||
from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
|
||||
from aiortc import (
|
||||
RTCConfiguration,
|
||||
RTCPeerConnection,
|
||||
@@ -26,7 +28,7 @@ from aiortc import (
|
||||
from aiortc.mediastreams import MediaStreamError
|
||||
|
||||
from .errors import failure
|
||||
from .frames import decode
|
||||
from .frames import START_CODE, decode
|
||||
from .http import request
|
||||
|
||||
NETWORKS = tuple(
|
||||
@@ -65,6 +67,10 @@ def admit_sdp(sdp):
|
||||
raise ValueError("Camera preview requires a private network")
|
||||
|
||||
|
||||
class PreviewCapacityError(ValueError):
|
||||
"""No peer was admitted; retrying cannot repeat a camera action."""
|
||||
|
||||
|
||||
class Source:
|
||||
def __init__(self, path, session):
|
||||
self.path, self.session = path, session
|
||||
@@ -75,11 +81,28 @@ class Source:
|
||||
self.started = time.monotonic()
|
||||
self.closed = threading.Event()
|
||||
self.thread = threading.Thread(target=self.pump, daemon=True)
|
||||
self.packets = self.gaps = self.resets = self.decode_errors = self.keyframes = 0
|
||||
self.packet_at = self.keyframe_at = None
|
||||
self.generation = None
|
||||
self.failure = None
|
||||
|
||||
def current(self):
|
||||
with self.lock:
|
||||
return self.sequence, self.frame, self.observed
|
||||
|
||||
def health(self):
|
||||
"""Bounded in-memory counters; no encoded media or monitoring history."""
|
||||
with self.lock:
|
||||
now = time.monotonic()
|
||||
return {
|
||||
"packets": self.packets, "frames": self.sequence,
|
||||
"packet_age_ms": round((now - self.packet_at) * 1000) if self.packet_at is not None else None,
|
||||
"keyframes": self.keyframes,
|
||||
"keyframe_age_ms": round((now - self.keyframe_at) * 1000) if self.keyframe_at is not None else None,
|
||||
"gaps": self.gaps, "resets": self.resets, "decode_errors": self.decode_errors,
|
||||
"generation": self.generation, "closed": self.closed.is_set(), "failure": self.failure,
|
||||
}
|
||||
|
||||
def pump(self):
|
||||
cursor, key, decoder, resized_at = 0, None, None, 0.0
|
||||
try:
|
||||
@@ -98,13 +121,38 @@ class Source:
|
||||
cursor = header["cursor"]
|
||||
if header["stream_index"] != 0:
|
||||
continue
|
||||
now = time.monotonic()
|
||||
keyframe = any(
|
||||
(data[marker.end()] & 31) == 5 if header["codec"] == 0
|
||||
else ((data[marker.end()] >> 1) & 63) in (16, 17, 18, 19, 20, 21)
|
||||
for marker in START_CODE.finditer(data) if marker.end() < len(data)
|
||||
)
|
||||
with self.lock:
|
||||
self.packets += 1
|
||||
self.packet_at = now
|
||||
self.generation = header["generation"]
|
||||
self.gaps += int(header["gap"])
|
||||
if keyframe:
|
||||
self.keyframes += 1
|
||||
self.keyframe_at = now
|
||||
current = (header["generation"], header["codec"])
|
||||
if decoder is None or key != current or header["gap"]:
|
||||
if key != current or header["gap"]:
|
||||
decoder = None
|
||||
key = current
|
||||
if decoder is None:
|
||||
# Parsing dependent NALs after a gap can fail while the
|
||||
# next IDR is still buffered in the parser. Recreating the
|
||||
# decoder then discards that IDR forever. Feed replays this
|
||||
# generation's parameter sets on keyframes, so resume only
|
||||
# from an independently decodable packet.
|
||||
if not keyframe:
|
||||
continue
|
||||
decoder = av.CodecContext.create(
|
||||
"h264" if header["codec"] == 0 else "hevc", "r"
|
||||
)
|
||||
decoder.thread_count = 1
|
||||
key = current
|
||||
with self.lock:
|
||||
self.resets += 1
|
||||
try:
|
||||
for packet in decoder.parse(data):
|
||||
for frame in decoder.decode(packet):
|
||||
@@ -124,7 +172,11 @@ class Source:
|
||||
resized_at = now
|
||||
except av.error.FFmpegError:
|
||||
decoder = None
|
||||
with self.lock:
|
||||
self.decode_errors += 1
|
||||
except (OSError, ValueError, RuntimeError) as error:
|
||||
with self.lock:
|
||||
self.failure = type(error).__name__
|
||||
logging.getLogger(__name__).warning(
|
||||
"X4 preview source stopped (%s)", type(error).__name__
|
||||
)
|
||||
@@ -138,17 +190,25 @@ class Source:
|
||||
|
||||
|
||||
class Track(VideoStreamTrack):
|
||||
def __init__(self, source):
|
||||
def __init__(self, source, budget=None):
|
||||
super().__init__()
|
||||
self.budget = budget
|
||||
self.source, self.sequence, self.next_at = source, 0, 0.0
|
||||
|
||||
async def recv(self):
|
||||
while self.readyState == "live" and not self.source.closed.is_set():
|
||||
await asyncio.sleep(max(0, self.next_at - time.monotonic()))
|
||||
width, fps = self.budget.video() if self.budget else (1280, 15)
|
||||
if not fps:
|
||||
await asyncio.sleep(.1)
|
||||
continue
|
||||
sequence, frame, observed = self.source.current()
|
||||
if frame is not None and sequence > self.sequence and time.monotonic() - observed < 2:
|
||||
self.sequence = sequence
|
||||
self.next_at = time.monotonic() + 1 / 15
|
||||
self.next_at = time.monotonic() + 1 / fps
|
||||
if frame.width > width:
|
||||
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
|
||||
frame = frame.reformat(width=width, height=height, format="yuv420p")
|
||||
# Distinct AV frames per encoder: force-keyframe decisions in
|
||||
# one browser must not mutate another browser's frame object.
|
||||
copy = av.VideoFrame(frame.width, frame.height, "yuv420p")
|
||||
@@ -235,7 +295,7 @@ class Peers:
|
||||
# competing decoder or accept a retained frame as fresh evidence.
|
||||
source = self.sources.get(key)
|
||||
if source is None or source.closed.is_set():
|
||||
return failure("preview_restart_required")
|
||||
return dict(failure("preview_restart_required"), result={"decoder": source.health() if source else None})
|
||||
initial = source.current()[0]
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < timeout:
|
||||
@@ -259,13 +319,14 @@ class Peers:
|
||||
},
|
||||
}
|
||||
await asyncio.sleep(0.02)
|
||||
return failure("preview_restart_required")
|
||||
return dict(failure("preview_restart_required"), result={"decoder": source.health()})
|
||||
|
||||
async def offer(self, key, path, params):
|
||||
admit_sdp(params["sdp"])
|
||||
if type(params.get("primary",False)) is not bool:raise ValueError("Invalid preview role")
|
||||
# Inventory remains independent; these limits bound active media only.
|
||||
if len(self.items) >= 4 or sum(item["key"] == key for item in self.items.values()) >= 2:
|
||||
raise ValueError("Закройте лишний просмотр камеры.")
|
||||
raise PreviewCapacityError("preview_capacity")
|
||||
source = self.source(key, path)
|
||||
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
||||
identifier = "peer_" + uuid.uuid4().hex
|
||||
@@ -284,6 +345,8 @@ class Peers:
|
||||
if frame
|
||||
else None,
|
||||
"fresh": frame is not None and time.monotonic() - observed < 2,
|
||||
"decoder": source.health(),
|
||||
"media_budget": entry["budget"].snapshot() if "budget" in entry else None,
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -302,6 +365,8 @@ class Peers:
|
||||
|
||||
@channel.on("message")
|
||||
def message(value):
|
||||
if value in ("view:primary", "view:secondary") and "budget" in entry:
|
||||
entry["budget"].primary = value == "view:primary"
|
||||
if value == "keepalive":
|
||||
entry["seen"] = time.monotonic()
|
||||
|
||||
@@ -320,16 +385,23 @@ class Peers:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
try:
|
||||
sender = pc.addTrack(Track(source))
|
||||
allocation = await adapt_peer(pc, "video", primary=params.get("primary",False))
|
||||
entry["budget"] = allocation
|
||||
sender = pc.addTrack(Track(source, allocation))
|
||||
cap_video_sender(sender, allocation)
|
||||
transceiver = next(item for item in pc.getTransceivers() if item.sender == sender)
|
||||
transceiver.setCodecPreferences(
|
||||
[
|
||||
codec
|
||||
for codec in RTCRtpSender.getCapabilities("video").codecs
|
||||
if codec.mimeType.lower() == "video/h264"
|
||||
# Keep H264's standard repair transport. Omitting RTX
|
||||
# forces NACK retries onto the primary SSRC, where old
|
||||
# primary frames are deliberately rejected by admission.
|
||||
if codec.mimeType.lower() in ("video/h264", "video/rtx")
|
||||
]
|
||||
)
|
||||
await pc.setRemoteDescription(RTCSessionDescription(sdp=params["sdp"], type="offer"))
|
||||
budget_peer(pc, "video", producer_id=allocation.id)
|
||||
await pc.setLocalDescription(await pc.createAnswer())
|
||||
task(watchdog())
|
||||
return {"peer_id": identifier, "sdp": pc.localDescription.sdp, "type": "answer"}
|
||||
@@ -381,6 +453,8 @@ class Engine:
|
||||
future = asyncio.run_coroutine_threadsafe(work, self.loop)
|
||||
try:
|
||||
return {"state": "complete", "result": future.result(timeout=20)}
|
||||
except PreviewCapacityError:
|
||||
return failure("preview_capacity")
|
||||
except FutureTimeout as error:
|
||||
future.cancel()
|
||||
raise RuntimeError("Camera preview timed out") from error
|
||||
|
||||
@@ -20,6 +20,7 @@ ACTIONS = {
|
||||
"files.list": 9,
|
||||
}
|
||||
MAX_PACKET = 4 * 1024 * 1024
|
||||
DownloadProgress = ctypes.CFUNCTYPE(None, ctypes.c_int64, ctypes.c_int64)
|
||||
|
||||
|
||||
class VideoHeader(ctypes.Structure):
|
||||
@@ -30,6 +31,8 @@ class VideoHeader(ctypes.Structure):
|
||||
("stream_index", ctypes.c_int32),
|
||||
("codec", ctypes.c_int32),
|
||||
("bytes", ctypes.c_uint32),
|
||||
("stream_type", ctypes.c_int32),
|
||||
("calibration_revision", ctypes.c_uint64),
|
||||
]
|
||||
|
||||
|
||||
@@ -52,7 +55,8 @@ def parameters(action, value):
|
||||
if action == "offer":
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or set(value) != {"sdp", "layer"}
|
||||
or set(value) not in ({"sdp", "layer"}, {"sdp", "layer", "primary"})
|
||||
or type(value.get("primary", False)) is not bool
|
||||
or value["layer"] != "preview"
|
||||
or not isinstance(value["sdp"], str)
|
||||
or not 0 < len(value["sdp"]) <= 32768
|
||||
@@ -123,7 +127,7 @@ class NativeCamera:
|
||||
self.video_lock = threading.Lock()
|
||||
self.api = ctypes.CDLL(str(library_path))
|
||||
self.api.mc_x4_abi.restype = ctypes.c_int
|
||||
if self.api.mc_x4_abi() != 1:
|
||||
if self.api.mc_x4_abi() != 2:
|
||||
raise RuntimeError("Incompatible camera adapter")
|
||||
self.api.mc_x4_open.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
|
||||
self.api.mc_x4_open.restype = ctypes.c_void_p
|
||||
@@ -135,6 +139,15 @@ class NativeCamera:
|
||||
ctypes.c_double,
|
||||
]
|
||||
self.api.mc_x4_call.restype = ctypes.c_char_p
|
||||
self.api.mc_x4_download.argtypes = [
|
||||
ctypes.c_void_p,
|
||||
ctypes.c_char_p,
|
||||
ctypes.c_char_p,
|
||||
DownloadProgress,
|
||||
]
|
||||
self.api.mc_x4_download.restype = ctypes.c_int
|
||||
self.api.mc_x4_cancel_download.argtypes = [ctypes.c_void_p]
|
||||
self.api.mc_x4_cancel_download.restype = None
|
||||
self.api.mc_x4_read_video.argtypes = [
|
||||
ctypes.c_void_p,
|
||||
ctypes.POINTER(VideoHeader),
|
||||
@@ -166,6 +179,24 @@ class NativeCamera:
|
||||
raise RuntimeError("Camera returned an invalid response")
|
||||
return result
|
||||
|
||||
def download(self, source, destination, progress):
|
||||
callback = DownloadProgress(progress)
|
||||
with self.lock:
|
||||
if not self.handle:
|
||||
raise RuntimeError("Camera session is closed")
|
||||
return (
|
||||
self.api.mc_x4_download(
|
||||
self.handle, source.encode(), str(destination).encode(), callback
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
def cancel_download(self):
|
||||
# Called only by the active transfer's watchdog. Taking the command
|
||||
# lock here would deadlock with synchronous DownloadCameraFile.
|
||||
if self.handle:
|
||||
self.api.mc_x4_cancel_download(self.handle)
|
||||
|
||||
def video(self):
|
||||
# SDK control calls may block for seconds. The callback queue has its
|
||||
# own native mutex and can be drained without taking the command lock.
|
||||
@@ -180,7 +211,13 @@ class NativeCamera:
|
||||
raise RuntimeError("Invalid video packet")
|
||||
if state == 0:
|
||||
return None
|
||||
if header.stream_index not in (0, 1) or header.codec not in (0, 1) or not header.bytes:
|
||||
if (
|
||||
header.stream_index not in (0, 1)
|
||||
or header.codec not in (0, 1)
|
||||
or not 0 <= header.stream_type <= 255
|
||||
or not header.calibration_revision
|
||||
or not header.bytes
|
||||
):
|
||||
raise RuntimeError("Unsupported video packet")
|
||||
return {name: getattr(header, name) for name, _ in VideoHeader._fields_}, bytes(
|
||||
self.buffer[: header.bytes]
|
||||
|
||||
@@ -196,6 +196,11 @@ class Recovery:
|
||||
decisions = []
|
||||
for ident, state in self.states.items():
|
||||
current = self.current.get(ident)
|
||||
if current and current.get("file_transfer", {}).get("active") is True:
|
||||
# Synchronous vendor downloads pause status polling. Do not
|
||||
# treat an intentionally busy control channel as a lost camera.
|
||||
self.absent.pop(ident, None)
|
||||
continue
|
||||
online = bool(current and current.get("online"))
|
||||
if online:
|
||||
self.absent.pop(ident, None)
|
||||
|
||||
@@ -8,6 +8,7 @@ import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .archive import Archive
|
||||
from .frames import Feed, encode
|
||||
from .http import Binary, Server
|
||||
from .identity import read_binding
|
||||
@@ -36,6 +37,8 @@ class Worker:
|
||||
self.feed = None
|
||||
self.operations = None
|
||||
self.runtime, self.state = runtime, state
|
||||
self.command_gate = threading.Lock()
|
||||
self.archive = None
|
||||
|
||||
def connect(self):
|
||||
# Bounded startup even if a vendor call never returns. No restart loop:
|
||||
@@ -55,6 +58,7 @@ class Worker:
|
||||
self.feed = Feed(self.camera)
|
||||
self.feed.thread.start()
|
||||
self.control = Control(self.camera, self.feed)
|
||||
self.archive = Archive(self.camera, self.state / "originals", self.command_gate)
|
||||
self.operations = Operations(
|
||||
self.binding.device_id, self.session, self.state / "operations", self.control
|
||||
)
|
||||
@@ -68,7 +72,12 @@ class Worker:
|
||||
def refresh(self):
|
||||
if read_binding(self.binding.port) != self.binding:
|
||||
raise RuntimeError("Camera transport changed")
|
||||
response = self.camera.call("details", {})
|
||||
if not self.command_gate.acquire(blocking=False):
|
||||
return
|
||||
try:
|
||||
response = self.camera.call("details", {})
|
||||
finally:
|
||||
self.command_gate.release()
|
||||
if response["state"] != "complete":
|
||||
raise RuntimeError("Camera status is unconfirmed")
|
||||
with self.status_lock:
|
||||
@@ -78,6 +87,7 @@ class Worker:
|
||||
self.revision += 1
|
||||
|
||||
def snapshot(self):
|
||||
transfer_active = bool(self.archive and self.archive.busy())
|
||||
with self.status_lock:
|
||||
state = dict(self.status)
|
||||
fresh = time.monotonic() - self.observed < 12
|
||||
@@ -98,7 +108,9 @@ class Worker:
|
||||
"verified": verified,
|
||||
"revision": revision,
|
||||
"observed_at": observed_at,
|
||||
"file_transfer": {"active": transfer_active},
|
||||
"preparation_safe": connected
|
||||
and not transfer_active
|
||||
and state.get("preview") == 0
|
||||
and state.get("recording") == 0,
|
||||
"status": state if fresh else {},
|
||||
@@ -108,19 +120,39 @@ class Worker:
|
||||
def dispatch(self, method, route, value, headers):
|
||||
if method == "GET" and route == "/snapshot":
|
||||
return self.snapshot()
|
||||
if method == "POST" and route == "/video":
|
||||
if method == "POST" and route in ("/archive/start", "/archive/status", "/archive/read"):
|
||||
keys = {"session_id", "id"} | (
|
||||
{"source"}
|
||||
if route.endswith("start")
|
||||
else {"offset"}
|
||||
if route.endswith("read")
|
||||
else set()
|
||||
)
|
||||
if not self.ready or value.get("session_id") != self.session or set(value) != keys:
|
||||
raise ValueError("Camera file session changed")
|
||||
if route == "/archive/start":
|
||||
return self.archive.start(value["id"], value["source"])
|
||||
if route == "/archive/status":
|
||||
return self.archive.status(value["id"])
|
||||
return Binary(self.archive.read(value["id"], value["offset"]))
|
||||
if method == "POST" and route in ("/video", "/sdk-video"):
|
||||
if (
|
||||
not self.ready
|
||||
or value.get("session_id") != self.session
|
||||
or set(value) != {"session_id", "cursor"}
|
||||
):
|
||||
raise ValueError("Camera video session changed")
|
||||
return Binary(encode(self.feed.read(value["cursor"])))
|
||||
return Binary(encode(self.feed.read(value["cursor"], original=route == "/sdk-video")))
|
||||
if method == "POST" and route == "/operation":
|
||||
if not self.ready:
|
||||
raise RuntimeError("Camera is unavailable")
|
||||
with acquisition():
|
||||
result = self.operations.execute(value)
|
||||
if not self.command_gate.acquire(blocking=False):
|
||||
raise RuntimeError("Camera file transfer or status read is active")
|
||||
try:
|
||||
with acquisition():
|
||||
result = self.operations.execute(value)
|
||||
finally:
|
||||
self.command_gate.release()
|
||||
# Poll asynchronously; a lost state read must not change a durable
|
||||
# acknowledged command result into a different receipt.
|
||||
if value.get("action_id") not in ("details", "settings.read", "files.list"):
|
||||
|
||||
Reference in New Issue
Block a user