From 869de32f41b9aeb346cc3cc4b9c4ce9861a8ac23 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 19 May 2026 01:02:14 +0100 Subject: [PATCH] Report budgeted cross-modal render evidence --- docs/implementation-plan.md | 4 +- localcast/sensor_fusion/__init__.py | 6 +++ localcast/sensor_fusion/chirp_pose.py | 54 +++++++++++++++++++++++++ localcast/sensor_fusion/spout_output.py | 24 ++++++++++- notes/current-system-map.md | 4 +- scripts/live_sensor_fusion.py | 31 ++++++++++++++ scripts/stream_spout.py | 1 + state/map.yaml | 8 ++-- tests/test_sensor_fusion.py | 35 ++++++++++++++++ 9 files changed, 159 insertions(+), 8 deletions(-) diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 5fa4939..f6f4217 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -31,9 +31,9 @@ - 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. - - `localcast.sensor_fusion.chirp_pose` converts live phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints. 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:*` render points and `chirp-camera-pose` LOD evidence. + - `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. + - 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. - `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary. - `docs/typed-visual-state.md` documents the CultCache/CultNet visual boundary. - OBS synchronized program surface: diff --git a/localcast/sensor_fusion/__init__.py b/localcast/sensor_fusion/__init__.py index 36b71e4..d90c656 100644 --- a/localcast/sensor_fusion/__init__.py +++ b/localcast/sensor_fusion/__init__.py @@ -70,12 +70,14 @@ from .clap_calibration import ( from .chirp_pose import ( CameraChirpPoseConstraint, CameraMicGeometry, + CameraPoseCorrectionEstimate, SpeakerGeometry, camera_mic_geometry_from_audio_profile, camera_sensor_id_for_microphone, constraints_from_phase_sources, default_camera_mic_geometry, default_speaker_geometry, + estimate_pose_corrections, phase_source_id_for_microphone, speaker_geometry_from_audio_profile, ) @@ -100,6 +102,7 @@ from .spout_output import ( frame_to_vertex_array, frame_with_point_budget, lower_frame_to_screen_brushes, + point_prefix_counts, ) __all__ = [ @@ -141,6 +144,7 @@ __all__ = [ "CameraSyncEstimate", "CameraChirpPoseConstraint", "CameraMicGeometry", + "CameraPoseCorrectionEstimate", "SpeakerGeometry", "camera_mic_geometry_from_audio_profile", "camera_sensor_id_for_microphone", @@ -161,6 +165,7 @@ __all__ = [ "VirtualCamera", "frame_to_vertex_array", "frame_with_point_budget", + "point_prefix_counts", "get_live_render_frame", "get_live_clap_events", "make_clap_events_frame", @@ -184,6 +189,7 @@ __all__ = [ "constraints_from_phase_sources", "default_camera_mic_geometry", "default_speaker_geometry", + "estimate_pose_corrections", "phase_source_id_for_microphone", "speaker_geometry_from_audio_profile", "remote_video_artifact_for_present_time", diff --git a/localcast/sensor_fusion/chirp_pose.py b/localcast/sensor_fusion/chirp_pose.py index d27aafa..567b376 100644 --- a/localcast/sensor_fusion/chirp_pose.py +++ b/localcast/sensor_fusion/chirp_pose.py @@ -39,6 +39,16 @@ class CameraChirpPoseConstraint: timestamp_ns: int +@dataclass(frozen=True) +class CameraPoseCorrectionEstimate: + sensor_id: str + position_m: np.ndarray + correction_m: np.ndarray + confidence: float + constraint_count: int + timestamp_ns: int + + def default_camera_mic_geometry() -> tuple[CameraMicGeometry, ...]: return ( CameraMicGeometry("kiyo-primary", "kiyo-0", np.array([-0.18, -0.72, 1.28], dtype=np.float64)), @@ -156,6 +166,50 @@ def constraints_from_phase_sources( return tuple(rows) +def estimate_pose_corrections( + constraints: Sequence[CameraChirpPoseConstraint], + *, + max_step_m: float = 0.35, +) -> tuple[CameraPoseCorrectionEstimate, ...]: + grouped: dict[str, list[CameraChirpPoseConstraint]] = {} + for constraint in constraints: + grouped.setdefault(constraint.sensor_id, []).append(constraint) + estimates: list[CameraPoseCorrectionEstimate] = [] + for sensor_id, rows in grouped.items(): + vectors = [] + weights = [] + positions = [] + for row in rows: + camera = np.asarray(row.camera_position_m, dtype=np.float64) + speaker = np.asarray(row.speaker_position_m, dtype=np.float64) + direction = camera - speaker + norm = float(np.linalg.norm(direction)) + if norm <= 1.0e-9: + continue + unit = direction / norm + confidence = max(0.0, min(1.0, float(row.confidence))) + vectors.append(unit * float(row.range_residual_m)) + weights.append(max(1.0e-6, confidence)) + positions.append(camera) + if not vectors: + continue + weighted = np.average(np.asarray(vectors, dtype=np.float64), axis=0, weights=np.asarray(weights, dtype=np.float64)) + magnitude = float(np.linalg.norm(weighted)) + if magnitude > max_step_m: + weighted = weighted / magnitude * float(max_step_m) + estimates.append( + CameraPoseCorrectionEstimate( + sensor_id=sensor_id, + position_m=np.average(np.asarray(positions, dtype=np.float64), axis=0, weights=np.asarray(weights, dtype=np.float64)), + correction_m=weighted.astype(np.float64), + confidence=float(min(1.0, np.mean(weights))), + constraint_count=len(vectors), + timestamp_ns=max(row.timestamp_ns for row in rows), + ) + ) + return tuple(sorted(estimates, key=lambda item: item.sensor_id)) + + def _nearest_speaker(position_m: np.ndarray, speakers: Sequence[SpeakerGeometry]) -> SpeakerGeometry: return min(speakers, key=lambda speaker: float(np.linalg.norm(np.asarray(position_m) - speaker.position_m))) diff --git a/localcast/sensor_fusion/spout_output.py b/localcast/sensor_fusion/spout_output.py index a85d0af..1765937 100644 --- a/localcast/sensor_fusion/spout_output.py +++ b/localcast/sensor_fusion/spout_output.py @@ -278,6 +278,7 @@ def is_pinned_render_point(point: RenderPointPacket) -> bool: return point.stable_key.startswith( ( "camera-chirp:", + "camera-pose-correction:", "camera-sync:", "clap-calibration:", "clap-ray:", @@ -287,6 +288,22 @@ def is_pinned_render_point(point: RenderPointPacket) -> bool: ) +def point_prefix_counts(points: tuple[RenderPointPacket, ...] | list[RenderPointPacket]) -> dict[str, int]: + counts: dict[str, int] = {} + for point in points: + prefix = point_prefix(point.stable_key) + counts[prefix] = counts.get(prefix, 0) + 1 + return dict(sorted(counts.items())) + + +def point_prefix(stable_key: str) -> str: + if ":" in stable_key: + return stable_key.split(":", 1)[0] + if stable_key.startswith("audio-event-"): + return "audio-event" + return stable_key + + def stable_hash(key: str, salt: int) -> int: digest = hashlib.blake2s(f"{salt}:{key}".encode("utf-8"), digest_size=8).digest() return int.from_bytes(digest, "little") @@ -298,7 +315,7 @@ def render_priority(point: RenderPointPacket, camera_preset_name: str) -> float: semantic = 1.0 if key.startswith("clap-calibration:"): semantic = 3.2 - elif key.startswith(("camera-sync:", "camera-chirp:")): + elif key.startswith(("camera-sync:", "camera-chirp:", "camera-pose-correction:")): semantic = 2.6 elif key.startswith(("clap-ray:", "clap-timing:")): semantic = 2.2 @@ -521,6 +538,7 @@ def write_status( point_count: int, frame_path: Path | None, last_error: str | None = None, + point_prefix_counts: dict[str, int] | None = None, ) -> None: path.parent.mkdir(parents=True, exist_ok=True) payload = { @@ -531,6 +549,8 @@ def write_status( "updated_monotonic_ns": time.monotonic_ns(), "last_error": last_error, } + if point_prefix_counts is not None: + payload["point_prefix_counts"] = dict(sorted(point_prefix_counts.items())) path.write_text(json.dumps(payload, indent=2), encoding="utf-8") @@ -600,6 +620,7 @@ class OpenGLSpoutPointRenderer: self.vao = None self.frames_sent = 0 self.last_render_point_count = 0 + self.last_render_prefix_counts: dict[str, int] = {} def __enter__(self) -> "OpenGLSpoutPointRenderer": self.open() @@ -724,6 +745,7 @@ class OpenGLSpoutPointRenderer: render_frame = frame_with_point_budget(frame, self.config.max_render_points, self.config.camera_preset) self.last_render_point_count = len(render_frame.points) + self.last_render_prefix_counts = point_prefix_counts(render_frame.points) vertices = frame_to_vertex_array(render_frame, self.config.point_scale) glBindFramebuffer(GL_FRAMEBUFFER, self.fbo) glViewport(0, 0, self.config.width, self.config.height) diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 3149d63..afc8eb8 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -106,8 +106,8 @@ Ownership: - `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. -- `localcast.sensor_fusion.chirp_pose` now turns phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints. 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:*` render points and `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. +- `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. - `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. diff --git a/scripts/live_sensor_fusion.py b/scripts/live_sensor_fusion.py index 755f06c..a7f4991 100644 --- a/scripts/live_sensor_fusion.py +++ b/scripts/live_sensor_fusion.py @@ -31,6 +31,7 @@ from localcast.sensor_fusion import ( constraints_from_phase_sources, detect_clap_events, dense_stereo_points, + estimate_pose_corrections, evidence_from_fusion_items, evidence_from_render_points, get_live_clap_events, @@ -692,6 +693,8 @@ class LiveChirpPoseMapper: points: list[RenderPointPacket] = [] for constraint in self.constraints: points.extend(chirp_pose_constraint_points(constraint, timestamp_ns)) + for estimate in estimate_pose_corrections(self.constraints): + points.extend(chirp_pose_correction_points(estimate, timestamp_ns)) return tuple(points) @@ -732,6 +735,34 @@ def chirp_pose_constraint_points( ) +def chirp_pose_correction_points(estimate, timestamp_ns: int) -> tuple[RenderPointPacket, ...]: + confidence = max(0.0, min(1.0, float(estimate.confidence))) + start = np.asarray(estimate.position_m, dtype=np.float64) + correction = np.asarray(estimate.correction_m, dtype=np.float64) + end = start + correction + magnitude = float(np.linalg.norm(correction)) + strength = min(1.0, magnitude / 0.25) + alpha = 0.22 + 0.55 * strength * confidence + return ( + render_point( + f"camera-pose-correction:{estimate.sensor_id}:origin", + start, + 0.022 + 0.045 * strength, + (0.35, 0.78, 1.0, alpha), + confidence, + timestamp_ns, + ), + render_point( + f"camera-pose-correction:{estimate.sensor_id}:target", + end, + 0.028 + 0.055 * strength, + (1.0, 0.90, 0.30, alpha), + confidence, + timestamp_ns, + ), + ) + + 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 diff --git a/scripts/stream_spout.py b/scripts/stream_spout.py index 25bb657..3424208 100644 --- a/scripts/stream_spout.py +++ b/scripts/stream_spout.py @@ -141,6 +141,7 @@ def main() -> None: point_count=renderer.last_render_point_count, frame_path=Path(frame_source_name), last_error=None if ok else "SpoutGL sendTexture returned false", + point_prefix_counts=renderer.last_render_prefix_counts, ) write_cult_status( status_cache_path, diff --git a/state/map.yaml b/state/map.yaml index 9ecd65d..4da0807 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -173,13 +173,15 @@ research: `oracle_time - camera_offset` for coherent point-cloud construction. `localcast.sensor_fusion.chirp_pose` converts live phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range - constraints, which the live producer emits as `camera-chirp:*` render - points and `chirp-camera-pose` LOD evidence. It can load geometry from + constraints and per-camera pose-correction estimates, which the live + producer emits as `camera-chirp:*` and `camera-pose-correction:*` render + points plus `chirp-camera-pose` LOD evidence. It can load geometry from the audio-field profile, falling back to the example/default geometry until measured local coordinates exist. These constraints augment visual calibration; they do not own image geometry. The Spout point-budget policy pins calibration and cross-modal constraints before spending adaptive LOD - budget on stable high-priority surfaces and frame-rotated samples. + budget on stable high-priority surfaces and frame-rotated samples, and + its JSON heartbeat reports budgeted point prefix counts. 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 ff84432..cbc62c2 100644 --- a/tests/test_sensor_fusion.py +++ b/tests/test_sensor_fusion.py @@ -33,8 +33,10 @@ from localcast.sensor_fusion import ( camera_sensor_id_for_microphone, constraints_from_phase_sources, detect_clap_events, + estimate_pose_corrections, frame_to_vertex_array, frame_with_point_budget, + point_prefix_counts, dense_stereo_points, get_live_clap_events, get_live_render_frame, @@ -351,6 +353,18 @@ class SensorFusionTests(unittest.TestCase): self.assertEqual(6, len(limited.points)) self.assertTrue(all(point.stable_key in keys for point in pinned)) + self.assertEqual(1, point_prefix_counts(limited.points)["camera-chirp"]) + self.assertEqual(1, point_prefix_counts(limited.points)["camera-sync"]) + self.assertEqual(1, point_prefix_counts(limited.points)["clap-calibration"]) + + def test_point_prefix_counts_groups_audio_events(self): + points = ( + RenderPointPacket("audio-event-16", np.zeros(3), 0.02, (1, 1, 1, 1), 1.0, 1), + RenderPointPacket("audio-event-17", np.zeros(3), 0.02, (1, 1, 1, 1), 1.0, 1), + RenderPointPacket("camera-chirp:kiyo:speaker:body", np.zeros(3), 0.02, (1, 1, 1, 1), 1.0, 1), + ) + + self.assertEqual({"audio-event": 2, "camera-chirp": 1}, point_prefix_counts(points)) def test_rasterizer_uses_gaussian_envelope_not_solid_ellipse(self): frame = RenderFramePacket( @@ -611,6 +625,27 @@ class SensorFusionTests(unittest.TestCase): self.assertAlmostEqual(0.12, constraint.range_residual_m) self.assertEqual(12_345, constraint.timestamp_ns) + def test_chirp_pose_constraints_produce_pose_correction_estimates(self): + constraints = constraints_from_phase_sources( + ( + {"sourceId": "kiyo-0", "distanceDeltaMeters": 0.20, "confidence": 0.8}, + ), + audio_time_ns=9_000, + camera_mics=( + CameraMicGeometry("kiyo-primary", "kiyo-0", np.array([1.0, 0.0, 0.0], dtype=np.float64)), + ), + speakers=( + SpeakerGeometry("speaker-left", np.array([0.0, 0.0, 0.0], dtype=np.float64)), + ), + ) + + estimates = estimate_pose_corrections(constraints) + + self.assertEqual(1, len(estimates)) + self.assertEqual("kiyo-primary", estimates[0].sensor_id) + self.assertTrue(np.allclose([0.20, 0.0, 0.0], estimates[0].correction_m)) + self.assertEqual(1, estimates[0].constraint_count) + def test_chirp_pose_geometry_loads_from_audio_profile(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "audio-field.json"