Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
305 lines
12 KiB
Python
305 lines
12 KiB
Python
"""Bounded live RRD publication for paired Node viewers, without a TCP listener.
|
|
|
|
Each view owns one recording for the acquisition, including across peer recovery.
|
|
Decoded frames coalesce before encoding; a bounded encoded outbox waits for the
|
|
viewer. Only complete, acknowledged RRD batches leave that outbox.
|
|
"""
|
|
|
|
import logging
|
|
import queue
|
|
import threading
|
|
import time
|
|
from contextlib import suppress
|
|
from uuid import uuid4
|
|
from dataclasses import replace
|
|
import math
|
|
|
|
from k1link.data_plane import DecodedPointCloudView
|
|
from k1link.viewer.rerun_bridge import RerunBridge
|
|
|
|
MAX_ENCODED_CHUNK = 8 * 1024 * 1024
|
|
LIVE_FRAME_MAX_AGE_SECONDS = 2.0
|
|
RESUME_GRACE_SECONDS = 300.0
|
|
logger = logging.getLogger(__name__)
|
|
_CURRENT_FRAME = object()
|
|
|
|
|
|
def preview_points(frame, limit):
|
|
"""Sample only the disposable view; preserve source, channels and provenance."""
|
|
stride = max(1, math.ceil(frame.point_count / max(1, limit)))
|
|
if stride == 1:
|
|
return frame
|
|
indices = range(0, frame.point_count, stride)
|
|
return replace(frame, positions_xyz=frame.positions_xyz[::stride],
|
|
intensities=frame.intensities[::stride] if frame.intensities is not None else None,
|
|
colors_rgb=b"".join(frame.colors_rgb[i*3:i*3+3] for i in indices)
|
|
if frame.colors_rgb is not None else None)
|
|
|
|
|
|
class PreviewResumeError(ValueError):
|
|
"""A view must be explicitly reopened; silently resetting history is forbidden."""
|
|
|
|
|
|
class RrdSubscriber:
|
|
def __init__(self, settings_provider, path_provider=None, budget=None):
|
|
self.closed = threading.Event()
|
|
self.budget = budget
|
|
self.next_publish = 0.0
|
|
self.inputs = {}
|
|
self.input_ready = threading.Condition()
|
|
self.delivery_lock = threading.Lock()
|
|
self.pending = None
|
|
self.batch_sequence = 0
|
|
self.detached_at = None
|
|
self.path_provider = path_provider
|
|
self.output = queue.Queue(maxsize=2)
|
|
self.settings_provider = settings_provider
|
|
self.last_frame = None
|
|
self.thread = threading.Thread(target=self.run, name="node-rerun-view", daemon=True)
|
|
self.thread.start()
|
|
|
|
def offer(self, envelope):
|
|
if self.closed.is_set():
|
|
return
|
|
with self.input_ready:
|
|
# Keep one latest envelope per modality: a pose burst must not
|
|
# starve PCL, and no network wait reaches the acquisition producer.
|
|
self.inputs[type(envelope)] = envelope
|
|
self.input_ready.notify()
|
|
|
|
def attach(self, after=0, budget=None):
|
|
if self.closed.is_set() or not self.delivery_lock.acquire(blocking=False):
|
|
raise RuntimeError("Preview is closed or still attached")
|
|
if after != self.batch_sequence and not (
|
|
self.pending is not None and after == self.batch_sequence - 1):
|
|
self.delivery_lock.release()
|
|
raise PreviewResumeError("Preview cursor does not match recording")
|
|
self.budget = budget
|
|
self.acknowledge(after)
|
|
self.detached_at = None
|
|
return self
|
|
|
|
def release(self):
|
|
self.detached_at = time.monotonic()
|
|
self.delivery_lock.release()
|
|
|
|
def next_batch(self, *, wait=True):
|
|
if self.pending is None:
|
|
value = self._read(wait=wait)
|
|
if not value:
|
|
return value
|
|
self.batch_sequence += 1
|
|
self.pending = (self.batch_sequence, *value)
|
|
return self.pending
|
|
|
|
def acknowledge(self, sequence):
|
|
if self.pending is not None and sequence == self.pending[0]:
|
|
self.pending = None
|
|
|
|
def _read(self, *, wait=True):
|
|
if self.closed.is_set():
|
|
return None
|
|
try:
|
|
return self.output.get(timeout=0.5) if wait else self.output.get_nowait()
|
|
except queue.Empty:
|
|
return b""
|
|
|
|
def read(self):
|
|
# Kept for native sink inspection; media delivery uses acknowledged batches.
|
|
value = self._read()
|
|
return value[0] if value else value
|
|
|
|
def snapshot(self, frame=_CURRENT_FRAME):
|
|
frame = self.last_frame if frame is _CURRENT_FRAME else frame
|
|
return {"type": "lidar-state", "sequence": frame[0] if frame else 0,
|
|
"age_ms": max(0, (time.monotonic_ns() - frame[1]) / 1_000_000) if frame else None,
|
|
"points": frame[2] if frame else 0}
|
|
|
|
def close(self):
|
|
self.closed.set()
|
|
|
|
def run(self):
|
|
binary = None
|
|
bridge = None
|
|
|
|
def output(recording):
|
|
nonlocal binary
|
|
binary = recording.binary_stream()
|
|
return "webrtc+rrd://" + str(uuid4())
|
|
|
|
try:
|
|
bridge = PreviewRerunBridge(settings_provider=self.settings_provider,
|
|
recording_output=output, path_provider=self.path_provider)
|
|
bridge.begin_session()
|
|
while not self.closed.is_set():
|
|
payload = binary.read()
|
|
# The SDK returns None while its live sink has no new bytes.
|
|
# An idle read is not EOF and must not retire the media peer.
|
|
if payload and len(payload) > MAX_ENCODED_CHUNK:
|
|
break
|
|
if payload:
|
|
# Backpressure is a pause, never EOF. At most two encoded
|
|
# batches plus this one and the in-flight batch are retained.
|
|
# Do not drop encoded bytes or restart a native recording.
|
|
while not self.closed.is_set():
|
|
try:
|
|
self.output.put((payload, self.last_frame), timeout=0.1)
|
|
break
|
|
except queue.Full:
|
|
continue
|
|
budget = self.budget
|
|
if budget is not None:
|
|
count, interval = budget.cloud()
|
|
if not count:
|
|
self.closed.wait(.1)
|
|
continue
|
|
# Wait before taking the coalesced latest input. Already
|
|
# encoded RRD batches keep their original reliable order.
|
|
self.closed.wait(max(0, self.next_publish-time.monotonic()))
|
|
with self.input_ready:
|
|
if not self.inputs:
|
|
self.input_ready.wait(timeout=0.1)
|
|
if not self.inputs:
|
|
continue
|
|
envelope = self.inputs.pop(next(iter(self.inputs)))
|
|
received = envelope.context.received_monotonic_ns
|
|
if (received is not None
|
|
and (time.monotonic_ns() - received) / 1_000_000_000
|
|
> LIVE_FRAME_MAX_AGE_SECONDS):
|
|
continue
|
|
if budget is not None:
|
|
count, interval = budget.cloud()
|
|
if not count:
|
|
continue
|
|
self.next_publish = time.monotonic() + interval
|
|
if isinstance(envelope, DecodedPointCloudView):
|
|
envelope = preview_points(envelope, count)
|
|
bridge.process(envelope)
|
|
if isinstance(envelope, DecodedPointCloudView):
|
|
self.last_frame = (
|
|
envelope.context.sequence,
|
|
envelope.context.received_monotonic_ns or time.monotonic_ns(),
|
|
envelope.point_count,
|
|
)
|
|
except Exception as error:
|
|
logger.warning("Node RRD subscriber failed exception=%s", type(error).__name__)
|
|
finally:
|
|
self.closed.set()
|
|
if bridge is not None:
|
|
with suppress(Exception):
|
|
bridge.close()
|
|
binary.read()
|
|
|
|
|
|
class PreviewRerunBridge(RerunBridge):
|
|
def __init__(self, *, path_provider=None, **kwargs):
|
|
self.path_provider = path_provider
|
|
super().__init__(**kwargs)
|
|
|
|
def _append_trajectory_pose(self, position, source_time_ns):
|
|
if self.path_provider is None:
|
|
return super()._append_trajectory_pose(position, source_time_ns)
|
|
# Route history belongs to the acquisition, including movement during
|
|
# preview congestion. The primary bridge already bounds its point count.
|
|
path = self.path_provider()
|
|
if self._path == path:
|
|
return False
|
|
self._path = path
|
|
return True
|
|
|
|
|
|
class NodeRerunBridge(RerunBridge):
|
|
def __init__(self, **kwargs):
|
|
self.lock = threading.Lock()
|
|
self.subscribers = []
|
|
self.views = {}
|
|
self.latest = {}
|
|
|
|
def output(recording):
|
|
self.binary = recording.binary_stream()
|
|
return "webrtc+rrd://" + str(uuid4())
|
|
|
|
super().__init__(**kwargs, recording_output=output)
|
|
self.binary.read()
|
|
|
|
def process(self, envelope):
|
|
super().process(envelope)
|
|
# The primary recording proves native publication and owns metrics.
|
|
# It is continuously drained even when no viewer is attached.
|
|
self.binary.read()
|
|
with self.lock:
|
|
self.latest[type(envelope)] = (time.monotonic(), envelope)
|
|
self._expire_views()
|
|
self.subscribers = [v for v in self.subscribers if not v.closed.is_set()]
|
|
for subscriber in self.subscribers:
|
|
subscriber.offer(envelope)
|
|
|
|
def process_perception(self, frame):
|
|
super().process_perception(frame)
|
|
self.binary.read()
|
|
|
|
def _expire_views(self):
|
|
for key, value in list(self.views.items()):
|
|
if (value.closed.is_set() or (value.detached_at is not None
|
|
and time.monotonic() - value.detached_at > RESUME_GRACE_SECONDS)):
|
|
value.close()
|
|
del self.views[key]
|
|
|
|
def subscribe(self, view_id=None, after=0, *, budget=None):
|
|
with self.lock:
|
|
self._expire_views()
|
|
if self._closed:
|
|
raise RuntimeError("Live acquisition is not active")
|
|
if view_id in self.views:
|
|
return self.views[view_id].attach(after, budget)
|
|
if after:
|
|
raise PreviewResumeError("Preview recording expired; reopen the view")
|
|
self.subscribers = [v for v in self.subscribers if not v.closed.is_set()]
|
|
if len(self.subscribers) >= 2:
|
|
raise RuntimeError("Close another live viewer")
|
|
subscriber = RrdSubscriber(self._settings_provider, lambda: list(self._path), budget)
|
|
for observed, envelope in self.latest.values():
|
|
if time.monotonic() - observed <= LIVE_FRAME_MAX_AGE_SECONDS:
|
|
subscriber.offer(envelope)
|
|
self.subscribers.append(subscriber)
|
|
if view_id is not None:
|
|
self.views[view_id] = subscriber
|
|
subscriber.attach(budget=budget)
|
|
return subscriber
|
|
|
|
def release_view(self, view_id):
|
|
with self.lock:
|
|
subscriber = self.views.pop(view_id, None)
|
|
if subscriber is not None:
|
|
subscriber.close()
|
|
|
|
def close(self):
|
|
with self.lock:
|
|
for subscriber in self.subscribers:
|
|
subscriber.close()
|
|
self.subscribers.clear()
|
|
self.latest.clear()
|
|
self.views.clear()
|
|
super().close()
|
|
self.binary.read()
|
|
|
|
|
|
class NodeRerunHub:
|
|
def __init__(self):
|
|
self.bridge = None
|
|
|
|
def create(self, **kwargs):
|
|
bridge = NodeRerunBridge(**kwargs)
|
|
self.bridge = bridge
|
|
return bridge
|
|
|
|
def subscribe(self, view_id=None, after=0, *, budget=None):
|
|
bridge = self.bridge
|
|
if bridge is None:
|
|
raise RuntimeError("Live acquisition is not active")
|
|
return bridge.subscribe(view_id, after, budget=budget)
|
|
|
|
def release_view(self, view_id):
|
|
if self.bridge is not None:
|
|
self.bridge.release_view(view_id)
|