diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 646fbb4..5a4761e 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -35,6 +35,7 @@ - Multi-LOD cells now carry first-pass material estimates: weighted albedo plus roughness/metallic hints derived from source evidence. Aquarium should treat this as relightable material evidence to refine, not as the final BRDF solve. - The Spout/audio overlay boundary clamps stale visual packets to the current audio reservoir edge. If camera geometry ages out, it is dropped instead of being broadcast out of sync. - Live fallback-only RGB/Leap mode exists for deadline operation when OpenCV/MSMF/DirectShow reads block longer than the five-second reservoir. It keeps the reservoir and OBS output alive while real camera capture is moved to nonblocking ingress. + - OpenCV camera reads now run behind `LatestFramePump` workers so blocking drivers cannot freeze the fusion hot loop. The live deadline command uses lower per-frame sample density (`--rgb-room-step 16 --leap-step 16 --points 64`) so the reservoir/TAA path stays fresh enough for Spout to render visual points inside the five-second budget. - `localcast.sensor_fusion.chirp_pose` converts live phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints and per-camera pose-correction estimates. It can load camera-mic and speaker geometry from the audio-field profile, with the example profile used as the live fallback until measured local geometry exists. `scripts/live_sensor_fusion.py` injects those constraints as `camera-chirp:*` and `camera-pose-correction:*` render points plus `chirp-camera-pose` LOD evidence. - `scripts/stream_spout.py` runs the deadline Spout sender loop from the typed cache with typed and JSON heartbeat status. - The deadline Spout renderer has a named `kiyo-mid-deru` virtual camera preset: eye at the midpoint between the two Kiyo-class cameras and target on the co-streamer body volume. It also applies a renderer-owned point budget with pinned calibration/cross-modal constraints, stable high-confidence anchors, and frame-varying remainder samples so downstream TAA/supersampling can accumulate detail without forcing every source claim into every OBS frame. Its JSON heartbeat reports the prefix counts that survived the render budget. diff --git a/localcast/sensor_fusion/adapters.py b/localcast/sensor_fusion/adapters.py index 3f365cf..180861b 100644 --- a/localcast/sensor_fusion/adapters.py +++ b/localcast/sensor_fusion/adapters.py @@ -2,8 +2,9 @@ from __future__ import annotations from dataclasses import dataclass import subprocess +import threading import time -from typing import BinaryIO, Iterator, Protocol +from typing import BinaryIO, Callable, Iterator, Protocol import numpy as np @@ -60,6 +61,120 @@ class FfmpegRawVideoConfig: ] +@dataclass(frozen=True) +class OpenCvCaptureConfig: + sensor_id: str + index: int + api: str + width: int + height: int + fps: float | None = None + + +class OpenCvFrameSource: + """OpenCV camera source. Use behind LatestFramePump for live loops.""" + + def __init__(self, config: OpenCvCaptureConfig): + self.config = config + self._capture = None + + def __enter__(self) -> "OpenCvFrameSource": + import cv2 + + capture = cv2.VideoCapture(self.config.index, cv2_api(self.config.api)) + if not capture.isOpened(): + try: + capture.release() + except Exception: + pass + raise RuntimeError(f"OpenCV capture did not open: {self.config}") + capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.config.width) + capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.config.height) + if self.config.fps is not None: + capture.set(cv2.CAP_PROP_FPS, float(self.config.fps)) + capture.set(cv2.CAP_PROP_BUFFERSIZE, 1) + self._capture = capture + return self + + def __exit__(self, exc_type, exc, tb) -> None: + if self._capture is not None: + try: + self._capture.release() + except Exception: + pass + self._capture = None + + def frames(self) -> Iterator[FramePacket]: + if self._capture is None: + raise RuntimeError("OpenCvFrameSource must be used as a context manager") + sequence = 0 + while True: + ok, frame = self._capture.read() + if not ok or frame is None: + return + yield FramePacket( + sensor_id=self.config.sensor_id, + timestamp_ns=time.monotonic_ns(), + sequence=sequence, + image_bgr=frame.copy(), + ) + sequence += 1 + + +class LatestFramePump: + """Runs a blocking FrameSource in a daemon thread and exposes its latest frame.""" + + def __init__(self, source_factory: Callable[[], FrameSource]): + self.source_factory = source_factory + self._lock = threading.Lock() + self._latest: FramePacket | None = None + self._error: str | None = None + self._thread: threading.Thread | None = None + + def start(self) -> None: + if self._thread is not None: + return + self._thread = threading.Thread(target=self._run, name="localcast-latest-frame-pump", daemon=True) + self._thread.start() + + def latest(self, *, max_age_ns: int | None = None, now_ns: int | None = None) -> FramePacket | None: + with self._lock: + frame = self._latest + if frame is None: + return None + if max_age_ns is not None: + current = time.monotonic_ns() if now_ns is None else int(now_ns) + if current - int(frame.timestamp_ns) > int(max_age_ns): + return None + return frame + + @property + def error(self) -> str | None: + with self._lock: + return self._error + + def _run(self) -> None: + try: + with self.source_factory() as source: # type: ignore[attr-defined] + for frame in source.frames(): + with self._lock: + self._latest = frame + self._error = None + except Exception as exc: + with self._lock: + self._error = repr(exc) + + +def cv2_api(name: str) -> int: + import cv2 + + return { + "any": 0, + "dshow": cv2.CAP_DSHOW, + "msmf": cv2.CAP_MSMF, + }[name] + + class FfmpegRawVideoSource: """Frame source adapter for DirectShow devices that FFmpeg negotiates better than OpenCV.""" diff --git a/localcast/sensor_fusion/clap_calibration.py b/localcast/sensor_fusion/clap_calibration.py index 5ab1a77..0d3af76 100644 --- a/localcast/sensor_fusion/clap_calibration.py +++ b/localcast/sensor_fusion/clap_calibration.py @@ -211,6 +211,8 @@ def detect_camera_motion_peaks( midpoint_ns = (previous.timestamp_ns + current.timestamp_ns) // 2 if abs(midpoint_ns - oracle_time_ns) > config.camera_window_ns: continue + if previous.image.shape[:2] != current.image.shape[:2]: + continue score, uv = frame_motion_score(previous.image, current.image) if score < config.min_camera_motion_score: continue diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 0057b57..db3ea6e 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -111,6 +111,7 @@ Ownership: - The live producer's temporal authority is a five-second spatiotemporal reservoir measured backward from the newest shared sample. RGB/Leap history expires against that shared edge, LOD evidence is clipped to the same window, and each render frame declares the exact reservoir slice with `source_time_min_ns` and `source_time_max_ns`. - Multi-LOD cache cells carry first-pass material evidence: weighted albedo plus roughness/metallic hints. Aquarium owns the real relighting/BRDF refinement, but it should receive material state from the reservoir rather than reverse-engineering it from screen brushes. - `stream_spout.py` clamps stale visual packets to the current audio reservoir edge before OBS sees them. If a camera path blocks past the five-second window, its stale points are dropped. Current live deadline mode uses `--rgb-fallback-only --leap-fallback-only` because direct OpenCV camera reads measured slower than the reservoir; the next cut is nonblocking camera ingress that fills the reservoir continuously. +- `LatestFramePump` now runs blocking OpenCV camera sources off the producer hot loop. Deadline live mode keeps per-frame visual density low enough for TAA/reservoir accumulation: roughly 1.6k Spout points at `audio_delta_ns: 0` with `--rgb-room-step 16 --leap-step 16 --points 64`. - `localcast.sensor_fusion.chirp_pose` now turns phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints and per-camera pose-correction estimates. It loads camera-mic and speaker geometry from the audio-field profile when available, falling back to the example profile/defaults. The live producer publishes those constraints as `camera-chirp:*` and `camera-pose-correction:*` render points plus `chirp-camera-pose` LOD evidence. Audio range/timing evidence augments visual calibration; it does not own image geometry. - The Spout point-budget policy pins calibration and cross-modal constraints before spending the remaining adaptive LOD budget on stable high-priority surface claims and frame-rotated samples. Its JSON heartbeat reports the prefix counts that survived the render budget. - The live producer also writes a multi-LOD scene cache with source kind and priority. Real Leap frames are the highest-priority timing/spatial evidence; Leap fallback frames are tagged as fallback and do not become ground truth. diff --git a/scripts/live_sensor_fusion.py b/scripts/live_sensor_fusion.py index 12a3bf2..1e02d0d 100644 --- a/scripts/live_sensor_fusion.py +++ b/scripts/live_sensor_fusion.py @@ -45,6 +45,7 @@ from localcast.sensor_fusion import ( speaker_geometry_from_audio_profile, ) from localcast.sensor_fusion.camera_control import AdaptiveCameraController, OpenCvCameraSettingPort +from localcast.sensor_fusion.adapters import LatestFramePump, OpenCvCaptureConfig, OpenCvFrameSource from audio_field.cultcache_audio import frame_to_numpy, get_live_audio_phase_field, get_live_spatial_audio_frame @@ -321,6 +322,7 @@ class RgbSplatSampler: self.fallback_dir = fallback_dir self.fallback_only = bool(fallback_only) self._captures: dict[int, object] = {} + self._pumps: dict[int, LatestFramePump] = {} self._frames: dict[int, np.ndarray] = {} self._timestamped_frames: dict[str, TimestampedFrame] = {} self._history = TimestampedFrameHistory(max_frames=720, max_age_ns=reservoir_ns) @@ -383,39 +385,27 @@ class RgbSplatSampler: return dict(self._timestamped_frames) def _read_frame(self, index: int) -> np.ndarray | None: - import cv2 - if self.fallback_only: return self._fallback_frame(index) - capture = self._captures.get(index) - if capture is None: - capture = cv2.VideoCapture(index, cv2_api(self.api)) - if capture.isOpened(): - capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.width) - capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height) - capture.set(cv2.CAP_PROP_BUFFERSIZE, 1) - self._captures[index] = capture - if self.adaptive_controls: - self._controllers[index] = AdaptiveCameraController() - self._setting_ports[index] = OpenCvCameraSettingPort(capture) - else: - try: - capture.release() - except Exception: - pass - return self._fallback_frame(index) - ok = False - frame = None - for _ in range(2): - ok, frame = capture.read() - if ok and frame is not None: - sensor_id = self._sensor_id(index) - stamped = TimestampedFrame(sensor_id, time.monotonic_ns(), frame.copy()) - self._timestamped_frames[sensor_id] = stamped - self._history.add(stamped) - self._tune_capture(index, frame) - self._frames[index] = frame - return frame + pump = self._pumps.get(index) + if pump is None: + sensor_id = self._sensor_id(index) + pump = LatestFramePump( + lambda sensor_id=sensor_id, index=index: OpenCvFrameSource( + OpenCvCaptureConfig(sensor_id=sensor_id, index=index, api=self.api, width=self.width, height=self.height) + ) + ) + pump.start() + self._pumps[index] = pump + packet = pump.latest(max_age_ns=DEFAULT_RESERVOIR_NS) + if packet is not None: + frame = packet.image_bgr + stamped = TimestampedFrame(packet.sensor_id, packet.timestamp_ns, frame.copy()) + self._timestamped_frames[packet.sensor_id] = stamped + self._history.add(stamped) + self._tune_capture(index, frame) + self._frames[index] = frame + return frame cached = self._frames.get(index) if cached is not None: return cached @@ -982,6 +972,7 @@ class LeapPackedMotionSampler: self.fallback_dir = fallback_dir self.fallback_only = bool(fallback_only) self._capture = None + self._pump: LatestFramePump | None = None self._previous_channels: dict[str, np.ndarray] = {} self._last_timestamp_ns: int | None = None self._last_frame_kind: str | None = None @@ -1026,28 +1017,26 @@ class LeapPackedMotionSampler: return tuple(points) def _read_frame(self) -> np.ndarray | None: - import cv2 - if self.fallback_only: return self._fallback_frame() - if self._capture is None: - capture = cv2.VideoCapture(self.index, cv2_api(self.api)) - if capture.isOpened(): - capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.width) - capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height) - capture.set(cv2.CAP_PROP_FPS, self.fps) - capture.set(cv2.CAP_PROP_BUFFERSIZE, 1) - self._capture = capture - else: - try: - capture.release() - except Exception: - pass - return self._fallback_frame() - ok, frame = self._capture.read() - if ok and frame is not None: + if self._pump is None: + self._pump = LatestFramePump( + lambda: OpenCvFrameSource( + OpenCvCaptureConfig( + sensor_id="leap", + index=self.index, + api=self.api, + width=self.width, + height=self.height, + fps=self.fps, + ) + ) + ) + self._pump.start() + packet = self._pump.latest(max_age_ns=DEFAULT_RESERVOIR_NS) + if packet is not None: self._last_frame_kind = "capture" - return frame + return packet.image_bgr return self._fallback_frame() def _fallback_frame(self) -> np.ndarray | None: diff --git a/state/map.yaml b/state/map.yaml index 21071bb..5c59072 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -202,7 +202,11 @@ research: OBS sees them. Current live deadline mode uses fallback-only RGB/Leap because synchronous OpenCV camera reads measured slower than the reservoir; the next coherent cut is nonblocking camera ingress that continuously - fills the five-second reservoir with real samples. + fills the five-second reservoir with real samples. `LatestFramePump` now + moves blocking OpenCV reads off the fusion hot loop; the running deadline + mode uses lower per-frame sample density so Spout can render visual points + inside the five-second budget while TAA/reservoir accumulation carries + detail over time. typed_visual_state: summary: docs/typed-visual-state.md key_decision: > diff --git a/tests/test_sensor_fusion.py b/tests/test_sensor_fusion.py index 153981c..090cb56 100644 --- a/tests/test_sensor_fusion.py +++ b/tests/test_sensor_fusion.py @@ -1,6 +1,7 @@ import io from pathlib import Path import tempfile +import time import unittest import numpy as np @@ -33,6 +34,7 @@ from localcast.sensor_fusion import ( camera_mic_geometry_from_audio_profile, camera_sensor_id_for_microphone, constraints_from_phase_sources, + detect_camera_motion_peaks, detect_clap_events, estimate_pose_corrections, frame_to_vertex_array, @@ -71,6 +73,7 @@ from scripts.live_sensor_fusion import ( from localcast.sensor_fusion.active_illumination import ActiveIlluminationController, IlluminationPulsePlan from audio_field.cultcache_audio import make_audio_source_events, make_spatial_audio_frame, put_live_spatial_audio_frame from localcast.sensor_fusion.adapters import read_raw_bgr_frames +from localcast.sensor_fusion.adapters import LatestFramePump, FramePacket def camera(sensor_id, x): @@ -676,6 +679,44 @@ class SensorFusionTests(unittest.TestCase): self.assertEqual(5_000_000_000, clamped.source_time_max_ns - clamped.source_time_min_ns) self.assertEqual(("fresh",), tuple(point.stable_key for point in clamped.points)) + def test_latest_frame_pump_exposes_newest_frame_without_blocking_reader(self): + class FakeSource: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return None + + def frames(self): + yield FramePacket("cam", 10, 0, np.zeros((1, 1, 3), dtype=np.uint8)) + yield FramePacket("cam", 20, 1, np.ones((1, 1, 3), dtype=np.uint8)) + + pump = LatestFramePump(lambda: FakeSource()) + pump.start() + deadline = time.monotonic() + 1.0 + latest = None + while time.monotonic() < deadline: + latest = pump.latest() + if latest is not None and latest.sequence == 1: + break + time.sleep(0.01) + + self.assertIsNotNone(latest) + self.assertEqual(1, latest.sequence) + self.assertEqual(20, latest.timestamp_ns) + + def test_camera_motion_peaks_skip_mismatched_frame_shapes(self): + frames = { + "leap": [ + TimestampedFrame("leap", 1_000, np.zeros((12, 16), dtype=np.float32)), + TimestampedFrame("leap", 2_000, np.zeros((24, 16), dtype=np.float32)), + ] + } + + peaks = detect_camera_motion_peaks(frames, 1_500) + + self.assertEqual([], peaks) + def test_chirp_pose_constraints_map_camera_mics_to_range_residuals(self): constraints = constraints_from_phase_sources( (