diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index e118cdd..f469b9c 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -21,6 +21,11 @@ - `scripts/audio_field.py` lists devices, validates shared or distributed profiles, checks local distributed sources, generates calibration sweeps, summarizes clock-domain sync requirements, preserves shared-input capture helpers, and encodes already aligned offline WAVs to FOA. - `audio_field/` contains testable core modules for source buffering, bounded latency convergence, injectable capture/alignment/encoder/sink ports, and pipeline orchestration. - `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.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. + - `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary. ## Temporary @@ -41,3 +46,4 @@ 8. Reconsider plugin/fork only if standard OBS Media Source cannot preserve the required behavior. 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. diff --git a/docs/obs-spout-streaming.md b/docs/obs-spout-streaming.md new file mode 100644 index 0000000..f98a534 --- /dev/null +++ b/docs/obs-spout-streaming.md @@ -0,0 +1,81 @@ +# OBS Spout Streaming + +## Objective + +Publish the live visual fusion state as a named GPU texture that OBS can receive through the Spout2 plugin. + +This is the deadline stream surface. It is not a preview window and it is not a desktop-capture workaround. LocalCastBridge emits a typed render-frame packet; the Spout sink turns that packet into a GPU texture named for OBS. + +## Current Mechanism + +```mermaid +flowchart TD + A["TrackCache / demo source"] --> B["RenderFramePacket JSON"] + B --> C["scripts/stream_spout.py"] + C --> D["OpenGL FBO"] + D --> E["Spout sender texture"] + E --> F["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. + +## Run + +Install calibration/runtime dependencies once: + +```powershell +.\.venv\Scripts\python.exe -m pip install -r .\requirements-calibration.txt +``` + +Start the Spout sender: + +```powershell +.\.venv\Scripts\python.exe .\scripts\stream_spout.py ` + --frame-json .\calibration\runs\live-render-frame.json ` + --demo-if-missing ` + --sender-name "LocalCastBridge Point Cloud" ` + --width 1920 ` + --height 1080 ` + --fps 60 ` + --status .\calibration\runs\stream-spout-status.json +``` + +For OBS, add a Spout2 Capture source and select `LocalCastBridge Point Cloud`. + +## Status + +The sender writes a heartbeat JSON file: + +```powershell +Get-Content .\calibration\runs\stream-spout-status.json +``` + +Fields: + +- `sender_name`: the Spout sender OBS should see. +- `frames_sent`: count of successful `sendTexture` calls. +- `point_count`: number of packet points in the last status update. +- `frame_path`: packet source path. +- `last_error`: `null` during healthy output. + +## 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. +- Latency is explicit in the packet timestamps. The renderer may buffer, but it may not silently erase the visual/audio alignment fields. + +## Aquarium Cut + +The next renderer cut is to move the `RenderFramePacket` consumer into Aquarium Engine: + +```text +RenderFramePacket +-> Aquarium typed runtime state +-> GPU splat/brush buffers +-> D3D render target +-> Spout2 sender texture +-> OBS Spout2 Capture +``` + +That is the coherent route to millions of splats. The current OpenGL sender exists so the stream has a live OBS texture today while preserving the boundary Aquarium needs tomorrow. diff --git a/docs/sensor-fusion-architecture.md b/docs/sensor-fusion-architecture.md index 266792f..ef23abb 100644 --- a/docs/sensor-fusion-architecture.md +++ b/docs/sensor-fusion-architecture.md @@ -37,7 +37,7 @@ flowchart TD F --> G["TrackCache"] G --> H["PointCloud PLY"] G --> I["RenderFramePacket"] - I --> J["Aquarium GPU renderer"] + I --> J["Spout sink / Aquarium GPU renderer"] J --> K["Spout2 sender texture"] K --> L["OBS Spout2 source"] ``` @@ -47,7 +47,9 @@ 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.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. - `config/sensor-fusion.example.json` owns the declarative rig shape: capture hints, intrinsics, extrinsics, latency, and fusion thresholds. ## Cache Discipline @@ -98,6 +100,17 @@ LocalCastBridge TrackCache `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. +The current streamable cut is: + +```text +RenderFramePacket JSON +-> OpenGL FBO point renderer +-> SpoutGL sendTexture +-> OBS Spout2 Capture source +``` + +This is deliberately a sink boundary, not a competing world model. Aquarium should replace the renderer body, not the capture/fusion/timing contract. + ## Latency Contract Latency is allowed. Drift is not. diff --git a/localcast/sensor_fusion/__init__.py b/localcast/sensor_fusion/__init__.py index 3716c0a..ad64931 100644 --- a/localcast/sensor_fusion/__init__.py +++ b/localcast/sensor_fusion/__init__.py @@ -12,6 +12,7 @@ from .core import ( load_fusion_config, ) from .render_bridge import RenderBridgeConfig, RenderFramePacket, RenderPointPacket, lower_points_to_render_frame +from .spout_output import SpoutOutputConfig, frame_to_vertex_array __all__ = [ "CameraModel", @@ -26,5 +27,7 @@ __all__ = [ "RenderBridgeConfig", "RenderFramePacket", "RenderPointPacket", + "SpoutOutputConfig", + "frame_to_vertex_array", "lower_points_to_render_frame", ] diff --git a/localcast/sensor_fusion/render_bridge.py b/localcast/sensor_fusion/render_bridge.py index b59f50e..7d10589 100644 --- a/localcast/sensor_fusion/render_bridge.py +++ b/localcast/sensor_fusion/render_bridge.py @@ -49,6 +49,17 @@ class RenderPointPacket: "source_timestamp_ns": int(self.source_timestamp_ns), } + @staticmethod + def from_dict(data: dict) -> "RenderPointPacket": + return RenderPointPacket( + stable_key=str(data.get("stable_key", "")), + xyz=np.asarray(data["xyz"], dtype=np.float64), + radius_m=float(data.get("radius_m", 0.025)), + color_rgba=tuple(float(v) for v in data.get("color_rgba", [1.0, 1.0, 1.0, 1.0])), + confidence=float(data.get("confidence", 1.0)), + source_timestamp_ns=int(data.get("source_timestamp_ns", 0)), + ) + @dataclass(frozen=True) class RenderFramePacket: @@ -83,6 +94,26 @@ class RenderFramePacket: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8") + @staticmethod + def from_dict(data: dict) -> "RenderFramePacket": + return RenderFramePacket( + schema=str(data.get("schema", "")), + frame_id=int(data.get("frame_id", 0)), + created_monotonic_ns=int(data.get("created_monotonic_ns", 0)), + source_time_min_ns=int(data.get("source_time_min_ns", 0)), + source_time_max_ns=int(data.get("source_time_max_ns", 0)), + present_time_ns=int(data.get("present_time_ns", 0)), + audio_alignment_time_ns=int(data.get("audio_alignment_time_ns", 0)), + spout_sender_name=str(data.get("spout_sender_name", "LocalCastBridge Point Cloud")), + target_width=int(data.get("target_width", 1920)), + target_height=int(data.get("target_height", 1080)), + points=tuple(RenderPointPacket.from_dict(item) for item in data.get("points", [])), + ) + + +def load_render_frame(path: Path) -> RenderFramePacket: + return RenderFramePacket.from_dict(json.loads(path.read_text(encoding="utf-8"))) + def lower_points_to_render_frame( points: tuple[TriangulatedPoint, ...], diff --git a/localcast/sensor_fusion/spout_output.py b/localcast/sensor_fusion/spout_output.py new file mode 100644 index 0000000..e48a2f9 --- /dev/null +++ b/localcast/sensor_fusion/spout_output.py @@ -0,0 +1,337 @@ +from __future__ import annotations + +from dataclasses import dataclass +import ctypes +import json +import math +from pathlib import Path +import time + +import numpy as np + +from .render_bridge import RenderFramePacket, RenderPointPacket, load_render_frame + + +@dataclass(frozen=True) +class SpoutOutputConfig: + sender_name: str = "LocalCastBridge Point Cloud" + width: int = 1920 + height: int = 1080 + fps: float = 60.0 + point_scale: float = 1.0 + demo_point_count: int = 4096 + + +class RenderFrameFileSource: + 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 = load_render_frame(self.path) + self._mtime_ns = mtime_ns + 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] = [] + for i in range(count): + u = i / count + ring = 0.15 + 1.15 * math.sqrt(u) + theta = i * 2.399963229728653 + now_s * 0.45 + z = 1.2 + 0.55 * math.sin(i * 0.031 + now_s * 0.9) + confidence = 0.35 + 0.65 * ((math.sin(i * 0.017 + now_s) + 1.0) * 0.5) + color = ( + 0.15 + 0.85 * confidence, + 0.35 + 0.35 * math.sin(theta + 1.7), + 0.70 + 0.25 * math.cos(theta), + 0.85, + ) + points.append( + RenderPointPacket( + stable_key=f"demo-{i}", + xyz=np.array([ring * math.cos(theta), ring * math.sin(theta), z], dtype=np.float64), + radius_m=0.018 + 0.035 * confidence, + color_rgba=color, + confidence=confidence, + source_timestamp_ns=time.monotonic_ns(), + ) + ) + now_ns = time.monotonic_ns() + return RenderFramePacket( + schema="localcast.sensor_fusion.render_frame.v1", + frame_id=int(now_s * config.fps), + created_monotonic_ns=now_ns, + source_time_min_ns=now_ns, + source_time_max_ns=now_ns, + present_time_ns=now_ns, + audio_alignment_time_ns=now_ns, + spout_sender_name=config.sender_name, + target_width=config.width, + target_height=config.height, + points=tuple(points), + ) + + +def frame_to_vertex_array(frame: RenderFramePacket, point_scale: float = 1.0) -> np.ndarray: + vertices = np.zeros((len(frame.points), 8), dtype=np.float32) + for index, point in enumerate(frame.points): + vertices[index, 0:3] = point.xyz.astype(np.float32) + rgba = np.asarray(point.color_rgba, dtype=np.float32) + confidence = max(0.0, min(1.0, float(point.confidence))) + vertices[index, 3:7] = np.clip(rgba, 0.0, 1.0) + vertices[index, 6] *= confidence + vertices[index, 7] = max(0.002, float(point.radius_m) * point_scale) + return vertices + + +def write_status( + path: Path, + *, + sender_name: str, + frames_sent: int, + point_count: int, + frame_path: Path | None, + last_error: str | None = None, +) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "sender_name": sender_name, + "frames_sent": frames_sent, + "point_count": point_count, + "frame_path": None if frame_path is None else str(frame_path), + "updated_monotonic_ns": time.monotonic_ns(), + "last_error": last_error, + } + path.write_text(json.dumps(payload, indent=2), encoding="utf-8") + + +class OpenGLSpoutPointRenderer: + def __init__(self, config: SpoutOutputConfig) -> None: + self.config = config + self.sender = None + self.texture = None + self.fbo = None + self.program = None + self.vbo = None + self.vao = None + self.frames_sent = 0 + + def __enter__(self) -> "OpenGLSpoutPointRenderer": + self.open() + return self + + def __exit__(self, exc_type, exc, tb) -> None: + self.close() + + def open(self) -> None: + import SpoutGL + from OpenGL.GL import ( + GL_ARRAY_BUFFER, + GL_BLEND, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER, + GL_RGBA, + GL_RGBA8, + GL_TEXTURE_2D, + GL_UNSIGNED_BYTE, + glBindBuffer, + glBindFramebuffer, + glBindTexture, + glBlendFunc, + glBufferData, + glEnable, + glEnableVertexAttribArray, + glFramebufferTexture2D, + glGenBuffers, + glGenFramebuffers, + glGenTextures, + glGenVertexArrays, + glBindVertexArray, + glTexImage2D, + glVertexAttribPointer, + GL_DYNAMIC_DRAW, + GL_FLOAT, + GL_ONE, + GL_ONE_MINUS_SRC_ALPHA, + ) + + from OpenGL.GL.shaders import compileProgram, compileShader + from OpenGL.GL import GL_FRAGMENT_SHADER, GL_VERTEX_SHADER + + self.sender = SpoutGL.SpoutSender() + self.sender.setSenderName(self.config.sender_name) + if not self.sender.createOpenGL(): + raise RuntimeError("SpoutGL could not create an OpenGL context") + + self.texture = glGenTextures(1) + glBindTexture(GL_TEXTURE_2D, self.texture) + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA8, + self.config.width, + self.config.height, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + None, + ) + self.fbo = glGenFramebuffers(1) + glBindFramebuffer(GL_FRAMEBUFFER, self.fbo) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.texture, 0) + + self.program = compileProgram( + compileShader(VERTEX_SHADER, GL_VERTEX_SHADER), + compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER), + ) + self.vao = glGenVertexArrays(1) + self.vbo = glGenBuffers(1) + glBindVertexArray(self.vao) + glBindBuffer(GL_ARRAY_BUFFER, self.vbo) + glBufferData(GL_ARRAY_BUFFER, 0, None, GL_DYNAMIC_DRAW) + stride = 8 * 4 + glEnableVertexAttribArray(0) + glVertexAttribPointer(0, 3, GL_FLOAT, False, stride, None) + glEnableVertexAttribArray(1) + glVertexAttribPointer(1, 4, GL_FLOAT, False, stride, ctypes.c_void_p(12)) + glEnableVertexAttribArray(2) + glVertexAttribPointer(2, 1, GL_FLOAT, False, stride, ctypes.c_void_p(28)) + glEnable(GL_BLEND) + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) + + def render(self, frame: RenderFramePacket) -> bool: + from OpenGL.GL import ( + GL_ARRAY_BUFFER, + GL_COLOR_BUFFER_BIT, + GL_DEPTH_BUFFER_BIT, + GL_DYNAMIC_DRAW, + GL_FALSE, + GL_FRAMEBUFFER, + GL_POINTS, + GL_TEXTURE_2D, + glBindBuffer, + glBindFramebuffer, + glBindVertexArray, + glBufferData, + glClear, + glClearColor, + glDrawArrays, + glFlush, + glGetUniformLocation, + glUniform2f, + glUniformMatrix4fv, + glUseProgram, + glViewport, + ) + + assert self.sender is not None + assert self.texture is not None + assert self.fbo is not None + assert self.program is not None + assert self.vbo is not None + assert self.vao is not None + + vertices = frame_to_vertex_array(frame, self.config.point_scale) + glBindFramebuffer(GL_FRAMEBUFFER, self.fbo) + glViewport(0, 0, self.config.width, self.config.height) + glClearColor(0.015, 0.018, 0.022, 1.0) + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + glUseProgram(self.program) + view_proj = camera_matrix(time.monotonic(), self.config.width / max(1, self.config.height)) + glUniformMatrix4fv(glGetUniformLocation(self.program, "u_view_proj"), 1, GL_FALSE, view_proj.astype(np.float32)) + glUniform2f(glGetUniformLocation(self.program, "u_viewport"), float(self.config.width), float(self.config.height)) + glBindVertexArray(self.vao) + glBindBuffer(GL_ARRAY_BUFFER, self.vbo) + glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_DYNAMIC_DRAW) + glDrawArrays(GL_POINTS, 0, len(vertices)) + glFlush() + ok = bool(self.sender.sendTexture(self.texture, GL_TEXTURE_2D, self.config.width, self.config.height, False, self.fbo)) + if ok: + self.frames_sent += 1 + return ok + + def close(self) -> None: + if self.sender is not None: + self.sender.releaseSender() + self.sender.closeOpenGL() + self.sender = None + + +def camera_matrix(now_s: float, aspect: float) -> np.ndarray: + eye = np.array([2.4 * math.sin(now_s * 0.08), -3.4, 1.85 + 0.2 * math.cos(now_s * 0.11)], dtype=np.float64) + target = np.array([0.0, 0.0, 1.15], dtype=np.float64) + up = np.array([0.0, 0.0, 1.0], dtype=np.float64) + return perspective(math.radians(58.0), aspect, 0.05, 50.0) @ look_at(eye, target, up) + + +def look_at(eye: np.ndarray, target: np.ndarray, up: np.ndarray) -> np.ndarray: + forward = target - eye + forward = forward / np.linalg.norm(forward) + side = np.cross(forward, up) + side = side / np.linalg.norm(side) + true_up = np.cross(side, forward) + matrix = np.eye(4, dtype=np.float64) + matrix[0, :3] = side + matrix[1, :3] = true_up + matrix[2, :3] = -forward + translate = np.eye(4, dtype=np.float64) + translate[:3, 3] = -eye + return matrix @ translate + + +def perspective(fov_y: float, aspect: float, near: float, far: float) -> np.ndarray: + f = 1.0 / math.tan(fov_y * 0.5) + matrix = np.zeros((4, 4), dtype=np.float64) + matrix[0, 0] = f / aspect + matrix[1, 1] = f + matrix[2, 2] = (far + near) / (near - far) + matrix[2, 3] = (2.0 * far * near) / (near - far) + matrix[3, 2] = -1.0 + return matrix + + +VERTEX_SHADER = """ +#version 330 core +layout(location = 0) in vec3 in_pos; +layout(location = 1) in vec4 in_color; +layout(location = 2) in float in_radius; +uniform mat4 u_view_proj; +uniform vec2 u_viewport; +out vec4 v_color; + +void main() { + vec4 clip = u_view_proj * vec4(in_pos, 1.0); + gl_Position = clip; + float radius_px = max(2.0, in_radius * u_viewport.y / max(0.05, abs(clip.w)) * 2.1); + gl_PointSize = radius_px; + v_color = in_color; +} +""" + + +FRAGMENT_SHADER = """ +#version 330 core +in vec4 v_color; +out vec4 out_color; + +void main() { + vec2 delta = gl_PointCoord * 2.0 - 1.0; + float radius2 = dot(delta, delta); + if (radius2 > 1.0) { + discard; + } + float alpha = (1.0 - smoothstep(0.45, 1.0, radius2)) * v_color.a; + out_color = vec4(v_color.rgb * alpha, alpha); +} +""" diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 33e6809..cf99d6e 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -23,6 +23,9 @@ Get-Content .\state\evidence.jsonl -Tail 8 - Sender-side video encoding is `h264_nvenc`. - Audio sources are separate SRT endpoints so OBS can mix them separately. - The repo contains scripts and docs, not a native OBS plugin. +- Visual fusion now has a deadline Spout sender: `scripts/stream_spout.py` consumes `RenderFramePacket` JSON, renders points into an OpenGL FBO, and publishes the Spout sender `LocalCastBridge Point Cloud` for OBS. +- The detached sender status file is `calibration/runs/stream-spout-status.json`; logs are `calibration/runs/stream-spout.log` and `calibration/runs/stream-spout.err.log`. +- Aquarium remains the intended dense splat/brush renderer behind the same `RenderFramePacket` boundary. Do not let the OpenGL sink become scene authority. - Neighbor sender is deployed at `C:\Meta\LocalCastBridge` on `192.168.1.84`. - Madman's desktop has `Start LocalCast Sender.cmd` and `Stop LocalCast Sender.cmd`. - Receiver OBS scene collection has `Neighbor PC - Video`, `Neighbor PC - Focusrite`, and `Neighbor PC - System Audio` Media Sources added. @@ -35,6 +38,9 @@ Get-Content .\state\evidence.jsonl -Tail 8 The useful next work is real hardware validation: +- in OBS, add/select a Spout2 Capture source named `LocalCastBridge Point Cloud` +- replace demo packets by writing live fusion packets to `calibration/runs/live-render-frame.json` +- move the packet consumer into Aquarium Engine once the stream survives deadline pressure - open OBS and smoke-test the three configured receiver sources from Madman's desktop launcher - tune latency once streams are live in OBS - add a real loopback/virtual audio capture source if system-output audio is required diff --git a/requirements-calibration.txt b/requirements-calibration.txt index 2c4daf6..dd087f7 100644 --- a/requirements-calibration.txt +++ b/requirements-calibration.txt @@ -2,3 +2,5 @@ opencv-contrib-python sounddevice scipy imageio-ffmpeg +PyOpenGL +SpoutGL diff --git a/scripts/stream_spout.py b/scripts/stream_spout.py new file mode 100644 index 0000000..a65ac24 --- /dev/null +++ b/scripts/stream_spout.py @@ -0,0 +1,78 @@ +import argparse +from pathlib import Path +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from localcast.sensor_fusion.spout_output import ( + OpenGLSpoutPointRenderer, + RenderFrameFileSource, + SpoutOutputConfig, + write_status, +) + + +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("--sender-name", default="LocalCastBridge Point Cloud") + parser.add_argument("--width", type=int, default=1920) + parser.add_argument("--height", type=int, default=1080) + parser.add_argument("--fps", type=float, default=60.0) + parser.add_argument("--point-scale", type=float, default=1.0) + 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("--duration", type=float, help="Optional run duration in seconds for smoke tests.") + args = parser.parse_args() + + frame_path = Path(args.frame_json) + status_path = Path(args.status) + config = SpoutOutputConfig( + sender_name=args.sender_name, + width=args.width, + height=args.height, + fps=args.fps, + 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) + frame_interval = 1.0 / max(1.0, args.fps) + start = time.monotonic() + last_status = 0.0 + + with OpenGLSpoutPointRenderer(config) as renderer: + while True: + now = time.monotonic() + if args.duration is not None and now - start >= args.duration: + break + frame = source.current_frame(now, config) + ok = renderer.render(frame) + if now - last_status >= 1.0: + write_status( + status_path, + sender_name=config.sender_name, + frames_sent=renderer.frames_sent, + point_count=len(frame.points), + frame_path=frame_path, + last_error=None if ok else "SpoutGL sendTexture returned false", + ) + last_status = now + sleep_for = frame_interval - (time.monotonic() - now) + if sleep_for > 0: + time.sleep(sleep_for) + write_status( + status_path, + sender_name=config.sender_name, + frames_sent=renderer.frames_sent, + point_count=0, + frame_path=frame_path, + last_error="stopped", + ) + + +if __name__ == "__main__": + main() diff --git a/state/evidence.jsonl b/state/evidence.jsonl index efd3957..3efa5dc 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -32,3 +32,5 @@ {"ts": "2026-05-18T14:57:32+00:00", "type": "decision", "status": "ok", "note": "Sensor-fusion sidecar starts with semantic observation authority: calibrated cameras plus timestamped 2D marker observations triangulate into cached 3D point claims, then lower to PLY/brush/splat packets. Capture adapters and render lowerings stay outside the pure fusion core so unit tests can inject synthetic cameras, frames, and observations."} {"ts": "2026-05-18T15:07:24+00:00", "type": "decision", "status": "ok", "note": "OBS visualization boundary: LocalCastBridge should emit typed render-frame packets from the sensor-fusion cache; Aquarium Engine should consume them, render points/brushes/splats to a GPU render target, and publish that texture as Spout sender 'LocalCastBridge Point Cloud'. Render packets carry visual presentation and audio-alignment timestamps so latency can converge with the ambisonic output timeline."} {"ts": "2026-05-18T15:12:32+00:00", "type": "verification", "status": "partial", "note": "Deadline audio path now supports distributed run manifests, local concurrent mic capture, sweep-arrival analysis, aligned six-channel WAV assembly with missing channels zero-filled, and FOA encoding. Live smoke captured local Kiyo-left, both PS Eye mics, and local Focusrite at 48 kHz; Kiyo-right profile query is currently missing and neighbor Focusrite remains remote/manual import."} +{"ts": "2026-05-18T15:19:47+00:00", "type": "decision", "status": "ok", "note": "Deadline OBS Spout path is now a live GPU sink: RenderFramePacket JSON feeds scripts/stream_spout.py, which renders to an OpenGL FBO and publishes Spout sender LocalCastBridge Point Cloud with heartbeat status. Aquarium remains the intended dense splat renderer behind the same packet boundary."} +{"ts": "2026-05-18T15:21:20+00:00", "type": "decision", "status": "ok", "note": "Calibration delay analysis now uses local chirplet refinement: coarse matched-filter sweep detection initializes a small fractional-delay/chirp-rate atom search, following chirplet parameter-estimation guidance. Plugged-in left/right sweeps produced sub-sample chirplet delays for Kiyo-left, both PS Eye mics, and local Focusrite; Kiyo-right remains missing and neighbor Focusrite still needs import."} diff --git a/state/map.yaml b/state/map.yaml index 6289d43..f350e98 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -115,6 +115,15 @@ research: render-frame packets with source timestamps, intended presentation time, audio-alignment time, target size, Spout sender name, and point/brush claims. Aquarium owns GPU rendering and Spout publication. + live_spout_deadline_sink: + summary: docs/obs-spout-streaming.md + key_decision: > + The deadline OBS surface is a real Spout sender named LocalCastBridge + Point Cloud. `scripts/stream_spout.py` consumes render-frame packets, + renders points into an OpenGL FBO, publishes the texture through SpoutGL, + and writes a heartbeat status file. This is a sink boundary, not a new + scene authority; Aquarium should replace the renderer body behind the + same RenderFramePacket contract for dense brush/splat rendering. sensor_fusion_architecture: summary: docs/sensor-fusion-architecture.md key_decision: > @@ -160,7 +169,10 @@ current_status: live input while delay/SRO estimates settle, but cache depth must converge toward real-time. Core audio modules now expose testable boundaries for buffering, latency convergence, injectable capture/alignment/encode/sink - ports, and pipeline orchestration. The first visual sensor-fusion sidecar is + ports, and pipeline orchestration. Calibration analysis now has a local + chirplet refinement pass: coarse sweep match followed by fractional-delay + and chirp-rate grid search around the detected arrival. The first visual + sensor-fusion sidecar is in place: `localcast.sensor_fusion.core` owns calibrated camera models, timestamped 2D observations, DLT triangulation, reprojection/confidence gating, a TTL track cache, and PLY point-cloud export; adapters own @@ -169,16 +181,23 @@ current_status: points into `localcast.sensor_fusion.render_frame.v1` packets carrying source time ranges, intended visual presentation time, audio-alignment time, target render size, Spout sender name, and point draw metadata for - Aquarium/Spout. Unit tests inject synthetic cameras and frames so the core - does not depend on live camera drivers. + Aquarium/Spout. A deadline OBS Spout sender is now live-shaped: + `scripts/stream_spout.py` reads render-frame JSON, renders points into an + OpenGL FBO, publishes Spout sender `LocalCastBridge Point Cloud`, and writes + `calibration/runs/stream-spout-status.json`; a smoke run sent real Spout + frames, and 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. 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. Then add an Aquarium Engine consumer for render-frame packets that - renders cached points/brushes into a GPU render target and publishes it as - Spout sender `LocalCastBridge Point Cloud` for OBS. In parallel, create local + core. 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 + ownership. In parallel, create local `config/audio-field.json`, confirm local Kiyo/PS Eye/Focusrite device matches, confirm the neighbor Focusrite shotgun capture/transport path, replace placeholder mic/speaker geometry diff --git a/tests/test_sensor_fusion.py b/tests/test_sensor_fusion.py index e4afdd8..3419734 100644 --- a/tests/test_sensor_fusion.py +++ b/tests/test_sensor_fusion.py @@ -9,8 +9,11 @@ from localcast.sensor_fusion import ( Observation2D, PointCloud, RenderBridgeConfig, + RenderFramePacket, SensorRig, + SpoutOutputConfig, TrackCache, + frame_to_vertex_array, lower_points_to_render_frame, ) from localcast.sensor_fusion.adapters import read_raw_bgr_frames @@ -146,6 +149,17 @@ class SensorFusionTests(unittest.TestCase): self.assertEqual(2_200, data["audio_alignment_time_ns"]) self.assertEqual(0.05, data["points"][0]["radius_m"]) + loaded = RenderFramePacket.from_dict(data) + vertices = frame_to_vertex_array(loaded, point_scale=2.0) + self.assertEqual((1, 8), vertices.shape) + self.assertAlmostEqual(0.10, float(vertices[0, 7]), places=6) + self.assertGreater(float(vertices[0, 6]), 0.0) + + def test_spout_output_config_is_importable_without_gpu_context(self): + config = SpoutOutputConfig(sender_name="unit-test", width=128, height=72, fps=30) + self.assertEqual("unit-test", config.sender_name) + self.assertEqual(128, config.width) + if __name__ == "__main__": unittest.main()