Use clap offsets for camera history sampling

This commit is contained in:
Meta Vens 2026-05-19 00:22:36 +01:00
commit 8e0dfbf5c1
8 changed files with 253 additions and 17 deletions

View file

@ -30,6 +30,7 @@
- `scripts/live_sensor_fusion.py` writes fused render frames into `calibration/runs/visual-state.msgpack`.
- The live visual producer writes a multi-LOD scene cache with source kind and priority. Real Leap frames are promoted as the highest-priority visual timing/spatial evidence; Leap fallback frames remain lower-priority diagnostics.
- Live clap calibration is wired into the visual producer. It keeps a rolling frame window from the Kiyo pair plus Leap, reads the live spatial audio frame for transient candidates, publishes `clap-events.msgpack`, injects clap calibration markers into the render frame, and writes clap evidence into the LOD cache. Kiyo stereo owns the current rough 3D solve; Leap owns the best visual timing witness until its geometric model is calibrated.
- Clap peaks now update a per-camera clock sync model. The point-cloud builder can sample camera history buffers at `oracle_time - camera_offset` instead of using whichever frame arrived last.
- `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 stable high-confidence anchors plus frame-varying remainder samples so downstream TAA/supersampling can accumulate detail without forcing every source claim into every OBS frame.
- `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary.
@ -73,8 +74,9 @@
11. Move the render-frame consumer into Aquarium Engine so dense brush/splat rendering replaces the deadline OpenGL point sink behind the same OBS Spout boundary.
12. Capture fixed-board ChArUco observations for every camera, solve `config/sensor-fusion.json`, and verify cross-view feature triangulation with `scripts/triangulate_surface_features.py`.
13. Replace synthetic live-fusion observations with PS3 Eye detector observations and calibrated surface-feature tracks.
14. Calibrate Leap as a geometric camera in the shared rig so the timing authority can also contribute direct 3D rays instead of only visual timing peaks.
15. Fix the live Leap capture backend so actual Leap frames, not fallback frames, populate `leap-ground-truth` cells in the multi-LOD cache.
16. Keep the neighbor loopback leg running through the scheduled interactive WASAPI capture path and use it as the timing witness once actual neighbor app audio is present.
17. Let the co-streamer surface delay drive the shared presentation buffer horizon for audio stems, AmbiX, and remote video.
18. Wire `stream_phase_field.py` and `stream_faust_mic_field.py` to the real live aligned-field producer instead of replaying WAV artifacts, then feed emitted active chirps back through loopback/mic capture so confidence maintenance closes against fresh observations instead of dry-run probe manifests.
14. Feed ultrasonic chirp delay estimates from Kiyo/PS Eye microphones into the shared scene map as camera-body pose constraints. The mics do not replace camera calibration; they add range/timing evidence for the physical camera bodies.
15. Calibrate Leap as a geometric camera in the shared rig so the timing authority can also contribute direct 3D rays instead of only visual timing peaks.
16. Fix the live Leap capture backend so actual Leap frames, not fallback frames, populate `leap-ground-truth` cells in the multi-LOD cache.
17. Keep the neighbor loopback leg running through the scheduled interactive WASAPI capture path and use it as the timing witness once actual neighbor app audio is present.
18. Let the co-streamer surface delay drive the shared presentation buffer horizon for audio stems, AmbiX, and remote video.
19. Wire `stream_phase_field.py` and `stream_faust_mic_field.py` to the real live aligned-field producer instead of replaying WAV artifacts, then feed emitted active chirps back through loopback/mic capture so confidence maintenance closes against fresh observations instead of dry-run probe manifests.

View file

@ -56,9 +56,12 @@ from .audio_overlay import AudioVisualSyncStatus, overlay_audio_events
from .media_artifacts import RemoteVideoArtifact, remote_video_artifact_for_present_time
from .clap_calibration import (
AudioTransientCandidate,
CameraClockSyncModel,
CameraMotionPeak,
CameraSyncEstimate,
ClapCalibrationEvent,
ClapDetectorConfig,
TimestampedFrameHistory,
TimestampedFrame,
detect_audio_transients,
detect_camera_motion_peaks,
@ -122,9 +125,12 @@ __all__ = [
"AudioVisualSyncStatus",
"AudioTransientCandidate",
"CameraMotionPeak",
"CameraClockSyncModel",
"CameraSyncEstimate",
"ClapCalibrationEvent",
"ClapDetectorConfig",
"TimestampedFrame",
"TimestampedFrameHistory",
"RemoteVideoArtifact",
"CLAP_EVENTS_KEY",
"LIVE_RENDER_FRAME_KEY",

View file

@ -58,6 +58,81 @@ class ClapCalibrationEvent:
camera_peaks: tuple[CameraMotionPeak, ...]
@dataclass(frozen=True)
class CameraSyncEstimate:
sensor_id: str
offset_ns: int
confidence: float
updated_by_event: str
observed_timestamp_ns: int
oracle_timestamp_ns: int
class CameraClockSyncModel:
def __init__(self, smoothing: float = 0.35) -> None:
self.smoothing = max(0.0, min(1.0, float(smoothing)))
self._estimates: dict[str, CameraSyncEstimate] = {}
def observe_event(self, event: ClapCalibrationEvent) -> None:
for peak in event.camera_peaks:
raw_offset = int(event.acoustic_oracle_ns - peak.timestamp_ns)
confidence = max(0.0, min(1.0, float(peak.score) * float(event.acoustic_confidence)))
previous = self._estimates.get(peak.sensor_id)
if previous is None:
offset = raw_offset
confidence = max(confidence, 1.0e-6)
else:
alpha = self.smoothing * confidence
offset = round((1.0 - alpha) * previous.offset_ns + alpha * raw_offset)
confidence = max(previous.confidence * 0.96, confidence)
self._estimates[peak.sensor_id] = CameraSyncEstimate(
sensor_id=peak.sensor_id,
offset_ns=int(offset),
confidence=float(confidence),
updated_by_event=event.stable_key,
observed_timestamp_ns=int(peak.timestamp_ns),
oracle_timestamp_ns=int(event.acoustic_oracle_ns),
)
def offset_ns(self, sensor_id: str) -> int:
estimate = self._estimates.get(sensor_id)
return 0 if estimate is None else estimate.offset_ns
def raw_time_for_oracle(self, sensor_id: str, oracle_time_ns: int) -> int:
return int(oracle_time_ns) - self.offset_ns(sensor_id)
def estimates(self) -> tuple[CameraSyncEstimate, ...]:
return tuple(sorted(self._estimates.values(), key=lambda item: item.sensor_id))
class TimestampedFrameHistory:
def __init__(self, max_frames: int = 120) -> None:
self.max_frames = max(2, int(max_frames))
self._frames: dict[str, list[TimestampedFrame]] = {}
def add(self, frame: TimestampedFrame) -> None:
bucket = self._frames.setdefault(frame.sensor_id, [])
if bucket and bucket[-1].timestamp_ns == frame.timestamp_ns:
return
bucket.append(frame)
bucket.sort(key=lambda item: item.timestamp_ns)
del bucket[:-self.max_frames]
def add_many(self, frames: Mapping[str, TimestampedFrame]) -> None:
for frame in frames.values():
self.add(frame)
def frames_by_sensor(self) -> dict[str, list[TimestampedFrame]]:
return {sensor_id: list(frames) for sensor_id, frames in self._frames.items()}
def nearest(self, sensor_id: str, raw_time_ns: int) -> TimestampedFrame | None:
frames = self._frames.get(sensor_id, [])
if not frames:
return None
target = int(raw_time_ns)
return min(frames, key=lambda frame: abs(frame.timestamp_ns - target))
def detect_audio_transients(
field: np.ndarray,
sample_rate: int,

View file

@ -105,6 +105,8 @@ Ownership:
- `localcast.sensor_fusion.cultcache_docs` owns typed visual state documents.
- `scripts/live_sensor_fusion.py` currently owns the live producer and writes `localcast.visual.render_frame` into CultCache.
- The live producer now keeps a rolling RGB/Leap frame window for clap calibration. Kiyo stereo motion gives the first rough 3D clap position; Leap participates as the high-precision visual timing witness until a calibrated Leap geometric model joins the rig.
- Clap peaks update a per-camera clock sync model. Camera history sampling uses `oracle_time - camera_offset`, so the point builder can reconstruct a shared instant instead of mixing latest frames from different clock domains.
- Ultrasonic chirps from the Kiyo and PS Eye microphones should feed camera-body pose constraints into the same scene map. Audio range/timing evidence augments visual calibration; it does not own image geometry.
- 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.
- `scripts/stream_spout.py` consumes typed CultCache state and publishes Spout. Its presentation camera defaults to `kiyo-mid-deru`: the virtual eye sits halfway between the two Kiyo-class cameras and aims at the co-streamer body target. Its render budget is temporal: high-confidence anchors stay stable while the remaining samples rotate by frame id for TAA/supersampling reconciliation.
- CultNet document replication is the intended API boundary for other producers/consumers.

View file

@ -20,12 +20,17 @@ from localcast.sensor_fusion import (
RenderPointPacket,
SensorRig,
SurfaceFeatureObservation,
CameraClockSyncModel,
CameraMotionPeak,
ClapCalibrationEvent,
TimestampedFrame,
TimestampedFrameHistory,
ClapDetectorConfig,
detect_clap_events,
dense_stereo_points,
evidence_from_fusion_items,
evidence_from_render_points,
get_live_clap_events,
make_clap_events_frame,
measure_frame_quality,
multilod_cache_from_evidence,
@ -283,6 +288,7 @@ class RgbSplatSampler:
self._captures: dict[int, object] = {}
self._frames: dict[int, np.ndarray] = {}
self._timestamped_frames: dict[str, TimestampedFrame] = {}
self._history = TimestampedFrameHistory(max_frames=96)
self._controllers: dict[int, AdaptiveCameraController] = {}
self._setting_ports: dict[int, OpenCvCameraSettingPort] = {}
@ -297,6 +303,34 @@ class RgbSplatSampler:
def splats(self, now_s: float, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
primary = self._read_frame(self.primary_index)
secondary = self._read_frame(self.secondary_index)
return self._splats_from_frames(primary, secondary, now_s, timestamp_ns)
def synced_splats(
self,
now_s: float,
timestamp_ns: int,
*,
sync_model: CameraClockSyncModel,
oracle_time_ns: int,
) -> tuple[RenderPointPacket, ...]:
self._read_frame(self.primary_index)
self._read_frame(self.secondary_index)
primary = self._history.nearest("kiyo-primary", sync_model.raw_time_for_oracle("kiyo-primary", oracle_time_ns))
secondary = self._history.nearest("kiyo-secondary", sync_model.raw_time_for_oracle("kiyo-secondary", oracle_time_ns))
return self._splats_from_frames(
None if primary is None else primary.image,
None if secondary is None else secondary.image,
now_s,
timestamp_ns,
)
def _splats_from_frames(
self,
primary: np.ndarray | None,
secondary: np.ndarray | None,
now_s: float,
timestamp_ns: int,
) -> tuple[RenderPointPacket, ...]:
points: list[RenderPointPacket] = []
if self.enable_cpu_dense_stereo and primary is not None and secondary is not None:
points.extend(rgb_dense_stereo_splats(primary, secondary, timestamp_ns, step=self.dense_step))
@ -339,7 +373,9 @@ class RgbSplatSampler:
ok, frame = capture.read()
if ok and frame is not None:
sensor_id = self._sensor_id(index)
self._timestamped_frames[sensor_id] = TimestampedFrame(sensor_id, time.monotonic_ns(), frame.copy())
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
@ -370,7 +406,9 @@ class RgbSplatSampler:
frame = cv2.imread(str(path))
if frame is not None:
sensor_id = self._sensor_id(index)
self._timestamped_frames[sensor_id] = TimestampedFrame(sensor_id, time.monotonic_ns(), frame.copy())
stamped = TimestampedFrame(sensor_id, time.monotonic_ns(), frame.copy())
self._timestamped_frames[sensor_id] = stamped
self._history.add(stamped)
return frame
return None
@ -458,8 +496,10 @@ class LiveClapCalibrator:
self.audio_cache = audio_cache
self.clap_cache = clap_cache
self.max_frames_per_sensor = max(2, int(max_frames_per_sensor))
self.frames_by_sensor: dict[str, list[TimestampedFrame]] = {}
self.history = TimestampedFrameHistory(max_frames=self.max_frames_per_sensor)
self.sync_model = CameraClockSyncModel()
self.last_audio_frame_id: int | None = None
self.last_audio_time_ns: int | None = None
self.last_event_key: str | None = None
left = rgb_dense_camera("kiyo-primary", -0.18, camera_width, camera_height)
right = rgb_dense_camera("kiyo-secondary", 0.18, camera_width, camera_height)
@ -478,20 +518,48 @@ class LiveClapCalibrator:
min_event_spacing_ns=220_000_000,
)
self.events = ()
self._restore_existing_events()
def _restore_existing_events(self) -> None:
if not self.clap_cache.exists():
return
frame = get_live_clap_events(self.clap_cache)
if frame is None or not frame.events:
return
events: list[ClapCalibrationEvent] = []
for event in frame.events:
peaks = tuple(
CameraMotionPeak(
sensor_id=str(peak.get("sensorId", "")),
timestamp_ns=int(peak.get("timestampNs", 0)),
uv=np.asarray(peak.get("uv", [0.0, 0.0]), dtype=np.float64),
score=float(peak.get("score", 0.0)),
)
for peak in event.camera_peaks
)
restored = ClapCalibrationEvent(
stable_key=event.stable_key,
position_m=event.position_m,
acoustic_oracle_ns=event.acoustic_oracle_ns,
visual_observed_ns=event.visual_observed_ns,
timing_uncertainty_us=event.timing_uncertainty_us,
visual_confidence=event.visual_confidence,
acoustic_confidence=event.acoustic_confidence,
camera_peaks=peaks,
)
self.sync_model.observe_event(restored)
events.append(restored)
self.events = tuple(events)
def observe_frames(self, frames: dict[str, TimestampedFrame]) -> None:
for sensor_id, frame in frames.items():
bucket = self.frames_by_sensor.setdefault(sensor_id, [])
if bucket and bucket[-1].timestamp_ns == frame.timestamp_ns:
continue
bucket.append(frame)
del bucket[:-self.max_frames_per_sensor]
self.history.add_many(frames)
def update(self, frame_id: int) -> tuple[RenderPointPacket, ...]:
audio = self._read_audio()
if audio is None or audio.frame_id == self.last_audio_frame_id:
return self._event_points(frame_id)
self.last_audio_frame_id = audio.frame_id
self.last_audio_time_ns = int(audio.audio_time_ns)
block = frame_to_numpy(audio)
events = detect_clap_events(
block,
@ -505,6 +573,8 @@ class LiveClapCalibrator:
if events:
self.events = tuple(events)
self.last_event_key = events[-1].stable_key
for event in events:
self.sync_model.observe_event(event)
put_live_clap_events(self.clap_cache, make_clap_events_frame(frame_id=frame_id, events=events))
elif not self.events:
put_live_clap_events(self.clap_cache, make_clap_events_frame(frame_id=frame_id, events=()))
@ -516,7 +586,10 @@ class LiveClapCalibrator:
return get_live_spatial_audio_frame(self.audio_cache)
def _frames_for_detection(self) -> dict[str, list[TimestampedFrame]]:
return {sensor_id: list(frames) for sensor_id, frames in self.frames_by_sensor.items()}
return self.history.frames_by_sensor()
def oracle_time_ns(self, fallback_ns: int) -> int:
return int(self.last_audio_time_ns if self.last_audio_time_ns is not None else fallback_ns)
def _event_points(self, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
points: list[RenderPointPacket] = []
@ -559,9 +632,29 @@ class LiveClapCalibrator:
int(peak.timestamp_ns),
)
)
for estimate in self.sync_model.estimates():
points.append(
render_point(
f"camera-sync:{estimate.sensor_id}",
sync_status_position(estimate.sensor_id),
0.035,
(0.45, 0.72, 1.0, 0.58),
estimate.confidence,
estimate.oracle_timestamp_ns,
)
)
return tuple(points)
def sync_status_position(sensor_id: str) -> np.ndarray:
positions = {
"kiyo-primary": np.array([-0.18, -0.72, 1.28], dtype=np.float64),
"kiyo-secondary": np.array([0.18, -0.72, 1.28], dtype=np.float64),
"leap": np.array([0.0, -0.18, 0.76], dtype=np.float64),
}
return positions.get(sensor_id, np.zeros(3, dtype=np.float64))
def pixel_ray_point(camera: CameraModel, uv: np.ndarray, *, distance_m: float) -> np.ndarray:
point = np.asarray([float(uv[0]), float(uv[1]), 1.0], dtype=np.float64)
direction_sensor = np.linalg.inv(camera.camera_matrix) @ point
@ -995,7 +1088,6 @@ def main() -> None:
created_monotonic_ns=time.monotonic_ns(),
)
timestamp_ns = frame.source_time_max_ns
rgb_points = () if rgb_sampler is None else rgb_sampler.splats(now, timestamp_ns)
leap_points = () if leap_sampler is None else leap_sampler.motion_splats(timestamp_ns)
if clap_calibrator is not None:
if rgb_sampler is not None:
@ -1010,6 +1102,17 @@ def main() -> None:
else "leap-fallback"
)
leap_source_priority = 3.0 if leap_source_kind == "leap-ground-truth" else 1.1
rgb_points = ()
if rgb_sampler is not None:
if clap_calibrator is not None and clap_calibrator.sync_model.estimates():
rgb_points = rgb_sampler.synced_splats(
now,
timestamp_ns,
sync_model=clap_calibrator.sync_model,
oracle_time_ns=clap_calibrator.oracle_time_ns(timestamp_ns),
)
else:
rgb_points = rgb_sampler.splats(now, timestamp_ns)
support_points = dim_fusion_points(tuple(frame.points)) if not rgb_points else ()
stochastic_points = transient_match_render_points(transient_matches, timestamp_ns)
clap_points = () if clap_calibrator is None else clap_calibrator.update(timestamp_ns)

View file

@ -114,6 +114,10 @@ def msgpack_head(path: Path):
"visualObservedNs": payload[3][-1][3],
"timingUncertaintyUs": payload[3][-1][4],
"cameraCount": len(payload[3][-1][7]) if len(payload[3][-1]) > 7 else 0,
"cameraOffsetsNs": {
str(peak.get("sensorId")): int(payload[3][-1][2]) - int(peak.get("timestampNs", payload[3][-1][2]))
for peak in (payload[3][-1][7] if len(payload[3][-1]) > 7 else [])
},
},
}
)

View file

@ -168,7 +168,12 @@ research:
treated as ground truth. Live clap calibration now uses the Kiyo stereo
pair for the first rough 3D impact solve and includes Leap motion as the
high-precision visual timing witness; Leap should become a geometric
camera authority after shared calibration.
camera authority after shared calibration. Clap peaks update per-camera
clock offsets, allowing history buffers to be sampled at
`oracle_time - camera_offset` for coherent point-cloud construction.
Ultrasonic chirp delay estimates from camera microphones are valid
camera-body pose evidence and should enter this same map as range/timing
constraints, not as a separate audio-only calibration story.
typed_visual_state:
summary: docs/typed-visual-state.md
key_decision: >

View file

@ -10,6 +10,7 @@ from localcast.sensor_fusion import (
BoardObservation,
BoardSpec,
CameraModel,
CameraClockSyncModel,
CameraIntrinsics,
CameraQualityTarget,
ClapDetectorConfig,
@ -23,6 +24,7 @@ from localcast.sensor_fusion import (
SensorRig,
SpoutOutputConfig,
TimestampedFrame,
TimestampedFrameHistory,
TrackCache,
VirtualCamera,
detect_clap_events,
@ -509,6 +511,43 @@ class SensorFusionTests(unittest.TestCase):
self.assertTrue(clap_cache.exists())
self.assertTrue(any(point.stable_key.startswith("clap-calibration:") for point in points))
estimates = {estimate.sensor_id: estimate for estimate in calibrator.sync_model.estimates()}
self.assertIn("kiyo-primary", estimates)
self.assertIn("kiyo-secondary", estimates)
restored = LiveClapCalibrator(
audio_cache=audio_cache,
clap_cache=clap_cache,
camera_width=width,
camera_height=height,
)
restored_estimates = {estimate.sensor_id: estimate for estimate in restored.sync_model.estimates()}
self.assertIn("kiyo-primary", restored_estimates)
self.assertIn("kiyo-secondary", restored_estimates)
def test_camera_sync_model_selects_history_frame_at_oracle_time(self):
event = type(
"Event",
(),
{
"stable_key": "clap:test",
"acoustic_oracle_ns": 1_000,
"acoustic_confidence": 1.0,
"camera_peaks": (
type("Peak", (), {"sensor_id": "cam-a", "timestamp_ns": 900, "score": 0.8})(),
),
},
)()
sync = CameraClockSyncModel(smoothing=1.0)
sync.observe_event(event)
history = TimestampedFrameHistory(max_frames=4)
for timestamp, value in ((880, 0.0), (900, 1.0), (940, 2.0)):
history.add(TimestampedFrame("cam-a", timestamp, np.full((2, 2), value, dtype=np.float32)))
selected = history.nearest("cam-a", sync.raw_time_for_oracle("cam-a", 1_000))
self.assertIsNotNone(selected)
self.assertEqual(900, selected.timestamp_ns)
self.assertEqual(100, sync.offset_ns("cam-a"))
def test_audio_source_events_overlay_against_audio_alignment_time(self):
frame = RenderFramePacket(