From c35a464a62cfc8c694a916c45fe70af140094a58 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 17:09:56 +0100 Subject: [PATCH] Add Aquarium spatial audio state stream --- audio_field/cultcache_audio.py | 233 ++++++++++++++++++++++++++ docs/aquarium-spatial-audio.md | 43 +++++ scripts/stream_spatial_audio.py | 149 ++++++++++++++++ tests/test_spatial_audio_cultcache.py | 49 ++++++ 4 files changed, 474 insertions(+) create mode 100644 audio_field/cultcache_audio.py create mode 100644 docs/aquarium-spatial-audio.md create mode 100644 scripts/stream_spatial_audio.py create mode 100644 tests/test_spatial_audio_cultcache.py diff --git a/audio_field/cultcache_audio.py b/audio_field/cultcache_audio.py new file mode 100644 index 0000000..b2166c5 --- /dev/null +++ b/audio_field/cultcache_audio.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +import sys +import time +from typing import Any + +import numpy as np + + +ROOT = Path(__file__).resolve().parents[1] +CULTCACHE_PY_SRC = ROOT.parent / "cultcache-py" / "src" +if CULTCACHE_PY_SRC.exists() and str(CULTCACHE_PY_SRC) not in sys.path: + sys.path.insert(0, str(CULTCACHE_PY_SRC)) + +from cultcache_py import CultCache, SingleFileMessagePackBackingStore, define_document_type # noqa: E402 + + +LIVE_SPATIAL_AUDIO_KEY = "localcast.audio.spatial-frame.live" +SPATIAL_AUDIO_SCHEMA_ID = "gamecult.localcast.audio.spatial_frame.v1" +AUDIO_STREAM_STATUS_KEY = "localcast.audio.stream-status.live" +AUDIO_STREAM_STATUS_SCHEMA_ID = "gamecult.localcast.audio.stream_status.v1" + + +@dataclass(frozen=True) +class CultSpatialAudioFrame: + schema_version: str + frame_id: int + created_monotonic_ns: int + audio_time_ns: int + sample_rate: int + start_sample: int + frame_count: int + channel_order: str + normalization: str + channels: tuple[str, ...] + sample_format: str + interleaved_pcm_f32le: bytes + + +@dataclass(frozen=True) +class CultAudioStreamStatus: + schema_version: str + stream_name: str + frames_sent: int + sample_rate: int + frame_count: int + channels: tuple[str, ...] + updated_monotonic_ns: int + last_error: str + + +def _pack(value: Any) -> bytes: + import msgpack + + return msgpack.packb(value, use_bin_type=True) + + +def _unpack(payload: bytes) -> Any: + import msgpack + + return msgpack.unpackb(payload, raw=False) + + +def _encode_audio_frame(frame: CultSpatialAudioFrame) -> list[Any]: + return [ + frame.schema_version, + frame.frame_id, + frame.created_monotonic_ns, + frame.audio_time_ns, + frame.sample_rate, + frame.start_sample, + frame.frame_count, + frame.channel_order, + frame.normalization, + list(frame.channels), + frame.sample_format, + frame.interleaved_pcm_f32le, + ] + + +def _decode_audio_frame(raw: Any) -> CultSpatialAudioFrame: + return CultSpatialAudioFrame( + schema_version=str(raw[0]), + frame_id=int(raw[1]), + created_monotonic_ns=int(raw[2]), + audio_time_ns=int(raw[3]), + sample_rate=int(raw[4]), + start_sample=int(raw[5]), + frame_count=int(raw[6]), + channel_order=str(raw[7]), + normalization=str(raw[8]), + channels=tuple(str(channel) for channel in raw[9]), + sample_format=str(raw[10]), + interleaved_pcm_f32le=bytes(raw[11]), + ) + + +def _encode_audio_status(status: CultAudioStreamStatus) -> list[Any]: + return [ + status.schema_version, + status.stream_name, + status.frames_sent, + status.sample_rate, + status.frame_count, + list(status.channels), + status.updated_monotonic_ns, + status.last_error, + ] + + +def _decode_audio_status(raw: Any) -> CultAudioStreamStatus: + return CultAudioStreamStatus( + schema_version=str(raw[0]), + stream_name=str(raw[1]), + frames_sent=int(raw[2]), + sample_rate=int(raw[3]), + frame_count=int(raw[4]), + channels=tuple(str(channel) for channel in raw[5]), + updated_monotonic_ns=int(raw[6]), + last_error=str(raw[7]), + ) + + +SPATIAL_AUDIO_FRAME_DOCUMENT = define_document_type( + "localcast.audio.spatial_frame", + encode=_encode_audio_frame, + decode=_decode_audio_frame, + name=lambda frame: LIVE_SPATIAL_AUDIO_KEY if isinstance(frame, CultSpatialAudioFrame) else None, + payload_encoder=_pack, + payload_decoder=_unpack, +) + +AUDIO_STREAM_STATUS_DOCUMENT = define_document_type( + "localcast.audio.stream_status", + encode=_encode_audio_status, + decode=_decode_audio_status, + name=lambda status: AUDIO_STREAM_STATUS_KEY if isinstance(status, CultAudioStreamStatus) else None, + payload_encoder=_pack, + payload_decoder=_unpack, +) + + +def _retry_cache_io(operation): + last_error: Exception | None = None + for _ in range(40): + try: + return operation() + except (PermissionError, EOFError, ValueError) as exc: + last_error = exc + time.sleep(0.01) + assert last_error is not None + raise last_error + + +def _open_audio_cache_once(path: Path) -> CultCache: + cache = ( + CultCache.builder() + .register_document_type(SPATIAL_AUDIO_FRAME_DOCUMENT) + .register_document_type(AUDIO_STREAM_STATUS_DOCUMENT) + .add_generic_store(SingleFileMessagePackBackingStore(path)) + .build() + ) + cache.pull_all_backing_stores() + return cache + + +def open_audio_cache(path: Path) -> CultCache: + return _retry_cache_io(lambda: _open_audio_cache_once(path)) + + +def make_spatial_audio_frame( + block: np.ndarray, + *, + frame_id: int, + sample_rate: int, + start_sample: int, + audio_time_ns: int, + channel_order: str = "ACN", + normalization: str = "SN3D", + channels: tuple[str, ...] = ("W", "Y", "Z", "X"), +) -> CultSpatialAudioFrame: + pcm = np.asarray(block, dtype=np.float32) + if pcm.ndim != 2: + raise ValueError("spatial audio block must be a 2D frames-by-channels array") + if pcm.shape[1] != len(channels): + raise ValueError(f"expected {len(channels)} channels, got {pcm.shape[1]}") + return CultSpatialAudioFrame( + schema_version=SPATIAL_AUDIO_SCHEMA_ID, + frame_id=frame_id, + created_monotonic_ns=time.monotonic_ns(), + audio_time_ns=audio_time_ns, + sample_rate=int(sample_rate), + start_sample=int(start_sample), + frame_count=int(pcm.shape[0]), + channel_order=channel_order, + normalization=normalization, + channels=channels, + sample_format="f32le-interleaved", + interleaved_pcm_f32le=np.ascontiguousarray(pcm, dtype=" np.ndarray: + if frame.sample_format != "f32le-interleaved": + raise ValueError(f"unsupported sample format: {frame.sample_format}") + pcm = np.frombuffer(frame.interleaved_pcm_f32le, dtype=" None: + def operation() -> None: + cache = open_audio_cache(path) + cache.put(SPATIAL_AUDIO_FRAME_DOCUMENT, LIVE_SPATIAL_AUDIO_KEY, frame) + + _retry_cache_io(operation) + + +def get_live_spatial_audio_frame(path: Path) -> CultSpatialAudioFrame | None: + def operation() -> CultSpatialAudioFrame | None: + cache = open_audio_cache(path) + return cache.get(SPATIAL_AUDIO_FRAME_DOCUMENT, LIVE_SPATIAL_AUDIO_KEY) + + return _retry_cache_io(operation) + + +def put_audio_stream_status(path: Path, status: CultAudioStreamStatus) -> None: + def operation() -> None: + cache = open_audio_cache(path) + cache.put(AUDIO_STREAM_STATUS_DOCUMENT, AUDIO_STREAM_STATUS_KEY, status) + + _retry_cache_io(operation) diff --git a/docs/aquarium-spatial-audio.md b/docs/aquarium-spatial-audio.md new file mode 100644 index 0000000..71fbde3 --- /dev/null +++ b/docs/aquarium-spatial-audio.md @@ -0,0 +1,43 @@ +# Aquarium Spatial Audio + +## Objective + +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; LocalCastBridge owns capture, sync, calibration, and stream timing. + +## Current Mechanism + +```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"] + D --> E["audio-state.msgpack / CultNet document_put"] + E --> F["Aquarium client"] + F --> G["native Faust spatial DSP"] +``` + +Live files: + +- `calibration/runs/audio-state.msgpack`: latest typed AmbiX audio block. +- `calibration/runs/audio-stream-status.msgpack`: audio publisher heartbeat. + +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` + +Publisher smoke command: + +```powershell +.\.venv\Scripts\python.exe .\scripts\stream_spatial_audio.py --input .\calibration\runs\audio-full-sync-20260518-165751\field-foa-ambix.wav --loop --duration 5 --smoke-readback +``` + +## Invariants + +- Aquarium owns rendering and Faust DSP, not microphone capture or clock correction. +- LocalCastBridge publishes declared AmbiX blocks, not undecoded heterogeneous microphone channels. +- 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. diff --git a/scripts/stream_spatial_audio.py b/scripts/stream_spatial_audio.py new file mode 100644 index 0000000..6dd7c17 --- /dev/null +++ b/scripts/stream_spatial_audio.py @@ -0,0 +1,149 @@ +import argparse +from pathlib import Path +import sys +import time + +import numpy as np +from scipy.io import wavfile + + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from audio_field.cultcache_audio import ( # noqa: E402 + AUDIO_STREAM_STATUS_SCHEMA_ID, + CultAudioStreamStatus, + get_live_spatial_audio_frame, + make_spatial_audio_frame, + put_audio_stream_status, + put_live_spatial_audio_frame, +) + + +def read_float_wav(path: Path) -> tuple[int, np.ndarray]: + rate, data = wavfile.read(path) + samples = data.astype(np.float32) + if np.issubdtype(data.dtype, np.integer): + samples /= np.iinfo(data.dtype).max + if samples.ndim == 1: + samples = samples[:, None] + return int(rate), samples + + +def synthetic_ambix(sample_rate: int, start_sample: int, frame_count: int) -> np.ndarray: + t = (np.arange(frame_count, dtype=np.float32) + float(start_sample)) / float(sample_rate) + w = 0.05 * np.sin(2.0 * np.pi * 220.0 * t) + az = 2.0 * np.pi * 0.08 * t + y = 0.03 * np.sin(2.0 * np.pi * 330.0 * t) * np.sin(az) + z = 0.01 * np.sin(2.0 * np.pi * 110.0 * t) + x = 0.03 * np.sin(2.0 * np.pi * 330.0 * t) * np.cos(az) + return np.stack([w, y, z, x], axis=1).astype(np.float32) + + +def source_block(samples: np.ndarray | None, sample_rate: int, start_sample: int, frame_count: int, *, loop: bool) -> np.ndarray | None: + if samples is None: + return synthetic_ambix(sample_rate, start_sample, frame_count) + if samples.shape[1] != 4: + raise SystemExit(f"AmbiX source must have 4 channels, got {samples.shape[1]}") + if start_sample >= len(samples) and not loop: + return None + block = np.zeros((frame_count, 4), dtype=np.float32) + written = 0 + cursor = start_sample + while written < frame_count: + if cursor >= len(samples): + if not loop: + break + cursor %= len(samples) + count = min(frame_count - written, len(samples) - cursor) + block[written : written + count] = samples[cursor : cursor + count] + written += count + cursor += count + return block + + +def main() -> None: + parser = argparse.ArgumentParser(description="Publish live AmbiX spatial audio blocks into typed CultCache state for Aquarium/Faust.") + parser.add_argument("--input", type=Path, default=ROOT / "calibration" / "runs" / "audio-full-sync-20260518-165751" / "field-foa-ambix.wav") + parser.add_argument("--cache", type=Path, default=ROOT / "calibration" / "runs" / "audio-state.msgpack") + parser.add_argument("--status-cache", type=Path, default=ROOT / "calibration" / "runs" / "audio-stream-status.msgpack") + parser.add_argument("--stream-name", default="LocalCastBridge AmbiX") + parser.add_argument("--chunk-frames", type=int, default=1024) + parser.add_argument("--duration", type=float) + parser.add_argument("--loop", action="store_true") + parser.add_argument("--synthetic", action="store_true") + parser.add_argument("--smoke-readback", action="store_true") + args = parser.parse_args() + + source = None + sample_rate = 48000 + if not args.synthetic: + sample_rate, source = read_float_wav(args.input) + if sample_rate != 48000: + raise SystemExit(f"Expected 48 kHz AmbiX source for Aquarium/Faust stream, got {sample_rate}") + + start_monotonic = time.monotonic() + audio_origin_ns = time.monotonic_ns() + frame_id = 0 + start_sample = 0 + last_status = 0.0 + while True: + now = time.monotonic() + if args.duration is not None and now - start_monotonic >= args.duration: + break + block = source_block(source, sample_rate, start_sample, args.chunk_frames, loop=args.loop) + if block is None: + break + audio_time_ns = audio_origin_ns + int(start_sample * 1_000_000_000 / sample_rate) + frame = make_spatial_audio_frame( + block, + frame_id=frame_id, + sample_rate=sample_rate, + start_sample=start_sample, + audio_time_ns=audio_time_ns, + ) + put_live_spatial_audio_frame(args.cache, frame) + if args.smoke_readback: + loaded = get_live_spatial_audio_frame(args.cache) + if loaded is None or loaded.frame_id != frame_id: + raise SystemExit("Audio CultCache smoke readback failed") + if now - last_status >= 1.0: + put_audio_stream_status( + args.status_cache, + CultAudioStreamStatus( + schema_version=AUDIO_STREAM_STATUS_SCHEMA_ID, + stream_name=args.stream_name, + frames_sent=frame_id + 1, + sample_rate=sample_rate, + frame_count=args.chunk_frames, + channels=("W", "Y", "Z", "X"), + updated_monotonic_ns=time.monotonic_ns(), + last_error="", + ), + ) + last_status = now + frame_id += 1 + start_sample += args.chunk_frames + target_time = start_monotonic + start_sample / sample_rate + sleep_for = target_time - time.monotonic() + if sleep_for > 0: + time.sleep(sleep_for) + + put_audio_stream_status( + args.status_cache, + CultAudioStreamStatus( + schema_version=AUDIO_STREAM_STATUS_SCHEMA_ID, + stream_name=args.stream_name, + frames_sent=frame_id, + sample_rate=sample_rate, + frame_count=args.chunk_frames, + channels=("W", "Y", "Z", "X"), + updated_monotonic_ns=time.monotonic_ns(), + last_error="stopped", + ), + ) + + +if __name__ == "__main__": + main() diff --git a/tests/test_spatial_audio_cultcache.py b/tests/test_spatial_audio_cultcache.py new file mode 100644 index 0000000..c820eba --- /dev/null +++ b/tests/test_spatial_audio_cultcache.py @@ -0,0 +1,49 @@ +import tempfile +import unittest +from pathlib import Path + +import numpy as np + +from audio_field.cultcache_audio import ( + SPATIAL_AUDIO_SCHEMA_ID, + frame_to_numpy, + get_live_spatial_audio_frame, + make_spatial_audio_frame, + put_live_spatial_audio_frame, +) + + +class SpatialAudioCultCacheTests(unittest.TestCase): + def test_spatial_audio_frame_round_trips_float32_ambix_block(self): + block = np.arange(32, dtype=np.float32).reshape(8, 4) / 32.0 + frame = make_spatial_audio_frame( + block, + frame_id=12, + sample_rate=48000, + start_sample=1024, + audio_time_ns=50_000, + ) + + self.assertEqual(SPATIAL_AUDIO_SCHEMA_ID, frame.schema_version) + self.assertEqual(("W", "Y", "Z", "X"), frame.channels) + self.assertEqual("ACN", frame.channel_order) + self.assertEqual("SN3D", frame.normalization) + np.testing.assert_allclose(block, frame_to_numpy(frame)) + + def test_live_spatial_audio_frame_round_trips_through_cultcache(self): + block = np.ones((16, 4), dtype=np.float32) + frame = make_spatial_audio_frame(block, frame_id=3, sample_rate=48000, start_sample=2048, audio_time_ns=90_000) + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "audio-state.msgpack" + put_live_spatial_audio_frame(path, frame) + loaded = get_live_spatial_audio_frame(path) + + self.assertIsNotNone(loaded) + self.assertEqual(3, loaded.frame_id) + self.assertEqual(2048, loaded.start_sample) + np.testing.assert_allclose(block, frame_to_numpy(loaded)) + + +if __name__ == "__main__": + unittest.main()