Preserve onboard preview recordings across backpressure and share the complete spatial scene
This commit is contained in:
+129
-28
@@ -1,8 +1,8 @@
|
||||
"""Bounded live RRD publication for paired Node viewers, without a TCP listener.
|
||||
|
||||
Every viewer receives a fresh native recording including StoreInfo/blueprint.
|
||||
Latest-value queues discard decoded preview frames before encoding; encoded
|
||||
RRD bytes are never dropped inside a stream. Slow viewers are closed instead.
|
||||
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
|
||||
@@ -17,13 +17,25 @@ 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()
|
||||
|
||||
|
||||
class PreviewResumeError(ValueError):
|
||||
"""A view must be explicitly reopened; silently resetting history is forbidden."""
|
||||
|
||||
|
||||
class RrdSubscriber:
|
||||
def __init__(self, settings_provider):
|
||||
def __init__(self, settings_provider, path_provider=None):
|
||||
self.closed = threading.Event()
|
||||
self.inputs = queue.Queue(maxsize=2)
|
||||
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
|
||||
@@ -33,22 +45,55 @@ class RrdSubscriber:
|
||||
def offer(self, envelope):
|
||||
if self.closed.is_set():
|
||||
return
|
||||
with suppress(queue.Full):
|
||||
if self.inputs.full():
|
||||
with suppress(queue.Empty):
|
||||
self.inputs.get_nowait()
|
||||
self.inputs.put_nowait(envelope)
|
||||
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 read(self):
|
||||
def attach(self, after=0):
|
||||
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.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)
|
||||
return self.output.get(timeout=0.5) if wait else self.output.get_nowait()
|
||||
except queue.Empty:
|
||||
return b""
|
||||
|
||||
def snapshot(self):
|
||||
frame = self.last_frame
|
||||
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}
|
||||
@@ -66,7 +111,8 @@ class RrdSubscriber:
|
||||
return "webrtc+rrd://" + str(uuid4())
|
||||
|
||||
try:
|
||||
bridge = RerunBridge(settings_provider=self.settings_provider, recording_output=output)
|
||||
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()
|
||||
@@ -75,13 +121,21 @@ class RrdSubscriber:
|
||||
if payload and len(payload) > MAX_ENCODED_CHUNK:
|
||||
break
|
||||
if payload:
|
||||
# Bound both bytes and waiting time. The archive/producer
|
||||
# never waits for this disposable preview subscription.
|
||||
self.output.put(payload, timeout=0.5)
|
||||
try:
|
||||
envelope = self.inputs.get(timeout=0.1)
|
||||
except queue.Empty:
|
||||
continue
|
||||
# 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
|
||||
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
|
||||
@@ -104,10 +158,28 @@ class RrdSubscriber:
|
||||
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):
|
||||
@@ -124,6 +196,7 @@ class NodeRerunBridge(RerunBridge):
|
||||
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)
|
||||
@@ -132,24 +205,48 @@ class NodeRerunBridge(RerunBridge):
|
||||
super().process_perception(frame)
|
||||
self.binary.read()
|
||||
|
||||
def subscribe(self):
|
||||
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):
|
||||
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)
|
||||
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 self._closed or len(self.subscribers) >= 2:
|
||||
raise RuntimeError("Live viewer unavailable")
|
||||
subscriber = RrdSubscriber(self._settings_provider)
|
||||
if len(self.subscribers) >= 2:
|
||||
raise RuntimeError("Close another live viewer")
|
||||
subscriber = RrdSubscriber(self._settings_provider, lambda: list(self._path))
|
||||
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()
|
||||
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()
|
||||
|
||||
@@ -163,8 +260,12 @@ class NodeRerunHub:
|
||||
self.bridge = bridge
|
||||
return bridge
|
||||
|
||||
def subscribe(self):
|
||||
def subscribe(self, view_id=None, after=0):
|
||||
bridge = self.bridge
|
||||
if bridge is None:
|
||||
raise RuntimeError("Live acquisition is not active")
|
||||
return bridge.subscribe()
|
||||
return bridge.subscribe(view_id, after)
|
||||
|
||||
def release_view(self, view_id):
|
||||
if self.bridge is not None:
|
||||
self.bridge.release_view(view_id)
|
||||
|
||||
Reference in New Issue
Block a user