Add live audio field and five-second reservoir

This commit is contained in:
Meta Vens 2026-05-19 01:43:17 +01:00
commit 792d274f7d
12 changed files with 655 additions and 25 deletions

View file

@ -44,6 +44,8 @@ class ActiveConfidenceMaintainer:
pattern: str = "single",
harmonic_root_hz: float = 440.0,
harmonic_voices: int = 24,
max_artifacts: int = 512,
manifest_max_bytes: int = 1_000_000,
):
self.optimizer = optimizer
self.sample_rate = int(sample_rate)
@ -56,10 +58,14 @@ class ActiveConfidenceMaintainer:
self.pattern = str(pattern)
self.harmonic_root_hz = float(harmonic_root_hz)
self.harmonic_voices = int(harmonic_voices)
self.max_artifacts = int(max_artifacts)
self.manifest_max_bytes = int(manifest_max_bytes)
if self.channels <= 0:
raise ValueError("channels must be positive")
if self.channel < 0 or self.channel >= self.channels:
raise ValueError("channel must be inside output channel count")
if self.max_artifacts <= 0:
raise ValueError("max_artifacts must be positive")
self.output_dir.mkdir(parents=True, exist_ok=True)
def update(self, meaning: PhaseFieldMeaning, reference_block: np.ndarray, *, force_masked: bool = False) -> EmittedProbe | None:
@ -80,7 +86,8 @@ class ActiveConfidenceMaintainer:
harmonic_root_hz=self.harmonic_root_hz,
harmonic_voices=self.harmonic_voices,
)
path = self.output_dir / f"probe-{meaning.frame_id:08d}-{request.source_id}.wav"
slot = meaning.frame_id % self.max_artifacts
path = self.output_dir / f"probe-slot-{slot:04d}-{request.source_id}.wav"
wavfile.write(path, self.sample_rate, waveform.astype(np.float32))
emitted = EmittedProbe(
request=request,
@ -92,7 +99,11 @@ class ActiveConfidenceMaintainer:
path=path,
emitted_monotonic_ns=time.monotonic_ns(),
)
append_probe_manifest(self.output_dir / "active-probes.jsonl", emitted)
append_probe_manifest(
self.output_dir / "active-probes.jsonl",
emitted,
max_bytes=self.manifest_max_bytes,
)
return emitted
@ -239,7 +250,7 @@ def db_to_amp(db: float) -> float:
return float(math.pow(10.0, float(db) / 20.0))
def append_probe_manifest(path: Path, emitted: EmittedProbe) -> None:
def append_probe_manifest(path: Path, emitted: EmittedProbe, *, max_bytes: int = 1_000_000) -> None:
row = {
"frameIndex": emitted.request.frame_index,
"sourceId": emitted.request.source_id,
@ -254,5 +265,8 @@ def append_probe_manifest(path: Path, emitted: EmittedProbe) -> None:
"path": str(emitted.path),
"emittedMonotonicNs": emitted.emitted_monotonic_ns,
}
if path.exists() and path.stat().st_size > int(max_bytes):
previous = path.with_name(f"{path.stem}.previous{path.suffix}")
path.replace(previous)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(row, sort_keys=True) + "\n")

View file

@ -138,7 +138,15 @@ Close the confidence loop by letting the phase-field stream schedule strategic a
.\.venv\Scripts\python.exe .\scripts\stream_phase_field.py --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 each emitted chirplet to `calibration/runs/active-probes`, and appends `active-probes.jsonl`. `--play-probes` sends the emitted chirplet to the default 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.
`--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.
For the current deadline rig, `scripts/stream_live_audio_field.py` owns the live local path:
```powershell
.\.venv\Scripts\python.exe .\scripts\stream_live_audio_field.py --profile .\config\audio-field.example.json --loopback-query Scarlett --maintain-confidence --play-probes --probe-output-query Scarlett
```
It publishes both `audio-mic-field.msgpack` and `audio-phase-field.msgpack` from visible local mics, records missing distributed channels as explicit placeholders, captures Scarlett loopback as the known reference, and resamples probe playback when the Scarlett output is exposed as 44.1 kHz while the capture field remains 48 kHz.
For the current live app, start the dense harmonic confidence-maintenance loop:
@ -261,7 +269,7 @@ The audio code is split so the hard parts can be tested without the room, driver
- `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 probe WAVs plus a manifest, and optionally plays them.
- `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.

View file

@ -31,6 +31,7 @@
- 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.
- `localcast.sensor_fusion.chirp_pose` converts live phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints and per-camera pose-correction estimates. It can load camera-mic and speaker geometry from the audio-field profile, with the example profile used as the live fallback until measured local geometry exists. `scripts/live_sensor_fusion.py` injects those constraints as `camera-chirp:*` and `camera-pose-correction:*` render points plus `chirp-camera-pose` LOD evidence.
- `scripts/stream_spout.py` runs the deadline Spout sender loop from the typed cache with typed and JSON heartbeat status.
- The deadline Spout renderer has a named `kiyo-mid-deru` virtual camera preset: eye at the midpoint between the two Kiyo-class cameras and target on the co-streamer body volume. It also applies a renderer-owned point budget with pinned calibration/cross-modal constraints, stable high-confidence anchors, and frame-varying remainder samples so downstream TAA/supersampling can accumulate detail without forcing every source claim into every OBS frame. Its JSON heartbeat reports the prefix counts that survived the render budget.
@ -48,6 +49,8 @@
- `scripts/stream_phase_field.py` publishes the live meaning document from an aligned mic field plus known program/loopback reference without exposing raw phase bands as the renderer API.
- `stream_phase_field.py` also writes `audio-phase-field-status.json`, which declares whether the phase estimator is running against replayed WAVs or closed-loop live capture. Current deadline mode is explicit `wav-replay` with open-loop probe playback.
- `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.
- `scripts/stream_live_audio_field.py` is the live local capture owner for the deadline rig. It publishes `localcast.audio.mic_field` and `localcast.audio.phase_field` from visible local WASAPI/PortAudio mics plus Scarlett loopback, reports missing rig channels as explicit placeholders, plays confidence probes through the selected Scarlett output, and resamples probe playback when the output device runs at 44.1 kHz while the field timeline remains 48 kHz.
- 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.
- `scripts/start-live-audio-phase-field.ps1` starts the live dense harmonic confidence loop with near-ultrasonic probes; `scripts/stop-live-audio-phase-field.ps1` stops the PID recorded in `logs/audio-phase-field.pid`.
- Faust voice-separation boundary:
- `localcast.audio.mic_field` publishes aligned six-mic float32 blocks at `calibration/runs/audio-mic-field.msgpack`.
@ -81,4 +84,4 @@
16. Fix the live Leap capture backend so actual Leap frames, not fallback frames, populate `leap-ground-truth` cells in the multi-LOD cache.
17. Keep the neighbor loopback leg running through the scheduled interactive WASAPI capture path and use it as the timing witness once actual neighbor app audio is present.
18. Let the co-streamer surface delay drive the shared presentation buffer horizon for audio stems, AmbiX, and remote video.
19. Wire `stream_phase_field.py` and `stream_faust_mic_field.py` to the real live aligned-field producer instead of replaying WAV artifacts, then feed emitted active chirps back through loopback/mic capture so `audio-phase-field-status.json` can report closed-loop probe capture.
19. Promote `scripts/stream_live_audio_field.py` from local deadline owner to the distributed owner by feeding it the neighbor Focusrite shotgun and neighbor loopback surfaces as synchronized live inputs instead of placeholders.

View file

@ -24,6 +24,7 @@ deadline scaffolding, but it is not enough for detailed reconstruction.
- 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
@ -96,9 +97,9 @@ sensor observation
-> 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. Later GPU buffers should mirror this shape: observation SoA, track SoA, brush packet SoA.
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 current CPU-authored shape for the next compute pass. It is not the final renderer. It groups stochastic/fused scene claims into multiple world-space voxel sizes, carrying center, radius, confidence, count, and source-time bounds so an Aquarium compute shader can reconcile fine and coarse claims without pulling the whole observation history through the renderer.
`visual-lod-cache.json` is the current CPU-authored shape for the next compute pass. It is not the final renderer. It groups stochastic/fused scene claims into multiple world-space voxel sizes, carrying center, radius, confidence, count, and source-time bounds so an Aquarium compute shader can reconcile fine and coarse claims without pulling anything older than the reservoir through the renderer.
## Test Boundaries
@ -169,6 +170,8 @@ Each render frame carries:
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.
## Next Cut
1. Capture ChArUco intrinsics for each camera with `scripts/charuco_calibration.py calibrate`.

View file

@ -106,8 +106,9 @@ class CameraClockSyncModel:
class TimestampedFrameHistory:
def __init__(self, max_frames: int = 120) -> None:
def __init__(self, max_frames: int = 120, max_age_ns: int | None = None) -> None:
self.max_frames = max(2, int(max_frames))
self.max_age_ns = None if max_age_ns is None else max(0, int(max_age_ns))
self._frames: dict[str, list[TimestampedFrame]] = {}
def add(self, frame: TimestampedFrame) -> None:
@ -117,6 +118,7 @@ class TimestampedFrameHistory:
bucket.append(frame)
bucket.sort(key=lambda item: item.timestamp_ns)
del bucket[:-self.max_frames]
self._expire_by_shared_latest()
def add_many(self, frames: Mapping[str, TimestampedFrame]) -> None:
for frame in frames.values():
@ -132,6 +134,29 @@ class TimestampedFrameHistory:
target = int(raw_time_ns)
return min(frames, key=lambda frame: abs(frame.timestamp_ns - target))
def latest_timestamp_ns(self) -> int | None:
latest = None
for frames in self._frames.values():
if frames:
timestamp = frames[-1].timestamp_ns
latest = timestamp if latest is None else max(latest, timestamp)
return latest
def _expire_by_shared_latest(self) -> None:
if self.max_age_ns is None:
return
latest = self.latest_timestamp_ns()
if latest is None:
return
cutoff = latest - self.max_age_ns
empty: list[str] = []
for sensor_id, frames in self._frames.items():
self._frames[sensor_id] = [frame for frame in frames if frame.timestamp_ns >= cutoff]
if not self._frames[sensor_id]:
empty.append(sensor_id)
for sensor_id in empty:
del self._frames[sensor_id]
def detect_audio_transients(
field: np.ndarray,

View file

@ -73,8 +73,9 @@ Ownership:
- `audio_field/` owns unit-testable buffering, bounded-latency convergence, injectable port protocols, and pipeline orchestration.
- Runtime sync owns per-block chirplet observations from known speaker output and updates delay/SRO/phase estimates with confidence gates before alignment.
- `audio_field.phase_meaning` owns extracting usable meaning from internal phase/chirplet evidence. The live cache publishes delay correction, coherence, confidence, distance-equivalent delta, reference-bleed/suppression estimates, correction energy, and active-probe need; raw phase bands stay inside the estimator.
- `stream_phase_field.py` writes `audio-phase-field-status.json` beside the typed phase cache. That status declares the current input mode and whether active probes are actually closed-loop. Current deadline mode is `wav-replay` with open-loop playback, so low confidence is a data-path truth rather than a mysterious estimator mood.
- Active probe optimization owns extra chirplet emission when confidence drops, bounded by level/spacing/audibility budget. `audio_field.active_probe` is the runtime join that converts phase-field confidence into emitted chirplet WAVs/manifests and optional default-device playback.
- `scripts/stream_live_audio_field.py` is the current live local capture owner. It publishes `localcast.audio.mic_field` and `localcast.audio.phase_field` from the visible local Kiyo/PS Eye/Scarlett inputs, uses Scarlett loopback as the known reference, and keeps missing neighbor/Kiyo-right channels as explicit placeholders until synchronized feeds exist.
- `audio-phase-field-status.json` declares the phase runtime mode. Current deadline mode is `live-local-capture` with closed-loop probe capture when Scarlett loopback is available.
- Active probe optimization owns extra chirplet emission when confidence drops, bounded by level/spacing/audibility budget. `audio_field.active_probe` is the runtime join that converts phase-field confidence into emitted chirplet WAVs/manifests and playback. Probe WAVs rotate through fixed slots and the manifest rotates at a byte cap; calibration may be dense, but artifacts must stay bounded.
- The camera/sensor-fusion pipeline may publish world poses later; it does not own audio clocks or channel timing.
- OBS may ingest rendered output later; it is not the authority for the Ambisonic field.
- Aquarium/Faust owns hot voice separation after LocalCastBridge publishes `localcast.audio.mic_field`; LocalCastBridge owns alignment, timing, mic roles, graph id, and controls.
@ -107,13 +108,14 @@ Ownership:
- `scripts/live_sensor_fusion.py` currently owns the live producer and writes `localcast.visual.render_frame` into CultCache.
- The live producer now keeps a rolling RGB/Leap frame window for clap calibration. Kiyo stereo motion gives the first rough 3D clap position; Leap participates as the high-precision visual timing witness until a calibrated Leap geometric model joins the rig.
- Clap peaks update a per-camera clock sync model. Camera history sampling uses `oracle_time - camera_offset`, so the point builder can reconstruct a shared instant instead of mixing latest frames from different clock domains.
- The live producer's temporal authority is a five-second spatiotemporal reservoir measured backward from the newest shared sample. RGB/Leap history expires against that shared edge, LOD evidence is clipped to the same window, and each render frame declares the exact reservoir slice with `source_time_min_ns` and `source_time_max_ns`.
- `localcast.sensor_fusion.chirp_pose` now turns phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints and per-camera pose-correction estimates. It loads camera-mic and speaker geometry from the audio-field profile when available, falling back to the example profile/defaults. The live producer publishes those constraints as `camera-chirp:*` and `camera-pose-correction:*` render points plus `chirp-camera-pose` LOD evidence. Audio range/timing evidence augments visual calibration; it does not own image geometry.
- The Spout point-budget policy pins calibration and cross-modal constraints before spending the remaining adaptive LOD budget on stable high-priority surface claims and frame-rotated samples. Its JSON heartbeat reports the prefix counts that survived the render budget.
- The live producer also writes a multi-LOD scene cache with source kind and priority. Real Leap frames are the highest-priority timing/spatial evidence; Leap fallback frames are tagged as fallback and do not become ground truth.
- `scripts/stream_spout.py` consumes typed CultCache state and publishes Spout. Its presentation camera defaults to `kiyo-mid-deru`: the virtual eye sits halfway between the two Kiyo-class cameras and aims at the co-streamer body target. Its render budget is temporal: high-confidence anchors stay stable while the remaining samples rotate by frame id for TAA/supersampling reconciliation.
- CultNet document replication is the intended API boundary for other producers/consumers.
Invariant: JSON is not the visual-state authority. The current renderer can still write a JSON heartbeat for human inspection, but live visual state lives in typed CultCache MessagePack documents. Leap outranks camera surfaces only when the frame source is actual Leap capture; diagnostics must stay labeled as diagnostics.
Invariant: JSON is not the visual-state authority. The current renderer can still write a JSON heartbeat for human inspection, but live visual state lives in typed CultCache MessagePack documents. Leap outranks camera surfaces only when the frame source is actual Leap capture; diagnostics must stay labeled as diagnostics. The reservoir horizon is five seconds; producers may fill gaps as late samples arrive inside that window, but they may not silently preserve older evidence in the live fusion cache.
## OBS Program Surface

View file

@ -48,6 +48,9 @@ from localcast.sensor_fusion.camera_control import AdaptiveCameraController, Ope
from audio_field.cultcache_audio import frame_to_numpy, get_live_audio_phase_field, get_live_spatial_audio_frame
DEFAULT_RESERVOIR_NS = 5_000_000_000
def acquire_runtime_lock(path: Path) -> BinaryIO | None:
import msvcrt
@ -65,6 +68,16 @@ def acquire_runtime_lock(path: Path) -> BinaryIO | None:
return handle
def reservoir_window_ns(latest_timestamp_ns: int, reservoir_ns: int) -> tuple[int, int]:
end_ns = int(latest_timestamp_ns)
return end_ns - int(reservoir_ns), end_ns
def evidence_in_reservoir(evidence: tuple, *, latest_timestamp_ns: int, reservoir_ns: int) -> tuple:
start_ns, end_ns = reservoir_window_ns(latest_timestamp_ns, reservoir_ns)
return tuple(item for item in evidence if start_ns <= int(item.timestamp_ns) <= end_ns)
def camera(sensor_id: str, x: float) -> CameraModel:
return CameraModel(
sensor_id=sensor_id,
@ -278,6 +291,7 @@ class RgbSplatSampler:
enable_cpu_dense_stereo: bool,
adaptive_controls: bool,
fallback_dir: Path,
reservoir_ns: int = DEFAULT_RESERVOIR_NS,
) -> None:
self.api = api
self.primary_index = primary_index
@ -293,7 +307,7 @@ class RgbSplatSampler:
self._captures: dict[int, object] = {}
self._frames: dict[int, np.ndarray] = {}
self._timestamped_frames: dict[str, TimestampedFrame] = {}
self._history = TimestampedFrameHistory(max_frames=96)
self._history = TimestampedFrameHistory(max_frames=720, max_age_ns=reservoir_ns)
self._controllers: dict[int, AdaptiveCameraController] = {}
self._setting_ports: dict[int, OpenCvCameraSettingPort] = {}
@ -496,12 +510,13 @@ class LiveClapCalibrator:
clap_cache: Path,
camera_width: int,
camera_height: int,
max_frames_per_sensor: int = 24,
max_frames_per_sensor: int = 720,
reservoir_ns: int = DEFAULT_RESERVOIR_NS,
) -> None:
self.audio_cache = audio_cache
self.clap_cache = clap_cache
self.max_frames_per_sensor = max(2, int(max_frames_per_sensor))
self.history = TimestampedFrameHistory(max_frames=self.max_frames_per_sensor)
self.history = TimestampedFrameHistory(max_frames=self.max_frames_per_sensor, max_age_ns=reservoir_ns)
self.sync_model = CameraClockSyncModel()
self.last_audio_frame_id: int | None = None
self.last_audio_time_ns: int | None = None
@ -510,7 +525,7 @@ class LiveClapCalibrator:
right = rgb_dense_camera("kiyo-secondary", 0.18, camera_width, camera_height)
self.rig = SensorRig(
cameras={left.sensor_id: left, right.sensor_id: right},
config=FusionConfig(max_pair_dt_ns=80_000_000, max_reprojection_error_px=80.0, cache_ttl_ns=1_000_000_000),
config=FusionConfig(max_pair_dt_ns=80_000_000, max_reprojection_error_px=80.0, cache_ttl_ns=reservoir_ns),
)
self.config = ClapDetectorConfig(
audio_window_samples=96,
@ -1132,13 +1147,15 @@ def main() -> None:
parser.add_argument("--no-clap-calibration", action="store_true")
parser.add_argument("--no-chirp-pose", action="store_true")
parser.add_argument("--no-stochastic-transients", action="store_true")
parser.add_argument("--reservoir-seconds", type=float, default=5.0)
args = parser.parse_args()
reservoir_ns = max(1, int(round(args.reservoir_seconds * 1_000_000_000)))
left = camera("ps3eye_left", -0.25)
right = camera("ps3eye_right", 0.25)
rig = SensorRig(
cameras={left.sensor_id: left, right.sensor_id: right},
config=FusionConfig(max_pair_dt_ns=30_000_000, max_reprojection_error_px=0.01, cache_ttl_ns=500_000_000),
config=FusionConfig(max_pair_dt_ns=30_000_000, max_reprojection_error_px=0.01, cache_ttl_ns=reservoir_ns),
)
render_config = RenderBridgeConfig(default_point_radius_m=0.035)
interval = 1.0 / max(1.0, args.fps)
@ -1161,6 +1178,7 @@ def main() -> None:
enable_cpu_dense_stereo=args.cpu_dense_stereo,
adaptive_controls=not args.no_adaptive_camera_controls,
fallback_dir=ROOT / "calibration" / "runs",
reservoir_ns=reservoir_ns,
)
leap_sampler = None if args.no_leap else LeapPackedMotionSampler(
api=args.leap_api,
@ -1176,6 +1194,7 @@ def main() -> None:
clap_cache=Path(args.clap_cache),
camera_width=args.rgb_width,
camera_height=args.rgb_height,
reservoir_ns=reservoir_ns,
)
audio_profile = Path(args.audio_profile)
if not audio_profile.exists() and audio_profile.name == "audio-field.json":
@ -1236,13 +1255,19 @@ def main() -> None:
stochastic_points = transient_match_render_points(transient_matches, timestamp_ns)
clap_points = () if clap_calibrator is None else clap_calibrator.update(timestamp_ns)
chirp_pose_points = () if chirp_pose_mapper is None else chirp_pose_mapper.update(timestamp_ns)
multilod_cache_from_evidence(
evidence = evidence_in_reservoir(
evidence_from_render_points(leap_points, source_kind=leap_source_kind, source_priority=leap_source_priority)
+ evidence_from_render_points(rgb_points, source_kind="rgb-surface", source_priority=1.4)
+ evidence_from_render_points(clap_points, source_kind="clap-calibration", source_priority=2.4)
+ evidence_from_render_points(chirp_pose_points, source_kind="chirp-camera-pose", source_priority=1.8)
+ evidence_from_fusion_items(transient_matches, source_kind="stochastic-transient", source_priority=1.2)
+ evidence_from_fusion_items(result.points, source_kind="synthetic-fusion", source_priority=0.8),
latest_timestamp_ns=timestamp_ns,
reservoir_ns=reservoir_ns,
)
source_time_min_ns, source_time_max_ns = reservoir_window_ns(timestamp_ns, reservoir_ns)
multilod_cache_from_evidence(
evidence,
levels=(0.01, 0.04, 0.16, 0.64),
created_monotonic_ns=time.monotonic_ns(),
).write_json(lod_cache_path)
@ -1250,8 +1275,8 @@ def main() -> None:
schema=frame.schema,
frame_id=frame.frame_id,
created_monotonic_ns=frame.created_monotonic_ns,
source_time_min_ns=frame.source_time_min_ns,
source_time_max_ns=timestamp_ns,
source_time_min_ns=source_time_min_ns,
source_time_max_ns=source_time_max_ns,
present_time_ns=timestamp_ns + render_config.visual_delay_ns,
audio_alignment_time_ns=timestamp_ns + render_config.audio_alignment_delay_ns,
spout_sender_name=frame.spout_sender_name,

View file

@ -0,0 +1,463 @@
import argparse
import json
import math
from pathlib import Path
import queue
import sys
import time
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from audio_field.active_probe import ActiveConfidenceMaintainer # noqa: E402
from audio_field.cultcache_audio import ( # noqa: E402
DEFAULT_MIC_FIELD_CHANNELS,
make_audio_phase_field,
make_mic_field_frame,
put_live_audio_phase_field,
put_live_mic_field_frame,
)
from audio_field.phase_meaning import LivePhaseMeaningExtractor # noqa: E402
from audio_field.probe_optimizer import ActiveProbeOptimizer, ProbePolicy # noqa: E402
from localcast.sensor_fusion import camera_sensor_id_for_microphone, phase_source_id_for_microphone # noqa: E402
HOST_SOURCE_BY_MIC_ID = {
"mic_focusrite_local": "host-focusrite",
"mic_focusrite_neighbor": "co-streamer-focusrite",
}
def load_profile(path: Path) -> dict:
return json.loads(Path(path).read_text(encoding="utf-8"))
def source_id_for_microphone(mic: dict) -> str | None:
return str(mic.get("phaseSourceId") or mic.get("sourceId") or HOST_SOURCE_BY_MIC_ID.get(str(mic.get("id", ""))) or phase_source_id_for_microphone(mic) or "")
def local_microphones(profile: dict, machine: str) -> list[dict]:
return [mic for mic in profile.get("microphones", []) if mic.get("machine") == machine and source_id_for_microphone(mic)]
def summarize_device(device: dict) -> dict:
return {
"index": int(device["index"]),
"name": str(device["name"]),
"hostapi": str(device.get("hostapi_name", "")),
"inputs": int(device.get("max_input_channels", 0)),
"outputs": int(device.get("max_output_channels", 0)),
"default_samplerate": float(device.get("default_samplerate", 0.0)),
}
def find_devices(sd, spec: dict, direction: str) -> list[dict]:
hostapis = sd.query_hostapis()
devices = sd.query_devices()
query = str(spec.get("query") or "").lower()
hostapi_name = str(spec.get("hostApi") or "").lower()
needed_channels = int(spec.get("channels") or 1)
channel_key = "max_input_channels" if direction == "input" else "max_output_channels"
matches = []
for device in devices:
if int(device[channel_key]) < needed_channels:
continue
hostapi = hostapis[device["hostapi"]]["name"]
if query and query not in str(device["name"]).lower():
continue
if hostapi_name and hostapi_name not in str(hostapi).lower():
continue
matches.append({**device, "hostapi_name": hostapi})
return matches
def match_indexed_device(sd, spec: dict, direction: str) -> dict:
matches = find_devices(sd, spec, direction)
match_index = int(spec.get("matchIndex", 0))
if match_index < 0 or match_index >= len(matches):
raise RuntimeError(f"No {direction} device match {match_index} for {spec!r}; found {len(matches)}")
return matches[match_index]
def local_device_groups(sd, mics: list[dict]) -> tuple[dict[str, dict], list[dict]]:
groups: dict[str, dict] = {}
missing = []
for mic in mics:
try:
device = match_indexed_device(sd, mic.get("device", {}), "input")
except RuntimeError as exc:
missing.append({"micId": mic.get("id"), "sourceId": source_id_for_microphone(mic), "error": str(exc)})
continue
channel = int(mic.get("device", {}).get("channel", 0))
key = str(device["index"])
groups.setdefault(key, {"device": device, "mics": [], "channels": channel + 1})
groups[key]["mics"].append(mic)
groups[key]["channels"] = max(int(groups[key]["channels"]), channel + 1)
return groups, missing
class InputGroupBuffer:
def __init__(self) -> None:
self.queue: queue.Queue[np.ndarray] = queue.Queue()
self.leftover = np.zeros((0, 0), dtype=np.float32)
def push(self, block: np.ndarray) -> None:
self.queue.put(np.asarray(block, dtype=np.float32).copy())
def read(self, frames: int, channels: int, timeout: float = 1.0) -> np.ndarray:
if self.leftover.shape[1] != channels:
self.leftover = np.zeros((0, channels), dtype=np.float32)
chunks = [self.leftover]
total = int(self.leftover.shape[0])
deadline = time.monotonic() + float(timeout)
while total < frames and time.monotonic() < deadline:
try:
item = self.queue.get(timeout=max(0.01, min(0.1, deadline - time.monotonic())))
except queue.Empty:
continue
if item.ndim == 1:
item = item[:, None]
if item.shape[1] < channels:
padded = np.zeros((item.shape[0], channels), dtype=np.float32)
padded[:, : item.shape[1]] = item
item = padded
chunks.append(item[:, :channels])
total += int(item.shape[0])
merged = np.concatenate(chunks, axis=0) if chunks else np.zeros((0, channels), dtype=np.float32)
if merged.shape[0] < frames:
padded = np.zeros((frames, channels), dtype=np.float32)
padded[: merged.shape[0]] = merged
self.leftover = np.zeros((0, channels), dtype=np.float32)
return padded
block = merged[:frames]
self.leftover = merged[frames:]
return block
def make_source_rows(meaning) -> list[dict]:
return [
{
"sourceId": source.source_id,
"channel": source.channel,
"delaySamples": source.smoothed_delay_samples,
"delayMs": source.delay_ms,
"distanceDeltaMeters": source.distance_delta_m,
"coherence": source.coherence,
"fitErrorRadians": source.fit_error_radians,
"confidence": source.confidence,
"referenceBleed": source.reference_bleed,
"suppressionWeight": source.suppression_weight,
"correctionEnergy": source.correction_energy,
}
for source in meaning.sources
]
def write_status(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({**payload, "updated_monotonic_ns": time.monotonic_ns()}, indent=2, sort_keys=True), encoding="utf-8")
def open_loopback_recorder(query: str, sample_rate: int, channels: int):
import soundcard as sc
matches = [
mic
for mic in sc.all_microphones(include_loopback=True)
if "loopback" in repr(mic).lower() and query.lower() in mic.name.lower()
]
if not matches:
raise RuntimeError(f"No loopback device matching {query!r}")
return matches[0].recorder(samplerate=sample_rate, channels=channels)
def play_probe_file(path: Path, *, device: int | None = None, output_rate: int | None = None) -> None:
from scipy.io import wavfile
from scipy import signal
import sounddevice as sd
rate, data = wavfile.read(path)
data = np.asarray(data, dtype=np.float32)
playback_rate = int(output_rate or rate)
if playback_rate != int(rate):
divisor = math.gcd(int(rate), playback_rate)
data = signal.resample_poly(data, playback_rate // divisor, int(rate) // divisor, axis=0).astype(np.float32)
sd.play(data, playback_rate, device=device, blocking=False)
def main() -> None:
parser = argparse.ArgumentParser(description="Capture local live mics into Faust/phase CultCache fields.")
parser.add_argument("--profile", type=Path, default=ROOT / "config" / "audio-field.json")
parser.add_argument("--fallback-profile", type=Path, default=ROOT / "config" / "audio-field.example.json")
parser.add_argument("--machine", default="local")
parser.add_argument("--mic-cache", type=Path, default=ROOT / "calibration" / "runs" / "audio-mic-field.msgpack")
parser.add_argument("--phase-cache", type=Path, default=ROOT / "calibration" / "runs" / "audio-phase-field.msgpack")
parser.add_argument("--status", type=Path, default=ROOT / "calibration" / "runs" / "live-audio-field-status.json")
parser.add_argument("--phase-status", type=Path, default=ROOT / "calibration" / "runs" / "audio-phase-field-status.json")
parser.add_argument("--sample-rate", type=int)
parser.add_argument("--chunk-frames", type=int, default=1024)
parser.add_argument("--duration", type=float)
parser.add_argument("--loopback-query", default="Scarlett")
parser.add_argument("--loopback-channels", type=int, default=2)
parser.add_argument("--no-loopback", action="store_true")
parser.add_argument("--maintain-confidence", action="store_true")
parser.add_argument("--target-confidence", type=float, default=0.72)
parser.add_argument("--trigger-confidence", type=float, default=0.45)
parser.add_argument("--min-probe-interval-frames", type=int, default=1)
parser.add_argument("--probe-level-dbfs", type=float, default=-24.0)
parser.add_argument("--probe-seconds", type=float, default=0.08)
parser.add_argument("--probe-output-dir", type=Path, default=ROOT / "calibration" / "runs" / "active-probes")
parser.add_argument("--probe-artifact-slots", type=int, default=512)
parser.add_argument("--probe-manifest-max-bytes", type=int, default=1_000_000)
parser.add_argument("--probe-output-query", default="Scarlett")
parser.add_argument("--probe-output-hostapi", default="WASAPI")
parser.add_argument("--probe-output-match-index", type=int, default=0)
parser.add_argument("--probe-start-hz", type=float, default=18500.0)
parser.add_argument("--probe-end-hz", type=float, default=22000.0)
parser.add_argument("--harmonic-root-hz", type=float, default=440.0)
parser.add_argument("--harmonic-voices", type=int, default=48)
parser.add_argument("--play-probes", action="store_true")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
profile_path = args.profile if args.profile.exists() else args.fallback_profile
profile = load_profile(profile_path)
sample_rate = int(args.sample_rate or profile.get("sampleRate", 48000))
channels = DEFAULT_MIC_FIELD_CHANNELS
source_index = {source_id: index for index, source_id in enumerate(channels)}
mics = local_microphones(profile, args.machine)
import sounddevice as sd
groups, missing = local_device_groups(sd, mics)
status_base = {
"input_mode": "live-local-capture",
"profile": str(profile_path),
"sample_rate": sample_rate,
"channels": list(channels),
"local_mics": [
{
"micId": mic.get("id"),
"sourceId": source_id_for_microphone(mic),
"cameraSensorId": camera_sensor_id_for_microphone(mic),
"device": mic.get("device"),
}
for mic in mics
],
"missing": missing,
"device_groups": [
{"device": summarize_device(group["device"]), "channels": int(group["channels"]), "mics": [mic.get("id") for mic in group["mics"]]}
for group in groups.values()
],
}
if args.dry_run:
write_status(args.status, {**status_base, "running": False, "dry_run": True})
print(json.dumps(status_base, indent=2))
return
buffers = {key: InputGroupBuffer() for key in groups}
streams = []
for key, group in groups.items():
buffer = buffers[key]
def callback(indata, frame_count, time_info, status, *, target=buffer):
target.push(indata)
streams.append(
sd.InputStream(
device=group["device"]["index"],
channels=int(group["channels"]),
samplerate=sample_rate,
dtype="float32",
callback=callback,
)
)
loopback_context = None
loopback_recorder = None
loopback_error = ""
if not args.no_loopback:
try:
loopback_context = open_loopback_recorder(args.loopback_query, sample_rate, args.loopback_channels)
loopback_recorder = loopback_context.__enter__()
except Exception as exc:
loopback_error = repr(exc)
loopback_context = None
loopback_recorder = None
probe_output_device = None
probe_output_error = ""
if args.play_probes:
try:
probe_output_device = match_indexed_device(
sd,
{
"query": args.probe_output_query,
"hostApi": args.probe_output_hostapi,
"channels": 2,
"matchIndex": args.probe_output_match_index,
},
"output",
)
except Exception as exc:
probe_output_error = repr(exc)
extractor = LivePhaseMeaningExtractor(channels, sample_rate, [250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 12000.0])
maintainer = None
if args.maintain_confidence:
maintainer = ActiveConfidenceMaintainer(
ActiveProbeOptimizer(
ProbePolicy(
target_confidence=args.target_confidence,
trigger_confidence=args.trigger_confidence,
min_interval_frames=args.min_probe_interval_frames,
max_probe_level_dbfs=args.probe_level_dbfs,
prefer_masked_windows=False,
)
),
sample_rate=sample_rate,
output_dir=args.probe_output_dir,
duration_seconds=args.probe_seconds,
start_hz=args.probe_start_hz,
end_hz=args.probe_end_hz,
channels=2,
channel=0,
pattern="harmonic-dense",
harmonic_root_hz=args.harmonic_root_hz,
harmonic_voices=args.harmonic_voices,
max_artifacts=args.probe_artifact_slots,
manifest_max_bytes=args.probe_manifest_max_bytes,
)
start = time.monotonic()
origin_ns = time.monotonic_ns()
frame_id = 0
last_status = 0.0
last_probe = None
probe_playback_error = ""
try:
for stream in streams:
stream.start()
while True:
now = time.monotonic()
if args.duration is not None and now - start >= args.duration:
break
field = np.zeros((args.chunk_frames, len(channels)), dtype=np.float32)
for key, group in groups.items():
block = buffers[key].read(args.chunk_frames, int(group["channels"]))
for mic in group["mics"]:
source_id = source_id_for_microphone(mic)
if source_id not in source_index:
continue
device_channel = int(mic.get("device", {}).get("channel", 0))
if device_channel < block.shape[1]:
field[:, source_index[source_id]] = block[:, device_channel]
if loopback_recorder is not None:
reference_block = loopback_recorder.record(numframes=args.chunk_frames)
reference = np.asarray(reference_block, dtype=np.float32)
if reference.ndim == 2:
reference = np.mean(reference, axis=1)
else:
reference = np.zeros(args.chunk_frames, dtype=np.float32)
audio_time_ns = origin_ns + int(frame_id * args.chunk_frames * 1_000_000_000 / sample_rate)
put_live_mic_field_frame(
args.mic_cache,
make_mic_field_frame(field, frame_id=frame_id, sample_rate=sample_rate, start_sample=frame_id * args.chunk_frames, audio_time_ns=audio_time_ns, channels=channels),
)
meaning = extractor.update(reference, field, frame_id=frame_id, start_sample=frame_id * args.chunk_frames, audio_time_ns=audio_time_ns)
put_live_audio_phase_field(
args.phase_cache,
make_audio_phase_field(
frame_id=meaning.frame_id,
sample_rate=meaning.sample_rate,
start_sample=meaning.start_sample,
frame_count=meaning.frame_count,
audio_time_ns=meaning.audio_time_ns,
reference_id="local-loopback-live",
sources=make_source_rows(meaning),
global_confidence=meaning.global_confidence,
needs_active_probe=meaning.needs_active_probe,
active_probe_reason=meaning.active_probe_reason,
),
)
emitted = None
if maintainer is not None:
emitted = maintainer.update(meaning, reference, force_masked=True)
if emitted is not None:
last_probe = {
"source_id": emitted.request.source_id,
"reason": emitted.request.reason,
"urgency": emitted.request.urgency,
"path": str(emitted.path),
"emitted_monotonic_ns": emitted.emitted_monotonic_ns,
}
if emitted is not None and args.play_probes:
try:
play_probe_file(
emitted.path,
device=None if probe_output_device is None else int(probe_output_device["index"]),
output_rate=None
if probe_output_device is None
else int(round(float(probe_output_device["default_samplerate"]))),
)
probe_playback_error = ""
except Exception as exc:
probe_playback_error = repr(exc)
if now - last_status >= 1.0:
live_payload = {
**status_base,
"running": True,
"dry_run": False,
"frame_id": frame_id,
"closed_loop_probe_capture": loopback_recorder is not None,
"loopback_query": args.loopback_query,
"loopback_error": loopback_error,
"probe_output": None if probe_output_device is None else summarize_device(probe_output_device),
"probe_output_error": probe_output_error,
"probe_playback_error": probe_playback_error,
"global_confidence": meaning.global_confidence,
"needs_active_probe": meaning.needs_active_probe,
"maintain_confidence": args.maintain_confidence,
"play_probes": args.play_probes,
"last_probe": last_probe,
}
write_status(args.status, live_payload)
write_status(
args.phase_status,
{
"input_mode": "live-local-capture",
"field": "sounddevice-local-mics",
"reference": "soundcard-loopback" if loopback_recorder is not None else "missing-loopback-zero-reference",
"frame_id": frame_id,
"global_confidence": meaning.global_confidence,
"needs_active_probe": meaning.needs_active_probe,
"maintain_confidence": args.maintain_confidence,
"play_probes": args.play_probes,
"probe_feedback_mode": "closed-loop-capture" if loopback_recorder is not None else "missing-loopback",
"closed_loop_probe_capture": loopback_recorder is not None,
"probe_playback_error": probe_playback_error,
"last_probe": last_probe,
},
)
last_status = now
frame_id += 1
finally:
for stream in streams:
try:
stream.stop()
stream.close()
except Exception:
pass
if loopback_context is not None:
try:
loopback_context.__exit__(None, None, None)
except Exception:
pass
write_status(args.status, {**status_base, "running": False, "stopped": True})
if __name__ == "__main__":
main()

View file

@ -139,11 +139,18 @@ research:
weights, correction energy, and active-probe need. `audio_field.active_probe`
closes the next loop by feeding that confidence state into
ActiveProbeOptimizer and emitting bounded chirplet WAVs/manifests, with
optional default-device playback. The live launcher now uses dense
harmonic near-ultrasonic probe textures so aliases have a musical
relationship instead of arbitrary squeal. `audio-phase-field-status.json`
optional playback. The live launcher now uses dense harmonic
near-ultrasonic probe textures so aliases have a musical relationship
instead of arbitrary squeal. Probe artifacts rotate through fixed slots
and the manifest rotates at a byte cap. `scripts/stream_live_audio_field.py`
is the current live local capture owner: it writes mic-field and
phase-field CultCache documents from visible local mics plus Scarlett
loopback, sends probes through the selected Scarlett output, resamples
probe playback when that output is 44.1 kHz, and reports missing
distributed channels as explicit placeholders. `audio-phase-field-status.json`
declares input mode and whether active probes are closed-loop; current
deadline mode is explicit `wav-replay` with open-loop probe playback.
deadline mode is `live-local-capture` with closed-loop probe capture when
Scarlett loopback is available.
This is learned audio-field state, not a phase display.
faust_voice_separation:
summary: docs/aquarium-spatial-audio.md
@ -183,7 +190,11 @@ research:
calibration; they do not own image geometry. The Spout point-budget policy
pins calibration and cross-modal constraints before spending adaptive LOD
budget on stable high-priority surfaces and frame-rotated samples, and
its JSON heartbeat reports budgeted point prefix counts.
its JSON heartbeat reports budgeted point prefix counts. The live fusion
producer now has an explicit five-second spatiotemporal reservoir:
RGB/Leap frame history expires from the newest shared sample, LOD evidence
is clipped to the same window, and each RenderFramePacket declares that
source window for Aquarium/OBS synchronization.
typed_visual_state:
summary: docs/typed-visual-state.md
key_decision: >

View file

@ -42,6 +42,38 @@ class ActiveProbeTests(unittest.TestCase):
self.assertTrue(emitted.path.exists())
self.assertTrue((Path(tmp) / "active-probes.jsonl").exists())
def test_probe_artifacts_use_bounded_slots(self):
reference = np.full(1024, 0.05, dtype=np.float32)
with tempfile.TemporaryDirectory() as tmp:
maintainer = ActiveConfidenceMaintainer(
ActiveProbeOptimizer(ProbePolicy(trigger_confidence=0.35, min_interval_frames=1)),
sample_rate=48000,
output_dir=Path(tmp),
max_artifacts=2,
)
paths = []
for frame_id in range(5):
meaning = PhaseFieldMeaning(
frame_id=frame_id,
audio_time_ns=frame_id,
sample_rate=48000,
start_sample=frame_id * 1024,
frame_count=1024,
reference_id="program",
sources=(SourcePhaseMeaning("weak", 0, 0.0, 0.0, 0.0, 0.0, 0.2, 1.0, 0.1, 0.1, 0.0, 0.0),),
global_confidence=0.2,
needs_active_probe=True,
active_probe_reason="weak",
)
emitted = maintainer.update(meaning, reference, force_masked=True)
self.assertIsNotNone(emitted)
paths.append(emitted.path.name)
self.assertEqual(2, len(list(Path(tmp).glob("probe-slot-*.wav"))))
self.assertEqual("probe-slot-0000-weak.wav", paths[0])
self.assertEqual("probe-slot-0000-weak.wav", paths[-1])
def test_probe_chirplet_respects_level_and_channel(self):
chirp = make_probe_chirplet(48000, duration_seconds=0.02, start_hz=1000, end_hz=4000, level_dbfs=-20, channels=2, channel=1)

View file

@ -17,6 +17,7 @@ from localcast.sensor_fusion import (
ClapDetectorConfig,
DenseStereoConfig,
FusionConfig,
LODEvidencePoint,
Observation2D,
PointCloud,
RenderBridgeConfig,
@ -56,7 +57,9 @@ from localcast.sensor_fusion import (
)
from localcast.sensor_fusion.spout_output import rasterize_frame_rgba
from scripts.live_sensor_fusion import (
DEFAULT_RESERVOIR_NS,
LiveClapCalibrator,
evidence_in_reservoir,
leap_channel_motion_points,
rgb_dense_camera,
rgb_dense_stereo_splats,
@ -600,6 +603,32 @@ class SensorFusionTests(unittest.TestCase):
self.assertEqual(900, selected.timestamp_ns)
self.assertEqual(100, sync.offset_ns("cam-a"))
def test_timestamp_history_expires_from_shared_five_second_edge(self):
history = TimestampedFrameHistory(max_frames=20, max_age_ns=DEFAULT_RESERVOIR_NS)
history.add(TimestampedFrame("cam-a", 1_000_000_000, np.zeros((1, 1), dtype=np.float32)))
history.add(TimestampedFrame("cam-b", 4_000_000_000, np.ones((1, 1), dtype=np.float32)))
history.add(TimestampedFrame("cam-a", 7_100_000_000, np.full((1, 1), 2.0, dtype=np.float32)))
frames = history.frames_by_sensor()
self.assertNotIn(1_000_000_000, [frame.timestamp_ns for frame in frames["cam-a"]])
self.assertEqual(7_100_000_000, history.latest_timestamp_ns())
self.assertIsNotNone(history.nearest("cam-b", 4_000_000_000))
def test_lod_evidence_is_clipped_to_visual_reservoir(self):
evidence = (
LODEvidencePoint("old", np.zeros(3), 1.0, 9, 1.0, "rgb"),
LODEvidencePoint("fresh", np.ones(3), 1.0, DEFAULT_RESERVOIR_NS + 10, 1.0, "rgb"),
)
kept = evidence_in_reservoir(
evidence,
latest_timestamp_ns=DEFAULT_RESERVOIR_NS + 10,
reservoir_ns=DEFAULT_RESERVOIR_NS,
)
self.assertEqual(("fresh",), tuple(item.stable_key for item in kept))
def test_chirp_pose_constraints_map_camera_mics_to_range_residuals(self):
constraints = constraints_from_phase_sources(
(

View file

@ -21,6 +21,7 @@ from audio_field.cultcache_audio import (
put_live_mic_field_frame,
put_live_spatial_audio_frame,
)
from scripts.stream_live_audio_field import local_microphones, source_id_for_microphone
class SpatialAudioCultCacheTests(unittest.TestCase):
@ -105,6 +106,20 @@ class SpatialAudioCultCacheTests(unittest.TestCase):
self.assertEqual(12.5, loaded.sources[0]["delaySamples"])
self.assertFalse(loaded.needs_active_probe)
def test_live_audio_field_maps_profile_mics_to_cache_sources(self):
profile = {
"microphones": [
{"id": "mic_focusrite_local", "machine": "local"},
{"id": "mic_kiyo_left", "machine": "local"},
{"id": "mic_focusrite_neighbor", "machine": "neighbor"},
{"id": "unknown", "machine": "local"},
]
}
mics = local_microphones(profile, "local")
self.assertEqual(("host-focusrite", "kiyo-0"), tuple(source_id_for_microphone(mic) for mic in mics))
def test_live_mic_field_round_trip_through_cultcache(self):
block = np.arange(48, dtype=np.float32).reshape(8, 6) / 48.0
frame = make_mic_field_frame(