Remove script-era Python stack

This commit is contained in:
Meta Vens 2026-05-21 18:48:47 +01:00
commit 6ca7915f2b
191 changed files with 442 additions and 126676 deletions

View file

@ -1,96 +1,14 @@
# Aquarium Spatial Audio
# Aquarium Spatial Audio
## Objective
Aquarium hosts the Mimir runtime UI and presents the synchronized program
surface. Faust/native DSP owns the hot audio graph behind that surface.
Publish the live spatial audio field through the same typed state discipline as the splat renderer. Aquarium consumes the AmbiX bus and hands it to native Faust DSP; Mimir owns capture, sync, calibration, and stream timing.
## Contract
## Current Mechanism
- Mimir.Runtime exposes bounded audio buffers and stream health.
- Native audio workers append mic, loopback, and network audio blocks.
- Faust/native DSP consumes aligned blocks and emits stems plus spatial bed.
- Aquarium shows controls and debug state, then routes final outputs toward OBS.
```mermaid
flowchart TD
A["aligned microphone field"] --> B["FOA encoder"]
B --> C["AmbiX ACN/SN3D W,Y,Z,X blocks"]
C --> D["localcast.audio.spatial_frame"]
A --> M["localcast.audio.mic_field"]
M --> N["Faust voice-separation graph"]
A --> H["source-event analysis"]
H --> I["localcast.audio.source_events"]
D --> E["audio-state.msgpack / CultNet document_put"]
M --> O["audio-mic-field.msgpack / CultNet document_put"]
I --> J["audio-events.msgpack / CultNet document_put"]
E --> F["Aquarium client"]
O --> F
J --> F
K["visual-state.msgpack"] --> F
F --> G["native Faust spatial DSP + volumetric renderer"]
```
Live files:
- `calibration/runs/audio-state.msgpack`: latest typed AmbiX audio block.
- `calibration/runs/audio-mic-field.msgpack`: latest aligned six-mic block for Faust voice separation.
- `calibration/runs/audio-stream-status.msgpack`: audio publisher heartbeat.
- `calibration/runs/audio-events.msgpack`: latest typed dialogue-focus and transient vector field.
- `calibration/runs/av-sync-status.json`: current Aquarium/Spout publisher view of visual frame id, audio frame id, audio delta, and synchronized event overlay count.
Document type:
- `localcast.audio.spatial_frame`
- schema id: `gamecult.localcast.audio.spatial_frame.v1`
- key: `localcast.audio.spatial-frame.live`
- payload: MessagePack array decoded as `CultSpatialAudioFrame`
- audio format: interleaved `float32`, 48 kHz, AmbiX ACN/SN3D channels `W,Y,Z,X`
Source event document type:
- `localcast.audio.source_events`
- schema id: `gamecult.localcast.audio.source_events.v1`
- key: `localcast.audio.source-events.live`
- payload: MessagePack array decoded as `CultAudioSourceEvents`
- contents: dialogue anchor weights plus witness-dominant transient events with sample time, estimated room position, direction, energy, confidence, and kind.
Mic-field document type:
- `localcast.audio.mic_field`
- schema id: `gamecult.localcast.audio.mic_field.v1`
- key: `localcast.audio.mic-field.live`
- payload: MessagePack array decoded as `CultAudioMicFieldFrame`
- audio format: interleaved `float32`, 48 kHz, aligned mic channels
- default channel order: `host-focusrite`, `co-streamer-focusrite`, `kiyo-0`, `kiyo-1`, `ps-eye-0`, `ps-eye-1`
- graph id: `localcast.faust.voice_separation.v1`
- Faust source: `faust/localcast_voice_separation.dsp`
AmbiX replay smoke command:
```powershell
.\.venv\Scripts\python.exe -m localcast.diagnostics.spatial_audio --input .\calibration\runs\audio-full-sync-20260518-165751\field-foa-ambix.wav --loop --duration 5 --smoke-readback
```
Faust mic-field replay smoke command:
```powershell
.\.venv\Scripts\python.exe -m localcast.diagnostics.faust_mic_field --input .\calibration\runs\audio-full-sync-20260518-165751\field-cleaned.wav --loop --duration 5 --smoke-readback
```
This exercises the old mic-field document shape. Production voice separation should read typed reservoir/CultNet data from the native live path; Python is not the hot publisher.
Source-event analysis command:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-source-events --profile .\calibration\runs\audio-field-loud-profile.json --input .\calibration\runs\<run-folder>\field-cleaned.wav --cache .\calibration\runs\audio-events.msgpack
```
Synchronized Aquarium/Spout publisher command:
The old Python/OpenGL Spout diagnostic launcher has been deleted. Aquarium is
the next OBS-facing publisher.
## Invariants
- Aquarium owns rendering and Faust DSP, not microphone capture or clock correction.
- Mimir publishes declared AmbiX blocks for the spatial bed and aligned six-mic blocks for Faust voice separation. Unaligned heterogeneous microphones still do not cross this boundary.
- Mimir publishes source-event geometry separately from AmbiX audio; render effects do not have to infer transient positions from the sound bed.
- Faust owns the voice-separation graph once the aligned mic field has crossed into Aquarium. Python may publish controls and telemetry, but it must not become the hot separation engine.
- Aquarium/Spout packaging selects audio source events against each visual frame's `audio_alignment_time_ns`; OBS should receive the already synchronized output rather than trying to align independent media sources.
- The audio frame carries `start_sample` and `audio_time_ns` so visual packets can align against the same bounded-latency timeline.
- OBS may receive a rendered monitor output later, but OBS is not the spatial bus authority.
The audio path should be inspectable from the app, but the app UI is not the DSP
engine. Runtime state crosses as typed buffers, descriptors, and controls.

View file

@ -1,276 +1,40 @@
# Audio Field Spine
# Audio Field
## Objective
Mimir's audio field is six microphones, loopback/program reference, and two
calibration speakers aligned into one presentation timeline.
Build the audio side around the real six-microphone rig: two Kiyo camera mics, two PS Eye camera mics, the local Focusrite ADC with a shielded cardioid near the host's face, and the neighbor Focusrite ADC with a shotgun mic pointed at the co-streamer.
The Focusrite channels are the dialogue anchors. The camera mics are spatial context, calibration evidence, and fallback texture. Treating all six as equal would be tidy on paper and stupid in the room, which is the classic way paper gets someone fired by physics.
## Current Mechanism
The repo has a profile and tool:
- `config/audio-field.example.json` declares each mic source, machine, device query, clock domain, field channel, quality priority, placeholder geometry, two local speaker channels, calibration sweep settings, and FOA AmbiX bus format.
- `scripts/audio_field.py` validates shared or distributed profiles, lists PortAudio devices, checks local distributed sources, generates calibration sweeps, summarizes the sync plan, preserves shared-input capture helpers, and encodes an already aligned six-channel WAV into first-order AmbiX.
The default profile is `distributed-clocks`. The coherent field is not captured directly. It is assembled after delay and sampling-rate-offset alignment.
Latency is allowed. The live goal is bounded buffered real-time: hold enough audio to estimate delay and slow clock drift, emit blocks behind the live edge, and converge instead of chasing instant output with bad math. The profile owns that latency policy.
Runtime sync is not optional for the real show. Static sweep calibration gives the first estimate; the live system must keep updating delay, sampling-rate offset, polarity, and phase confidence as devices drift. Known speaker output is telemetry: every calibration chirplet or intentionally embedded probe gives the estimator a fresh phase-field observation.
If passive telemetry is not enough, the system should emit extra chirplets automatically. That is an optimization loop: spend the smallest audible probe budget that raises sync confidence enough to protect the field.
## Pipeline
## Live Target
```mermaid
flowchart TD
A["config/audio-field.json"] --> B["audio_field.py validate"]
C["local Focusrite shielded cardioid"] --> D["local reference timeline"]
E["neighbor Focusrite shotgun"] --> F["remote high-quality dialogue capture"]
G["Kiyo + PS Eye camera mics"] --> H["spatial/context captures"]
I["2 local speakers"] --> J["calibration sweep / pulse"]
J --> D
J --> F
J --> H
D --> K["delay + SRO alignment"]
F --> K
A["mic / loopback capture drivers"] --> B["Mimir.Runtime audio buffers"]
C["speaker probe scheduler"] --> B
B --> D["native alignment + phase state"]
D --> E["Faust/native DSP"]
E --> F["host voice"]
E --> G["co-streamer voice"]
E --> H["ambient / transients"]
E --> I["loopback stems"]
E --> J["spatial bed"]
F --> K["OBS"]
G --> K
H --> K
K --> L["bounded field cache"]
P["known speaker chirplets"] --> Q["runtime delay/SRO/phase estimator"]
R["confidence probe optimizer"] --> P
D --> Q
F --> Q
H --> Q
Q --> S["live phase-meaning extractor"]
S --> T["phase-field meaning cache"]
S --> K
L --> M["aligned six-channel blocks"]
M --> N["FOA encoder"]
N --> O["AmbiX ACN/SN3D output"]
I --> K
J --> K
```
## Commands
Create a local profile first:
```powershell
Copy-Item .\config\audio-field.example.json .\config\audio-field.json
```
List audio devices:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py devices
```
Probe whether a Focusrite path accepts high-rate capture:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py probe-rates --device-query Scarlett --hostapi WASAPI --direction input --channels 1 --rate 48000 --rate 96000
```
Probe the speaker output path separately:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py probe-rates --device-query Scarlett --hostapi WASAPI --direction output --channels 2 --rate 44100 --rate 48000 --rate 96000
```
Validate the profile and local device matches:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py validate --profile .\config\audio-field.json --check-devices
```
Summarize the clock domains and required alignment path:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py sync-plan --profile .\config\audio-field.json
```
Generate a calibration sweep without touching hardware:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py make-stimulus --profile .\config\audio-field.json
```
Create a distributed run folder that can accept one WAV per mic:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py init-run --profile .\config\audio-field.json
```
Record all locally visible distributed mics for a deadline calibration pass:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-local-calibration --profile .\config\audio-field.json --seconds 10
```
For passive runtime sync against ground-truth program output, capture the Scarlett loopback with the local mics:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-local-calibration --profile .\config\audio-field.json --seconds 20 --record-loopback --loopback-query Scarlett --loopback-rate 48000
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-reference-sync --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --window-seconds 4 --hop-seconds 1 --method normalized --min-score 0.08
```
The loopback path is ground-truth content, but not automatically a perfect ground-truth clock. If WASAPI loopback reports discontinuities, use the stable windows and treat the rest as suspect.
For dense runtime calibration, emit a low-level multiband chirplet texture instead of one big sweep:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-probe-train --profile .\config\audio-field.json --seconds 8 --chirp-seconds 0.03 --chirps-per-second 16 --probe-band 180:500 --probe-band 600:1200 --probe-band 1500:3000 --probe-band 3500:7000 --probe-band 8000:14000 --probe-level-offset-db -18 --output-rate 44100 --loopback-rate 48000
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-probe-train --profile .\config\audio-field.json --run .\calibration\runs\<run-folder>
```
`analyze-probe-train` is the offline live-fit evidence path: it uses each event's band-specific chirplet, gates weak loopback/mic detections, estimates phase-derived delay deltas across frequency bands, and updates a smoothed phase/frequency mapping. Coarse delays still include device latency; the volumetric room solve must fit latency, drift, phase response, and acoustic path jointly.
Replay extracted phase-field meaning from an aligned field and known program/loopback reference:
```powershell
.\.venv\Scripts\python.exe -m localcast.diagnostics.audio_phase_field --field .\calibration\runs\<run-folder>\field-program-cleaned.wav --reference .\calibration\runs\<run-folder>\ground_truth_loopback.wav --cache .\calibration\runs\audio-phase-field.msgpack
```
This is not a phase oscilloscope. Raw phase bands stay internal. The diagnostic document publishes consequences: per-source delay correction, distance-equivalent delta, coherence, fit error, confidence, reference-bleed estimate, suppression weight, correction energy, and whether the active probe optimizer should spend chirps.
Exercise the confidence loop by letting the replay schedule strategic active probes:
```powershell
.\.venv\Scripts\python.exe -m localcast.diagnostics.audio_phase_field --field .\calibration\runs\<run-folder>\field-program-cleaned.wav --reference .\calibration\runs\<run-folder>\ground_truth_loopback.wav --cache .\calibration\runs\audio-phase-field.msgpack --maintain-confidence --ultrasonic-probes --play-probes
```
`--maintain-confidence` converts low-confidence phase-field state into `ActiveProbeOptimizer` requests, writes emitted chirplets under `calibration/runs/active-probes`, and appends `active-probes.jsonl`. Probe files rotate through fixed slots and the manifest rotates at a byte cap, because a calibration loop that creates infinite tiny WAV files is just a storage leak with a physics degree. `--play-probes` sends the emitted chirplet to the selected output device through `sounddevice`; omit it for dry-run scheduling. `--ultrasonic-probes` uses the highest safe band under Nyquist, roughly `18.5-22 kHz` at 48 kHz. This can fail silently in the physical world if the speaker, mic, driver, or resampler refuses to carry that band; the confidence feedback is the judge, not the command line's self-esteem.
The old Python live local-capture bridge is quarantined as `localcast.diagnostics.audio_live_field`. It documents the deadline experiment, but production local mic and loopback capture now belongs in native workers that append typed sample handles through `LocalcastProducer`.
Record local mics while playing one speaker sweep. Use the output rate that the device probe says is real:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-local-calibration --profile .\config\audio-field.json --seconds 10 --play-sweep --speaker-channel 0 --output-rate 44100
```
After dropping the neighbor Focusrite WAV into the run's `sources/` folder, estimate sweep arrivals and assemble the aligned field:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-distributed --profile .\config\audio-field.json --run .\calibration\runs\<run-folder>
.\.venv\Scripts\python.exe .\scripts\audio_field.py assemble-aligned --profile .\config\audio-field.json --run .\calibration\runs\<run-folder>
```
For the stream-day compensated field, use the sweep-derived response pass during assembly:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py assemble-aligned --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --compensate-response
```
This estimates each mic's magnitude response from the calibration sweep relative to the reference Focusrite, smooths the inverse curve, clips it to bounded boost/cut limits, and writes `response-compensation.json`. It deliberately corrects magnitude only; phase stays owned by the timing/sync path.
Record the neighbor Focusrite shotgun directly into an existing distributed run over SSH/SFTP:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-remote-focusrite --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --seconds 10 --sample-rate 48000
```
This records `Analogue 1 + 2 (Focusrite USB Audio)` on `192.168.1.84` with remote FFmpeg, pulls it back as `sources/mic_focusrite_neighbor.wav`, and updates the run manifest. Use this for calibration imports; the existing OBS SRT source is still the live monitoring/streaming path.
`analyze-distributed` now does a deadline-grade chirplet refinement by default: it uses the coarse sweep matched-filter peak as the initial time-of-arrival, then searches a small fractional-delay and chirp-rate neighborhood with chirplet atoms. Tune the local search when needed:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-distributed --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --chirplet-refine --search-samples 3 --fractional-steps 8 --rate-ppm 150
```
This is not a full adaptive chirplet decomposition engine. It is the stream-day version: enough chirplet parameter search to get sub-sample timing refinement without turning calibration into a thesis defense in the middle of setup.
Encode an offline aligned six-channel WAV to FOA AmbiX:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py encode-foa --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-aligned.wav --output .\calibration\runs\<run-folder>\field-foa-ambix.wav
```
Replay the same aligned six-channel field directly to the old mic-field document for Faust smoke tests:
```powershell
.\.venv\Scripts\python.exe -m localcast.diagnostics.faust_mic_field --input .\calibration\runs\<run-folder>\field-cleaned.wav --loop --realtime --smoke-readback
```
This writes `localcast.audio.mic_field` into `calibration/runs/audio-mic-field.msgpack` with channel roles and graph id `localcast.faust.voice_separation.v1`. It is a diagnostic replay path. The live path is native capture into the rolling reservoir, then Aquarium/Faust consumption.
Suppress room/transient witness energy before FOA encoding:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py suppress-room --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-aligned.wav --output .\calibration\runs\<run-folder>\field-cleaned.wav
.\.venv\Scripts\python.exe .\scripts\audio_field.py encode-foa --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-cleaned.wav --output .\calibration\runs\<run-folder>\field-cleaned-foa-ambix.wav
```
This first suppression pass treats the Focusrite dialogue anchors as wanted direct sources and the camera mics as room/transient witnesses. It attenuates witness-heavy broadband transients, lightly subtracts witness room energy from anchors, and writes a JSON report. It is deliberately a stream-side cleanup stage, not physical cancellation in the room.
Suppress known speaker/program bleed using output loopback as ground truth:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py suppress-reference --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-aligned.wav --reference .\calibration\runs\<run-folder>\ground_truth_loopback.wav --output .\calibration\runs\<run-folder>\field-program-suppressed.wav
```
This is the music-as-both-enemy-and-teacher path. The reference program audio is transformed into a time/frequency transfer estimate per mic channel, reconstructed as predicted bleed, subtracted from the aligned field, and exported as phase/frequency mapping evidence. A future live loop should publish the known program stem as its own OBS/Aquarium channel while using the same ground truth to keep learning the room.
Estimate dialogue focus and volumetric transient events:
```powershell
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-source-events --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-cleaned.wav --cache .\calibration\runs\audio-events.msgpack
```
This emits `localcast.audio.source_events` for Aquarium. Dialogue anchors produce voice-focus weights; camera/context mics produce witness-dominant transient events with sample time, estimated room position, direction, energy, and confidence. This is the boundary between a clean vocal bed and renderer-visible clutter: clicks, taps, and other spatial transients should become geometry instead of being smeared into the voice mix.
The `play-record` and `record-field` commands remain for a `shared-input-device` profile only. They deliberately refuse the distributed rig until an alignment stage emits one coherent six-channel WAV.
## Invariants
- Each physical microphone declares its machine, device query, clock domain, field channel, geometry, gain, delay, polarity, directivity, and role.
- The local Focusrite shielded cardioid is the default reference mic.
- The neighbor Focusrite shotgun is the co-streamer dialogue anchor and should be captured losslessly for calibration.
- Focusrite captures should use the best available native/exclusive path and high-rate calibration capture when practical, then resample into the field timeline after alignment.
- Playback sample rate is its own device fact. Probe it separately; do not assume the Scarlett input and output paths accept the same rates through PortAudio/WASAPI.
- Distributed-clock microphones must be aligned and resampled into one reference timeline before FOA encoding.
- Output may run behind live input by the configured latency budget, but it must converge toward real-time instead of letting cache depth grow without bound.
- Sweep arrival estimates should use chirplet refinement when calibration signal quality allows it; plain matched-filter peaks are a fallback, not the precision path.
- Runtime sync updates delay/SRO/phase estimates from known speaker chirplets every block/frame, gated by confidence so a bad observation freezes rather than poisons the field.
- Active chirplet probes are scheduled by an optimization loop, not by panic. It should prefer masked windows, respect minimum spacing and level caps, and maximize expected confidence gain per audible intrusion.
- Ultrasonic probes are allowed only as a bounded optimization strategy. They must stay below Nyquist, remain level-capped, and prove themselves by raising measured confidence; hardware may distort or discard them.
- Dense probe textures should be harmonically organized so any lower-band aliases land closer to musical relationships than arbitrary squeal. This is damage control, not a license to trust aliasing.
- FOA output is AmbiX: ACN channel order, SN3D normalization, channels `W,Y,Z,X`.
- The Faust voice-separation input is the aligned six-mic field, not the AmbiX collapse. Voice separation needs anchor and witness channels before spatial rendering destroys useful evidence.
- Speaker calibration is a measurement path, not a generic monitor output.
- Source-event geometry is published beside the AmbiX bed; render effects do not have to infer transient positions from mixed audio.
- Phase/chirplet evidence is reduced into alignment, correction, suppression, and probe-control meaning before it crosses the live cache boundary. Raw phase is an estimator detail, not a renderer API.
- Camera fusion may publish listener or source pose later, but it does not own audio channel timing.
- Focusrite dialogue mics are the voice anchors.
- Camera mics are spatial/context witnesses.
- Loopback/program audio is timing evidence where available.
- Distributed inputs must be aligned and resampled before they become program
stems.
- Probe signals are budgeted telemetry, not a permanent audio bed.
- Faust/native DSP owns the hot separation and spatialization graph.
## Module Boundaries
## Next Cut
The audio code is split so the hard parts can be tested without the room, drivers, or neighbor machine:
- `audio_field.buffering` owns source buffers and ordered field assembly.
- `audio_field.latency` owns the bounded-delay real-time convergence policy.
- `audio_field.ports` declares injectable capture, alignment, encoder, and sink protocols.
- `audio_field.pipeline` wires those ports together without knowing whether the source is a real Focusrite, an SRT receiver, a WAV fixture, or a test double.
- The next runtime estimator module should own chirplet observations, delay/SRO/phase state, confidence gates, and phase-field updates. It should feed the aligner; it should not be hidden inside the FOA encoder.
- The active probe optimizer owns whether to emit extra chirplets. It reads sync confidence and probe budget, then decides when and where an intentional chirplet is worth the cost.
- `audio_field.active_probe` owns the runtime join between phase-field confidence and emitted chirplet probes. It converts extracted source confidence into sync states, applies masking/spacing policy, writes bounded probe WAV slots plus a rotating manifest, and optionally plays them.
- `audio_field.phase_meaning` owns live extraction of meaning from phase/chirplet evidence. It consumes known reference audio plus aligned mic windows, keeps the smoothed phase/frequency state internal, and emits only actionable state for alignment, suppression, and probe control.
- Room suppression owns stream-side cleanup: dialogue anchors define desired direct energy, spatial/context mics act as witnesses for room and transient clutter, and the cleaned aligned field feeds FOA/Aquarium/Faust.
- Source-event analysis owns non-vocal spatial facts: dialogue focus weights and localized transient vectors are published beside the AmbiX bed, not hidden inside it.
- Aquarium/Faust owns the hot voice-separation graph after `localcast.audio.mic_field`; Mimir owns alignment, timing, roles, and control publication.
- `scripts/audio_field.py` stays as the operator CLI and hardware probe surface.
This is the portfolio-piece line: each module owns one invariant, and the tests use mocks/fakes instead of asking a driver stack to please be emotionally available.
## First Cut Limits
The current encoder is a source-style FOA mix from calibrated microphone channels and declared orientations. It accepts an already aligned six-channel WAV. It does not capture or align independent USB/network clocks by itself, and it is not a full arbitrary-array sound-field reconstruction.
Next honest steps:
1. Confirm local Kiyo, PS Eye, local Focusrite, and local speaker device matches.
2. Confirm the neighbor Focusrite capture path, preferably native/exclusive or the best FFmpeg/driver route available on that machine.
3. Probe the local and neighbor Focusrites for 48 kHz and 96 kHz capture support through the best available driver path.
4. Capture the two Focusrite anchors losslessly during calibration; prefer 96 kHz when driver/device support is real, then resample after sync.
5. Replace placeholder mic/speaker geometry with measured world coordinates.
6. Build the delay/SRO alignment stage that feeds `audio_field.buffering.FieldAssemblyCache`.
7. Emit aligned six-channel blocks under the configured latency policy.
8. Encode the first FOA AmbiX test only after that aligned WAV/block stream exists.
Add native audio capture workers that append typed blocks into
`Mimir.Runtime`, then expose buffer depth, clock state, delay estimates, and
stem routing in Aquarium UI.

View file

@ -1,245 +1,24 @@
# Calibration Harness
# Calibration
This is the first physical-device calibration spine for the expanded spatial rig.
Calibration data is measured truth for the live runtime. It is not the runtime.
## Objective
## Current Policy
Turn connected cameras, microphones, speakers, and near-field sensors into timestamped observations that can be calibrated into one world coordinate system.
- Keep calibration artifacts under `calibration/` when they record real device
identity, timing, geometry, or audio response.
- Prefer vendor SDKs, native driver APIs, Media Foundation, DirectShow, libusb,
LeapC, and GPU interop for new capture work.
- Treat old measurements as evidence only when they still change a live
decision.
## Current Mechanism
## Needed Measurements
The harness uses a repo-local Python environment:
- Leap stereo IR cadence and device timestamp behavior.
- Per-camera intrinsics and fixed rig extrinsics.
- Mic/speaker positions and polarity.
- Loopback delay for local and co-streamer playback paths.
- OBS presentation delay for bridge endpoints.
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r .\requirements-calibration.txt
```
Run discovery:
```powershell
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py discover
```
Capture camera snapshots:
```powershell
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py snapshot --max-index 10
```
List DirectShow devices and options through FFmpeg:
```powershell
$ff = .\.venv\Scripts\python.exe -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"
& $ff -hide_banner -list_devices true -f dshow -i dummy
& $ff -hide_banner -list_options true -f dshow -i video="PS3 Eye Universal"
```
Probe camera mode behavior:
```powershell
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py mode-probe --api msmf --index 0 --profile 320x240x120
```
Smoke-test input devices:
```powershell
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py audio-smoke --duration 1.0
```
Outputs are written under `calibration/runs/`, which is ignored by git. The manifest files are the disposable lab notebook for the live machine.
## Invariants
- Observations must include device identity, API/backend, timestamp, and confidence or failure reason.
- Calibration files may refer to devices by stable identity where possible, not only by fragile camera index.
- The world model owns truth. Snapshots, audio probes, splat packets, and debug images are evidence.
- Do not assume LeapUVC raw access and Ultraleap tracking coexist.
- Do not assume camera-attached microphones share the camera video clock.
## First Cut
The first useful calibration target is not a full point cloud. It is:
1. identify which video devices can produce frames
2. identify which microphone devices can produce samples
3. capture snapshots from each accessible camera
4. record RMS/peak data from each accessible mic
5. fix driver/backend issues for devices that are attached but inaccessible
## First Probe On This Machine
Run artifacts:
- `calibration/runs/20260518T124230Z-discover/manifest.json`
- `calibration/runs/20260518T124231Z-audio-smoke/manifest.json`
- `calibration/runs/20260518T124257Z-snapshot/manifest.json`
Observed video access:
- `dshow:0` / `msmf:0`: LeapUVC raw stereo IR image, visible as green/magenta packed output.
- `dshow:1` / `msmf:1`: Razer Kiyo-class RGB camera.
- `dshow:2` / `msmf:2`: second Razer Kiyo-class RGB camera, likely Kiyo Pro.
- `dshow:3`: first PS3 Eye through PS3 Eye Universal Driver / PS3EyeDirectShow.
- `dshow:4`: second PS3 Eye through PS3 Eye Universal Driver / PS3EyeDirectShow.
Mode probe notes:
- Historical diagnostic only: `msmf:0` LeapUVC accepted a `320x240x120` request and reported about 115 fps, while the old OpenCV probe measured around 52 fps. Treat that as evidence that the sensor mode is plausible and that the diagnostic path is too soft for live timing. Mimir live ingest should talk directly to the driver path.
- Kiyo RGB devices produce snapshots, but initial isolated mode probes against Kiyo indices timed out. Do not trust FPS configuration for Kiyos until a backend-specific capture path is chosen.
- PS3 Eye default DirectShow capture works at `640x480` near 30 fps. High-FPS tracking modes are not proven yet; mode probes against the DirectShow filter can hang or collide with another open handle, so test them sequentially.
Observed audio access over WASAPI at 48 kHz:
- Scarlett Solo USB microphone
- Razer Kiyo Pro microphone
- Razer Kiyo microphone
- both `USB Camera-B4.09.24.1` microphone devices, presumed PS3 Eye audio interfaces
- Scarlett Solo speaker output
## ChArUco Target
A first calibration target has been generated:
```powershell
.\.venv\Scripts\python.exe .\scripts\charuco_calibration.py board
```
Output:
- `calibration/targets/charuco-8x6-dict4x4-100.png`
- `calibration/targets/charuco-8x6-dict4x4-100.json`
Capture intrinsics frames for a camera:
```powershell
.\.venv\Scripts\python.exe .\scripts\charuco_calibration.py capture --api dshow --index 1 --frames 25
```
Solve intrinsics from a capture run:
```powershell
.\.venv\Scripts\python.exe .\scripts\charuco_calibration.py calibrate --images .\calibration\runs\<run-folder>
```
## PS3 Eye Driver Cut
Use the open-driver path first. The current candidate is the opentrack PS3 Eye open driver route:
1. uninstall any old CL Eye / PS3 Eye video driver
2. use Zadig on PS3 Eye interface `MI_00`
3. install `libusb-win32` first
4. if that fails, try `libusbK`
5. re-run:
```powershell
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py discover --max-index 10
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py snapshot --max-index 10
```
Do not install the driver over `MI_01`; that is the working generic USB audio interface.
CL Eye / Code Laboratories is historical reference material only. Do not make this repo depend on a paid, stale, or redistributed proprietary driver. Reverse engineering should stay inside interoperability research boundaries; the live machine should prefer the open driver.
opentrack/libusb status:
- Both PS3 Eye `MI_00` video interfaces are now bound as `libusb-win32 devices` and show `OK` in PnP.
- `E:\Tools\opentrack\modules\ps3eye-mode-test.exe` sees the cameras well enough to enumerate good modes up to `320x240@205Hz` and `640x480@83Hz`.
- Frame reads still fail with repeated `ps3eye: payload error, data[1]=78` and `can't read any frame`.
That means the next fault is not "missing driver"; it is driver/backend/USB streaming. opentrack's guide recommends `libusb-win32` first and `libusbK` as a fallback. PSMove's PS3 Eye documentation says WinUSB through Zadig has been tested with PS3EYEDriver on Windows. If libusb-win32 continues to enumerate modes but fail frames, try the fallback in this order on `MI_00` only:
1. `libusbK`
2. `WinUSB`
After each driver swap, rerun:
```powershell
& 'E:\Tools\opentrack\modules\ps3eye-mode-test.exe'
& 'E:\Tools\opentrack\modules\ps3eye-frame-test.exe'
```
Fallback results so far:
- `libusbK` with both Eyes direct to motherboard: all opentrack modes report `GOOD`, including `320x240@30`, but frame reads still fail with `payload error, data[1]=78/79` and `bad header`.
- `WinUSB` with both live `MI_00` instances: opentrack mode test still reports all modes `GOOD`, but one camera open reports `Access is denied` and frame streaming still repeats `payload error, data[1]=78/79`.
- `libusb-win32`, `libusbK`, and `WinUSB` have all failed frame reads through opentrack on this machine.
That path is currently rejected for frame capture on this machine. Keep it as a mode-enumeration reference, not the live capture path.
Working DirectShow path:
- Installed AllanCat `PS3 Eye Universal Driver` / `PS3EyeDirectShow` from `PS3EyeInstaller1.1.msi`.
- Installed source filters:
- `C:\Program Files\PS3 Eye Universal Driver\PS3EyeSourceFilter64.dll`
- `C:\Program Files (x86)\PS3 Eye Universal Driver\PS3EyeSourceFilter.dll`
- The filter's camera count is controlled by `ChangeCameraNumber.bat`, which unregisters/registers the source filter with `/i:<count>`.
- With two cameras connected, register both filters for two cameras from an elevated shell:
```powershell
$dll32 = 'C:\Program Files (x86)\PS3 Eye Universal Driver\PS3EyeSourceFilter.dll'
$dll64 = 'C:\Program Files\PS3 Eye Universal Driver\PS3EyeSourceFilter64.dll'
Start-Process regsvr32.exe -ArgumentList "/n /i:2 `"$dll32`"" -Verb RunAs -Wait
Start-Process regsvr32.exe -ArgumentList "/n /i:2 `"$dll64`"" -Verb RunAs -Wait
```
After registration, this machine exposes:
- `dshow:3`: PS3 Eye, default `640x480`, about 30 fps.
- `dshow:4`: PS3 Eye, default `640x480`, about 30 fps.
- Simultaneous three-second capture from indices 3 and 4 produced 90 frames each, about 29.8-30.0 fps.
- DirectShow device names are `PS3 Eye Universal` and `PS3 Eye Universal2`; use these names when forcing high-rate modes through FFmpeg.
Known caveats:
- Historical diagnostic only: OpenCV `mode-probe` calls that set width/height/fps may time out against the PS3EyeDirectShow filter.
- Parallel probes can race the same libusb/backend state and produce `Access is denied`; test PS3 Eye mode changes one handle at a time.
- Historical diagnostic only: OpenCV by index did not negotiate high-rate PS3 Eye modes correctly. It can report a requested FPS while delivering the wrong shape or frame rate.
- FFmpeg by DirectShow device name does negotiate the filter pins correctly. Verified modes:
- single `PS3 Eye Universal` at `640x480@30/40/50/60`; `640x480@60` delivered about 56 fps over three seconds
- single `PS3 Eye Universal` at `320x240@30/40/50/60`; `320x240@60` delivered 180 frames over three seconds
- single `PS3 Eye Universal2` at `640x480@60` and `320x240@60`; both delivered about 59-60 fps
- dual `640x480@60` delivered about 54-56 fps per Eye over five seconds
- dual `320x240@60` delivered 300 frames per Eye over five seconds
- Requests above 60 fps through the installed DirectShow filter do not increase delivered frame rate. `320x240@70` still delivered about 60 fps; `640x480@70` delivered about 51-52 fps.
Current tracking capture command shape:
```powershell
$ff = .\.venv\Scripts\python.exe -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"
& $ff -hide_banner -f dshow -video_size 320x240 -framerate 60 -pixel_format bgr24 -i video="PS3 Eye Universal" -an -f rawvideo -
& $ff -hide_banner -f dshow -video_size 320x240 -framerate 60 -pixel_format bgr24 -i video="PS3 Eye Universal2" -an -f rawvideo -
```
That command emits raw BGR frames to stdout. A real tracker should launch each FFmpeg capture as a child process, read fixed-size `320 * 240 * 3` frame packets, and timestamp packet arrival at the process boundary.
Next escalation is no longer "find any video path." It is:
- capture ChArUco intrinsics for `dshow:3` and `dshow:4` at the working default mode
- use FFmpeg DirectShow capture for PS3 Eye tracking at `320x240@60`
- patch/rebuild PS3EyeDirectShow if more than 60 fps is required; the installed filter advertises a practical 60 fps ceiling
- keep Leap/Kiyos/PS3 Eyes split across USB root paths where possible
Also test with one PS3 Eye unplugged and each camera connected directly to a motherboard USB 2.0/3.x port, not through a hub. A libusb issue report shows PS3 Eye/opentrack access can break when certain USB-C hubs are present, even when the camera itself is not plugged into that hub.
USB topology note from this machine:
- The two PS3 Eyes, Razer Kiyo, Razer Kiyo Pro, and Leap Motion are effectively sharing the same external hub/root path.
- After binding both PS3 Eye `MI_00` interfaces, one PS3 Eye composite device and one PS3 Eye audio interface showed `Unknown`, while both `MI_00` interfaces remained visible as `libusb-win32`.
- Two `Unknown USB Device (Device Descriptor Request Failed)` entries were also present on the same hub path.
That makes the hub/root topology a live suspect. A USB3 hub does not make old USB2 high-bandwidth devices independent; USB2 traffic still shares the hub's USB2 side and transaction scheduling. iPiSoft's multiple-PS Eye guidance says a single USB2 hub is only acceptable for low-resolution capture, and opentrack's guide says to try another USB2/USB3 controller if the camera fails.
Practical next cut:
1. Test one PS3 Eye alone on the current hub.
2. If it still fails, test one PS3 Eye alone on a different motherboard root port/controller.
3. Once one streams, add the second PS3 Eye at low tracking mode first, e.g. `320x240@60`, then increase.
4. Put Kiyos/Leap on a different hub/root path if possible.
5. If no physical split is possible, plan for lower PS3 Eye rates and treat the hub as a scarce shared resource, not a magic blue rectangle.
Mirrored references:
- `research/visual-spatial-map/mirrors/opentrack-ps3-eye-open-driver-instructions.html`
- `research/visual-spatial-map/mirrors/zadig-home.html`
- `research/visual-spatial-map/mirrors/code-laboratories-cl-eye-driver.html`
Calibration tooling should be native or vendor-backed from here. If a measurement
cannot be reproduced without the deleted scripting stack, record the gap and
rebuild the measurement path in the live language stack.

View file

@ -1,212 +1,69 @@
# Implementation Plan
# Implementation Plan
## Current Cut Line
`docs/native-rebuild-plan.md` is now the active plan.
Mimir is now a C# app/runtime plus native reservoir project. The live stream
machine must be direct-driver and native-buffer first:
No more Python live hot path. No more OpenGL production Spout sink. No more JSON
live data stores. Edge JSON may define CultNet schema or export diagnostics, but
the real process/network data stays typed because every subsystem is under our
control.
- `src/Mimir.App` hosts Aquarium Engine for windowing, rendering, and the D3D12
bridge.
- `src/Mimir.Runtime` owns stream descriptors, source polling, direct push
ingest, one rolling buffer per configured audio/video stream, and the
synchronization hub Aquarium can inspect.
- `native/reservoir` owns the lower native rolling-buffer invariant for
Aquarium/Faust integration.
- PowerShell/FFmpeg/SRT remains a bridge utility for LAN OBS feeds. It is not
the synchronized program authority.
The native reservoir is now one time-ordered rolling buffer with typed views.
The previous shared-edge typed rings proved the retention invariant; the new
shape removes independent per-kind storage from the live foundation.
The near-term viable stream app is Aquarium-hosted: it ingests local or
networked video/audio feeds as producers into the same five-second in-memory
`LocalcastRuntime`, exposes debug/settings/output control through Aquarium UI,
and emits synchronized OBS program video plus separately controllable audio
stems. Mimir now owns its own C# solution while referencing Aquarium Engine as
the windowing/rendering library and D3D12 bridge. `docs/viable-stream-app.md`
is the current cut line for that app.
The v1 OBS bridge is now gated by a bounded smoke-test witness ledger. No
plugin/native receiver expansion is justified until
`calibration/runs/obs-v1-smoke-ledger.json` records sender capture, SRT receive,
and OBS presentation timestamps for every planned endpoint with bounded drift,
latency, and confidence.
The old script stack is gone. Do not add a compatibility edge unless it protects
a named invariant that the native runtime cannot protect yet.
## Implemented
- Mimir public identity and repo Face:
- `README.md` now presents the project as Mimir: local sensors, coherent
field.
- `Mimir.png` is the user-repixelized 256px avatar source.
- `assets/branding/mimir-avatar-256.png` is the project branding copy.
- `.voidbot/voice/mimir.png` and `.voidbot/voice/identity.json` are the
VoidBot-facing persona surfaces for the Mimir Face.
- `.voidbot/state/mimir.cc` is the typed persistent Face state. It is seeded
with durable birth memories for Mimir identity, native-reservoir target,
ownership boundaries, audio-field discipline, and heartbeat agency pressure.
- `docs/mimir-face.md` defines Mimir's jurisdiction, voice, heartbeat
behavior, and inherited memories. VoidBot is only the mouth/scheduler.
- Perfect Machine contract:
- `docs/perfect-machine.md` defines the target native machine: one five-second spatiotemporal reservoir, Aquarium-owned dense visual fusion/material/brush rendering, Faust-owned hot audio DSP, OBS-owned broadcast controls, and Mimir-owned calibration/config/status.
- `docs/viable-stream-app.md` defines the first useful application cut:
Aquarium hosts the in-memory five-second runtime, owns runtime UI and
output management, treats local/networked feeds as producers, and emits
synchronized OBS program surfaces.
- `Mimir.slnx` contains `src/Mimir.App` and `src/Mimir.Runtime`.
`Mimir.App` launches `AquariumHost` from Aquarium Engine, and
`Mimir.Runtime` supplies the Aquarium client runtime factory.
- `Mimir.Runtime` now owns `MimirSynchronizationHub`,
`MimirRollingStreamBuffer`, stream descriptors, and the `IMimirStreamSource`
adapter seam. It initializes one bounded rolling buffer per configured
audio/video stream and polls registered local/network sources each frame.
Local devices should feed through native push adapters; process-backed
sources are compatibility edges for network/diagnostic command ingest, not
the six-camera capture foundation.
- `MimirVideoFrameDescriptor` is the first video-frame hot-path descriptor:
dimensions, pixel format, stride, device timestamp, and optional native/GPU
handle. Leap stereo IR should enter Mimir through this native descriptor,
with OpenCV kept out of the hot loop.
- `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` define the
live driver-facing seam. LeapUVC/libusb, LeapC images, Media Foundation,
DirectShow, or GPU shared texture capture should plug in here.
- `config/perfect-machine.example.json` declares the contract shape for six cameras, six microphones, reservoir typed views, native authorities, outputs, and the demotion of bridge scripts to tooling.
- `native/reservoir` is the first native Rust crate. It implements one
shared-edge five-second rolling buffer with typed views and proves that
every kind expires from the newest live sample.
- `native/reservoir/include/localcast_reservoir.h` exposes the initial
Aquarium/Faust C ABI: opaque reservoir create/destroy, sample-handle push,
edge/window queries, ring counts, and latest sample lookup by sensor hash.
The ABI now exposes total rolling-buffer length and typed-view length.
- `localcast_hash_source_id` owns stable FNV-1a source hashing for native
producers; empty/null source ids produce zero and are rejected.
- `localcast_producer_create_for_source` is the preferred producer constructor
for adapters because it keeps source-id hashing inside the native ABI.
- `LocalcastRuntime` wraps the current reservoir with typed native producer
calls and total/typed read functions. It is the intended live spine for
Aquarium/Faust bindings.
- `LocalcastProducer` owns native ingress source identity and sequence
assignment before appending live handles into `LocalcastRuntime`.
- `LocalcastAudioBlockDescriptor` is the first typed payload descriptor for
caller-owned float32 interleaved audio blocks. The reservoir stores only the
descriptor pointer as a payload handle; audio memory remains owned by
native/Faust producers.
- `LocalcastRenderPacketDescriptor` gives render packets the same typed
descriptor boundary: caller-owned point buffer, point count/stride, target
size, source window, present time, audio-alignment time, and optional
metadata handle.
- `LocalcastRenderPoint` is the first fixed point-buffer element ABI for
Aquarium decoding: stable-key hash, source timestamp, position, radius,
color/alpha, and confidence.
- Repo-local persistence machinery.
- First architecture map.
- Example config for one video source plus two audio sources.
- Sender device discovery script.
- Sender launch script with dry-run mode and per-source FFmpeg commands.
- OBS receiver setup notes.
- Neighbor sender deployment under `C:\Meta\Mimir`.
- Madman's desktop start/stop launchers for the sender.
- Receiver OBS scene has `Neighbor PC - Video` and `Neighbor PC - Focusrite` Media Sources.
- Direct co-streamer loopback capture is now attempted with the repo WASAPI shim instead of Voicemeeter.
- Receiver OBS scene has `Neighbor PC - System Audio` on SRT port `5102`.
- Sender script uses `-nostdin` and repo-root logs so desktop launchers stay alive and diagnostics land in `C:\Meta\Mimir\logs`.
- Sender video config is `1920x1080` for the interactive desktop. The `1024x768` SSH session size is not the streaming target.
- Desktop `.cmd` launchers delegate to PowerShell wrappers so paths with spaces and apostrophes are handled in one place.
- Audio-field sidecar profile and tool:
- `config/audio-field.example.json` declares the actual distributed six-mic rig: two Kiyo mics, two PS Eye mics, local Focusrite shielded cardioid, neighbor Focusrite shotgun on the co-streamer, two local speakers, placeholder geometry, clock domains, capture policy, calibration sweep settings, and FOA AmbiX ACN/SN3D output.
- `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.calibration_space` solves fixed-board ChArUco observations into camera poses in one common world frame.
- `localcast.sensor_fusion.surface_features` matches cross-view features and triangulates calibrated surface tracks.
- `localcast.sensor_fusion.render_bridge` emits render-frame packets with visual/audio timing metadata and Spout sender identity.
- `localcast.diagnostics.visual_cache` stores diagnostic visual state as typed
CultCache MessagePack documents. It is not the production live boundary.
- `localcast.diagnostics.render_math` owns pure diagnostic render budgeting,
camera projection, brush lowering, and CPU rasterization tests without an
OpenGL or OpenCV requirement.
- The Python/OpenGL Spout publisher and launcher have been deleted.
Production Spout2 publication belongs to Aquarium.
- `localcast.diagnostics.visual_producer` contains the old Python visual
producer code. It is diagnostic/migration code, not production runtime, and
no longer has a script launcher.
- 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.
- The live visual producer now uses an explicit five-second spatiotemporal reservoir. RGB/Leap frame history expires from the newest shared sample, the multi-LOD cache only accepts evidence inside that same window, and `RenderFramePacket.source_time_min_ns/source_time_max_ns` declares the reservoir slice being rendered.
- Multi-LOD cells now carry first-pass material estimates: weighted albedo plus roughness/metallic hints derived from source evidence. Aquarium should treat this as relightable material evidence to refine, not as the final BRDF solve.
- The Spout/audio overlay boundary clamps stale visual packets to the current audio reservoir edge. If camera geometry ages out, it is dropped instead of being broadcast out of sync.
- Live fallback-only RGB/Leap mode exists for deadline operation when OpenCV/MSMF/DirectShow reads block longer than the five-second reservoir. It keeps the reservoir and OBS output alive while real camera capture is moved to nonblocking ingress.
- OpenCV camera reads now run behind `LatestFramePump` workers so blocking drivers cannot freeze the fusion hot loop. The live deadline command uses lower per-frame sample density (`--rgb-room-step 16 --leap-step 16 --points 64`) so the reservoir/TAA path stays fresh enough for Spout to render visual points inside the five-second budget.
- `localcast.sensor_fusion.chirp_pose` converts live phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints and per-camera pose-correction estimates. It can load camera-mic and speaker geometry from the audio-field profile, with the example profile used as the live fallback until measured local geometry exists. The diagnostic visual producer can inject those constraints as `camera-chirp:*` and `camera-pose-correction:*` render points plus `chirp-camera-pose` LOD evidence.
- Diagnostic render math still has a named `kiyo-mid-deru` virtual camera
preset and point budget for CPU tests. Aquarium should own the production
version of that policy.
- `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary.
- `docs/typed-visual-state.md` documents the diagnostic CultCache file shape
and the CultNet visual schema target.
- OBS synchronized program surface:
- `scripts/obs_smoke_test.py` creates the v1 OBS smoke-test endpoint plan,
event template, and witness ledger.
- `localcast.obs_smoke` owns the pure endpoint planning and ledger summary
logic: per-stage timestamps, matched end-to-end latency, endpoint drift, and
confidence.
- `docs/obs-v1-smoke-test.md` is the runbook for collecting
`sender_capture`, `srt_receive`, and `obs_present` evidence before receiver
expansion.
- `scripts/setup_obs_synced_program.py` derives OBS-controllable stems from an aligned program audio timeline: host voice, co-streamer voice, ambient, transients, co-streamer loopback, and local loopback.
- `scripts/capture_co_streamer_surfaces.py` captures neighbor Focusrite and neighbor loopback with local loopback ground truth, estimates the late remote-family offset, and writes aligned co-streamer surfaces for the stem packer.
- `scripts/wasapi-loopback-capture.ps1` is the direct primary-playback loopback path. It must run in the neighbor's interactive console session; SSH-only capture sees the device but receives no render packets.
- The tool creates/updates local OBS Media Sources for those stems and mutes/disables raw unsynchronized inputs.
- Strict mode disables every scene item except the synchronized Mimir program video and stem controls.
- Live phase-field meaning:
- `audio_field.phase_meaning` extracts actionable delay, coherence, confidence, suppression, correction-energy, and active-probe need from internal phase/chirplet evidence.
- `localcast.audio.phase_field` is a typed CultCache document at `calibration/runs/audio-phase-field.msgpack`.
- `localcast.diagnostics.audio_phase_field` can replay an aligned mic field plus known program/loopback reference into the phase-field document for diagnostics. It is not a live bridge authority.
- `localcast.diagnostics.audio_phase_field` can write `audio-phase-field-status.json` during replay so estimator behavior remains inspectable while the native ingest path is built.
- `audio_field.active_probe` wires low phase-field confidence into `ActiveProbeOptimizer`, emits bounded chirplet WAVs plus `active-probes.jsonl`, and can play probes through the default output device.
- `localcast.diagnostics.audio_live_field` preserves the old local WASAPI/PortAudio capture experiment as diagnostic code only. Production local mic and loopback ingest belongs in native capture workers that append typed handles through `LocalcastProducer`.
- Active probe maintenance only targets source ids backed by live local capture devices. Missing distributed channels remain stable placeholders in the mic/phase field, but they do not consume chirp budget.
- Active probe artifacts are bounded: emitted chirps rotate through a fixed slot set and the manifest rotates at a byte cap. The calibration loop is allowed to be noisy; it is not allowed to become an unbounded filesystem leak.
- Faust voice-separation boundary:
- `localcast.audio.mic_field` publishes aligned six-mic float32 blocks at `calibration/runs/audio-mic-field.msgpack`.
- `faust/localcast_voice_separation.dsp` is the first Aquarium-hosted graph surface for host voice, co-streamer voice, ambient, transient, and loopback stems.
- `localcast.diagnostics.faust_mic_field` can replay aligned WAV blocks into the old mic-field document for smoke tests. It is not a live publisher.
- Mimir public identity, branding, and Face memory.
- `Mimir.slnx` with `src/Mimir.App` and `src/Mimir.Runtime`.
- Aquarium host bootstrapping from `Mimir.App`.
- `MimirSynchronizationHub`, `MimirRollingStreamBuffer`, stream descriptors, and
`IMimirStreamSource`.
- Configurable five-second default rolling buffers for local and network audio
and video streams.
- `MimirNativeIngestStreamSource` for direct push ingest into runtime buffers.
- `MimirProcessStreamSource` for bridge/network command edges.
- `MimirVideoFrameDescriptor` for dimensions, pixel format, stride, device
timestamp, and native/GPU handle metadata.
- `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` as the live
driver-facing seam for Leap, Media Foundation, DirectShow, libusb, LeapC, or
shared texture capture.
- `native/reservoir` with one shared-edge rolling buffer, typed views, C ABI,
source-id hashing, producer helpers, and typed audio/render payload
descriptors.
- Windows bridge scripts for sender discovery/start/stop and simple OBS Media
Source ingest.
- Documentation for OBS receiver setup, native rebuild boundaries, the viable
stream app, and the Mimir Face.
## Temporary
- Audio and video are separate SRT endpoints. This preserves OBS mixing authority but may need latency tuning.
- The OBS v1 smoke ledger currently owns the receiver expansion gate. Until a
real run passes, endpoint coherence is unknown rather than assumed.
- Audio defaults to AAC inside MPEG-TS for compatibility; test Opus later only if there is a concrete reason.
- Desktop capture uses `gdigrab` first because it is broadly available. `ddagrab` is a candidate once the installed FFmpeg build is confirmed.
- The scripts assume Windows sender and OBS receiver on the same LAN.
- The Python visual producer is a diagnostic/migration fossil only. The OpenGL
Spout sink has been deleted.
- Python audio publishers are diagnostic fossils only. The AmbiX, phase-field,
live-local-capture, and Faust mic-field publisher modules live under
`localcast.diagnostics.*`; the live PowerShell launchers for phase-field and
Faust mic-field publication have been deleted.
- Audio and video may still traverse separate OBS/SRT endpoints during bridge
testing so OBS can preserve independent controls.
- Process-backed stream sources are only acceptable for network bridge feeds or
diagnostics. Six-camera local ingest belongs behind direct capture drivers.
- Calibration artifacts may remain on disk as evidence, but live state must be
in memory inside Mimir/Aquarium/native runtime surfaces.
## Next
1. Delete remaining diagnostic command dependence on `localcast.diagnostics.visual_producer`,
diagnostic JSON render-frame adapters, and diagnostic JSON LOD adapters.
Reservoir-window clipping, Leap packed transforms, RGB reference splats, and
clap calibration have been split out of the producer monolith.
2. Bind Aquarium/Faust to the rolling-buffer `LocalcastRuntime`.
Aquarium now has a safe-code native reservoir binding layer, injected frame
source seam, and native `ILocalCastVisualFrameSource` that reads render
packet handles through `ILocalCastNativeRuntime` with an injected payload
decoder. It also has the matching safe-code audio block and render packet
descriptor bindings, plus a render descriptor decoder that reads timing and
target metadata from native payload handles and decodes the first native
point-buffer ABI by default. Aquarium also exposes the native source-id hash
wrapper and source-id producer constructor. The next Aquarium cut is wiring
native runtime creation into the app path once a producer exists to feed it.
3. Move camera/mic/loopback ingest into native capture workers that use
`LocalcastProducer` to append typed sample handles.
4. Move feature extraction, flow, cross-view matching, LOD reconciliation,
material fitting, brush/splat rendering, and Spout2 publication into
Aquarium GPU compute.
5. Move mic alignment, room suppression, voice separation, Ambisonic/HOA
spatialization, and stem generation into Faust/native DSP.
6. Keep FFmpeg/SRT scripts as simple LAN ingest/capture utilities, not the
synchronized program authority.
7. Run the v1 OBS smoke test against the actual sender/receiver setup and keep
the ledger as evidence before any receiver/plugin/native OBS expansion.
1. Implement concrete direct capture drivers for Leap stereo IR first, then the
other cameras.
2. Feed those drivers into `MimirVideoCaptureDriverSource` and prove sustained
frame cadence in the rolling buffers.
3. Add native audio capture workers for local mic, loopback, and network audio
feeds.
4. Bind Aquarium UI to the synchronization hub so buffer depth, stream cadence,
source timestamps, and output settings are visible and adjustable.
5. Move GPU feature extraction, fusion, material fitting, render budgeting, and
Spout2 publication into Aquarium.
6. Move mic alignment, room suppression, voice separation, spatialization, and
stem generation into Faust/native DSP.
7. Keep the OBS bridge witness ledger as evidence before expanding receiver
machinery.

View file

@ -32,7 +32,7 @@ Mimir must not:
- claim ownership over OBS composition, Aquarium rendering, Faust DSP, or FFmpeg
capture;
- revive Python live hot paths, OpenGL production Spout, or JSON live stores;
- revive deleted script hot paths, OpenGL production Spout, or JSON live stores;
- turn progress updates into lore fog;
- preserve old work because it exists;
- let heartbeat chatter become a substitute for shipped cuts.
@ -71,7 +71,6 @@ Invariants:
- FFmpeg owns simple capture, encode, and transport in V1 bridge mode.
- Mimir/this repo owns configuration, calibration, launch/status, typed
contracts, memory, and operational repeatability.
- Python is tooling and diagnostics, not a live presentation hot path.
- JSON is schema or diagnostic export, not live process/network data.
- Missing synchronized feeds are explicit absence or placeholders, not stale or
unsynchronized substitutions.
@ -138,8 +137,8 @@ When VoidBot wakes Mimir for a heartbeat:
1. Read `state/map.yaml`, `notes/fresh-workspace-handoff.md`,
`notes/current-system-map.md`, and `docs/implementation-plan.md`.
2. Run `tools/localcast_state.py status`.
3. Check `git status --short --branch`.
2. Check `git status --short --branch`.
3. Read the tail of `state/evidence.jsonl`.
4. Report only meaningful drift, completed work, blockers, or next bounded
moves.
5. If nothing changed, say so briefly and name the next useful cut.
@ -164,9 +163,9 @@ These are the lessons Mimir should remember at birth:
- Icon explorations and prompts live under `assets/branding/`.
- The strongest avatar direction was the voxel-mask Face: mythic, symmetrical,
sensor-rooted, and readable as a profile image.
- The Python/OpenGL Spout publisher was deleted. Do not revive it.
- Python producers, CultCache files, and JSON adapters are diagnostics or
migration fossils. They are not production runtime authority.
- The deleted script-era presentation stack stays deleted. Do not revive it.
- CultCache files and JSON adapters are diagnostics or migration fossils. They
are not production runtime authority.
- `native/reservoir` is the first native foundation. It now uses one
time-ordered rolling buffer with typed views.
- `LocalcastRuntime` is the intended live spine. `LocalcastProducer` owns source

View file

@ -1,160 +1,71 @@
# Native Rebuild Plan
# Native Rebuild Plan
This is the cut line after the architectural teardown.
The live system must be rebuilt around one native rolling reservoir. Python and
OpenGL are no longer acceptable live foundations. Python may remain as offline
calibration, schema tests, device discovery, migration probes, and forensic
tools only. If a future change needs Python or an OpenGL Spout sink in the live
path, treat that as evidence the native boundary is missing, not as permission
to extend the deadline bridge.
This is the live cut line: Mimir is a direct-driver, native-buffer, Aquarium
hosted stream machine.
## Objective
Make the second PC available in OBS as synchronized program video plus
separately controllable audio while preserving the real ownership model:
Make the room available in OBS as synchronized program video plus separately
controllable audio while preserving ownership:
- Mimir owns config, calibration, contract tests, launch, status, and
CultNet schema.
- One native runtime owns live sample timing and retention.
- Aquarium owns GPU visual fusion, material/brush/splat rendering, and Spout2
publication.
- Faust/native DSP owns hot audio alignment, suppression, voice separation,
stems, and spatial bed generation.
- Mimir owns configuration, calibration truth, runtime contracts, launch,
status, and persistence.
- Mimir.Runtime owns in-memory stream buffers and runtime synchronization.
- Native capture workers own device reads and append typed sample handles.
- Aquarium owns GPU fusion, rendering, D3D12 interop, UI, and Spout2 output.
- Faust/native DSP owns hot audio alignment, suppression, separation, stems, and
spatial bed generation.
- OBS owns broadcast controls.
## Durable State Model
Durable state is declarative or evidentiary. It is not the live machine.
- `config/localcast.json`: LAN sender/receiver endpoints, OBS source names, and
FFmpeg/NVENC settings for simple bridge mode.
- `config/sensor-fusion.json`: measured camera identity, intrinsics, extrinsics,
capture hints, and calibration timestamps.
- `config/audio-field.json`: measured mic/speaker identity, geometry, clock
domains, channel order, roles, gain, delay, and polarity.
- CultNet schema JSON: edge schema only. The actual runtime documents are typed
CultNet documents, not JSON data files.
- Calibration artifacts: WAVs, images, manifests, solves, and evidence ledgers.
- `state/*` and `notes/*`: rehydration memory for agents, never runtime truth.
## Runtime State Model
The runtime state is one native rolling buffer with a single edge.
```mermaid
flowchart TD
C["native capture workers"] --> R["LocalcastRuntime rolling reservoir"]
A["audio capture / loopback workers"] --> R
R --> Q["Aquarium GPU fusion + render"]
C["direct camera drivers"] --> R["Mimir.Runtime buffers"]
A["audio / loopback drivers"] --> R
N["network feed producers"] --> R
R --> Q["Aquarium UI + GPU fusion"]
R --> F["Faust/native DSP"]
Q --> S["Spout2 sender"]
Q --> S["Spout2/program video"]
F --> P["program stems + spatial bed"]
S --> O["OBS"]
P --> O
R --> N["typed CultNet status/docs"]
```
The reservoir stores sample handles in one time-ordered rolling buffer. Each
sample has:
The app-level runtime initializes one rolling buffer per configured audio or
video stream, defaulting to five seconds. The lower native reservoir keeps the
single-edge typed-handle invariant for Aquarium/Faust integration.
- kind: camera frame, camera feature, scene ray, surface claim, material claim,
audio block, phase claim, event claim, render packet, or status claim
- source id
- source timestamp
- arrival timestamp
- sequence
- payload handle
- provenance flags, which must be zero for live reservoir samples
Typed ring views may exist as indexes over the rolling buffer, but they do not
own retention. Expiry happens once, against the reservoir edge. No private
history outlives the rolling buffer.
Payload memory belongs to the producing domain. Aquarium owns GPU image,
feature, surface, material, and render payloads. Faust/native DSP owns audio
buffers and stem payloads. The reservoir owns timing, identity, ordering,
retention, and handle lookup.
Typed payload descriptors may cross the ABI when they clarify ownership without
copying data. `LocalcastAudioBlockDescriptor` describes caller-owned interleaved
float32 audio blocks for native/Faust producers; the reservoir stores its
address as the payload handle and does not own the bytes.
`LocalcastRenderPacketDescriptor` does the same for visual render packets:
caller-owned point buffers and timing metadata are explicit, while Aquarium owns
decode/upload/rendering.
The first point-buffer element is `LocalcastRenderPoint`; it is deliberately
small so a native producer can kill file-backed render-frame transport before
the richer material/brush payloads arrive.
Payload memory belongs to the producing domain. The reservoir and runtime own
timing, identity, ordering, retention, and lookup. They do not pretend to own
camera driver buffers, GPU textures, or DSP audio memory.
## Authoritative Boundaries
- Config/calibration crosses into runtime as immutable measured truth plus
explicit profile version.
- Capture workers cross into runtime by appending typed sample handles.
- Aquarium crosses the reservoir boundary by sampling typed visual/audio timing
handles and publishing a Spout2 texture.
- Faust/native DSP crosses the reservoir boundary by sampling audio/phase/event
handles and publishing typed stem/spatial-bed documents or OBS-facing audio
surfaces.
- CultNet carries typed process/network documents for status, control, and
external consumers. JSON exists only to declare schema or export diagnostics.
- OBS receives final program surfaces. It does not own synchronization or scene
reconstruction.
## Derived, Not Stored
- Render packets are derived from reservoir claims.
- LOD cells are derived from current reservoir contents.
- Brush/splat packets are derived by Aquarium.
- Audio event overlays are derived from event claims and presentation time.
- Point budgets are derived from typed claim metadata, not string prefixes.
- JSON heartbeat/status files are diagnostic exports only, if they survive at
all.
## Delete Early
Delete or quarantine these before adding new live features:
- Python live producers.
- Python live audio/visual hot loops.
- OpenGL Spout renderer.
- Synthetic/fallback visual evidence in the production path.
- JSON render-frame and LOD stores as live data.
- Renderer-owned semantic priority based on stable-key prefixes.
- Multiple Python copies of reservoir-window clipping.
- File mtime caches used as lifecycle or data freshness authority.
- Config/calibration crosses into runtime as measured truth plus profile
version.
- Capture drivers cross into runtime by appending typed samples.
- Aquarium consumes current visual/audio timing state and publishes the program
video surface.
- Faust/native DSP consumes audio/phase/event handles and publishes stems.
- OBS receives final program surfaces. It does not own synchronization.
## Impossible By Construction
- A sample older than the reservoir window is visible to live consumers.
- A diagnostic/fallback source enters a ground-truth reservoir kind.
- A renderer invents scene priority from display names or string prefixes.
- JSON becomes live data transport.
- Python becomes the production hot path.
- OpenGL becomes the production Spout sink.
- A sample older than the rolling window is visible to live consumers.
- A process bridge becomes the six-camera local capture foundation.
- File polling becomes the native runtime API.
- OBS broadcasts raw unsynchronized sources as the synchronized program.
- Two modules own the reservoir edge.
## Migration Order
1. Freeze this plan in persistence and stop feature work on the Python/OpenGL
bridge.
2. Rewrite `native/reservoir` from typed independent rings to one rolling buffer
with typed indexes/views.
3. Add contract tests proving single-edge expiry, typed view queries, latest
lookup, and impossible fallback admission.
4. Add the minimal Aquarium/Faust C ABI over the rolling buffer.
5. Move any remaining useful Python packet/schema code into diagnostics or
contract tests.
6. Keep the Python visual producer and compatibility adapters under
`localcast.diagnostics` only until they can be deleted.
7. Build the Aquarium-owned Spout publisher. Do not revive the Python/OpenGL
path.
8. Move audio hot path into Faust/native DSP behind typed reservoir handles.
9. Keep FFmpeg/SRT scripts only as simple V1 LAN bridge and capture utilities.
10. Delete dead compatibility files once no diagnostic command depends on them.
Small commits are allowed. Small evasions are not. If a commit preserves the
deadline bridge by adding an adapter around it, it is probably feeding the old
machine again.
1. Keep the C# app/runtime as the public Mimir surface.
2. Implement Leap stereo IR direct ingest first and measure sustained cadence.
3. Add the remaining local camera drivers through the same source seam.
4. Add native audio capture workers and feed aligned blocks to Faust/native DSP.
5. Bind Aquarium UI to stream health, buffer depth, source timestamps, settings,
and output management.
6. Move GPU fusion and Spout2 publication fully into Aquarium.
7. Keep FFmpeg/SRT scripts only as bridge utilities until direct program output
makes them unnecessary.

View file

@ -100,7 +100,7 @@ The sender FFmpeg build does not expose a native `wasapi` input device, so it
cannot directly capture primary playback by itself. `scripts\wasapi-loopback-capture.ps1`
is the direct Core Audio loopback path. It works when launched in the logged-in
console session and audio is actually rendering; SSH-only launches can open the
endpoint but receive no render packets. `scripts\capture_co_streamer_surfaces.py`
endpoint but receive no render packets. The native/co-streamer capture path
therefore schedules the WASAPI loopback leg into the interactive session and
pulls the resulting raw float PCM back for alignment.

View file

@ -1,32 +1,8 @@
# OBS Spout Streaming
## Current Status
The Python/OpenGL Spout sender has been deleted.
Mimir no longer carries a runnable OpenGL publication path. The only
surviving pieces are diagnostic packet/brush math in
`localcast.diagnostics.render_math` and typed diagnostic visual documents in
`localcast.diagnostics.visual_cache`.
# OBS Spout Streaming
Production Spout2 publication belongs to Aquarium.
## Target
```text
native rolling reservoir
-> Aquarium typed runtime state
-> GPU feature/fusion/material/brush buffers
-> D3D render target
-> Spout2 sender texture
-> OBS Spout2 Capture
```
## Invariants
- OBS receives a named Spout2 texture from Aquarium, not Python/OpenGL.
- Mimir may expose diagnostic typed documents and CPU render math, but
it does not own the production renderer.
- JSON remains a diagnostic/status surface only.
- The neighbor SRT video feed is a timed media artifact and must share the same
presentation ledger as Aquarium output and Faust audio.
OBS should receive a named Spout2 texture from the Aquarium-hosted Mimir app.
The bridge scripts can keep SRT Media Sources alive while direct output matures,
but synchronized program video should come from Aquarium once the runtime has
live camera buffers.

View file

@ -1,85 +1,20 @@
# OBS V1 Smoke Test
No plugin/native receiver work gets promoted until this ledger exists for the
plain FFmpeg/SRT OBS path.
The OBS bridge is allowed to remain only while it leaves evidence.
The smoke test is deliberately small:
## Witness Ledger
- `sender_capture`: sender-side flash/chirp or packet-origin timestamp.
- `srt_receive`: receiver-side stream arrival timestamp.
- `obs_present`: OBS preview/recording presentation timestamp.
- endpoint drift: media-time slope versus receiver monotonic time.
- end-to-end latency: matched `eventId` from `sender_capture` to `obs_present`.
- confidence: stage coverage, observation count, event confidence, latency, and drift.
`calibration/runs/obs-v1-smoke-ledger.json` records bridge evidence:
The output ledger is `calibration/runs/obs-v1-smoke-ledger.json`. A passing
ledger sets `gate.pluginOrNativeReceiverExpansionAllowed` to `true`. Anything
else means the bridge is still talking without enough clocks. Adorable, but no.
- sender capture timestamp;
- receiver transport timestamp;
- OBS presentation timestamp;
- endpoint drift;
- end-to-end latency;
- confidence and operator notes.
## Run
## Pass Condition
From the repo root:
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json plan
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json template-events
```
Edit `calibration/runs/obs-v1-smoke-events.jsonl` with real observations from
one bounded pass. Use the same `eventId` for the same visible flash or audible
chirp as it moves through stages.
Then summarize:
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json summarize
```
## Event Shape
Each line is one JSON object:
```json
{
"endpoint": "video",
"stage": "obs_present",
"eventId": "video-flash-001",
"monotonicNs": 1000180000000,
"wallTimeNs": null,
"mediaTimeNs": 180000000,
"confidence": 0.9,
"note": "OBS recording frame containing flash"
}
```
Required stages are:
- `sender_capture`
- `srt_receive`
- `obs_present`
`monotonicNs` is mandatory because wall clocks lie casually. `wallTimeNs` is
optional human correlation only. `mediaTimeNs` is optional for individual events,
but drift confidence needs at least two receiver-side media-time observations.
## Thresholds
Defaults:
- maximum absolute endpoint drift: `100 ppm`
- maximum end-to-end latency: `500 ms`
Override them when running the summary:
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json --max-abs-drift-ppm 50 --max-latency-ms 350 summarize
```
## Interpretation
`status: ok` means every planned endpoint has enough timestamp evidence for this
bounded pass. It does not prove the native reservoir is done. It proves the v1
OBS bridge has a clocked witness.
`status: fail` means stop bridge expansion and fix the missing or drifting
stage first.
Every planned endpoint needs matching evidence at all three stages before the
receiver path grows new machinery. A visible source in OBS proves pixels arrived.
It does not prove the program is synchronized.

View file

@ -1,200 +1,80 @@
# Perfect Machine
# Perfect Machine
## Objective
Build one synchronized spatial stream machine from six cameras, six microphones,
two speakers, Leap timing, Aquarium GPU rendering, Faust DSP, and OBS output.
The bridge scripts are not the product. They are scaffolding, launch surfaces,
calibration tools, and compatibility probes. The live hot path belongs to native
runtime code, GPU compute, and Faust.
The product is not a pile of bridge scripts. The product is a coherent live
field with explicit owners.
## Current Mechanism
The repo currently proves the contracts:
```mermaid
flowchart TD
A["camera/audio/phase/render producers"] --> B["LocalcastRuntime C ABI"]
B --> C["5s native reservoir"]
C --> D["Aquarium GPU + Faust DSP"]
D --> E["Spout/audio stems"]
E --> F["OBS"]
A["direct capture / network producers"] --> B["Mimir.Runtime rolling buffers"]
B --> C["native reservoir handles"]
C --> D["Aquarium GPU + UI"]
C --> E["Faust/native DSP"]
D --> F["Spout2/program video"]
E --> G["program stems"]
F --> H["OBS"]
G --> H
```
The old CultCache/Python/Spout path remains a compatibility diagnostic. It is
not the runtime API.
## Invariants
- One five-second spatiotemporal reservoir is the live authority.
- The reservoir is keyed by one shared presentation clock.
- Every sample has sensor id, local hardware time if available, arrival time,
calibrated world transform, confidence, and provenance.
- One five-second live window is the timing authority.
- Every stream has a bounded rolling buffer.
- Missing data is absence, not a stale substitute.
- Late data can refine the reservoir while it is inside the five-second window.
- Anything older than the live reservoir is offline calibration evidence, not
broadcast geometry.
- Audio clocks, camera clocks, Leap timing, remote video, and OBS presentation
are reconciled before rendering.
- Late data can refine the live window only while it remains inside the window.
- Aquarium owns dense visual fusion, temporal accumulation, material fitting,
brush/splat generation, final render target, and Spout publication.
- Faust owns hot audio DSP: voice separation, room suppression, Ambisonic/HOA
spatialization, and loopback/source stem generation.
- Mimir owns configuration, calibration, typed contracts, launch,
status, persistence, and compatibility surfaces.
## Native Runtime Shape
```mermaid
flowchart TD
A["camera capture workers"] --> R["5s native reservoir"]
B["mic/loopback capture workers"] --> R
C["Leap worker"] --> R
D["remote video/audio ingest"] --> R
E["speaker probe scheduler"] --> R
R --> F["clock/pose optimizer"]
F --> R
R --> G["Aquarium GPU fusion"]
G --> H["multi-LOD surface/material field"]
H --> I["brush/splat/TAA renderer"]
R --> J["Faust DSP graph"]
J --> K["program stems + spatial bed"]
I --> L["Spout2 texture"]
K --> M["OBS audio controls"]
L --> N["OBS video source"]
```
rendering, D3D12 interop, UI, and Spout publication.
- Faust/native DSP owns hot audio alignment, suppression, voice separation,
spatialization, and stem generation.
- Mimir owns configuration, calibration truth, runtime contracts, launch,
status, and persistence.
## Reservoir Contract
The reservoir stores one time-ordered rolling buffer of sample handles, not one
giant JSON-ish object and not independent per-kind histories. Typed views over
that buffer expose the kinds consumers need.
The native reservoir stores time-ordered sample handles with typed views. It
owns retention and lookup, not payload memory. Producers append. Optimizers
refine. Aquarium/Faust consume.
Required sample kinds / typed views:
Required sample kinds include camera frames, camera features, scene rays,
surface claims, material claims, audio blocks, phase claims, event claims, and
render packets.
- `camera_frame`: raw or GPU-importable image handles plus timestamps.
- `camera_feature`: keypoints, descriptors, optical flow, confidence, sensor id.
- `scene_ray`: calibrated rays from feature observations.
- `surface_claim`: triangulated or depth-estimated world samples.
- `material_claim`: albedo, roughness, metallic/specular hints, view direction.
- `audio_block`: aligned mic/loopback samples and per-source clock state.
- `phase_claim`: delay/SRO/phase/coherence estimates from chirplets and program
reference.
- `event_claim`: claps, transients, gestures, active illumination pulses.
- `render_packet`: selected brush/splat work for the current presentation frame.
The reservoir owns retention. Producers append. Optimizers refine. Renderers
sample. No stage owns a private history that can outlive the reservoir.
`LocalcastRuntime` is the first native owner above the raw reservoir. It exposes
typed producer calls for each sample kind so camera capture, audio capture,
phase estimation, material fitting, event detection, and render planning all
append into one shared five-second window without crossing a Python file cache.
It also exposes total and typed-view reads so Aquarium/Faust can consume that
same window without building private histories.
`LocalcastProducer` is the first native capture-worker boundary. It owns sample
kind, source identity, and sequence assignment before appending live handles into
`LocalcastRuntime`; hardware adapters should provide timestamps and payload
handles, not reservoir authority.
`LocalcastRuntime` and `LocalcastProducer` are the lower native boundary.
`Mimir.Runtime` is the app-level synchronization surface that Aquarium hosts and
debugs.
## Visual Fusion
Camera fusion is feature matching across the reservoir, not a latest-frame
operation.
The visual path should:
- ingest all cameras continuously into pinned/native buffers referenced by
reservoir sample handles;
- extract features and flow on GPU where possible;
- match every plausible cross-view feature within time and epipolar bounds;
- use Leap as the strongest near-field timing/spatial witness when live;
- estimate surface points, normals, confidence, and material observations;
- keep multi-LOD cells resident for Aquarium compute reconciliation;
- emit only the frame budget needed for OBS while TAA accumulates detail.
The live target is not "points per frame." The live target is evidence per
reservoir window and how much of it Aquarium can reconcile before presentation.
Camera fusion is cross-view evidence across the rolling window, not
latest-frame display. Leap stereo IR is the timing ground-truth candidate. The
driver path should deliver frame descriptors with device timestamps and native
or GPU handles, then Aquarium should do feature extraction, flow, matching,
material estimation, brush/splat budgeting, and final presentation on GPU.
## Audio Fusion
The audio path should:
The audio path aligns all microphones and loopbacks into one presentation
timeline, feeds Faust/native DSP with bounded blocks, and emits host voice,
co-streamer voice, ambient, transients, local loopback, co-streamer loopback,
and spatial bed as synchronized outputs.
- align all six microphones into one clocked field;
- use Focusrite dialogue mics as voice anchors;
- use camera mics as spatial/context witnesses;
- use loopback/program audio as ground truth where available;
- emit active probes only for channels that can observe them;
- continuously update delay, SRO, phase, frequency response, and confidence;
- feed Faust with aligned mic channels and control telemetry;
- produce host voice, co-streamer voice, ambient, transients, local loopback,
co-streamer loopback, and spatial bed as synchronized outputs.
Raw phase is internal. Meaning crosses the boundary.
Raw estimator detail stays inside the audio runtime. Meaning crosses the
boundary.
## Cut Line
Cut these from the hot path:
- Python dense rendering.
- Python camera feature extraction in the presentation loop.
- File polling as a native runtime API.
- OBS-side sync between independent raw sources.
- Stale geometry clamped into looking current.
- Probe scheduling against placeholder channels.
- file polling as a runtime API;
- process capture as the six-camera local foundation;
- OBS-side synchronization between raw sources;
- stale geometry clamped into looking current;
- probe scheduling against placeholder channels.
Keep these as tooling:
- Python calibration scripts.
- Python contract tests.
- Python device discovery.
- Compatibility Spout sender for diagnostics.
- Offline analysis and reproducible evidence ledgers.
## First Native Cut
1. Define the native reservoir ABI from `config/perfect-machine.example.json`.
2. Build a native reservoir process or Aquarium module that owns the five-second
rolling buffer.
3. Move camera ingest into native capture workers that write reservoir samples.
4. Move audio ingest/phase claims into the same presentation-clock reservoir.
5. Let Aquarium consume reservoir surfaces/material claims directly on GPU.
6. Let Faust consume reservoir audio blocks and source controls directly.
7. Keep the old bridge only as a comparison and fallback surface.
## Native Work Started
`native/reservoir` is the first native crate. It implements the shared-edge
five-second rolling reservoir invariant:
- append samples into one rolling buffer with typed views;
- advance the reservoir edge from the newest sample;
- evict all sample kinds against the same edge;
- query the latest valid sample per sensor inside a typed view.
It now builds as `rlib`, `cdylib`, and `staticlib`, with a small C ABI declared
in `native/reservoir/include/localcast_reservoir.h`:
- create/destroy an opaque `LocalcastReservoir`;
- push timestamped sample metadata into a typed view of the rolling buffer;
- advance/query the shared edge and window start;
- query total length and typed-view length;
- read samples by total rolling-buffer index or typed-view index;
- query the latest sample for a sensor hash.
- reject diagnostic/probe/fallback and unknown-flagged samples at the live
reservoir boundary via sample provenance flags.
- create/destroy an opaque `LocalcastRuntime`;
- create/destroy opaque `LocalcastProducer` ingress helpers;
- push live producer samples while the producer owns sequence/source metadata;
- append typed camera/audio/phase/event/render handles through producer calls;
- query a native runtime status struct with shared edge, window start, total
count, and typed-view counts;
- read runtime samples by total rolling-buffer index, typed-view index, and
latest sensor hash.
The ABI carries `payload_handle`, not payload bytes. Aquarium owns image,
feature, surface, material, and GPU memory interpretation. Faust/native DSP owns
audio buffer interpretation. The reservoir owns only retention, sample kind,
timestamp order, and the five-second shared-edge invariant.
Keep PowerShell/FFmpeg/SRT only as bridge utility while native ingest matures.

View file

@ -1,221 +1,31 @@
# Sensor Fusion Architecture
# Sensor Fusion Architecture
## Objective
Visual fusion belongs in Aquarium over current Mimir runtime buffers.
Produce an aligned, timestamped point cloud from the local visual rig while allowing latency, buffering, and cache convergence. The live render path can lag behind capture; it may not lie about coordinate ownership.
## Current Mechanism
The rig currently has usable capture surfaces:
- PS3 Eyes through FFmpeg DirectShow device names `PS3 Eye Universal` and `PS3 Eye Universal2`, verified at dual `320x240@60`.
- Kiyo-class RGB cameras through native Windows camera APIs such as Media
Foundation or DirectShow for color evidence.
- LeapUVC raw IR through native LeapUVC/libusb or LeapC image APIs for
near-field timing evidence.
- ChArUco tooling for intrinsics capture, but no shared fusion state yet.
That is capture. Capture is not a world model. The previous live producer also
painted camera colors onto guessed body and room surfaces. That was useful
deadline scaffolding, but it is not enough for detailed reconstruction.
## Invariants
- World coordinates own truth.
- Capture adapters emit timestamped observations; they do not own fusion semantics.
- Fusion core is pure and testable: calibrated camera models plus 2D observations in, 3D points/confidence out.
- Point clouds and later brush/splat packets are cached render lowerings, not the canonical scene.
- A missing high-detail update renders stale-but-bounded state until better evidence arrives.
- The live temporal reservoir is five seconds wide, measured backward from the newest shared sample. Every camera, Leap, audio-derived calibration point, and LOD claim must either land inside that window or leave the live cache.
## Intended Change
The live pipeline now has two measurement-quality paths: sparse marker fusion
for calibrated tracked objects and GPU-owned dense RGB stereo/flow for surface
detail. A CPU dense stereo matcher exists only as a debug reference and is
opt-in through `--cpu-dense-stereo`; production dense fusion may not route
through Python loops. The provisional Kiyo geometry remains a lie detector, not
truth, until `config/sensor-fusion.json` carries measured extrinsics.
The first pipeline slice adds these boundaries:
## Live Flow
```mermaid
flowchart TD
A["Capture adapters"] --> B["FramePacket ring"]
B --> C["Camera quality controller"]
C --> D["manual exposure/gain/focus commands"]
B --> E["Detection adapter"]
E --> F["Observation2D"]
B --> G["Dense stereo matcher"]
H["SensorRig calibration"] --> I["Fusion core"]
F --> I
I --> J["TrackCache"]
F --> Q["stochastic transient matcher"]
Q --> R["scene-ray / LOD cache"]
G --> K["RGB surface claims"]
J --> L["PointCloud PLY"]
J --> M["CultCache RenderFrame document"]
R --> M
K --> M
M --> N["Spout sink / Aquarium GPU renderer"]
N --> O["Spout2 sender texture"]
O --> P["OBS Spout2 source"]
A["direct camera drivers"] --> B["Mimir.Runtime video buffers"]
C["Leap stereo IR driver"] --> B
B --> D["native reservoir handles"]
D --> E["Aquarium GPU feature extraction"]
E --> F["cross-view matching + flow"]
F --> G["surface/material claims"]
G --> H["brush/splat render budget"]
H --> I["Spout2/program video"]
```
## Ownership
## Invariants
- `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.calibration_space` owns fixed-board common-space calibration: ChArUco corner observations plus intrinsics become `CameraModel.world_from_sensor` transforms in one room frame.
- `localcast.sensor_fusion.surface_features` owns cross-view feature observations, descriptor matching, and triangulated surface tracks. It consumes calibrated cameras; it does not invent camera geometry.
- `localcast.sensor_fusion.stochastic_mapping` owns transient feature hypothesis sampling, image-pixel to scene-ray lowering, learned image-ray bias cells, and multi-LOD scene cache packets for later compute-shader reconciliation.
- `localcast.sensor_fusion.camera_control` owns measurement-quality policy: luminance, clipping, contrast, and sharpness in; normalized exposure/gain/focus commands out. Driver adapters own translating those commands to native camera APIs, vendor tools, or no-op mocks.
- `localcast.sensor_fusion.dense_stereo` owns a debug CPU reference for dense calibrated RGB surface claims. It is useful for tests and shader parity, but the live million-splat path belongs to Aquarium/GPU compute.
- `localcast.sensor_fusion.active_illumination` owns deliberate light pulses as calibration telemetry. A Tuya bulb is an optional local-network actuator, not a rendering authority; its pulse timestamps are evidence for camera exposure/depth response.
- `localcast.sensor_fusion.clap_calibration` owns deliberate clap detection: chirplet-synced audio transients nominate oracle timestamps, camera frame windows around that oracle look for motion derivatives, calibrated camera peaks triangulate the impact point, and only audio-plus-visual agreement becomes a clap calibration event.
- `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.diagnostics.visual_cache` owns the typed CultCache document shape
used by diagnostic visual-state files. Production visual state should cross
the native/CultNet boundary directly, not through this Python file adapter.
- `localcast.diagnostics.render_math` owns pure diagnostic render budgeting,
camera projection, brush lowering, and CPU rasterization. It has unit tests
and does not require a GPU context.
- `scripts/sensor_fusion.py` owns CLI composition for offline observation files.
- The Python/OpenGL Spout publisher has been deleted. No Mimir Python
module owns OBS publication.
- `config/sensor-fusion.example.json` owns the declarative rig shape: capture hints, intrinsics, extrinsics, latency, and fusion thresholds.
## Cache Discipline
This follows the same architectural lesson as `fractal-domains-cache-that-bites.md`: state begins as semantic claims in a named domain, then lowers into cheaper packets.
For this project:
```text
sensor observation
-> calibrated world ray
-> triangulated marker claim
-> stochastic transient hypothesis
-> multi-LOD scene cache
-> cached track
-> render frame packet
-> Aquarium brush/splat packet
-> Spout sender texture
-> OBS source
```
The cache is not a bucket. `TrackCache` has a TTL and confidence update rule so the system can buffer and converge without pretending stale points are fresh. The live frame reservoir is explicitly five seconds wide: frame history expires from the newest shared sample, LOD evidence is clipped to that same interval, and each `RenderFramePacket` reports the exact source window. Later GPU buffers should mirror this shape: observation SoA, track SoA, material/BRDF estimate SoA, brush packet SoA.
`visual-lod-cache.json` is the diagnostic CPU-authored shape for the next
compute pass. JSON serialization lives under `localcast.diagnostics.lod_json`,
not in the mapping model. It groups stochastic/fused scene claims into multiple
world-space voxel sizes, carrying center, radius, confidence, count, source-time
bounds, and first-pass material estimates. The material channel is deliberately
modest: weighted albedo plus roughness/metallic hints so Aquarium can start
relighting brush/splat packets without treating screen-space color as the whole
truth. A later shader pass should replace those hints with multi-view BRDF
fitting inside the same reservoir.
## Test Boundaries
The core can be tested without cameras:
- synthetic cameras triangulate a known point
- timestamp windows reject stale pairs
- track cache expiry is deterministic
- raw-frame adapter can be tested from an in-memory byte stream
- fixed-board ChArUco observations solve camera poses into the expected common frame
- matched surface descriptors triangulate to a known 3D point
- stochastic transient matches triangulate descriptor-consistent rays and lower them into a multi-LOD scene cache
- adaptive camera control responds to overexposure without live hardware
- dense stereo turns shifted textured camera pairs into calibrated RGB surface claims
Those tests matter because camera drivers are not unit-test dependencies. They are weather.
## OBS And Spout Boundary
OBS should see a named Spout sender, not a camera window, file tail, or desktop capture. Current references confirm the ordinary Windows path: the Off World Live OBS Spout2 plugin receives Spout shared textures, while the Spout2 SDK is the app-side texture sharing surface.
The intended production handoff is:
```text
Mimir TrackCache
-> CultCache render-frame document
-> Aquarium Engine typed runtime state
-> GPU point/brush/splat buffer
-> D3D render target
-> Spout2 sender named "Mimir Point Cloud"
-> OBS Spout2 Capture source
```
`RenderFramePacket` is the diagnostic Python in-process shape. The diagnostic
file boundary is a typed CultCache MessagePack document. Compatibility JSON
read/write now lives under `localcast.diagnostics.render_frame_json`; the
production packet module does not own file serialization. The production live
boundary is native typed state plus CultNet `document_put`.
Clap calibration events use the same typed-state rule. A clap is not every sharp
audio transient. The detector first finds a sharp broadband audio onset in the
audio oracle timeline, then opens a short camera window around that timestamp
and looks for high frame-derivative peaks per camera. At least the configured
minimum number of cameras must agree; when a calibrated rig is available, their
motion centroids are triangulated into a world-space impact point. The typed
`localcast.calibration.clap_events` document carries stable event id, acoustic
oracle time, visual observed time, timing uncertainty, confidence, world
position, and the contributing camera peaks. Aquarium consumes those events as
high-confidence calibration constraints beside ultrasonic chirplet room evidence.
The current streamable cut is:
```text
CultCache render-frame document
-> Aquarium typed runtime state
-> D3D render target
-> Spout2 sender
-> 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.
Each render frame carries:
- `source_time_min_ns` and `source_time_max_ns`: the observation window that produced the cached points.
- `present_time_ns`: when the visual frame wants to be presented after visual buffering.
- `audio_alignment_time_ns`: the corresponding ambisonic output time.
That lets the final stream compositor buffer point-cloud visuals until they align with the bounded audio-field cache. The renderer may show a slightly older world if the packet is coherent and labeled. It may not quietly mix fresh audio with stale visual geometry and call that sync.
Current live deadline rule: `source_time_max_ns - source_time_min_ns` is five seconds. Late-arriving samples can fill the reservoir while they are inside that window; anything older is evidence for offline calibration, not the live program surface.
The Spout/audio overlay applies the same rule at the consumer boundary. If the visual producer or a camera driver stalls, OBS receives a packet clamped to the current audio edge with stale points removed. The current live fallback mode uses cached/synthetic RGB and Leap frames because the old diagnostic capture path measured slower than the reservoir; real cameras need nonblocking native-driver ingress feeding the same reservoir instead of blocking the producer loop.
- Device timestamps beat arrival timestamps when available.
- Leap is the first timing-camera candidate.
- Process capture is a bridge edge, not the local six-camera foundation.
- Aquarium owns GPU extraction, fusion, material fitting, and render budgeting.
- Runtime buffers own retention and stream health, not scene reconstruction.
## Next Cut
1. Capture ChArUco intrinsics for each camera with `scripts/charuco_calibration.py calibrate`.
2. Capture fixed-board observations from every camera and solve shared extrinsics with `scripts/solve_common_camera_space.py`.
3. Use `scripts/triangulate_surface_features.py` on calibrated image pairs to prove real cross-view surface tracks before promoting the matcher into the live producer.
4. Replace the synthetic stochastic transient observations in
`localcast.diagnostics.visual_producer` with real native/Aquarium ORB/flow
observations from driver-ingested PS3 Eye/Kiyo/Leap frames, then delete the
Python diagnostic producer.
5. Move dense matching and LOD reconciliation from CPU block search/JSON to GPU-resident stereo/flow and compute-shader cache reduction so the million-sample target is not murdered by Python loops.
6. If a Tuya light is available on the local network, run `scripts/pulse_tuya_light.py` with its local key and align pulse timestamps against camera brightness response.
7. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections.
8. Record an observation run from the two PS3 Eyes into typed CultCache docs.
9. Feed `RenderFramePacket` and the multi-LOD scene cache into Aquarium Engine.
10. Publish the render target as a Spout2 sender and receive it in OBS.
11. Delete compatibility JSON render-frame paths once no diagnostic script depends on them.
## References
- Multi-camera calibration and triangulation are the geometry spine. OpenCV may
remain an offline calibration library; it is not live frame ingest. See
`research/visual-spatial-map/summary.md`.
- Jacob and Haeb-Umbach 2015 motivates audio-visual coordinate alignment. See `research/visual-spatial-map/mirrors/krekovic-2015-audio-visual-geometry-calibration.pdf`.
- Kerbl et al. 2023 and RTG-SLAM motivate splats as render packets, not state ownership. See `research/visual-spatial-map/summary.md` and `research/gpu-fusion-splatting/summary.md`.
- Spout2 and the OBS Spout2 plugin are the Windows/OBS texture-sharing bridge. See `research/spout-obs-bridge/summary.md`.
- `E:\Projects\gamecult-site\GameCult\Blog\fractal-domains-cache-that-bites.md` supplies the cache discipline: semantic authority first, backend packet lowering second.
Implement one concrete direct capture driver, feed `MimirVideoFrameDescriptor`
samples into `MimirVideoCaptureDriverSource`, and measure sustained cadence over
the default five-second window.

View file

@ -1,119 +1,15 @@
# Diagnostic Typed Visual State
# Typed Visual State
## Objective
Typed visual state now means native/runtime descriptors and Aquarium-readable
payload handles, not file-polled render documents.
Keep the diagnostic visual file shape as typed CultCache documents and expose
the production boundary as native CultNet document messages.
## Boundary
JSON is no longer the authority for visual state. The diagnostic renderer
consumes `calibration/runs/visual-state.msgpack`, which stores a
`localcast.visual.render_frame` CultCache document. Production visual state must
not be owned by this Python file adapter.
- Capture drivers append frame descriptors.
- The runtime owns stream buffering and health.
- Native reservoir handles preserve shared timing and typed lookup.
- Aquarium decodes visual payloads, runs GPU fusion, and publishes the program
surface.
## Current Mechanism
```mermaid
flowchart TD
A["diagnostics.visual_producer"] --> B["SensorRig.fuse"]
B --> C["RenderFramePacket"]
C --> D["CultRenderFrame"]
X["audio-state.msgpack"] --> Y["audio event overlay"]
Z["audio-events.msgpack"] --> Y
D --> Y
Y --> E["CultCache MessagePack store"]
E --> F["diagnostic readers"]
F --> G["render_math CPU checks"]
G --> H["Aquarium replacement work"]
```
Diagnostic files:
- `calibration/runs/visual-state.msgpack`: typed diagnostic visual frame state.
- `calibration/runs/visual-stream-status.msgpack`: typed diagnostic stream
status state.
- `calibration/runs/stream-spout-status.json`: legacy heartbeat shape for quick
terminal checks when a diagnostic publisher exists.
- `calibration/runs/av-sync-status.json`: visual/audio sync heartbeat shape for
Aquarium/native publishers.
## 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
`localcast.calibration.clap_events`
- schema id: `gamecult.localcast.calibration.clap_events.v1`
- key: `localcast.calibration.clap-events.live`
- payload: MessagePack array, decoded as `CultClapEventsFrame`
- owns: deliberate clap calibration events aligned against the audio timing oracle
- fields: stable key, world position, acoustic oracle timestamp, visual observed timestamp, timing uncertainty in microseconds, visual/acoustic confidence, and contributing camera motion peaks
## 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.
That arrangement is diagnostic scaffolding. Aquarium, native capture, and remote
sensor nodes should publish the same typed document through CultNet
`document_put` messages rather than treating a Python-polled file as live
authority.
The live visual frame may contain multiple claim families. `dense-rgb:*` claims
are calibrated two-camera RGB surface samples from the debug CPU stereo
reference or, in the intended production path, Aquarium/GPU dense stereo and
flow. `room-rgb:*` claims are camera-resolved room/background surface samples;
`host-rgb:*` and `deru-rgb:*` claims are fallback RGB body/object surface
samples; and `leap-motion:*` claims are high-rate LeapUVC packed-channel motion
samples. Leap packed maps are split into explicit green, magenta, red, and blue
channels before publication so the downstream accumulator can use Leap as the
strongest timing/motion witness without pretending the packed image is one
ordinary RGB camera.
Mimir does not own the final splat budget. It publishes dense typed
claims with stable keys and timestamps; Aquarium owns temporal accumulation,
renderer residency, and any GPU-side reduction needed to make million-splat
frames presentable.
## Audio Synchronization
The deleted Python/OpenGL sender used to read `calibration/runs/audio-state.msgpack`
and `calibration/runs/audio-events.msgpack` while rendering the diagnostic
visual frame. That responsibility now belongs in Aquarium/native code: select
source events against `RenderFramePacket.audio_alignment_time_ns`, add
synchronized renderer-visible transient geometry, and write/publish sync status
with visual frame id, audio frame id, audio delta, event counts, and remote
video status.
The audio bed still travels as `localcast.audio.spatial_frame`; the visual render packet only receives renderer-visible transient geometry. That keeps the machine legible: audio owns sound, source-event analysis owns acoustic facts, Aquarium owns the final pixel/audio package for OBS.
The neighbor SRT video feed is also a timed media artifact. OBS/Aquarium must
delay or present the remote video according to the same presentation clock as
the Spout texture and AmbiX bed. This value is presentation delay, not only the
SRT socket's `latency` parameter.
## Cut Line
- Keep: typed CultCache document contracts and MessagePack payloads.
- Keep temporarily: JSON heartbeat for human shell checks.
- Cut next: JSON render-frame polling now that it is isolated under diagnostics.
- Do not add a second scene authority. Sensor fusion owns world claims; renderer owns pixels.
- Do not make OBS synchronize separate sources. Aquarium receives synchronized visual/audio documents and emits the OBS-facing package.
- Do not treat the neighbor SRT video feed as untimed scenery. It is a presentation artifact and belongs in the same sync status as audio and render frames.
Any remaining file export should be treated as a diagnostic artifact, not as a
live data path.

View file

@ -52,7 +52,7 @@ flowchart TD
private buffers, or a parallel synchronization model.
- Missing feeds become explicit absence or silent/blank placeholders inside the
program model. Stale samples do not get stretched into looking current.
- Python may inspect, calibrate, and test. It does not run the live hot path.
- Calibration and diagnostics do not run the live hot path.
## First Viable Cut
@ -126,7 +126,7 @@ to the driver, GPU, and capture APIs.
Leap should be treated as the timing-camera candidate only when the native
adapter preserves device timestamps or captures a monotonic timestamp
immediately on frame receipt. Do not put OpenCV in the live ingest path.
immediately on frame receipt.
## Cut Line