diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index f469b9c..09146f4 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -23,9 +23,12 @@ - `docs/audio-field.md` maps the audio pipeline and its invariants. - Sensor-fusion render bridge: - `localcast.sensor_fusion.render_bridge` emits render-frame packets with visual/audio timing metadata and Spout sender identity. + - `localcast.sensor_fusion.cultcache_docs` stores live visual state as typed CultCache MessagePack documents. - `localcast.sensor_fusion.spout_output` renders render-frame packets into a GPU texture and publishes it as a named Spout sender for OBS. - - `scripts/stream_spout.py` runs the deadline Spout sender loop with a heartbeat status file. + - `scripts/live_sensor_fusion.py` writes fused render frames into `calibration/runs/visual-state.msgpack`. + - `scripts/stream_spout.py` runs the deadline Spout sender loop from the typed cache with typed and JSON heartbeat status. - `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary. + - `docs/typed-visual-state.md` documents the CultCache/CultNet visual boundary. ## Temporary @@ -47,3 +50,4 @@ 9. Create local `config/audio-field.json`, confirm local Kiyo/PS Eye/Focusrite device matches, and confirm the neighbor Focusrite shotgun capture/transport path. 10. Replace placeholder mic/speaker geometry with measured world coordinates, then build the delay/SRO alignment stage that feeds the bounded field cache and emits aligned six-channel blocks before FOA encoding. 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. Replace synthetic live-fusion observations with PS3 Eye detector observations. diff --git a/docs/obs-spout-streaming.md b/docs/obs-spout-streaming.md index 5694e50..adfeaae 100644 --- a/docs/obs-spout-streaming.md +++ b/docs/obs-spout-streaming.md @@ -10,7 +10,7 @@ This is the deadline stream surface. It is not a preview window and it is not a ```mermaid flowchart TD - A["TrackCache / demo source"] --> B["RenderFramePacket JSON"] + A["Sensor fusion producer"] --> B["CultCache render-frame doc"] B --> C["scripts/stream_spout.py"] C --> D["ScreenBrushPacket lowering"] D --> E["OpenGL texture/FBO"] @@ -18,7 +18,7 @@ flowchart TD F --> G["OBS Spout2 Capture"] ``` -Aquarium Engine remains the intended authority for dense brush/splat rendering. The useful boundary is `RenderFramePacket`: Aquarium can replace the OpenGL renderer behind the same packet contract without changing capture, fusion, timing, or OBS ingestion. +Aquarium Engine remains the intended authority for dense brush/splat rendering. The useful boundary is the typed `localcast.visual.render_frame` CultCache document: Aquarium can replace the OpenGL renderer behind the same packet contract without changing capture, fusion, timing, or OBS ingestion. The deadline sink borrows the Zyphos brush rule rather than pretending points are enough: each render point lowers into a compact anisotropic screen brush with center, radii, rotation, and color. That shape mirrors Aquarium's bounded brush/splat direction while keeping the stream path simple enough to verify under pressure. @@ -34,13 +34,24 @@ Start the Spout sender: ```powershell .\.venv\Scripts\python.exe .\scripts\stream_spout.py ` - --frame-json .\calibration\runs\live-render-frame.json ` + --source cultcache ` + --frame-cache .\calibration\runs\visual-state.msgpack ` --demo-if-missing ` --sender-name "LocalCastBridge Point Cloud" ` --width 1920 ` --height 1080 ` --fps 60 ` - --status .\calibration\runs\stream-spout-status.json + --status .\calibration\runs\stream-spout-status.json ` + --status-cache .\calibration\runs\visual-stream-status.msgpack +``` + +Start the current live fusion producer: + +```powershell +.\.venv\Scripts\python.exe .\scripts\live_sensor_fusion.py ` + --cache .\calibration\runs\visual-state.msgpack ` + --fps 30 ` + --points 256 ``` For OBS, add a Spout2 Capture source and select `LocalCastBridge Point Cloud`. On this workstation, OBS websocket was enabled locally and the Off World Live `win-spout` plugin was installed under `C:\ProgramData\obs-studio\plugins\win-spout`. @@ -61,11 +72,14 @@ Fields: - `frame_path`: packet source path. - `last_error`: `null` during healthy output. +The typed status document is written to `calibration/runs/visual-stream-status.msgpack`. The JSON file is only the blunt terminal heartbeat. + ## Invariants - OBS receives a named Spout texture. - The Spout sink owns presentation only; it does not own camera calibration, fusion, or scene truth. -- JSON packet polling is a deadline ABI. The field contract survives; the transport can become shared memory or Aquarium runtime state later. +- CultCache MessagePack documents are the live local state authority. CultNet document replication is the process/network boundary. +- JSON render-frame polling is compatibility scaffolding only. - Latency is explicit in the packet timestamps. The renderer may buffer, but it may not silently erase the visual/audio alignment fields. ## Aquarium Cut @@ -74,6 +88,7 @@ The next renderer cut is to move the `RenderFramePacket` consumer into Aquarium ```text RenderFramePacket +-> CultRenderFrame / CultNet document_put -> Aquarium typed runtime state -> compact anisotropic brush/splat buffers -> D3D render target diff --git a/docs/sensor-fusion-architecture.md b/docs/sensor-fusion-architecture.md index ef23abb..39c20c7 100644 --- a/docs/sensor-fusion-architecture.md +++ b/docs/sensor-fusion-architecture.md @@ -36,7 +36,7 @@ flowchart TD D --> F F --> G["TrackCache"] G --> H["PointCloud PLY"] - G --> I["RenderFramePacket"] + G --> I["CultCache RenderFrame document"] I --> J["Spout sink / Aquarium GPU renderer"] J --> K["Spout2 sender texture"] K --> L["OBS Spout2 source"] @@ -46,7 +46,8 @@ flowchart TD - `localcast.sensor_fusion.core` owns calibrated camera models, 2D observations, DLT triangulation, reprojection gating, confidence scoring, point-cloud export, and track cache expiry. - `localcast.sensor_fusion.adapters` owns driver-facing frame ingress. Its first concrete adapter is an FFmpeg raw BGR reader for the PS3 Eye DirectShow path. -- `localcast.sensor_fusion.render_bridge` owns the render-frame ABI: cached point claims plus target dimensions, Spout sender name, source timestamp range, intended visual presentation time, and ambisonic/audio alignment time. +- `localcast.sensor_fusion.render_bridge` owns the in-process render-frame ABI: cached point claims plus target dimensions, Spout sender name, source timestamp range, intended visual presentation time, and ambisonic/audio alignment time. +- `localcast.sensor_fusion.cultcache_docs` owns the typed CultCache document boundary for live visual state. - `localcast.sensor_fusion.spout_output` owns the deadline OBS publication sink: render-frame packet in, GPU texture plus Spout sender heartbeat out. - `scripts/sensor_fusion.py` owns CLI composition for offline observation files. - `scripts/stream_spout.py` owns the live Spout sender loop for OBS. @@ -90,7 +91,7 @@ The intended production handoff is: ```text LocalCastBridge TrackCache --> RenderFramePacket JSON/binary stream +-> CultCache render-frame document -> Aquarium Engine typed runtime state -> GPU point/brush/splat buffer -> D3D render target @@ -98,13 +99,14 @@ LocalCastBridge TrackCache -> OBS Spout2 Capture source ``` -`RenderFramePacket` is a scaffold ABI, not the final hot path. JSON is useful for inspection, tests, and handoff. Once Aquarium consumes the shape, switch the transport to a binary or shared-memory ring with the same fields. The invariant is the packet contract, not JSON. +`RenderFramePacket` is the in-process shape. The live boundary is now a typed CultCache MessagePack document, with CultNet `document_put` as the intended process/network API boundary. JSON render-frame files are compatibility scaffolding only. The current streamable cut is: ```text -RenderFramePacket JSON --> OpenGL FBO point renderer +CultCache render-frame document +-> compact anisotropic screen brush lowering +-> OpenGL texture upload -> SpoutGL sendTexture -> OBS Spout2 Capture source ``` @@ -127,12 +129,12 @@ That lets the final stream compositor buffer point-cloud visuals until they alig 1. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections. 2. Load real ChArUco intrinsics/extrinsics into `config/sensor-fusion.json`. -3. Record an observation JSONL/JSON run from the two PS3 Eyes. +3. Record an observation run from the two PS3 Eyes into typed CultCache docs. 4. Generate a live sparse PLY stream or debug preview. 5. Feed `RenderFramePacket` into Aquarium Engine. 6. Add Aquarium-side GPU point/brush rendering to a D3D render target. 7. Publish the render target as a Spout2 sender and receive it in OBS. -8. Replace JSON packet transport with a binary/shared-memory ring once the contract is stable. +8. Replace compatibility JSON render-frame paths once no deadline script depends on them. ## References diff --git a/docs/typed-visual-state.md b/docs/typed-visual-state.md new file mode 100644 index 0000000..5b395cf --- /dev/null +++ b/docs/typed-visual-state.md @@ -0,0 +1,62 @@ +# Typed Visual State + +## Objective + +Keep visual fusion state as typed CultCache documents and expose the boundary as CultNet document messages. + +JSON is no longer the authority for live visual state. The renderer consumes `calibration/runs/visual-state.msgpack`, which stores a `localcast.visual.render_frame` CultCache document. + +## Current Mechanism + +```mermaid +flowchart TD + A["live_sensor_fusion.py"] --> B["SensorRig.fuse"] + B --> C["RenderFramePacket"] + C --> D["CultRenderFrame"] + D --> E["CultCache MessagePack store"] + E --> F["stream_spout.py"] + F --> G["ScreenBrushPacket lowering"] + G --> H["Spout sender"] + H --> I["OBS Spout2 Capture"] +``` + +Live files: + +- `calibration/runs/visual-state.msgpack`: typed live visual frame state. +- `calibration/runs/visual-stream-status.msgpack`: typed stream status state. +- `calibration/runs/stream-spout-status.json`: compatibility heartbeat for quick terminal checks. + +## Document Types + +`localcast.visual.render_frame` + +- schema id: `gamecult.localcast.visual.render_frame.v1` +- key: `localcast.visual.render-frame.live` +- payload: MessagePack array, decoded as `CultRenderFrame` +- owns: frame timing, Spout sender identity, target size, and render points + +`localcast.visual.stream_status` + +- schema id: `gamecult.localcast.visual.stream_status.v1` +- key: `localcast.visual.stream-status.live` +- payload: MessagePack array, decoded as `CultStreamStatus` +- owns: sender heartbeat and renderer health + +## CultNet Boundary + +The API boundary is CultNet document replication, not ad hoc file polling: + +```text +CultNetDocumentPut(localcast.visual.render_frame) +-> CultCache local store +-> renderer frame source +``` + +For the deadline rig, both producer and renderer share the local CultCache file. The boundary is still the document contract: a future camera process, Aquarium process, or remote sensor node should publish the same document through CultNet `document_put` messages rather than inventing another transport shape. + +## Cut Line + +- Keep: typed CultCache document contracts and MessagePack payloads. +- Keep temporarily: JSON heartbeat for human shell checks. +- Cut next: JSON render-frame polling once no script depends on it. +- Do not add a second scene authority. Sensor fusion owns world claims; renderer owns pixels. diff --git a/localcast/sensor_fusion/__init__.py b/localcast/sensor_fusion/__init__.py index dcffe1d..163d742 100644 --- a/localcast/sensor_fusion/__init__.py +++ b/localcast/sensor_fusion/__init__.py @@ -12,6 +12,14 @@ from .core import ( load_fusion_config, ) from .render_bridge import RenderBridgeConfig, RenderFramePacket, RenderPointPacket, lower_points_to_render_frame +from .cultcache_docs import ( + LIVE_RENDER_FRAME_KEY, + CultRenderFrame, + CultRenderPoint, + CultStreamStatus, + get_live_render_frame, + put_live_render_frame, +) from .spout_output import ScreenBrushPacket, SpoutOutputConfig, frame_to_vertex_array, lower_frame_to_screen_brushes __all__ = [ @@ -27,9 +35,15 @@ __all__ = [ "RenderBridgeConfig", "RenderFramePacket", "RenderPointPacket", + "LIVE_RENDER_FRAME_KEY", + "CultRenderFrame", + "CultRenderPoint", + "CultStreamStatus", "ScreenBrushPacket", "SpoutOutputConfig", "frame_to_vertex_array", + "get_live_render_frame", "lower_frame_to_screen_brushes", "lower_points_to_render_frame", + "put_live_render_frame", ] diff --git a/localcast/sensor_fusion/cultcache_docs.py b/localcast/sensor_fusion/cultcache_docs.py new file mode 100644 index 0000000..75d4449 --- /dev/null +++ b/localcast/sensor_fusion/cultcache_docs.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +import sys +import time +from typing import Any + +import numpy as np + +from .render_bridge import RenderFramePacket, RenderPointPacket + + +ROOT = Path(__file__).resolve().parents[2] +CULTCACHE_PY_SRC = ROOT.parent / "cultcache-py" / "src" +if CULTCACHE_PY_SRC.exists() and str(CULTCACHE_PY_SRC) not in sys.path: + sys.path.insert(0, str(CULTCACHE_PY_SRC)) + +from cultcache_py import CultCache, SingleFileMessagePackBackingStore, define_document_type # noqa: E402 + + +LIVE_RENDER_FRAME_KEY = "localcast.visual.render-frame.live" +RENDER_FRAME_SCHEMA_ID = "gamecult.localcast.visual.render_frame.v1" +STREAM_STATUS_KEY = "localcast.visual.stream-status.live" +STREAM_STATUS_SCHEMA_ID = "gamecult.localcast.visual.stream_status.v1" + + +@dataclass(frozen=True) +class CultRenderPoint: + stable_key: str + xyz: tuple[float, float, float] + radius_m: float + color_rgba: tuple[float, float, float, float] + confidence: float + source_timestamp_ns: int + + +@dataclass(frozen=True) +class CultRenderFrame: + schema_version: str + frame_id: int + created_monotonic_ns: int + source_time_min_ns: int + source_time_max_ns: int + present_time_ns: int + audio_alignment_time_ns: int + spout_sender_name: str + target_width: int + target_height: int + points: tuple[CultRenderPoint, ...] + + +@dataclass(frozen=True) +class CultStreamStatus: + sender_name: str + frames_sent: int + point_count: int + frame_source: str + updated_monotonic_ns: int + last_error: str + + +def _pack(value: Any) -> bytes: + import msgpack + + return msgpack.packb(value, use_bin_type=True) + + +def _unpack(payload: bytes) -> Any: + import msgpack + + return msgpack.unpackb(payload, raw=False) + + +def _encode_point(point: CultRenderPoint) -> list[Any]: + return [ + point.stable_key, + list(point.xyz), + point.radius_m, + list(point.color_rgba), + point.confidence, + point.source_timestamp_ns, + ] + + +def _decode_point(raw: Any) -> CultRenderPoint: + return CultRenderPoint( + stable_key=str(raw[0]), + xyz=(float(raw[1][0]), float(raw[1][1]), float(raw[1][2])), + radius_m=float(raw[2]), + color_rgba=(float(raw[3][0]), float(raw[3][1]), float(raw[3][2]), float(raw[3][3])), + confidence=float(raw[4]), + source_timestamp_ns=int(raw[5]), + ) + + +def _encode_render_frame(frame: CultRenderFrame) -> list[Any]: + return [ + frame.schema_version, + frame.frame_id, + frame.created_monotonic_ns, + frame.source_time_min_ns, + frame.source_time_max_ns, + frame.present_time_ns, + frame.audio_alignment_time_ns, + frame.spout_sender_name, + frame.target_width, + frame.target_height, + [_encode_point(point) for point in frame.points], + ] + + +def _decode_render_frame(raw: Any) -> CultRenderFrame: + return CultRenderFrame( + schema_version=str(raw[0]), + frame_id=int(raw[1]), + created_monotonic_ns=int(raw[2]), + source_time_min_ns=int(raw[3]), + source_time_max_ns=int(raw[4]), + present_time_ns=int(raw[5]), + audio_alignment_time_ns=int(raw[6]), + spout_sender_name=str(raw[7]), + target_width=int(raw[8]), + target_height=int(raw[9]), + points=tuple(_decode_point(point) for point in raw[10]), + ) + + +def _encode_status(status: CultStreamStatus) -> list[Any]: + return [ + status.sender_name, + status.frames_sent, + status.point_count, + status.frame_source, + status.updated_monotonic_ns, + status.last_error, + ] + + +def _decode_status(raw: Any) -> CultStreamStatus: + return CultStreamStatus( + sender_name=str(raw[0]), + frames_sent=int(raw[1]), + point_count=int(raw[2]), + frame_source=str(raw[3]), + updated_monotonic_ns=int(raw[4]), + last_error=str(raw[5]), + ) + + +RENDER_FRAME_DOCUMENT = define_document_type( + "localcast.visual.render_frame", + encode=_encode_render_frame, + decode=_decode_render_frame, + name=lambda frame: LIVE_RENDER_FRAME_KEY if isinstance(frame, CultRenderFrame) else None, + payload_encoder=_pack, + payload_decoder=_unpack, +) + +STREAM_STATUS_DOCUMENT = define_document_type( + "localcast.visual.stream_status", + encode=_encode_status, + decode=_decode_status, + name=lambda status: STREAM_STATUS_KEY if isinstance(status, CultStreamStatus) else None, + payload_encoder=_pack, + payload_decoder=_unpack, +) + + +def _retry_cache_io(operation): + last_error: Exception | None = None + for _ in range(40): + try: + return operation() + except (PermissionError, EOFError, ValueError) as exc: + last_error = exc + time.sleep(0.01) + assert last_error is not None + raise last_error + + +def _open_visual_cache_once(path: Path) -> CultCache: + cache = ( + CultCache.builder() + .register_document_type(RENDER_FRAME_DOCUMENT) + .register_document_type(STREAM_STATUS_DOCUMENT) + .add_generic_store(SingleFileMessagePackBackingStore(path)) + .build() + ) + cache.pull_all_backing_stores() + return cache + + +def open_visual_cache(path: Path) -> CultCache: + return _retry_cache_io(lambda: _open_visual_cache_once(path)) + + +def render_frame_to_cult(frame: RenderFramePacket) -> CultRenderFrame: + return CultRenderFrame( + schema_version=RENDER_FRAME_SCHEMA_ID, + frame_id=frame.frame_id, + created_monotonic_ns=frame.created_monotonic_ns, + source_time_min_ns=frame.source_time_min_ns, + source_time_max_ns=frame.source_time_max_ns, + present_time_ns=frame.present_time_ns, + audio_alignment_time_ns=frame.audio_alignment_time_ns, + spout_sender_name=frame.spout_sender_name, + target_width=frame.target_width, + target_height=frame.target_height, + points=tuple( + CultRenderPoint( + stable_key=point.stable_key, + xyz=(float(point.xyz[0]), float(point.xyz[1]), float(point.xyz[2])), + radius_m=point.radius_m, + color_rgba=point.color_rgba, + confidence=point.confidence, + source_timestamp_ns=point.source_timestamp_ns, + ) + for point in frame.points + ), + ) + + +def cult_render_frame_to_packet(frame: CultRenderFrame) -> RenderFramePacket: + return RenderFramePacket( + schema="localcast.sensor_fusion.render_frame.v1", + frame_id=frame.frame_id, + created_monotonic_ns=frame.created_monotonic_ns, + source_time_min_ns=frame.source_time_min_ns, + source_time_max_ns=frame.source_time_max_ns, + present_time_ns=frame.present_time_ns, + audio_alignment_time_ns=frame.audio_alignment_time_ns, + spout_sender_name=frame.spout_sender_name, + target_width=frame.target_width, + target_height=frame.target_height, + points=tuple( + RenderPointPacket( + stable_key=point.stable_key, + xyz=np.asarray(point.xyz, dtype=np.float64), + radius_m=point.radius_m, + color_rgba=point.color_rgba, + confidence=point.confidence, + source_timestamp_ns=point.source_timestamp_ns, + ) + for point in frame.points + ), + ) + + +def put_live_render_frame(path: Path, frame: RenderFramePacket) -> None: + def operation() -> None: + cache = open_visual_cache(path) + cache.put(RENDER_FRAME_DOCUMENT, LIVE_RENDER_FRAME_KEY, render_frame_to_cult(frame)) + + _retry_cache_io(operation) + + +def get_live_render_frame(path: Path) -> RenderFramePacket | None: + def operation() -> RenderFramePacket | None: + cache = open_visual_cache(path) + frame = cache.get(RENDER_FRAME_DOCUMENT, LIVE_RENDER_FRAME_KEY) + return None if frame is None else cult_render_frame_to_packet(frame) + + return _retry_cache_io(operation) + + +def put_stream_status(path: Path, status: CultStreamStatus) -> None: + def operation() -> None: + cache = open_visual_cache(path) + cache.put(STREAM_STATUS_DOCUMENT, STREAM_STATUS_KEY, status) + + _retry_cache_io(operation) diff --git a/localcast/sensor_fusion/spout_output.py b/localcast/sensor_fusion/spout_output.py index 6aca1aa..e829161 100644 --- a/localcast/sensor_fusion/spout_output.py +++ b/localcast/sensor_fusion/spout_output.py @@ -11,6 +11,7 @@ import time import numpy as np from .render_bridge import RenderFramePacket, RenderPointPacket, load_render_frame +from .cultcache_docs import CultStreamStatus, get_live_render_frame, put_stream_status @dataclass(frozen=True) @@ -51,6 +52,27 @@ class RenderFrameFileSource: return demo_render_frame(now_s, config) +class CultCacheRenderFrameSource: + def __init__(self, path: Path, demo_if_missing: bool = False, demo_point_count: int = 4096) -> None: + self.path = path + self.demo_if_missing = demo_if_missing + self.demo_point_count = demo_point_count + self._mtime_ns: int | None = None + self._frame: RenderFramePacket | None = None + + def current_frame(self, now_s: float, config: SpoutOutputConfig) -> RenderFramePacket: + if self.path.exists(): + mtime_ns = self.path.stat().st_mtime_ns + if self._frame is None or mtime_ns != self._mtime_ns: + self._frame = get_live_render_frame(self.path) + self._mtime_ns = mtime_ns + if self._frame is not None: + return self._frame + if not self.demo_if_missing: + raise FileNotFoundError(self.path) + return demo_render_frame(now_s, config) + + def demo_render_frame(now_s: float, config: SpoutOutputConfig) -> RenderFramePacket: count = max(1, int(config.demo_point_count)) points: list[RenderPointPacket] = [] @@ -173,6 +195,28 @@ def write_status( path.write_text(json.dumps(payload, indent=2), encoding="utf-8") +def write_cult_status( + path: Path, + *, + sender_name: str, + frames_sent: int, + point_count: int, + frame_source: str, + last_error: str | None = None, +) -> None: + put_stream_status( + path, + CultStreamStatus( + sender_name=sender_name, + frames_sent=frames_sent, + point_count=point_count, + frame_source=frame_source, + updated_monotonic_ns=time.monotonic_ns(), + last_error="" if last_error is None else last_error, + ), + ) + + class OpenGLSpoutPointRenderer: def __init__(self, config: SpoutOutputConfig) -> None: self.config = config diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 373c61c..6c6a581 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -72,3 +72,25 @@ Ownership: - OBS may ingest rendered output later; it is not the authority for the Ambisonic field. Invariant: distributed camera/Focusrite microphones must be aligned and resampled into one reference timeline before FOA encoding. Latency is allowed as bounded buffering, but cache depth must converge toward real-time. Speaker output chirplets are live telemetry; delay/SRO/phase state must update during runtime, not only during setup. Extra chirplets may be emitted automatically when confidence drops, but only under the active probe optimizer's budget. The local shielded cardioid and neighbor shotgun are the high-quality dialogue anchors; camera mics provide spatial/context evidence. + +## Visual Fusion Sidecar + +```mermaid +flowchart TD + A["synthetic/live observations"] --> B["SensorRig.fuse"] + B --> C["RenderFramePacket"] + C --> D["CultCache visual-state.msgpack"] + D --> E["stream_spout.py"] + E --> F["ScreenBrushPacket lowering"] + F --> G["Spout sender"] + G --> H["OBS Spout2 Capture"] +``` + +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. +- `scripts/stream_spout.py` consumes typed CultCache state and publishes Spout. +- CultNet document replication is the intended API boundary for other producers/consumers. + +Invariant: JSON is not the visual-state authority. The current renderer can still write a JSON heartbeat for human inspection, but live visual state lives in typed CultCache MessagePack documents. diff --git a/requirements-calibration.txt b/requirements-calibration.txt index a420bc4..ea83dc9 100644 --- a/requirements-calibration.txt +++ b/requirements-calibration.txt @@ -5,3 +5,4 @@ scipy imageio-ffmpeg PyOpenGL SpoutGL +msgpack diff --git a/scripts/live_sensor_fusion.py b/scripts/live_sensor_fusion.py new file mode 100644 index 0000000..bd0f2de --- /dev/null +++ b/scripts/live_sensor_fusion.py @@ -0,0 +1,103 @@ +import argparse +from pathlib import Path +import sys +import time + +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from localcast.sensor_fusion import ( + CameraModel, + FusionConfig, + Observation2D, + RenderBridgeConfig, + SensorRig, + put_live_render_frame, + lower_points_to_render_frame, +) + + +def camera(sensor_id: str, x: float) -> CameraModel: + return CameraModel( + sensor_id=sensor_id, + camera_matrix=np.array([[300.0, 0.0, 160.0], [0.0, 300.0, 120.0], [0.0, 0.0, 1.0]]), + dist_coeffs=np.zeros(5), + world_from_sensor=np.array( + [ + [1.0, 0.0, 0.0, x], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] + ), + width=320, + height=240, + ) + + +def synthetic_observations(rig: SensorRig, now_s: float, count: int) -> list[Observation2D]: + left = rig.cameras["ps3eye_left"] + right = rig.cameras["ps3eye_right"] + timestamp = time.monotonic_ns() + observations: list[Observation2D] = [] + for index in range(count): + u = index / max(1, count) + theta = index * 2.399963229728653 + now_s * 0.65 + radius = 0.12 + 1.05 * np.sqrt(u) + point = np.array( + [ + radius * np.cos(theta), + radius * np.sin(theta), + 1.25 + 0.45 * np.sin(index * 0.041 + now_s), + ], + dtype=np.float64, + ) + marker = f"synthetic-fused-{index}" + observations.append(Observation2D("ps3eye_left", marker, timestamp, left.project_world(point), 0.95)) + observations.append(Observation2D("ps3eye_right", marker, timestamp, right.project_world(point), 0.92)) + return observations + + +def main() -> None: + parser = argparse.ArgumentParser(description="Write live sensor-fusion render frames into typed CultCache state.") + parser.add_argument("--cache", default=str(ROOT / "calibration" / "runs" / "visual-state.msgpack")) + parser.add_argument("--fps", type=float, default=30.0) + parser.add_argument("--points", type=int, default=256) + parser.add_argument("--duration", type=float) + args = parser.parse_args() + + left = camera("ps3eye_left", -0.25) + right = camera("ps3eye_right", 0.25) + rig = SensorRig( + cameras={left.sensor_id: left, right.sensor_id: right}, + config=FusionConfig(max_pair_dt_ns=30_000_000, max_reprojection_error_px=0.01, cache_ttl_ns=500_000_000), + ) + render_config = RenderBridgeConfig(default_point_radius_m=0.035) + interval = 1.0 / max(1.0, args.fps) + start = time.monotonic() + frame_id = 0 + cache_path = Path(args.cache) + while True: + now = time.monotonic() + if args.duration is not None and now - start >= args.duration: + break + observations = synthetic_observations(rig, now, args.points) + result = rig.fuse(observations) + frame = lower_points_to_render_frame( + result.points, + render_config, + frame_id=frame_id, + created_monotonic_ns=time.monotonic_ns(), + ) + put_live_render_frame(cache_path, frame) + frame_id += 1 + sleep_for = interval - (time.monotonic() - now) + if sleep_for > 0: + time.sleep(sleep_for) + + +if __name__ == "__main__": + main() diff --git a/scripts/stream_spout.py b/scripts/stream_spout.py index a65ac24..35181d5 100644 --- a/scripts/stream_spout.py +++ b/scripts/stream_spout.py @@ -8,9 +8,11 @@ if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from localcast.sensor_fusion.spout_output import ( + CultCacheRenderFrameSource, OpenGLSpoutPointRenderer, RenderFrameFileSource, SpoutOutputConfig, + write_cult_status, write_status, ) @@ -18,6 +20,7 @@ from localcast.sensor_fusion.spout_output import ( def main() -> None: parser = argparse.ArgumentParser(description="Publish render-frame packets as a named Spout texture for OBS.") parser.add_argument("--frame-json", default=str(ROOT / "calibration" / "runs" / "synthetic-render-frame.json")) + parser.add_argument("--frame-cache", default=str(ROOT / "calibration" / "runs" / "visual-state.msgpack")) parser.add_argument("--sender-name", default="LocalCastBridge Point Cloud") parser.add_argument("--width", type=int, default=1920) parser.add_argument("--height", type=int, default=1080) @@ -26,11 +29,15 @@ def main() -> None: parser.add_argument("--demo-if-missing", action="store_true") parser.add_argument("--demo-point-count", type=int, default=4096) parser.add_argument("--status", default=str(ROOT / "calibration" / "runs" / "stream-spout-status.json")) + parser.add_argument("--status-cache", default=str(ROOT / "calibration" / "runs" / "visual-stream-status.msgpack")) + parser.add_argument("--source", choices=["cultcache", "json"], default="cultcache") parser.add_argument("--duration", type=float, help="Optional run duration in seconds for smoke tests.") args = parser.parse_args() frame_path = Path(args.frame_json) + frame_cache_path = Path(args.frame_cache) status_path = Path(args.status) + status_cache_path = Path(args.status_cache) config = SpoutOutputConfig( sender_name=args.sender_name, width=args.width, @@ -39,7 +46,12 @@ def main() -> None: point_scale=args.point_scale, demo_point_count=args.demo_point_count, ) - source = RenderFrameFileSource(frame_path, demo_if_missing=args.demo_if_missing, demo_point_count=args.demo_point_count) + if args.source == "cultcache": + source = CultCacheRenderFrameSource(frame_cache_path, demo_if_missing=args.demo_if_missing, demo_point_count=args.demo_point_count) + frame_source_name = str(frame_cache_path) + else: + source = RenderFrameFileSource(frame_path, demo_if_missing=args.demo_if_missing, demo_point_count=args.demo_point_count) + frame_source_name = str(frame_path) frame_interval = 1.0 / max(1.0, args.fps) start = time.monotonic() last_status = 0.0 @@ -57,7 +69,15 @@ def main() -> None: sender_name=config.sender_name, frames_sent=renderer.frames_sent, point_count=len(frame.points), - frame_path=frame_path, + frame_path=Path(frame_source_name), + last_error=None if ok else "SpoutGL sendTexture returned false", + ) + write_cult_status( + status_cache_path, + sender_name=config.sender_name, + frames_sent=renderer.frames_sent, + point_count=len(frame.points), + frame_source=frame_source_name, last_error=None if ok else "SpoutGL sendTexture returned false", ) last_status = now @@ -69,7 +89,15 @@ def main() -> None: sender_name=config.sender_name, frames_sent=renderer.frames_sent, point_count=0, - frame_path=frame_path, + frame_path=Path(frame_source_name), + last_error="stopped", + ) + write_cult_status( + status_cache_path, + sender_name=config.sender_name, + frames_sent=renderer.frames_sent, + point_count=0, + frame_source=frame_source_name, last_error="stopped", ) diff --git a/state/evidence.jsonl b/state/evidence.jsonl index ec94f3a..097d7d0 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -40,3 +40,4 @@ {"ts": "2026-05-18T15:38:07+00:00", "type": "verification", "status": "ok", "note": "OBS puppet pass installed win-spout, enabled local obs-websocket without auth, created Spout2 Capture source LocalCastBridge Point Cloud, and verified a nonblack OBS screenshot from the live Spout sender. Zyphos sample/research shifted the deadline sink from point sprites toward compact anisotropic screen brush packets."} {"ts": "2026-05-18T15:44:14+00:00", "type": "verification", "status": "ok", "note": "Remote Focusrite shotgun capture path verified: SSH to 192.168.1.84 runs remote FFmpeg against Analogue 1 + 2 (Focusrite USB Audio), SFTP pulls a mono 48 kHz float WAV into a distributed calibration run, and the manifest records mic_focusrite_neighbor as field channel 5."} {"ts": "2026-05-18T15:59:44+00:00", "type": "verification", "status": "partial", "note": "Simultaneous audio-field calibration run audio-full-sync-20260518-165751 captured local Kiyo-left, both PS Eye mics, local Focusrite, and neighbor Focusrite shotgun. Chirplet analysis aligned five sources; Kiyo-right remains missing. Response-compensated six-channel field and FOA AmbiX WAV were produced under calibration/runs/audio-full-sync-20260518-165751."} +{"ts": "2026-05-18T16:06:28+00:00", "type": "verification", "status": "ok", "note": "Visual pipeline now uses typed CultCache MessagePack state: live_sensor_fusion.py writes localcast.visual.render_frame to visual-state.msgpack, stream_spout.py consumes that document and publishes Spout. CultNet document_put is documented as the API boundary; JSON render-frame files are compatibility only. Live OBS heartbeat shows 256 fused points from visual-state.msgpack."} diff --git a/state/map.yaml b/state/map.yaml index d154512..1fe766a 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -133,6 +133,15 @@ research: capture adapters, detection, triangulation, track caching, and point-cloud export as separate testable authorities. This follows the fractal-domain cache rule: semantic claims first, cached backend lowerings second. + typed_visual_state: + summary: docs/typed-visual-state.md + key_decision: > + Live visual state now lives in typed CultCache MessagePack documents: + `localcast.visual.render_frame` in `calibration/runs/visual-state.msgpack` + and `localcast.visual.stream_status` in + `calibration/runs/visual-stream-status.msgpack`. CultNet document_put is + the intended process/network API boundary. JSON render-frame files are no + longer the authority. current_status: summary: > @@ -188,21 +197,26 @@ current_status: source time ranges, intended visual presentation time, audio-alignment time, target render size, Spout sender name, and point draw metadata for Aquarium/Spout. A deadline OBS Spout sender is now live-shaped: - `scripts/stream_spout.py` reads render-frame JSON, lowers points into - compact anisotropic screen brush packets, uploads an OpenGL texture, - publishes Spout sender `LocalCastBridge Point Cloud`, and writes + `scripts/live_sensor_fusion.py` now writes fused render frames into typed + CultCache state at `calibration/runs/visual-state.msgpack`. `scripts/stream_spout.py` + consumes that CultCache document, lowers points into compact anisotropic + screen brush packets, uploads an OpenGL texture, publishes Spout sender + `LocalCastBridge Point Cloud`, and writes both typed status + `calibration/runs/visual-stream-status.msgpack` and compatibility JSON `calibration/runs/stream-spout-status.json`; OBS now has a Spout2 Capture source pointed at that sender, and an OBS websocket screenshot verified - nonblack brush output. The detached sender can run demo packets until live - fusion writes `calibration/runs/live-render-frame.json`. Unit tests inject - synthetic cameras and frames so the core does not depend on live camera - drivers. + nonblack brush output. The live producer currently uses synthetic calibrated + observations through the real `SensorRig.fuse` path until camera detector + observations replace them. Unit tests inject synthetic cameras and frames so + the core does not depend on live camera drivers. next_action: > Capture real ChArUco intrinsics/extrinsics for the PS3 Eyes and Kiyos, replace `config/sensor-fusion.example.json` placeholder transforms with a - local `config/sensor-fusion.json`, then add a detector adapter that turns - FFmpeg PS3 Eye frames into marker `Observation2D` records for the fusion - core. In parallel, move the render-frame consumer into Aquarium Engine so + local `config/sensor-fusion.json`, then replace the synthetic live producer + with a detector adapter that turns FFmpeg PS3 Eye frames into marker + `Observation2D` records for the fusion core and publishes the same typed + CultCache/CultNet render-frame document. In parallel, move the render-frame + consumer into Aquarium Engine so Aquarium renders cached points/brushes into its GPU render target and publishes or hands off the same Spout sender `LocalCastBridge Point Cloud` for OBS, replacing the deadline OpenGL point sink without changing packet diff --git a/tests/test_sensor_fusion.py b/tests/test_sensor_fusion.py index 1339fbb..29ac01f 100644 --- a/tests/test_sensor_fusion.py +++ b/tests/test_sensor_fusion.py @@ -1,4 +1,6 @@ import io +from pathlib import Path +import tempfile import unittest import numpy as np @@ -14,8 +16,10 @@ from localcast.sensor_fusion import ( SpoutOutputConfig, TrackCache, frame_to_vertex_array, + get_live_render_frame, lower_frame_to_screen_brushes, lower_points_to_render_frame, + put_live_render_frame, ) from localcast.sensor_fusion.adapters import read_raw_bgr_frames @@ -164,6 +168,27 @@ class SensorFusionTests(unittest.TestCase): self.assertEqual("unit-test", config.sender_name) self.assertEqual(128, config.width) + def test_render_frame_round_trips_through_typed_cultcache_doc(self): + left = camera("left", -0.25) + right = camera("right", 0.25) + point = SensorRig(cameras={"left": left, "right": right}).fuse( + [ + Observation2D("left", "ball", 1_000, left.project_world(np.array([0.0, 0.0, 2.0])), 1.0), + Observation2D("right", "ball", 1_000, right.project_world(np.array([0.0, 0.0, 2.0])), 1.0), + ] + ).points[0] + frame = lower_points_to_render_frame((point,), RenderBridgeConfig(), frame_id=3, created_monotonic_ns=10) + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "visual-state.msgpack" + put_live_render_frame(path, frame) + loaded = get_live_render_frame(path) + + self.assertIsNotNone(loaded) + self.assertEqual(3, loaded.frame_id) + self.assertEqual(1, len(loaded.points)) + self.assertEqual("ball", loaded.points[0].stable_key) + if __name__ == "__main__": unittest.main()