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:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent e06ff9a214
commit fa8bde584f
94 changed files with 8892 additions and 375 deletions
+7 -4
View File
@@ -20,7 +20,7 @@ from missioncore_plugin_sdk.v0alpha2.session import DeviceSessionSnapshot
MODEL = {
"plugin_id": "missioncore.realsense",
"plugin_version": "0.6.6",
"plugin_version": "0.6.7",
"model_id": "realsense.d455",
}
@@ -238,6 +238,7 @@ class Device:
"last_frame": self.last_frame,
"recording": self.record,
"playback_id": self.playback_id,
"preview_priority_v1": True,
"layers": list(self.images)
+ (["points"] if self.depth is not None else [])
+ (["motion"] if self.motion else []),
@@ -577,13 +578,13 @@ class Device:
self.revision += 1
return {"ok": True, "value": item["value"]}
def points(self):
def points(self, limit=2000):
depth, intrinsics = self.depth, self.intrinsics
if depth is None or intrinsics is None:
if depth is None or intrinsics is None or limit <= 0:
return []
# SDK deprojection respects the camera's actual distortion model.
h, w = depth.shape
stride = max(8, math.ceil(math.sqrt(h * w / 2000)))
stride = max(8, math.ceil(math.sqrt(h * w / min(2000, limit))))
result = []
for y in range(0, h, stride):
for x in range(0, w, stride):
@@ -592,6 +593,8 @@ class Device:
result.extend(
round(v, 4) for v in rs.rs2_deproject_pixel_to_point(intrinsics, [x, y], z)
)
if len(result) >= min(2000, limit) * 3:
return result
return result
def recordings(self):
+61 -20
View File
@@ -8,6 +8,8 @@ import uuid
from fractions import Fraction
import aioice.ice
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, RTCSessionDescription, VideoStreamTrack
from av import VideoFrame
@@ -33,24 +35,34 @@ aioice.ice.get_host_addresses = lambda use_ipv4, use_ipv6: [
class CameraTrack(VideoStreamTrack):
def __init__(self, device, layer):
def __init__(self, device, layer, budget=None):
super().__init__()
self.device, self.layer = device, layer
self.device, self.layer, self.budget = device, layer, budget
self.next_at = 0.0
self.started = None
self.sequence = 0
async def recv(self):
# Fixed 15 Hz preview clock; raw hardware timing is independent.
if self.started is None:
self.started = time.monotonic()
await asyncio.sleep(max(0, self.started + self.sequence / 15 - time.monotonic()))
pts, base = self.sequence * 6000, Fraction(1, 90000)
self.sequence += 1
while self.layer not in self.device.images:
await asyncio.sleep(0.1)
frame = VideoFrame.from_ndarray(self.device.images[self.layer], format="rgb24")
frame.pts, frame.time_base = pts, base
return frame
while True:
width, fps = self.budget.video() if self.budget else (1280, 15)
now = time.monotonic()
sequence = self.device.frames.get(self.layer, 0)
fresh = now - self.device.last_frame.get("monotonic_ns", 0) / 1e9 < 2
if (fps and now >= self.next_at and fresh and sequence != self.sequence
and self.layer in self.device.images):
# One latest hardware image; no replay of a stalled source.
frame = VideoFrame.from_ndarray(self.device.images[self.layer], format="rgb24")
self.sequence = sequence
self.next_at = now + 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")
frame.pts, frame.time_base = round((now-self.started)*90000), Fraction(1,90000)
return frame
await asyncio.sleep(.02)
class Peers:
@@ -59,6 +71,8 @@ class Peers:
async def offer(self, device, params):
layer = params.get("layer", "color")
if type(params.get("primary", False)) is not bool:
raise ValueError("Invalid preview role")
if layer not in ("color", "depth", "infrared1", "infrared2", "points", "motion"):
raise ValueError("Неизвестный слой камеры.")
if len(self.items) >= 4:
@@ -73,14 +87,17 @@ class Peers:
raise ValueError("Просмотр доступен только в частной сети.")
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
ident = "peer_" + uuid.uuid4().hex
self.items[ident] = {"pc": pc, "seen": time.monotonic()}
self.items[ident] = {"pc": pc, "seen": time.monotonic(), "tasks": set(), "channel": None}
allocation = None
async def telemetry(channel):
try:
while pc.connectionState not in ("failed", "closed"):
if time.monotonic() - self.items.get(ident, {}).get("seen", 0) > 30:
break
if channel.readyState == "open" and channel.bufferedAmount < 65536:
interval = .25
pending = getattr(pc, "_missioncore_pending_media", lambda: 0)()
if channel.readyState == "open" and channel.bufferedAmount < 16384 and pending < 16384 and allocation and allocation.bps:
payload = {
"layer": layer,
"motion": device.motion,
@@ -88,30 +105,50 @@ class Peers:
"acquisition": device.acquisition,
}
if layer == "points":
payload["points"] = await asyncio.to_thread(device.points)
channel.send(json.dumps(payload, allow_nan=False))
await asyncio.sleep(0.25)
count, interval = allocation.cloud(2000, 48)
payload["points"] = await asyncio.to_thread(device.points, count)
payload["media_budget"] = allocation.snapshot()
raw = json.dumps(payload, allow_nan=False)
# A single JSON message must fit the bounded SCTP burst.
while len(raw.encode()) > 16384 and payload.get("points"):
values = payload["points"]
payload["points"] = [v for i in range(0,len(values),6) for v in values[i:i+3]]
raw = json.dumps(payload, allow_nan=False)
if len(raw.encode()) <= 16384:
channel.send(raw)
await asyncio.sleep(interval)
finally:
await self.close(ident)
@pc.on("datachannel")
def datachannel(channel):
entry = self.items.get(ident)
if entry is None or entry["channel"] is not None:
channel.close()
return
entry["channel"] = channel
@channel.on("message")
def message(value):
if value in ("view:primary", "view:secondary") and allocation and layer not in ("points", "motion"):
allocation.primary = value == "view:primary"
if value == "keepalive" and ident in self.items:
self.items[ident]["seen"] = time.monotonic()
asyncio.create_task(telemetry(channel))
task = asyncio.create_task(telemetry(channel))
self.items[ident]["tasks"].add(task)
@pc.on("connectionstatechange")
async def changed():
if pc.connectionState in ("failed", "closed"):
self.items.pop(ident, None)
await self.close(ident)
try:
await pc.setRemoteDescription(RTCSessionDescription(sdp=sdp, type="offer"))
allocation = await adapt_peer(pc, "cloud" if layer in ("points", "motion") else "video", primary=params.get("primary", False) and layer not in ("points", "motion"))
if layer not in ("points", "motion"):
pc.addTrack(CameraTrack(device, layer))
sender = pc.addTrack(CameraTrack(device, layer, allocation))
cap_video_sender(sender, allocation)
budget_peer(pc, "cloud" if layer in ("points", "motion") else "video", producer_id=allocation.id)
await pc.setLocalDescription(await pc.createAnswer())
async def expiry():
@@ -119,7 +156,7 @@ class Peers:
if ident in self.items and pc.connectionState != "connected":
await self.close(ident)
asyncio.create_task(expiry())
self.items[ident]["tasks"].add(asyncio.create_task(expiry()))
return {"peer_id": ident, "sdp": pc.localDescription.sdp, "type": "answer"}
except Exception:
await self.close(ident)
@@ -128,5 +165,9 @@ class Peers:
async def close(self, ident):
entry = self.items.pop(ident, None)
if entry:
tasks = [t for t in entry["tasks"] if t is not asyncio.current_task()]
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await entry["pc"].close()
return {"ok": True}