Add live phase-field meaning stream
This commit is contained in:
parent
905fc60dbd
commit
5d9c08797c
10 changed files with 517 additions and 4 deletions
|
|
@ -23,6 +23,8 @@ AUDIO_STREAM_STATUS_KEY = "localcast.audio.stream-status.live"
|
|||
AUDIO_STREAM_STATUS_SCHEMA_ID = "gamecult.localcast.audio.stream_status.v1"
|
||||
LIVE_SOURCE_EVENTS_KEY = "localcast.audio.source-events.live"
|
||||
SOURCE_EVENTS_SCHEMA_ID = "gamecult.localcast.audio.source_events.v1"
|
||||
LIVE_PHASE_FIELD_KEY = "localcast.audio.phase-field.live"
|
||||
PHASE_FIELD_SCHEMA_ID = "gamecult.localcast.audio.phase_field.v1"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -65,6 +67,21 @@ class CultAudioSourceEvents:
|
|||
voice_focus: tuple[dict[str, Any], ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultAudioPhaseField:
|
||||
schema_version: str
|
||||
frame_id: int
|
||||
audio_time_ns: int
|
||||
sample_rate: int
|
||||
start_sample: int
|
||||
frame_count: int
|
||||
reference_id: str
|
||||
sources: tuple[dict[str, Any], ...]
|
||||
global_confidence: float
|
||||
needs_active_probe: bool
|
||||
active_probe_reason: str
|
||||
|
||||
|
||||
def _pack(value: Any) -> bytes:
|
||||
import msgpack
|
||||
|
||||
|
|
@ -163,6 +180,38 @@ def _decode_source_events(raw: Any) -> CultAudioSourceEvents:
|
|||
)
|
||||
|
||||
|
||||
def _encode_phase_field(field: CultAudioPhaseField) -> list[Any]:
|
||||
return [
|
||||
field.schema_version,
|
||||
field.frame_id,
|
||||
field.audio_time_ns,
|
||||
field.sample_rate,
|
||||
field.start_sample,
|
||||
field.frame_count,
|
||||
field.reference_id,
|
||||
list(field.sources),
|
||||
field.global_confidence,
|
||||
field.needs_active_probe,
|
||||
field.active_probe_reason,
|
||||
]
|
||||
|
||||
|
||||
def _decode_phase_field(raw: Any) -> CultAudioPhaseField:
|
||||
return CultAudioPhaseField(
|
||||
schema_version=str(raw[0]),
|
||||
frame_id=int(raw[1]),
|
||||
audio_time_ns=int(raw[2]),
|
||||
sample_rate=int(raw[3]),
|
||||
start_sample=int(raw[4]),
|
||||
frame_count=int(raw[5]),
|
||||
reference_id=str(raw[6]),
|
||||
sources=tuple(dict(item) for item in raw[7]),
|
||||
global_confidence=float(raw[8]),
|
||||
needs_active_probe=bool(raw[9]),
|
||||
active_probe_reason=str(raw[10]),
|
||||
)
|
||||
|
||||
|
||||
SPATIAL_AUDIO_FRAME_DOCUMENT = define_document_type(
|
||||
"localcast.audio.spatial_frame",
|
||||
encode=_encode_audio_frame,
|
||||
|
|
@ -190,6 +239,15 @@ SOURCE_EVENTS_DOCUMENT = define_document_type(
|
|||
payload_decoder=_unpack,
|
||||
)
|
||||
|
||||
PHASE_FIELD_DOCUMENT = define_document_type(
|
||||
"localcast.audio.phase_field",
|
||||
encode=_encode_phase_field,
|
||||
decode=_decode_phase_field,
|
||||
name=lambda field: LIVE_PHASE_FIELD_KEY if isinstance(field, CultAudioPhaseField) else None,
|
||||
payload_encoder=_pack,
|
||||
payload_decoder=_unpack,
|
||||
)
|
||||
|
||||
|
||||
def _retry_cache_io(operation):
|
||||
last_error: Exception | None = None
|
||||
|
|
@ -209,6 +267,7 @@ def _open_audio_cache_once(path: Path) -> CultCache:
|
|||
.register_document_type(SPATIAL_AUDIO_FRAME_DOCUMENT)
|
||||
.register_document_type(AUDIO_STREAM_STATUS_DOCUMENT)
|
||||
.register_document_type(SOURCE_EVENTS_DOCUMENT)
|
||||
.register_document_type(PHASE_FIELD_DOCUMENT)
|
||||
.add_generic_store(SingleFileMessagePackBackingStore(path))
|
||||
.build()
|
||||
)
|
||||
|
|
@ -319,3 +378,47 @@ def get_live_audio_source_events(path: Path) -> CultAudioSourceEvents | None:
|
|||
return cache.get(SOURCE_EVENTS_DOCUMENT, LIVE_SOURCE_EVENTS_KEY)
|
||||
|
||||
return _retry_cache_io(operation)
|
||||
|
||||
|
||||
def make_audio_phase_field(
|
||||
*,
|
||||
frame_id: int,
|
||||
sample_rate: int,
|
||||
start_sample: int,
|
||||
frame_count: int,
|
||||
audio_time_ns: int,
|
||||
reference_id: str,
|
||||
sources: list[dict[str, Any]] | tuple[dict[str, Any], ...],
|
||||
global_confidence: float,
|
||||
needs_active_probe: bool,
|
||||
active_probe_reason: str = "",
|
||||
) -> CultAudioPhaseField:
|
||||
return CultAudioPhaseField(
|
||||
schema_version=PHASE_FIELD_SCHEMA_ID,
|
||||
frame_id=int(frame_id),
|
||||
audio_time_ns=int(audio_time_ns),
|
||||
sample_rate=int(sample_rate),
|
||||
start_sample=int(start_sample),
|
||||
frame_count=int(frame_count),
|
||||
reference_id=str(reference_id),
|
||||
sources=tuple(dict(item) for item in sources),
|
||||
global_confidence=float(global_confidence),
|
||||
needs_active_probe=bool(needs_active_probe),
|
||||
active_probe_reason=str(active_probe_reason),
|
||||
)
|
||||
|
||||
|
||||
def put_live_audio_phase_field(path: Path, field: CultAudioPhaseField) -> None:
|
||||
def operation() -> None:
|
||||
cache = open_audio_cache(path)
|
||||
cache.put(PHASE_FIELD_DOCUMENT, LIVE_PHASE_FIELD_KEY, field)
|
||||
|
||||
_retry_cache_io(operation)
|
||||
|
||||
|
||||
def get_live_audio_phase_field(path: Path) -> CultAudioPhaseField | None:
|
||||
def operation() -> CultAudioPhaseField | None:
|
||||
cache = open_audio_cache(path)
|
||||
return cache.get(PHASE_FIELD_DOCUMENT, LIVE_PHASE_FIELD_KEY)
|
||||
|
||||
return _retry_cache_io(operation)
|
||||
|
|
|
|||
159
audio_field/phase_meaning.py
Normal file
159
audio_field/phase_meaning.py
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from audio_field.phase_fit import IterativeFrequencyPhaseMapper, SmoothPhaseField, estimate_phase_delay
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourcePhaseMeaning:
|
||||
source_id: str
|
||||
channel: int
|
||||
delay_samples: float
|
||||
smoothed_delay_samples: float
|
||||
delay_ms: float
|
||||
distance_delta_m: float
|
||||
coherence: float
|
||||
fit_error_radians: float
|
||||
confidence: float
|
||||
reference_bleed: float
|
||||
suppression_weight: float
|
||||
correction_energy: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PhaseFieldMeaning:
|
||||
frame_id: int
|
||||
audio_time_ns: int
|
||||
sample_rate: int
|
||||
start_sample: int
|
||||
frame_count: int
|
||||
reference_id: str
|
||||
sources: tuple[SourcePhaseMeaning, ...]
|
||||
global_confidence: float
|
||||
needs_active_probe: bool
|
||||
active_probe_reason: str
|
||||
|
||||
|
||||
class LivePhaseMeaningExtractor:
|
||||
"""Extracts live alignment and cleanup meaning from internal phase evidence."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
source_ids: list[str] | tuple[str, ...],
|
||||
sample_rate: int,
|
||||
frequencies_hz: list[float] | tuple[float, ...],
|
||||
*,
|
||||
reference_id: str = "program-reference",
|
||||
speed_of_sound_mps: float = 343.0,
|
||||
min_confidence: float = 0.35,
|
||||
smoothing: float = 0.25,
|
||||
max_step_samples: float = 32.0,
|
||||
):
|
||||
if not source_ids:
|
||||
raise ValueError("at least one source_id is required")
|
||||
self.source_ids = tuple(str(source_id) for source_id in source_ids)
|
||||
self.sample_rate = int(sample_rate)
|
||||
self.frequencies_hz = tuple(float(frequency) for frequency in frequencies_hz)
|
||||
self.reference_id = str(reference_id)
|
||||
self.speed_of_sound_mps = float(speed_of_sound_mps)
|
||||
self.min_confidence = float(min_confidence)
|
||||
self._phase_field = SmoothPhaseField(smoothing=smoothing, max_step_samples=max_step_samples)
|
||||
self._mapper = IterativeFrequencyPhaseMapper(self.frequencies_hz, self.sample_rate)
|
||||
|
||||
def update(
|
||||
self,
|
||||
reference: np.ndarray,
|
||||
field: np.ndarray,
|
||||
*,
|
||||
frame_id: int,
|
||||
start_sample: int,
|
||||
audio_time_ns: int,
|
||||
) -> PhaseFieldMeaning:
|
||||
ref = np.asarray(reference, dtype=np.float32).reshape(-1)
|
||||
samples = np.asarray(field, dtype=np.float32)
|
||||
if samples.ndim != 2:
|
||||
raise ValueError("field must be a frames-by-channels array")
|
||||
count = min(len(ref), samples.shape[0])
|
||||
if count <= 0:
|
||||
raise ValueError("reference and field must contain samples")
|
||||
ref = ref[:count]
|
||||
samples = samples[:count]
|
||||
|
||||
source_rows: list[SourcePhaseMeaning] = []
|
||||
for channel, source_id in enumerate(self.source_ids):
|
||||
if channel >= samples.shape[1]:
|
||||
continue
|
||||
observed = samples[:, channel]
|
||||
estimate = estimate_phase_delay(ref, observed, self.sample_rate, self.frequencies_hz)
|
||||
coherence = mean_band_coherence(estimate.bands)
|
||||
bleed = normalized_correlation(ref, observed)
|
||||
confidence = phase_confidence(coherence, estimate.fit_error_radians, bleed, ref, observed)
|
||||
smoothed_delay = self._phase_field.update(source_id, estimate.delay_samples, confidence)
|
||||
correction = self._mapper.update(source_id, estimate, confidence)
|
||||
delay_ms = 1000.0 * smoothed_delay / float(self.sample_rate)
|
||||
source_rows.append(
|
||||
SourcePhaseMeaning(
|
||||
source_id=source_id,
|
||||
channel=channel,
|
||||
delay_samples=float(estimate.delay_samples),
|
||||
smoothed_delay_samples=float(smoothed_delay),
|
||||
delay_ms=float(delay_ms),
|
||||
distance_delta_m=float(smoothed_delay * self.speed_of_sound_mps / float(self.sample_rate)),
|
||||
coherence=float(coherence),
|
||||
fit_error_radians=float(estimate.fit_error_radians),
|
||||
confidence=float(confidence),
|
||||
reference_bleed=float(bleed),
|
||||
suppression_weight=float(max(0.0, min(1.0, bleed * confidence))),
|
||||
correction_energy=float(np.sqrt(np.mean(correction * correction))) if correction.size else 0.0,
|
||||
)
|
||||
)
|
||||
|
||||
global_confidence = float(np.mean([row.confidence for row in source_rows])) if source_rows else 0.0
|
||||
low_sources = [row.source_id for row in source_rows if row.confidence < self.min_confidence]
|
||||
return PhaseFieldMeaning(
|
||||
frame_id=int(frame_id),
|
||||
audio_time_ns=int(audio_time_ns),
|
||||
sample_rate=self.sample_rate,
|
||||
start_sample=int(start_sample),
|
||||
frame_count=int(count),
|
||||
reference_id=self.reference_id,
|
||||
sources=tuple(source_rows),
|
||||
global_confidence=global_confidence,
|
||||
needs_active_probe=bool(low_sources or global_confidence < self.min_confidence),
|
||||
active_probe_reason=", ".join(low_sources) if low_sources else ("global-confidence" if global_confidence < self.min_confidence else ""),
|
||||
)
|
||||
|
||||
|
||||
def mean_band_coherence(bands) -> float:
|
||||
values = [float(band.coherence) for band in bands]
|
||||
return float(np.mean(values)) if values else 0.0
|
||||
|
||||
|
||||
def phase_confidence(coherence: float, fit_error_radians: float, reference_bleed: float, reference: np.ndarray, observed: np.ndarray) -> float:
|
||||
energy_gate = min(1.0, rms(observed) / max(rms(reference) * 0.05, 1e-9))
|
||||
fit_gate = math.exp(-max(0.0, float(fit_error_radians)))
|
||||
bleed_gate = math.sqrt(max(0.0, min(1.0, float(reference_bleed))))
|
||||
return float(max(0.0, min(1.0, float(coherence) * fit_gate * energy_gate * bleed_gate)))
|
||||
|
||||
|
||||
def normalized_correlation(reference: np.ndarray, observed: np.ndarray) -> float:
|
||||
ref = np.asarray(reference, dtype=np.float64).reshape(-1)
|
||||
obs = np.asarray(observed, dtype=np.float64).reshape(-1)
|
||||
count = min(len(ref), len(obs))
|
||||
if count <= 1:
|
||||
return 0.0
|
||||
ref = ref[:count] - float(np.mean(ref[:count]))
|
||||
obs = obs[:count] - float(np.mean(obs[:count]))
|
||||
denom = float(np.linalg.norm(ref) * np.linalg.norm(obs))
|
||||
if denom <= 1e-12:
|
||||
return 0.0
|
||||
return float(max(0.0, min(1.0, abs(float(np.dot(ref, obs) / denom)))))
|
||||
|
||||
|
||||
def rms(samples: np.ndarray) -> float:
|
||||
x = np.asarray(samples, dtype=np.float64).reshape(-1)
|
||||
return float(np.sqrt(np.mean(x * x))) if x.size else 0.0
|
||||
|
|
@ -42,7 +42,9 @@ flowchart TD
|
|||
D --> Q
|
||||
F --> Q
|
||||
H --> Q
|
||||
Q --> K
|
||||
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"]
|
||||
|
|
@ -120,7 +122,15 @@ For dense runtime calibration, emit a low-level multiband chirplet texture inste
|
|||
.\.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 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.
|
||||
`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.
|
||||
|
||||
Publish live extracted phase-field meaning from an aligned field and known program/loopback reference:
|
||||
|
||||
```powershell
|
||||
.\.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
|
||||
```
|
||||
|
||||
This is not a phase oscilloscope. Raw phase bands stay internal. The live cache 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.
|
||||
|
||||
Record local mics while playing one speaker sweep. Use the output rate that the device probe says is real:
|
||||
|
||||
|
|
@ -207,6 +217,7 @@ The `play-record` and `record-field` commands remain for a `shared-input-device`
|
|||
- 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.
|
||||
- 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.
|
||||
|
||||
## Module Boundaries
|
||||
|
|
@ -219,6 +230,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.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.
|
||||
- `scripts/audio_field.py` stays as the operator CLI and hardware probe surface.
|
||||
|
|
|
|||
|
|
@ -37,6 +37,10 @@
|
|||
- `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 LocalCastBridge 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`.
|
||||
- `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.
|
||||
|
||||
## Temporary
|
||||
|
||||
|
|
@ -62,3 +66,4 @@
|
|||
13. Replace synthetic live-fusion observations with PS3 Eye detector observations and calibrated surface-feature tracks.
|
||||
14. 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.
|
||||
15. Let the co-streamer surface delay drive the shared presentation buffer horizon for audio stems, AmbiX, and remote video.
|
||||
16. Wire `stream_phase_field.py` to the real live aligned-field producer instead of replaying WAV artifacts, then feed its low-confidence state into the active chirplet probe optimizer.
|
||||
|
|
|
|||
|
|
@ -54,7 +54,9 @@ flowchart TD
|
|||
D --> Q
|
||||
F --> Q
|
||||
H --> Q
|
||||
Q --> K["delay + SRO alignment"]
|
||||
Q --> S["phase-meaning extractor"]
|
||||
S --> T["audio-phase-field.msgpack"]
|
||||
S --> K["delay + SRO alignment"]
|
||||
K --> L["bounded field cache"]
|
||||
L --> M["aligned six-channel blocks"]
|
||||
M --> N["FOA encoder"]
|
||||
|
|
@ -67,6 +69,7 @@ Ownership:
|
|||
- `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.
|
||||
- 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.
|
||||
- Active probe optimization owns extra chirplet emission when confidence drops, bounded by level/spacing/audibility budget.
|
||||
- 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.
|
||||
|
|
|
|||
|
|
@ -64,6 +64,19 @@ def msgpack_head(path: Path):
|
|||
"focusCount": len(payload[7]) if len(payload) > 7 else 0,
|
||||
}
|
||||
)
|
||||
elif summary["type"] == "localcast.audio.phase_field":
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"sampleRate": payload[3],
|
||||
"startSample": payload[4],
|
||||
"frameCount": payload[5],
|
||||
"referenceId": payload[6],
|
||||
"sourceCount": len(payload[7]) if len(payload) > 7 else 0,
|
||||
"globalConfidence": payload[8] if len(payload) > 8 else 0.0,
|
||||
"needsActiveProbe": payload[9] if len(payload) > 9 else True,
|
||||
}
|
||||
)
|
||||
elif summary["type"] in ("localcast.visual.stream_status", "localcast.audio.stream_status"):
|
||||
summary["payloadHead"] = head
|
||||
return summary
|
||||
|
|
@ -87,6 +100,7 @@ def main() -> None:
|
|||
"audio-events.msgpack",
|
||||
"visual-stream-status.msgpack",
|
||||
"audio-stream-status.msgpack",
|
||||
"audio-phase-field.msgpack",
|
||||
"stream-spout-status.json",
|
||||
"av-sync-status.json",
|
||||
]
|
||||
|
|
@ -99,6 +113,7 @@ def main() -> None:
|
|||
"visualHead": msgpack_head(runs / "visual-state.msgpack"),
|
||||
"audioHead": msgpack_head(runs / "audio-state.msgpack"),
|
||||
"eventsHead": msgpack_head(runs / "audio-events.msgpack"),
|
||||
"phaseFieldHead": msgpack_head(runs / "audio-phase-field.msgpack"),
|
||||
}
|
||||
print(json.dumps(payload, indent=2, default=str))
|
||||
|
||||
|
|
|
|||
137
scripts/stream_phase_field.py
Normal file
137
scripts/stream_phase_field.py
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
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 make_audio_phase_field, put_live_audio_phase_field # noqa: E402
|
||||
from audio_field.phase_meaning import LivePhaseMeaningExtractor # noqa: E402
|
||||
|
||||
|
||||
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 parse_frequencies(values: list[str]) -> list[float]:
|
||||
out: list[float] = []
|
||||
for value in values:
|
||||
out.extend(float(part) for part in value.split(",") if part.strip())
|
||||
return out
|
||||
|
||||
|
||||
def make_source_ids(count: int, explicit: list[str]) -> tuple[str, ...]:
|
||||
if explicit:
|
||||
if len(explicit) != count:
|
||||
raise SystemExit(f"expected {count} --source-id values, got {len(explicit)}")
|
||||
return tuple(explicit)
|
||||
return tuple(f"channel-{index}" for index in range(count))
|
||||
|
||||
|
||||
def source_dicts(meaning) -> list[dict]:
|
||||
rows = []
|
||||
for source in meaning.sources:
|
||||
rows.append(
|
||||
{
|
||||
"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,
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Publish live extracted phase-field meaning from reference and aligned mic WAVs.")
|
||||
parser.add_argument("--field", type=Path, required=True, help="Aligned frames-by-channel mic field WAV.")
|
||||
parser.add_argument("--reference", type=Path, required=True, help="Known program/loopback reference WAV.")
|
||||
parser.add_argument("--cache", type=Path, default=ROOT / "calibration" / "runs" / "audio-phase-field.msgpack")
|
||||
parser.add_argument("--source-id", action="append", default=[])
|
||||
parser.add_argument("--reference-id", default="program-reference")
|
||||
parser.add_argument("--frequency", action="append", default=["250,500,1000,2000,4000,8000,12000"])
|
||||
parser.add_argument("--chunk-frames", type=int, default=4096)
|
||||
parser.add_argument("--hop-frames", type=int, default=2048)
|
||||
parser.add_argument("--duration", type=float)
|
||||
parser.add_argument("--loop", action="store_true")
|
||||
parser.add_argument("--realtime", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
sample_rate, field = read_float_wav(args.field)
|
||||
reference_rate, reference = read_float_wav(args.reference)
|
||||
if reference_rate != sample_rate:
|
||||
raise SystemExit(f"reference sample rate {reference_rate} does not match field sample rate {sample_rate}")
|
||||
reference_mono = reference[:, 0]
|
||||
source_ids = make_source_ids(field.shape[1], args.source_id)
|
||||
extractor = LivePhaseMeaningExtractor(
|
||||
source_ids,
|
||||
sample_rate,
|
||||
parse_frequencies(args.frequency),
|
||||
reference_id=args.reference_id,
|
||||
)
|
||||
|
||||
start_monotonic = time.monotonic()
|
||||
audio_origin_ns = time.monotonic_ns()
|
||||
frame_id = 0
|
||||
cursor = 0
|
||||
max_samples = min(len(reference_mono), len(field))
|
||||
while cursor + args.chunk_frames <= max_samples:
|
||||
if args.duration is not None and time.monotonic() - start_monotonic >= args.duration:
|
||||
break
|
||||
block_ref = reference_mono[cursor : cursor + args.chunk_frames]
|
||||
block_field = field[cursor : cursor + args.chunk_frames]
|
||||
audio_time_ns = audio_origin_ns + int(cursor * 1_000_000_000 / sample_rate)
|
||||
meaning = extractor.update(
|
||||
block_ref,
|
||||
block_field,
|
||||
frame_id=frame_id,
|
||||
start_sample=cursor,
|
||||
audio_time_ns=audio_time_ns,
|
||||
)
|
||||
put_live_audio_phase_field(
|
||||
args.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=meaning.reference_id,
|
||||
sources=source_dicts(meaning),
|
||||
global_confidence=meaning.global_confidence,
|
||||
needs_active_probe=meaning.needs_active_probe,
|
||||
active_probe_reason=meaning.active_probe_reason,
|
||||
),
|
||||
)
|
||||
frame_id += 1
|
||||
cursor += args.hop_frames
|
||||
if cursor + args.chunk_frames > max_samples and args.loop:
|
||||
cursor = 0
|
||||
if args.realtime:
|
||||
target_time = start_monotonic + cursor / sample_rate
|
||||
sleep_for = target_time - time.monotonic()
|
||||
if sleep_for > 0:
|
||||
time.sleep(sleep_for)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -125,6 +125,15 @@ research:
|
|||
writes a heartbeat status file. This is a sink boundary, not a new scene
|
||||
authority; Aquarium should replace the renderer body behind the same
|
||||
RenderFramePacket contract for dense brush/splat rendering.
|
||||
live_audio_phase_meaning:
|
||||
summary: docs/audio-field.md
|
||||
key_decision: >
|
||||
Phase/chirplet evidence now has a live semantic boundary:
|
||||
`audio_field.phase_meaning` keeps raw phase internal and publishes
|
||||
`localcast.audio.phase_field` with delay correction, coherence,
|
||||
confidence, distance-equivalent delta, reference-bleed/suppression
|
||||
weights, correction energy, and active-probe need. This is learned
|
||||
audio-field state, not a phase display.
|
||||
sensor_fusion_architecture:
|
||||
summary: docs/sensor-fusion-architecture.md
|
||||
key_decision: >
|
||||
|
|
@ -212,7 +221,11 @@ current_status:
|
|||
except synchronized LocalCastBridge program surfaces. Co-streamer surface
|
||||
capture now records neighbor Focusrite and neighbor loopback while recording
|
||||
local loopback ground truth, then writes aligned co-streamer surface WAVs
|
||||
for the stem packer. The neighbor desktop launcher no longer uses
|
||||
for the stem packer. Live phase-field meaning now writes
|
||||
`localcast.audio.phase_field` to `calibration/runs/audio-phase-field.msgpack`
|
||||
from internal chirplet/phase evidence so downstream code sees delay,
|
||||
coherence, confidence, suppression, correction, and probe-control state
|
||||
instead of raw phases. The neighbor desktop launcher no longer uses
|
||||
Voicemeeter; it restores the Focusrite speakers as the primary playback
|
||||
device and the Focusrite analogue input as the default capture device. A
|
||||
direct Core Audio WASAPI loopback shim now works when launched in the
|
||||
|
|
|
|||
33
tests/test_phase_meaning.py
Normal file
33
tests/test_phase_meaning.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from audio_field.phase_meaning import LivePhaseMeaningExtractor
|
||||
|
||||
|
||||
class PhaseMeaningTests(unittest.TestCase):
|
||||
def test_extractor_turns_phase_evidence_into_actionable_state(self):
|
||||
sample_rate = 48000
|
||||
delay = 10
|
||||
t = np.arange(8192, dtype=np.float32) / sample_rate
|
||||
reference = (
|
||||
np.sin(2 * np.pi * 500 * t)
|
||||
+ 0.7 * np.sin(2 * np.pi * 1000 * t)
|
||||
+ 0.4 * np.sin(2 * np.pi * 2000 * t)
|
||||
).astype(np.float32)
|
||||
observed = np.pad(reference, (delay, 0))[: len(reference)]
|
||||
field = np.stack([observed, 0.05 * np.sin(2 * np.pi * 300 * t).astype(np.float32)], axis=1)
|
||||
extractor = LivePhaseMeaningExtractor(("anchor", "witness"), sample_rate, [500, 1000, 2000])
|
||||
|
||||
meaning = extractor.update(reference, field, frame_id=4, start_sample=2048, audio_time_ns=99)
|
||||
|
||||
self.assertEqual(4, meaning.frame_id)
|
||||
self.assertEqual(2, len(meaning.sources))
|
||||
self.assertGreater(meaning.sources[0].confidence, meaning.sources[1].confidence)
|
||||
self.assertGreater(meaning.sources[0].suppression_weight, 0.2)
|
||||
self.assertAlmostEqual(delay, meaning.sources[0].delay_samples, delta=2.0)
|
||||
self.assertTrue(meaning.needs_active_probe)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -7,10 +7,13 @@ import numpy as np
|
|||
from audio_field.cultcache_audio import (
|
||||
SPATIAL_AUDIO_SCHEMA_ID,
|
||||
frame_to_numpy,
|
||||
get_live_audio_phase_field,
|
||||
get_live_audio_source_events,
|
||||
get_live_spatial_audio_frame,
|
||||
make_audio_phase_field,
|
||||
make_audio_source_events,
|
||||
make_spatial_audio_frame,
|
||||
put_live_audio_phase_field,
|
||||
put_live_audio_source_events,
|
||||
put_live_spatial_audio_frame,
|
||||
)
|
||||
|
|
@ -68,6 +71,36 @@ class SpatialAudioCultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(1, loaded.events[0]["eventId"])
|
||||
self.assertEqual(4, loaded.voice_focus[0]["anchorChannel"])
|
||||
|
||||
def test_live_phase_field_round_trip_through_cultcache(self):
|
||||
field = make_audio_phase_field(
|
||||
frame_id=8,
|
||||
sample_rate=48000,
|
||||
start_sample=8192,
|
||||
frame_count=4096,
|
||||
audio_time_ns=456,
|
||||
reference_id="local-loopback",
|
||||
sources=[
|
||||
{
|
||||
"sourceId": "host-focusrite",
|
||||
"delaySamples": 12.5,
|
||||
"confidence": 0.92,
|
||||
"suppressionWeight": 0.6,
|
||||
}
|
||||
],
|
||||
global_confidence=0.72,
|
||||
needs_active_probe=False,
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "audio-phase-field.msgpack"
|
||||
put_live_audio_phase_field(path, field)
|
||||
loaded = get_live_audio_phase_field(path)
|
||||
|
||||
self.assertIsNotNone(loaded)
|
||||
self.assertEqual("local-loopback", loaded.reference_id)
|
||||
self.assertEqual(12.5, loaded.sources[0]["delaySamples"])
|
||||
self.assertFalse(loaded.needs_active_probe)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in a new issue