Add buffered audio field pipeline seams

This commit is contained in:
Meta Vens 2026-05-18 15:56:03 +01:00
commit 2671f8b81a
13 changed files with 372 additions and 16 deletions

1
audio_field/__init__.py Normal file
View file

@ -0,0 +1 @@
"""Core audio-field building blocks for LocalCastBridge."""

102
audio_field/buffering.py Normal file
View file

@ -0,0 +1,102 @@
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True)
class AudioChunk:
source_id: str
start_sample: int
sample_rate: int
samples: np.ndarray
@property
def end_sample(self) -> int:
return self.start_sample + int(self.samples.shape[0])
class SourceBuffer:
"""Append-only sample buffer with timeline-indexed reads."""
def __init__(self, source_id: str, sample_rate: int):
self.source_id = source_id
self.sample_rate = sample_rate
self._start_sample = 0
self._samples = np.empty((0,), dtype=np.float32)
self._initialized = False
@property
def start_sample(self) -> int:
return self._start_sample
@property
def end_sample(self) -> int:
return self._start_sample + int(self._samples.shape[0])
def push(self, chunk: AudioChunk) -> None:
if chunk.source_id != self.source_id:
raise ValueError(f"chunk source {chunk.source_id!r} does not match buffer {self.source_id!r}")
if chunk.sample_rate != self.sample_rate:
raise ValueError(f"chunk sample rate {chunk.sample_rate} does not match buffer {self.sample_rate}")
samples = np.asarray(chunk.samples, dtype=np.float32).reshape(-1)
if not self._initialized:
self._start_sample = chunk.start_sample
self._samples = samples.copy()
self._initialized = True
return
if chunk.start_sample < self.end_sample:
raise ValueError(f"overlapping chunk for {self.source_id}: {chunk.start_sample} < {self.end_sample}")
gap = chunk.start_sample - self.end_sample
if gap:
self._samples = np.concatenate([self._samples, np.zeros(gap, dtype=np.float32), samples])
return
self._samples = np.concatenate([self._samples, samples])
def has_window(self, start_sample: int, frame_count: int) -> bool:
end_sample = start_sample + frame_count
return self._initialized and self.start_sample <= start_sample and self.end_sample >= end_sample
def read_window(self, start_sample: int, frame_count: int) -> np.ndarray:
if not self.has_window(start_sample, frame_count):
raise ValueError(f"{self.source_id} does not cover [{start_sample}, {start_sample + frame_count})")
offset = start_sample - self.start_sample
return self._samples[offset : offset + frame_count].copy()
def trim_before(self, sample_index: int) -> None:
if not self._initialized or sample_index <= self.start_sample:
return
keep_from = min(sample_index, self.end_sample) - self.start_sample
self._samples = self._samples[keep_from:]
self._start_sample += keep_from
class FieldAssemblyCache:
"""Caches aligned mono sources and assembles ordered multichannel windows."""
def __init__(self, field_order: list[tuple[int, str]], sample_rate: int):
self.field_order = sorted(field_order)
self.buffers = {
source_id: SourceBuffer(source_id=source_id, sample_rate=sample_rate)
for _, source_id in self.field_order
}
def push(self, chunk: AudioChunk) -> None:
self.buffers[chunk.source_id].push(chunk)
def has_window(self, start_sample: int, frame_count: int) -> bool:
return all(buffer.has_window(start_sample, frame_count) for buffer in self.buffers.values())
def assemble(self, start_sample: int, frame_count: int) -> np.ndarray:
if not self.has_window(start_sample, frame_count):
raise ValueError(f"field cache does not cover [{start_sample}, {start_sample + frame_count})")
channels = [
self.buffers[source_id].read_window(start_sample, frame_count)
for _, source_id in self.field_order
]
return np.stack(channels, axis=1)
def trim_before(self, sample_index: int) -> None:
for buffer in self.buffers.values():
buffer.trim_before(sample_index)

50
audio_field/latency.py Normal file
View file

@ -0,0 +1,50 @@
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class LatencyPolicy:
sample_rate: int
target_latency_ms: float
max_latency_ms: float
block_size: int
@property
def target_latency_samples(self) -> int:
return int(round(self.sample_rate * self.target_latency_ms / 1000.0))
@property
def max_latency_samples(self) -> int:
return int(round(self.sample_rate * self.max_latency_ms / 1000.0))
class RealtimeConvergence:
"""Chooses when an aligned field may be emitted behind the live edge."""
def __init__(self, policy: LatencyPolicy):
if policy.target_latency_samples > policy.max_latency_samples:
raise ValueError("target latency cannot exceed max latency")
self.policy = policy
self._next_start_sample = 0
@property
def next_start_sample(self) -> int:
return self._next_start_sample
def ready_start_samples(self, latest_by_source: dict[str, int]) -> list[int]:
if not latest_by_source:
return []
live_edge = min(latest_by_source.values())
emit_until = live_edge - self.policy.target_latency_samples
starts: list[int] = []
while self._next_start_sample + self.policy.block_size <= emit_until:
starts.append(self._next_start_sample)
self._next_start_sample += self.policy.block_size
return starts
def is_lagging(self, latest_by_source: dict[str, int]) -> bool:
if not latest_by_source:
return False
live_edge = min(latest_by_source.values())
return live_edge - self._next_start_sample > self.policy.max_latency_samples

47
audio_field/pipeline.py Normal file
View file

@ -0,0 +1,47 @@
from __future__ import annotations
from audio_field.buffering import FieldAssemblyCache
from audio_field.latency import RealtimeConvergence
from audio_field.ports import CaptureSource, ClockAligner, FieldEncoder, FieldSink
class AudioFieldPipeline:
"""Small orchestration shell with injectable capture, alignment, encode, and sink ports."""
def __init__(
self,
sources: list[CaptureSource],
aligner: ClockAligner,
cache: FieldAssemblyCache,
convergence: RealtimeConvergence,
encoder: FieldEncoder,
sink: FieldSink,
):
self.sources = sources
self.aligner = aligner
self.cache = cache
self.convergence = convergence
self.encoder = encoder
self.sink = sink
self.latest_by_source: dict[str, int] = {}
def poll_once(self) -> int:
for source in self.sources:
chunk = source.read()
if chunk is None:
continue
aligned = self.aligner.align(chunk)
self.cache.push(aligned)
self.latest_by_source[aligned.source_id] = aligned.end_sample
emitted = 0
for start_sample in self.convergence.ready_start_samples(self.latest_by_source):
frame_count = self.convergence.policy.block_size
if not self.cache.has_window(start_sample, frame_count):
continue
field = self.cache.assemble(start_sample, frame_count)
encoded = self.encoder.encode(field)
self.sink.write(start_sample, encoded)
self.cache.trim_before(start_sample + frame_count)
emitted += 1
return emitted

29
audio_field/ports.py Normal file
View file

@ -0,0 +1,29 @@
from __future__ import annotations
from typing import Protocol
import numpy as np
from audio_field.buffering import AudioChunk
class CaptureSource(Protocol):
source_id: str
def read(self) -> AudioChunk | None:
"""Return the next raw chunk, or None when no data is currently available."""
class ClockAligner(Protocol):
def align(self, chunk: AudioChunk) -> AudioChunk:
"""Map a source chunk into the shared field timeline."""
class FieldEncoder(Protocol):
def encode(self, aligned_field: np.ndarray) -> np.ndarray:
"""Encode an aligned field frame into the output representation."""
class FieldSink(Protocol):
def write(self, start_sample: int, field: np.ndarray) -> None:
"""Write one emitted field block."""

View file

@ -14,7 +14,14 @@
"referenceMicId": "mic_focusrite_local",
"strategy": "calibration-ping-plus-adaptive-resampling",
"requiresAlignmentBeforeEncoding": true,
"maxExpectedSroPpm": 200
"maxExpectedSroPpm": 200,
"latencyPolicy": {
"mode": "bounded-buffered-realtime",
"targetLatencyMs": 750,
"maxLatencyMs": 2500,
"convergesToRealtime": true,
"dropOrStretchWhenBehind": "stretch-first-drop-only-on-overrun"
}
},
"ambisonicBus": {
"order": 1,

View file

@ -15,6 +15,8 @@ The repo has a profile and tool:
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.
## Pipeline
```mermaid
@ -30,9 +32,10 @@ flowchart TD
D --> K["delay + SRO alignment"]
F --> K
H --> K
K --> L["aligned six-channel field WAV"]
L --> M["FOA encoder"]
M --> N["AmbiX ACN/SN3D WAV: W,Y,Z,X"]
K --> L["bounded field cache"]
L --> M["aligned six-channel blocks"]
M --> N["FOA encoder"]
N --> O["AmbiX ACN/SN3D output"]
```
## Commands
@ -95,10 +98,23 @@ The `play-record` and `record-field` commands remain for a `shared-input-device`
- 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.
- FOA output is AmbiX: ACN channel order, SN3D normalization, channels `W,Y,Z,X`.
- Speaker calibration is a measurement path, not a generic monitor output.
- Camera fusion may publish listener or source pose later, but it does not own audio channel timing.
## Module Boundaries
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.
- `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.
@ -110,5 +126,6 @@ Next honest steps:
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 emits one six-channel WAV ordered by `fieldChannel`.
7. Encode the first FOA AmbiX test only after that aligned WAV exists.
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.

View file

@ -19,6 +19,7 @@
- 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.
## Temporary
@ -39,4 +40,4 @@
7. Decide whether a small OBS scene/source generator is worth adding.
8. Reconsider plugin/fork only if standard OBS Media Source cannot preserve the required behavior.
9. Create local `config/audio-field.json`, confirm local Kiyo/PS Eye/Focusrite device matches, and confirm the neighbor Focusrite shotgun capture/transport path.
10. Replace placeholder mic/speaker geometry with measured world coordinates, then build the delay/SRO alignment stage that emits one six-channel WAV before FOA encoding.
10. Replace placeholder mic/speaker geometry with measured world coordinates, then build the delay/SRO alignment stage that feeds the bounded field cache and emits aligned six-channel blocks before FOA encoding.

View file

@ -52,16 +52,18 @@ flowchart TD
D --> K["delay + SRO alignment"]
F --> K
H --> K
K --> L["aligned six-channel field"]
L --> M["FOA encoder"]
M --> N["AmbiX ACN/SN3D bus: W,Y,Z,X"]
K --> L["bounded field cache"]
L --> M["aligned six-channel blocks"]
M --> N["FOA encoder"]
N --> O["AmbiX ACN/SN3D bus: W,Y,Z,X"]
```
Ownership:
- `config/audio-field.json` owns mic/speaker identity, machine/device mapping, clock domains, field channel order, geometry, gain, delay, polarity, role/quality priority, capture policy, and Ambisonic bus format.
- `scripts/audio_field.py` owns profile validation, local device checks, calibration stimulus generation, clock-domain planning, shared-input capture helpers, and FOA encoding of already aligned six-channel WAVs.
- `audio_field/` owns unit-testable buffering, bounded-latency convergence, injectable port protocols, and pipeline orchestration.
- 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.
Invariant: distributed camera/Focusrite microphones must be aligned and resampled into one reference timeline before FOA encoding. The local shielded cardioid and neighbor shotgun are the high-quality dialogue anchors; camera mics provide spatial/context evidence.
Invariant: distributed camera/Focusrite microphones must be aligned and resampled into one reference timeline before FOA encoding. Latency is allowed as bounded buffering, but cache depth must converge toward real-time. The local shielded cardioid and neighbor shotgun are the high-quality dialogue anchors; camera mics provide spatial/context evidence.

View file

@ -415,7 +415,7 @@ def cmd_analyze_calibration(args):
raise SystemExit(f"Sample-rate mismatch in {record['file']}: {rec_rate} != {sample_rate}")
recorded = as_float_matrix(recorded)
for mic in profile["microphones"]:
channel = int(mic["channel"])
channel = mic_channel(mic)
if channel >= recorded.shape[1]:
continue
delay, peak, polarity = estimate_delay(recorded[:, channel], sweep)
@ -530,6 +530,7 @@ def cmd_sync_plan(args):
"profile": str(args.profile),
"captureMode": profile.get("captureMode", "shared-input-device"),
"capturePolicy": profile.get("capturePolicy", {}),
"clockModel": profile.get("clockModel", {}),
"referenceMicId": profile.get("clockModel", {}).get("referenceMicId") or profile.get("calibration", {}).get("referenceMicId"),
"priorityMics": anchors,
"clockDomains": [{"id": key, "microphones": value} for key, value in sorted(groups.items())],

View file

@ -28,3 +28,4 @@
{"ts": "2026-05-18T14:25:36+00:00", "type": "verification", "status": "ok", "note": "PS3 Eye video path found: AllanCat PS3 Eye Universal Driver / PS3EyeDirectShow exposes both Eyes as DirectShow indices 3 and 4 after registering the source filter for two cameras; simultaneous default 640x480 capture produced about 30 fps from both. High-FPS DirectShow mode negotiation remains unproven."}
{"ts": "2026-05-18T14:48:48+00:00", "type": "verification", "status": "ok", "note": "PS3 Eye frame-rate squeeze: OpenCV DirectShow indices are reliable only at default 640x480@30; FFmpeg DirectShow capture by device name negotiates high-rate modes. Both PS3 Eyes simultaneously delivered 320x240@60 with 300 frames per Eye over five seconds. Dual 640x480@60 works but settles around 54-56 fps per Eye. Requests above 60 fps through the installed PS3EyeDirectShow filter do not increase delivered frame rate."}
{"ts": "2026-05-18T14:50:58+00:00", "type": "verification", "status": "partial", "note": "Audio profile updated for actual distributed rig: local Focusrite shielded cardioid and neighbor Focusrite shotgun are dialogue anchors; Kiyo/PS Eye mics are spatial/context sources. Local PortAudio/WASAPI probe: Scarlett input accepts 48 kHz and rejects 96 kHz; Scarlett output accepts 44.1 kHz and rejects 48/96 kHz, so ASIO/native Focusrite access must be checked before high-rate calibration."}
{"ts": "2026-05-18T14:55:13+00:00", "type": "decision", "status": "ok", "note": "Audio field live output may use bounded buffering: latency is acceptable while delay/SRO estimates settle, but cache depth must converge toward real-time. Core audio code now has testable seams for buffers, latency policy, injectable capture/alignment/encoder/sink ports, and pipeline orchestration."}

View file

@ -44,7 +44,7 @@ active_subgoals:
- Smoke-test each audio endpoint in OBS and tune latency.
- Decide whether an OBS source generator or plugin investigation is justified.
- Evaluate the Ambisonic AquaSynth path as a separate synchronized multichannel audio pipeline; do not treat heterogeneous mic feeds as raw first-order ambisonic A-format without geometry, calibration, and a shared clock.
- Build the six-microphone/two-speaker audio-field sidecar around the actual distributed camera/Focusrite clocks, explicit geometry, speaker calibration, delay/SRO alignment, and FOA AmbiX output.
- Build the six-microphone/two-speaker audio-field sidecar around the actual distributed camera/Focusrite clocks, explicit geometry, speaker calibration, bounded buffering, delay/SRO alignment, testable pipeline seams, and FOA AmbiX output.
research:
ambisonic_aquasynth:
@ -137,7 +137,12 @@ current_status:
resampled into one six-channel reference timeline. Local PortAudio/WASAPI
probe shows the Scarlett input accepts 48 kHz but rejects 96 kHz, while the
Scarlett output accepts 44.1 kHz and rejects 48/96 kHz on this path; check
ASIO/native Focusrite access before relying on high-rate calibration.
ASIO/native Focusrite access before relying on high-rate calibration. Audio
latency is now an explicit bounded-buffering policy: output may run behind
live input while delay/SRO estimates settle, but cache depth must converge
toward real-time. Core audio modules now expose testable boundaries for
buffering, latency convergence, injectable capture/alignment/encode/sink
ports, and pipeline orchestration.
next_action: >
Use FFmpeg DirectShow device names `PS3 Eye Universal` and `PS3 Eye
Universal2` for PS3 Eye tracking capture at 320x240@60, then capture
@ -147,5 +152,5 @@ current_status:
config/audio-field.json, confirm local Kiyo/PS Eye/Focusrite device matches,
confirm the neighbor Focusrite shotgun capture/transport path, replace
placeholder mic/speaker geometry with measured world coordinates, then build
the delay/SRO alignment stage that emits one six-channel WAV for FOA
encoding.
the delay/SRO alignment stage that feeds the bounded field cache and emits
aligned six-channel blocks for FOA encoding.

View file

@ -0,0 +1,93 @@
import unittest
import numpy as np
from audio_field.buffering import AudioChunk, FieldAssemblyCache, SourceBuffer
from audio_field.latency import LatencyPolicy, RealtimeConvergence
from audio_field.pipeline import AudioFieldPipeline
class IdentityAligner:
def align(self, chunk):
return chunk
class IdentityEncoder:
def encode(self, aligned_field):
return aligned_field
class ListSink:
def __init__(self):
self.writes = []
def write(self, start_sample, field):
self.writes.append((start_sample, field.copy()))
class ListSource:
def __init__(self, source_id, chunks):
self.source_id = source_id
self.chunks = list(chunks)
def read(self):
if not self.chunks:
return None
return self.chunks.pop(0)
class BufferingTests(unittest.TestCase):
def test_source_buffer_fills_gaps_with_silence(self):
buffer = SourceBuffer("a", 48000)
buffer.push(AudioChunk("a", 0, 48000, np.array([1.0, 2.0], dtype=np.float32)))
buffer.push(AudioChunk("a", 4, 48000, np.array([5.0], dtype=np.float32)))
np.testing.assert_allclose(buffer.read_window(0, 5), np.array([1.0, 2.0, 0.0, 0.0, 5.0]))
def test_field_cache_assembles_field_channel_order(self):
cache = FieldAssemblyCache([(1, "b"), (0, "a")], 48000)
cache.push(AudioChunk("a", 0, 48000, np.array([1.0, 2.0], dtype=np.float32)))
cache.push(AudioChunk("b", 0, 48000, np.array([3.0, 4.0], dtype=np.float32)))
field = cache.assemble(0, 2)
np.testing.assert_allclose(field, np.array([[1.0, 3.0], [2.0, 4.0]], dtype=np.float32))
class LatencyTests(unittest.TestCase):
def test_convergence_emits_blocks_behind_live_edge(self):
policy = LatencyPolicy(sample_rate=48000, target_latency_ms=100.0, max_latency_ms=500.0, block_size=480)
convergence = RealtimeConvergence(policy)
starts = convergence.ready_start_samples({"a": 4800 + 960, "b": 4800 + 960})
self.assertEqual(starts, [0, 480])
self.assertFalse(convergence.is_lagging({"a": 4800 + 960, "b": 4800 + 960}))
class PipelineTests(unittest.TestCase):
def test_pipeline_uses_injected_ports(self):
chunks_a = [AudioChunk("a", 0, 48000, np.ones(480, dtype=np.float32))]
chunks_b = [AudioChunk("b", 0, 48000, np.ones(480, dtype=np.float32) * 2)]
cache = FieldAssemblyCache([(0, "a"), (1, "b")], 48000)
convergence = RealtimeConvergence(
LatencyPolicy(sample_rate=48000, target_latency_ms=0.0, max_latency_ms=100.0, block_size=480)
)
sink = ListSink()
pipeline = AudioFieldPipeline(
sources=[ListSource("a", chunks_a), ListSource("b", chunks_b)],
aligner=IdentityAligner(),
cache=cache,
convergence=convergence,
encoder=IdentityEncoder(),
sink=sink,
)
self.assertEqual(pipeline.poll_once(), 1)
self.assertEqual(len(sink.writes), 1)
self.assertEqual(sink.writes[0][0], 0)
self.assertEqual(sink.writes[0][1].shape, (480, 2))
np.testing.assert_allclose(sink.writes[0][1][0], np.array([1.0, 2.0], dtype=np.float32))
if __name__ == "__main__":
unittest.main()