Remove script-era Python stack
This commit is contained in:
parent
d1eca0776e
commit
6ca7915f2b
191 changed files with 442 additions and 126676 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -3,8 +3,6 @@ config/audio-field.json
|
|||
logs/
|
||||
*.log
|
||||
*.tmp
|
||||
__pycache__/
|
||||
.venv/
|
||||
calibration/runs/
|
||||
tools/drivers/
|
||||
tools/obs-spout2-plugin/
|
||||
|
|
|
|||
27
AGENTS.md
27
AGENTS.md
|
|
@ -6,8 +6,7 @@ Mimir is the public face of this repo: the local realtime field machine for
|
|||
turning cameras, microphones, speakers, and timing signals into one coherent
|
||||
OBS-facing volumetric program surface.
|
||||
|
||||
`localcast` remains the implementation surface where existing scripts, ABIs,
|
||||
schemas, paths, and compatibility docs still use that name.
|
||||
Some native ABI names still use `localcast` until a deliberate rename cut exists.
|
||||
|
||||
Keep this repo blunt. The goal is not to fork OBS for sport. Use existing OBS and FFmpeg surfaces until a real invariant is impossible without native code.
|
||||
|
||||
|
|
@ -30,17 +29,6 @@ VoidBot heartbeat contract, read `docs/mimir-face.md`.
|
|||
changes. Put it in a separate state commit so Face memory and status do not
|
||||
stay stranded as local-only residue.
|
||||
|
||||
## Persistence Commands
|
||||
|
||||
Use a real Python if the Windows Store alias gets cute. In this Codex workstation, the bundled runtime is:
|
||||
`C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe`.
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_state.py status
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_state.py add-evidence --type decision --status ok --note "..."
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_prepare_compaction.py
|
||||
```
|
||||
|
||||
## Session Bootstrap And Re-entry Protocol
|
||||
|
||||
On a fresh session, do this before editing:
|
||||
|
|
@ -51,22 +39,23 @@ On a fresh session, do this before editing:
|
|||
- `notes/current-system-map.md`
|
||||
- `docs/implementation-plan.md`
|
||||
2. run:
|
||||
- `& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_state.py status`
|
||||
- `git status --short --branch`
|
||||
- `git log --oneline -5`
|
||||
- `Get-Content .\state\evidence.jsonl -Tail 8`
|
||||
3. restate the current mechanism, intended change, and next bounded move before broad edits
|
||||
|
||||
After compaction, resume, or suspicious continuity loss:
|
||||
|
||||
1. rerun `& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_state.py status`
|
||||
1. rerun `git status --short --branch`
|
||||
2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md`
|
||||
3. treat the persisted next action as orientation, not permission to wander
|
||||
|
||||
When the user says to prepare for imminent compaction:
|
||||
|
||||
1. run `tools/localcast_prepare_compaction.py` before editing persistence surfaces
|
||||
2. use its warnings as the checklist for map, handoff, scratch, evidence, and git hygiene
|
||||
1. immediately write the hot context into a collision-proof scratch file under `state/`
|
||||
2. use `state/map.yaml`, `notes/fresh-workspace-handoff.md`, `notes/current-system-map.md`, `state/scratch.md`, `state/evidence.jsonl`, and git status as the checklist for map, handoff, scratch, evidence, and git hygiene
|
||||
3. update only the state that actually changed
|
||||
4. run `tools/localcast_prepare_compaction.py` again after edits
|
||||
5. commit the completed persistence pass unless the work is deliberately mid-surgery
|
||||
4. commit the completed persistence pass unless the work is deliberately mid-surgery
|
||||
|
||||
## Operating Discipline
|
||||
|
||||
|
|
|
|||
20
README.md
20
README.md
|
|
@ -7,8 +7,8 @@ The public job is simple: make the physical room available as a synchronized
|
|||
OBS-facing program surface. The actual machine stays disciplined. Mimir owns
|
||||
configuration, calibration, launch, status, and typed contracts; Aquarium owns
|
||||
GPU fusion and Spout publication; Faust owns hot audio DSP; OBS owns broadcast
|
||||
composition. The old SRT bridge is compatibility scaffolding over the same
|
||||
boring truth: stable endpoints beat theatrical plumbing.
|
||||
composition. The SRT bridge is compatibility scaffolding over the same boring
|
||||
truth: stable endpoints beat theatrical plumbing.
|
||||
|
||||
Start with `docs/perfect-machine.md` for the live architecture.
|
||||
|
||||
|
|
@ -58,11 +58,11 @@ That path is stricter than the OBS endpoint path: microphones feeding the Ambiso
|
|||
|
||||
## Current Status
|
||||
|
||||
This repo is the first coherent scaffold for Mimir: architecture docs,
|
||||
persistence machinery, and Windows scripts for device discovery, config
|
||||
validation, and FFmpeg command generation. The deeper target is the native
|
||||
five-second reservoir feeding Aquarium and Faust; the bridge scripts remain the
|
||||
plain, inspectable path into OBS while the field machine grows teeth.
|
||||
This repo now has a C# app/runtime surface plus the first native reservoir
|
||||
crate. `src/Mimir.Runtime` owns the rolling synchronization buffers and direct
|
||||
driver ingest seams; `src/Mimir.App` hosts the Aquarium Engine window/render
|
||||
bridge. The Windows scripts remain a plain LAN bridge into OBS while the native
|
||||
field machine grows teeth.
|
||||
|
||||
## Quick Start
|
||||
|
||||
|
|
@ -98,11 +98,13 @@ OBS documents SRT playback through VLC Source or Media Source, and Media Source
|
|||
|
||||
## Repo State
|
||||
|
||||
Rehydrate with the bundled Python from this Codex workstation, or any normal Python 3:
|
||||
Rehydrate with the map, handoff, and git. No helper runtime is required:
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_state.py status
|
||||
git status --short --branch
|
||||
git log --oneline -5
|
||||
Get-Content .\state\map.yaml
|
||||
Get-Content .\notes\fresh-workspace-handoff.md
|
||||
Get-Content .\notes\current-system-map.md
|
||||
Get-Content .\state\evidence.jsonl -Tail 8
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
"""Core audio-field building blocks for Mimir."""
|
||||
|
|
@ -1,278 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
from scipy.io import wavfile
|
||||
|
||||
from audio_field.phase_meaning import PhaseFieldMeaning
|
||||
from audio_field.probe_optimizer import ActiveProbeOptimizer, ProbeRequest
|
||||
from audio_field.runtime_sync import SyncState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EmittedProbe:
|
||||
request: ProbeRequest
|
||||
sample_rate: int
|
||||
start_hz: float
|
||||
end_hz: float
|
||||
duration_seconds: float
|
||||
channel: int
|
||||
path: Path
|
||||
emitted_monotonic_ns: int
|
||||
|
||||
|
||||
class ActiveConfidenceMaintainer:
|
||||
"""Turns low phase-field confidence into bounded active chirplet probes."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
optimizer: ActiveProbeOptimizer,
|
||||
*,
|
||||
sample_rate: int,
|
||||
output_dir: Path,
|
||||
duration_seconds: float = 0.03,
|
||||
start_hz: float = 1800.0,
|
||||
end_hz: float = 9000.0,
|
||||
channels: int = 2,
|
||||
channel: int = 0,
|
||||
pattern: str = "single",
|
||||
harmonic_root_hz: float = 440.0,
|
||||
harmonic_voices: int = 24,
|
||||
max_artifacts: int = 512,
|
||||
manifest_max_bytes: int = 1_000_000,
|
||||
eligible_source_ids: set[str] | frozenset[str] | None = None,
|
||||
):
|
||||
self.optimizer = optimizer
|
||||
self.sample_rate = int(sample_rate)
|
||||
self.output_dir = Path(output_dir)
|
||||
self.duration_seconds = float(duration_seconds)
|
||||
self.start_hz = float(start_hz)
|
||||
self.end_hz = float(end_hz)
|
||||
self.channels = int(channels)
|
||||
self.channel = int(channel)
|
||||
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)
|
||||
self.eligible_source_ids = None if eligible_source_ids is None else frozenset(str(source_id) for source_id in eligible_source_ids)
|
||||
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:
|
||||
states = sync_states_from_phase_meaning(meaning)
|
||||
if self.eligible_source_ids is not None:
|
||||
states = {source_id: state for source_id, state in states.items() if source_id in self.eligible_source_ids}
|
||||
if not states:
|
||||
return None
|
||||
masked = force_masked or is_masked_window(reference_block)
|
||||
request = self.optimizer.choose_probe(meaning.frame_id, states, masked_window=masked)
|
||||
if request is None:
|
||||
return None
|
||||
waveform = make_probe_waveform(
|
||||
self.sample_rate,
|
||||
duration_seconds=self.duration_seconds,
|
||||
start_hz=self.start_hz,
|
||||
end_hz=self.end_hz,
|
||||
level_dbfs=request.level_dbfs,
|
||||
channels=self.channels,
|
||||
channel=self.channel,
|
||||
pattern=self.pattern,
|
||||
harmonic_root_hz=self.harmonic_root_hz,
|
||||
harmonic_voices=self.harmonic_voices,
|
||||
)
|
||||
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,
|
||||
sample_rate=self.sample_rate,
|
||||
start_hz=self.start_hz,
|
||||
end_hz=self.end_hz,
|
||||
duration_seconds=self.duration_seconds,
|
||||
channel=self.channel,
|
||||
path=path,
|
||||
emitted_monotonic_ns=time.monotonic_ns(),
|
||||
)
|
||||
append_probe_manifest(
|
||||
self.output_dir / "active-probes.jsonl",
|
||||
emitted,
|
||||
max_bytes=self.manifest_max_bytes,
|
||||
)
|
||||
return emitted
|
||||
|
||||
|
||||
def sync_states_from_phase_meaning(meaning: PhaseFieldMeaning) -> dict[str, SyncState]:
|
||||
return {
|
||||
source.source_id: SyncState(
|
||||
delay_samples=source.smoothed_delay_samples,
|
||||
phase_radians=0.0,
|
||||
rate_scale=1.0,
|
||||
confidence=source.confidence,
|
||||
last_frame_index=meaning.frame_id,
|
||||
)
|
||||
for source in meaning.sources
|
||||
}
|
||||
|
||||
|
||||
def is_masked_window(reference_block: np.ndarray, *, min_rms_dbfs: float = -42.0, crest_factor_limit: float = 8.0) -> bool:
|
||||
samples = np.asarray(reference_block, dtype=np.float32).reshape(-1)
|
||||
if samples.size == 0:
|
||||
return False
|
||||
rms = float(np.sqrt(np.mean(samples.astype(np.float64) ** 2)))
|
||||
if rms <= db_to_amp(min_rms_dbfs):
|
||||
return False
|
||||
peak = float(np.max(np.abs(samples)))
|
||||
crest = peak / max(rms, 1e-12)
|
||||
return crest <= float(crest_factor_limit)
|
||||
|
||||
|
||||
def make_probe_chirplet(
|
||||
sample_rate: int,
|
||||
*,
|
||||
duration_seconds: float,
|
||||
start_hz: float,
|
||||
end_hz: float,
|
||||
level_dbfs: float,
|
||||
channels: int = 2,
|
||||
channel: int = 0,
|
||||
) -> np.ndarray:
|
||||
frames = max(8, int(round(float(duration_seconds) * int(sample_rate))))
|
||||
t = np.arange(frames, dtype=np.float64) / float(sample_rate)
|
||||
chirp = signal.chirp(t, f0=float(start_hz), f1=float(end_hz), t1=float(duration_seconds), method="linear")
|
||||
taper = signal.windows.tukey(frames, alpha=0.5)
|
||||
chirp = chirp * taper
|
||||
peak = float(np.max(np.abs(chirp)))
|
||||
if peak > 0.0:
|
||||
chirp = chirp / peak
|
||||
chirp = chirp * db_to_amp(level_dbfs)
|
||||
out = np.zeros((frames, int(channels)), dtype=np.float32)
|
||||
out[:, int(channel)] = chirp.astype(np.float32)
|
||||
return out
|
||||
|
||||
|
||||
def make_probe_waveform(
|
||||
sample_rate: int,
|
||||
*,
|
||||
duration_seconds: float,
|
||||
start_hz: float,
|
||||
end_hz: float,
|
||||
level_dbfs: float,
|
||||
channels: int = 2,
|
||||
channel: int = 0,
|
||||
pattern: str = "single",
|
||||
harmonic_root_hz: float = 440.0,
|
||||
harmonic_voices: int = 24,
|
||||
) -> np.ndarray:
|
||||
if pattern == "single":
|
||||
return make_probe_chirplet(
|
||||
sample_rate,
|
||||
duration_seconds=duration_seconds,
|
||||
start_hz=start_hz,
|
||||
end_hz=end_hz,
|
||||
level_dbfs=level_dbfs,
|
||||
channels=channels,
|
||||
channel=channel,
|
||||
)
|
||||
if pattern == "harmonic-dense":
|
||||
return make_harmonic_probe_texture(
|
||||
sample_rate,
|
||||
duration_seconds=duration_seconds,
|
||||
start_hz=start_hz,
|
||||
end_hz=end_hz,
|
||||
level_dbfs=level_dbfs,
|
||||
channels=channels,
|
||||
channel=channel,
|
||||
root_hz=harmonic_root_hz,
|
||||
voices=harmonic_voices,
|
||||
)
|
||||
raise ValueError(f"unknown probe pattern: {pattern}")
|
||||
|
||||
|
||||
def make_harmonic_probe_texture(
|
||||
sample_rate: int,
|
||||
*,
|
||||
duration_seconds: float,
|
||||
start_hz: float,
|
||||
end_hz: float,
|
||||
level_dbfs: float,
|
||||
channels: int = 2,
|
||||
channel: int = 0,
|
||||
root_hz: float = 440.0,
|
||||
voices: int = 24,
|
||||
) -> np.ndarray:
|
||||
frames = max(8, int(round(float(duration_seconds) * int(sample_rate))))
|
||||
texture = np.zeros(frames, dtype=np.float64)
|
||||
harmonics = harmonic_frequencies(float(root_hz), float(start_hz), float(end_hz))
|
||||
if not harmonics:
|
||||
harmonics = list(np.linspace(float(start_hz), float(end_hz), max(1, int(voices))))
|
||||
span_hz = max(40.0, min(420.0, (float(end_hz) - float(start_hz)) / max(4.0, float(voices))))
|
||||
voice_count = max(1, int(voices))
|
||||
for index in range(voice_count):
|
||||
center = harmonics[index % len(harmonics)]
|
||||
direction = -1.0 if index % 2 else 1.0
|
||||
f0 = clamp(center - direction * span_hz * 0.5, float(start_hz), float(end_hz))
|
||||
f1 = clamp(center + direction * span_hz * 0.5, float(start_hz), float(end_hz))
|
||||
voice_frames = max(8, min(frames, int(round(frames * 0.38))))
|
||||
offset = int(((index * 0.61803398875) % 1.0) * max(1, frames - voice_frames))
|
||||
t = np.arange(voice_frames, dtype=np.float64) / float(sample_rate)
|
||||
chirp = signal.chirp(t, f0=f0, f1=f1, t1=voice_frames / float(sample_rate), method="linear")
|
||||
chirp *= signal.windows.tukey(voice_frames, alpha=0.7)
|
||||
chirp *= 0.55 + 0.45 * ((index % 5) / 4.0)
|
||||
texture[offset : offset + voice_frames] += chirp
|
||||
peak = float(np.max(np.abs(texture)))
|
||||
if peak > 0.0:
|
||||
texture = texture / peak
|
||||
texture *= db_to_amp(level_dbfs)
|
||||
out = np.zeros((frames, int(channels)), dtype=np.float32)
|
||||
out[:, int(channel)] = texture.astype(np.float32)
|
||||
return out
|
||||
|
||||
|
||||
def harmonic_frequencies(root_hz: float, start_hz: float, end_hz: float) -> list[float]:
|
||||
if root_hz <= 0.0:
|
||||
raise ValueError("root_hz must be positive")
|
||||
first = max(1, int(math.ceil(start_hz / root_hz)))
|
||||
last = int(math.floor(end_hz / root_hz))
|
||||
return [root_hz * harmonic for harmonic in range(first, last + 1)]
|
||||
|
||||
|
||||
def clamp(value: float, low: float, high: float) -> float:
|
||||
return max(low, min(high, value))
|
||||
|
||||
|
||||
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, *, max_bytes: int = 1_000_000) -> None:
|
||||
row = {
|
||||
"frameIndex": emitted.request.frame_index,
|
||||
"sourceId": emitted.request.source_id,
|
||||
"reason": emitted.request.reason,
|
||||
"levelDbfs": emitted.request.level_dbfs,
|
||||
"urgency": emitted.request.urgency,
|
||||
"sampleRate": emitted.sample_rate,
|
||||
"startHz": emitted.start_hz,
|
||||
"endHz": emitted.end_hz,
|
||||
"durationSeconds": emitted.duration_seconds,
|
||||
"channel": emitted.channel,
|
||||
"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")
|
||||
|
|
@ -1,102 +0,0 @@
|
|||
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)
|
||||
|
|
@ -1,576 +0,0 @@
|
|||
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"
|
||||
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"
|
||||
LIVE_MIC_FIELD_KEY = "localcast.audio.mic-field.live"
|
||||
MIC_FIELD_SCHEMA_ID = "gamecult.localcast.audio.mic_field.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
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultAudioSourceEvents:
|
||||
schema_version: str
|
||||
frame_id: int
|
||||
audio_time_ns: int
|
||||
sample_rate: int
|
||||
start_sample: int
|
||||
frame_count: int
|
||||
events: tuple[dict[str, Any], ...]
|
||||
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
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultAudioMicFieldFrame:
|
||||
schema_version: str
|
||||
frame_id: int
|
||||
created_monotonic_ns: int
|
||||
audio_time_ns: int
|
||||
sample_rate: int
|
||||
start_sample: int
|
||||
frame_count: int
|
||||
channels: tuple[str, ...]
|
||||
roles: tuple[dict[str, Any], ...]
|
||||
graph_id: str
|
||||
controls: tuple[dict[str, Any], ...]
|
||||
sample_format: str
|
||||
interleaved_pcm_f32le: bytes
|
||||
|
||||
|
||||
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]),
|
||||
)
|
||||
|
||||
|
||||
def _encode_source_events(events: CultAudioSourceEvents) -> list[Any]:
|
||||
return [
|
||||
events.schema_version,
|
||||
events.frame_id,
|
||||
events.audio_time_ns,
|
||||
events.sample_rate,
|
||||
events.start_sample,
|
||||
events.frame_count,
|
||||
list(events.events),
|
||||
list(events.voice_focus),
|
||||
]
|
||||
|
||||
|
||||
def _decode_source_events(raw: Any) -> CultAudioSourceEvents:
|
||||
return CultAudioSourceEvents(
|
||||
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]),
|
||||
events=tuple(dict(item) for item in raw[6]),
|
||||
voice_focus=tuple(dict(item) for item in raw[7]),
|
||||
)
|
||||
|
||||
|
||||
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]),
|
||||
)
|
||||
|
||||
|
||||
def _encode_mic_field(frame: CultAudioMicFieldFrame) -> 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,
|
||||
list(frame.channels),
|
||||
list(frame.roles),
|
||||
frame.graph_id,
|
||||
list(frame.controls),
|
||||
frame.sample_format,
|
||||
frame.interleaved_pcm_f32le,
|
||||
]
|
||||
|
||||
|
||||
def _decode_mic_field(raw: Any) -> CultAudioMicFieldFrame:
|
||||
return CultAudioMicFieldFrame(
|
||||
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]),
|
||||
channels=tuple(str(channel) for channel in raw[7]),
|
||||
roles=tuple(dict(item) for item in raw[8]),
|
||||
graph_id=str(raw[9]),
|
||||
controls=tuple(dict(item) for item in raw[10]),
|
||||
sample_format=str(raw[11]),
|
||||
interleaved_pcm_f32le=bytes(raw[12]),
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
SOURCE_EVENTS_DOCUMENT = define_document_type(
|
||||
"localcast.audio.source_events",
|
||||
encode=_encode_source_events,
|
||||
decode=_decode_source_events,
|
||||
name=lambda events: LIVE_SOURCE_EVENTS_KEY if isinstance(events, CultAudioSourceEvents) else None,
|
||||
payload_encoder=_pack,
|
||||
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,
|
||||
)
|
||||
|
||||
MIC_FIELD_DOCUMENT = define_document_type(
|
||||
"localcast.audio.mic_field",
|
||||
encode=_encode_mic_field,
|
||||
decode=_decode_mic_field,
|
||||
name=lambda frame: LIVE_MIC_FIELD_KEY if isinstance(frame, CultAudioMicFieldFrame) 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)
|
||||
.register_document_type(SOURCE_EVENTS_DOCUMENT)
|
||||
.register_document_type(PHASE_FIELD_DOCUMENT)
|
||||
.register_document_type(MIC_FIELD_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="<f4").tobytes(),
|
||||
)
|
||||
|
||||
|
||||
def frame_to_numpy(frame: CultSpatialAudioFrame) -> 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="<f4")
|
||||
return pcm.reshape((frame.frame_count, len(frame.channels))).copy()
|
||||
|
||||
|
||||
def put_live_spatial_audio_frame(path: Path, frame: CultSpatialAudioFrame) -> 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)
|
||||
|
||||
|
||||
def make_audio_source_events(
|
||||
*,
|
||||
frame_id: int,
|
||||
sample_rate: int,
|
||||
start_sample: int,
|
||||
frame_count: int,
|
||||
audio_time_ns: int,
|
||||
events: list[dict[str, Any]],
|
||||
voice_focus: list[dict[str, Any]],
|
||||
) -> CultAudioSourceEvents:
|
||||
return CultAudioSourceEvents(
|
||||
schema_version=SOURCE_EVENTS_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),
|
||||
events=tuple(dict(item) for item in events),
|
||||
voice_focus=tuple(dict(item) for item in voice_focus),
|
||||
)
|
||||
|
||||
|
||||
def put_live_audio_source_events(path: Path, events: CultAudioSourceEvents) -> None:
|
||||
def operation() -> None:
|
||||
cache = open_audio_cache(path)
|
||||
cache.put(SOURCE_EVENTS_DOCUMENT, LIVE_SOURCE_EVENTS_KEY, events)
|
||||
|
||||
_retry_cache_io(operation)
|
||||
|
||||
|
||||
def get_live_audio_source_events(path: Path) -> CultAudioSourceEvents | None:
|
||||
def operation() -> CultAudioSourceEvents | None:
|
||||
cache = open_audio_cache(path)
|
||||
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)
|
||||
|
||||
|
||||
DEFAULT_MIC_FIELD_CHANNELS = (
|
||||
"host-focusrite",
|
||||
"co-streamer-focusrite",
|
||||
"kiyo-0",
|
||||
"kiyo-1",
|
||||
"ps-eye-0",
|
||||
"ps-eye-1",
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_MIC_FIELD_ROLES = (
|
||||
{"channel": 0, "sourceId": "host-focusrite", "role": "host-voice-anchor"},
|
||||
{"channel": 1, "sourceId": "co-streamer-focusrite", "role": "co-streamer-voice-anchor"},
|
||||
{"channel": 2, "sourceId": "kiyo-0", "role": "room-witness"},
|
||||
{"channel": 3, "sourceId": "kiyo-1", "role": "room-witness"},
|
||||
{"channel": 4, "sourceId": "ps-eye-0", "role": "spatial-witness"},
|
||||
{"channel": 5, "sourceId": "ps-eye-1", "role": "spatial-witness"},
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_FAUST_VOICE_CONTROLS = (
|
||||
{"path": "/host/gain", "value": 1.0},
|
||||
{"path": "/host/witness_reject", "value": 0.35},
|
||||
{"path": "/co_streamer/gain", "value": 1.0},
|
||||
{"path": "/co_streamer/witness_reject", "value": 0.35},
|
||||
{"path": "/ambient/gain", "value": 0.6},
|
||||
{"path": "/transients/gain", "value": 0.7},
|
||||
)
|
||||
|
||||
|
||||
def make_mic_field_frame(
|
||||
block: np.ndarray,
|
||||
*,
|
||||
frame_id: int,
|
||||
sample_rate: int,
|
||||
start_sample: int,
|
||||
audio_time_ns: int,
|
||||
channels: tuple[str, ...] = DEFAULT_MIC_FIELD_CHANNELS,
|
||||
roles: tuple[dict[str, Any], ...] = DEFAULT_MIC_FIELD_ROLES,
|
||||
graph_id: str = "localcast.faust.voice_separation.v1",
|
||||
controls: tuple[dict[str, Any], ...] = DEFAULT_FAUST_VOICE_CONTROLS,
|
||||
) -> CultAudioMicFieldFrame:
|
||||
pcm = np.asarray(block, dtype=np.float32)
|
||||
if pcm.ndim != 2:
|
||||
raise ValueError("mic field 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 CultAudioMicFieldFrame(
|
||||
schema_version=MIC_FIELD_SCHEMA_ID,
|
||||
frame_id=int(frame_id),
|
||||
created_monotonic_ns=time.monotonic_ns(),
|
||||
audio_time_ns=int(audio_time_ns),
|
||||
sample_rate=int(sample_rate),
|
||||
start_sample=int(start_sample),
|
||||
frame_count=int(pcm.shape[0]),
|
||||
channels=tuple(channels),
|
||||
roles=tuple(dict(item) for item in roles),
|
||||
graph_id=str(graph_id),
|
||||
controls=tuple(dict(item) for item in controls),
|
||||
sample_format="f32le-interleaved",
|
||||
interleaved_pcm_f32le=np.ascontiguousarray(pcm, dtype="<f4").tobytes(),
|
||||
)
|
||||
|
||||
|
||||
def mic_field_to_numpy(frame: CultAudioMicFieldFrame) -> 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="<f4")
|
||||
return pcm.reshape((frame.frame_count, len(frame.channels))).copy()
|
||||
|
||||
|
||||
def put_live_mic_field_frame(path: Path, frame: CultAudioMicFieldFrame) -> None:
|
||||
def operation() -> None:
|
||||
cache = open_audio_cache(path)
|
||||
cache.put(MIC_FIELD_DOCUMENT, LIVE_MIC_FIELD_KEY, frame)
|
||||
|
||||
_retry_cache_io(operation)
|
||||
|
||||
|
||||
def get_live_mic_field_frame(path: Path) -> CultAudioMicFieldFrame | None:
|
||||
def operation() -> CultAudioMicFieldFrame | None:
|
||||
cache = open_audio_cache(path)
|
||||
return cache.get(MIC_FIELD_DOCUMENT, LIVE_MIC_FIELD_KEY)
|
||||
|
||||
return _retry_cache_io(operation)
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
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
|
||||
|
|
@ -1,167 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PhaseBand:
|
||||
frequency_hz: float
|
||||
phase_delta_radians: float
|
||||
coherence: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PhaseDelayEstimate:
|
||||
delay_samples: float
|
||||
delay_ms: float
|
||||
fit_error_radians: float
|
||||
bands: tuple[PhaseBand, ...]
|
||||
|
||||
|
||||
class SmoothPhaseField:
|
||||
"""Smooths phase-derived delay deltas over a bounded evidence window."""
|
||||
|
||||
def __init__(self, smoothing: float = 0.25, max_step_samples: float = 32.0):
|
||||
if not 0.0 <= smoothing <= 1.0:
|
||||
raise ValueError("smoothing must be between 0 and 1")
|
||||
self.smoothing = float(smoothing)
|
||||
self.max_step_samples = float(max_step_samples)
|
||||
self._delay_by_source: dict[str, float] = {}
|
||||
|
||||
def update(self, source_id: str, delay_delta_samples: float, confidence: float) -> float:
|
||||
previous = self._delay_by_source.get(source_id)
|
||||
if previous is None:
|
||||
self._delay_by_source[source_id] = float(delay_delta_samples)
|
||||
return float(delay_delta_samples)
|
||||
step = float(delay_delta_samples) - previous
|
||||
step = max(-self.max_step_samples, min(self.max_step_samples, step))
|
||||
alpha = self.smoothing * max(0.0, min(1.0, float(confidence)))
|
||||
updated = previous + alpha * step
|
||||
self._delay_by_source[source_id] = updated
|
||||
return updated
|
||||
|
||||
def state(self) -> dict[str, float]:
|
||||
return dict(self._delay_by_source)
|
||||
|
||||
|
||||
class IterativeFrequencyPhaseMapper:
|
||||
"""Learns a smooth per-source frequency correction from phase residuals."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
frequencies_hz: list[float] | tuple[float, ...],
|
||||
sample_rate: int,
|
||||
*,
|
||||
learning_rate: float = 0.2,
|
||||
max_phase_step_radians: float = 0.2,
|
||||
):
|
||||
self.frequencies_hz = tuple(float(f) for f in frequencies_hz)
|
||||
self.sample_rate = int(sample_rate)
|
||||
self.learning_rate = float(learning_rate)
|
||||
self.max_phase_step_radians = float(max_phase_step_radians)
|
||||
self._phase_by_source: dict[str, np.ndarray] = {}
|
||||
|
||||
def correction_for(self, source_id: str) -> np.ndarray:
|
||||
return self._phase_by_source.get(source_id, np.zeros(len(self.frequencies_hz), dtype=np.float64)).copy()
|
||||
|
||||
def update(self, source_id: str, estimate: PhaseDelayEstimate, confidence: float) -> np.ndarray:
|
||||
current = self._phase_by_source.get(source_id)
|
||||
if current is None:
|
||||
current = np.zeros(len(self.frequencies_hz), dtype=np.float64)
|
||||
residual = phase_residuals_with_sample_rate(self.frequencies_hz, estimate, self.sample_rate)
|
||||
if len(residual) != len(current):
|
||||
return current.copy()
|
||||
step = -self.learning_rate * max(0.0, min(1.0, float(confidence))) * residual
|
||||
step = np.clip(step, -self.max_phase_step_radians, self.max_phase_step_radians)
|
||||
updated = current + step
|
||||
self._phase_by_source[source_id] = updated
|
||||
return updated.copy()
|
||||
|
||||
def state(self) -> dict[str, list[float]]:
|
||||
return {source_id: values.tolist() for source_id, values in self._phase_by_source.items()}
|
||||
|
||||
|
||||
def phase_residuals_with_sample_rate(frequencies_hz: tuple[float, ...] | list[float], estimate: PhaseDelayEstimate, sample_rate: int) -> np.ndarray:
|
||||
by_frequency = {round(band.frequency_hz, 6): band.phase_delta_radians for band in estimate.bands}
|
||||
delay_seconds = estimate.delay_samples / float(sample_rate)
|
||||
residuals = []
|
||||
for frequency in frequencies_hz:
|
||||
phase = by_frequency.get(round(float(frequency), 6))
|
||||
if phase is None:
|
||||
return np.asarray([], dtype=np.float64)
|
||||
expected = -2.0 * math.pi * float(frequency) * delay_seconds
|
||||
residuals.append(wrap_phase(phase - expected))
|
||||
return np.asarray(residuals, dtype=np.float64)
|
||||
|
||||
|
||||
def wrap_phase(value: float) -> float:
|
||||
return (float(value) + math.pi) % (2.0 * math.pi) - math.pi
|
||||
|
||||
|
||||
def estimate_phase_delay(
|
||||
reference: np.ndarray,
|
||||
observed: np.ndarray,
|
||||
sample_rate: int,
|
||||
frequencies_hz: list[float] | tuple[float, ...],
|
||||
*,
|
||||
max_abs_delay_ms: float = 3.0,
|
||||
) -> PhaseDelayEstimate:
|
||||
ref = np.asarray(reference, dtype=np.float32).reshape(-1)
|
||||
obs = np.asarray(observed, dtype=np.float32).reshape(-1)
|
||||
count = min(len(ref), len(obs))
|
||||
if count < 8:
|
||||
return PhaseDelayEstimate(0.0, 0.0, 0.0, tuple())
|
||||
ref = ref[:count] - float(np.mean(ref[:count]))
|
||||
obs = obs[:count] - float(np.mean(obs[:count]))
|
||||
window = np.hanning(count).astype(np.float32)
|
||||
ref = ref * window
|
||||
obs = obs * window
|
||||
fft_size = int(2 ** math.ceil(math.log2(max(16, count))))
|
||||
ref_fft = np.fft.rfft(ref, n=fft_size)
|
||||
obs_fft = np.fft.rfft(obs, n=fft_size)
|
||||
bin_hz = float(sample_rate) / float(fft_size)
|
||||
|
||||
rows = []
|
||||
phases = []
|
||||
weights = []
|
||||
bands = []
|
||||
for frequency in frequencies_hz:
|
||||
if frequency <= 0 or frequency >= sample_rate / 2:
|
||||
continue
|
||||
index = int(round(float(frequency) / bin_hz))
|
||||
if index <= 0 or index >= len(ref_fft):
|
||||
continue
|
||||
cross = obs_fft[index] * np.conj(ref_fft[index])
|
||||
magnitude = float(abs(cross))
|
||||
denom = float(abs(obs_fft[index]) * abs(ref_fft[index]))
|
||||
coherence = 0.0 if denom <= 1e-12 else max(0.0, min(1.0, magnitude / denom))
|
||||
if magnitude <= 1e-12:
|
||||
continue
|
||||
phase = float(np.angle(cross))
|
||||
rows.append([-2.0 * math.pi * float(frequency), 1.0])
|
||||
phases.append(phase)
|
||||
weights.append(max(1e-6, coherence))
|
||||
bands.append(PhaseBand(float(frequency), phase, coherence))
|
||||
if len(rows) < 2:
|
||||
return PhaseDelayEstimate(0.0, 0.0, 0.0, tuple(bands))
|
||||
|
||||
phases_array = np.unwrap(np.asarray(phases, dtype=np.float64))
|
||||
design = np.asarray(rows, dtype=np.float64)
|
||||
weights_array = np.sqrt(np.asarray(weights, dtype=np.float64))
|
||||
weighted_design = design * weights_array[:, None]
|
||||
weighted_phase = phases_array * weights_array
|
||||
delay_seconds, phase_offset = np.linalg.lstsq(weighted_design, weighted_phase, rcond=None)[0]
|
||||
max_abs_delay = float(max_abs_delay_ms) / 1000.0
|
||||
delay_seconds = max(-max_abs_delay, min(max_abs_delay, float(delay_seconds)))
|
||||
fitted = design @ np.asarray([delay_seconds, phase_offset])
|
||||
fit_error = float(np.sqrt(np.mean((phases_array - fitted) ** 2)))
|
||||
delay_samples = delay_seconds * float(sample_rate)
|
||||
return PhaseDelayEstimate(
|
||||
delay_samples=delay_samples,
|
||||
delay_ms=1000.0 * delay_seconds,
|
||||
fit_error_radians=fit_error,
|
||||
bands=tuple(bands),
|
||||
)
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
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
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
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
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
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."""
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
"""Probe-band selection helpers without diagnostic runtime dependencies."""
|
||||
|
||||
|
||||
def parse_probe_band(value: str) -> tuple[float, float]:
|
||||
parts = value.split(":")
|
||||
if len(parts) != 2:
|
||||
raise ValueError(f"probe band must be start:end Hz, got {value!r}")
|
||||
return float(parts[0]), float(parts[1])
|
||||
|
||||
|
||||
def ultrasonic_probe_band(sample_rate: int) -> tuple[float, float]:
|
||||
nyquist = 0.5 * float(sample_rate)
|
||||
end_hz = min(22_000.0, nyquist - 1200.0)
|
||||
start_hz = min(18_500.0, end_hz - 2500.0)
|
||||
if end_hz <= 16_000.0 or start_hz <= 0.0:
|
||||
raise ValueError(f"sample rate {sample_rate} leaves no useful ultrasonic probe band")
|
||||
return start_hz, end_hz
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from audio_field.runtime_sync import SyncState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProbePolicy:
|
||||
target_confidence: float = 0.65
|
||||
trigger_confidence: float = 0.35
|
||||
min_interval_frames: int = 45
|
||||
max_probe_level_dbfs: float = -18.0
|
||||
prefer_masked_windows: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProbeRequest:
|
||||
frame_index: int
|
||||
source_id: str
|
||||
reason: str
|
||||
level_dbfs: float
|
||||
urgency: float
|
||||
|
||||
|
||||
class ActiveProbeOptimizer:
|
||||
"""Schedules intentional chirplets when runtime sync confidence is weak."""
|
||||
|
||||
def __init__(self, policy: ProbePolicy):
|
||||
self.policy = policy
|
||||
self._last_probe_frame: int | None = None
|
||||
|
||||
def choose_probe(
|
||||
self,
|
||||
frame_index: int,
|
||||
states: dict[str, SyncState],
|
||||
masked_window: bool = False,
|
||||
) -> ProbeRequest | None:
|
||||
if self._last_probe_frame is not None:
|
||||
if frame_index - self._last_probe_frame < self.policy.min_interval_frames:
|
||||
return None
|
||||
if self.policy.prefer_masked_windows and not masked_window:
|
||||
return None
|
||||
|
||||
weak = [
|
||||
(source_id, state)
|
||||
for source_id, state in states.items()
|
||||
if state.confidence < self.policy.trigger_confidence
|
||||
]
|
||||
if not weak:
|
||||
return None
|
||||
|
||||
source_id, state = min(weak, key=lambda item: item[1].confidence)
|
||||
urgency = max(0.0, self.policy.target_confidence - state.confidence)
|
||||
self._last_probe_frame = frame_index
|
||||
return ProbeRequest(
|
||||
frame_index=frame_index,
|
||||
source_id=source_id,
|
||||
reason="sync-confidence-below-trigger",
|
||||
level_dbfs=self.policy.max_probe_level_dbfs,
|
||||
urgency=urgency,
|
||||
)
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
"""Audio-field profile helpers with no runtime device dependencies."""
|
||||
|
||||
from localcast.sensor_fusion import phase_source_id_for_microphone
|
||||
|
||||
|
||||
HOST_SOURCE_BY_MIC_ID = {
|
||||
"mic_focusrite_local": "host-focusrite",
|
||||
"mic_focusrite_neighbor": "co-streamer-focusrite",
|
||||
}
|
||||
|
||||
|
||||
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)]
|
||||
|
|
@ -1,105 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReferenceSuppressionReport:
|
||||
channel: int
|
||||
input_rms: float
|
||||
predicted_rms: float
|
||||
output_rms: float
|
||||
reduction_db: float
|
||||
phase_mapping: tuple[tuple[float, float, float], ...]
|
||||
|
||||
|
||||
def suppress_program_reference(
|
||||
field: np.ndarray,
|
||||
reference: np.ndarray,
|
||||
sample_rate: int,
|
||||
channels: list[int] | tuple[int, ...],
|
||||
*,
|
||||
nperseg: int = 2048,
|
||||
noverlap: int = 1536,
|
||||
regularization: float = 1e-6,
|
||||
subtraction_strength: float = 0.85,
|
||||
) -> tuple[np.ndarray, list[ReferenceSuppressionReport]]:
|
||||
x = np.asarray(field, dtype=np.float32)
|
||||
ref = np.asarray(reference, dtype=np.float32).reshape(-1)
|
||||
if x.ndim != 2:
|
||||
raise ValueError("field must be frames-by-channels")
|
||||
ref = pad_or_trim(ref, len(x))
|
||||
cleaned = x.copy()
|
||||
reports = []
|
||||
for channel in channels:
|
||||
ch = int(channel)
|
||||
if ch < 0 or ch >= x.shape[1]:
|
||||
continue
|
||||
transfer, freqs = estimate_transfer(reference=ref, observed=x[:, ch], sample_rate=sample_rate, nperseg=nperseg, noverlap=noverlap, regularization=regularization)
|
||||
predicted = synthesize_reference(reference=ref, transfer=transfer, sample_rate=sample_rate, nperseg=nperseg, noverlap=noverlap)
|
||||
predicted = pad_or_trim(predicted, len(x))
|
||||
before = x[:, ch]
|
||||
after = before - float(subtraction_strength) * predicted
|
||||
cleaned[:, ch] = after.astype(np.float32)
|
||||
before_rms = rms(before)
|
||||
after_rms = rms(after)
|
||||
reports.append(
|
||||
ReferenceSuppressionReport(
|
||||
channel=ch,
|
||||
input_rms=before_rms,
|
||||
predicted_rms=rms(predicted),
|
||||
output_rms=after_rms,
|
||||
reduction_db=20.0 * np.log10(max(after_rms, 1e-12) / max(before_rms, 1e-12)),
|
||||
phase_mapping=phase_mapping(freqs, transfer),
|
||||
)
|
||||
)
|
||||
return cleaned.astype(np.float32), reports
|
||||
|
||||
|
||||
def estimate_transfer(*, reference: np.ndarray, observed: np.ndarray, sample_rate: int, nperseg: int, noverlap: int, regularization: float):
|
||||
freqs, _, ref_stft = signal.stft(reference, fs=sample_rate, nperseg=nperseg, noverlap=noverlap, boundary="zeros", padded=True)
|
||||
_, _, obs_stft = signal.stft(pad_or_trim(observed, len(reference)), fs=sample_rate, nperseg=nperseg, noverlap=noverlap, boundary="zeros", padded=True)
|
||||
numerator = np.sum(obs_stft * np.conj(ref_stft), axis=1)
|
||||
denominator = np.sum(np.abs(ref_stft) ** 2, axis=1) + float(regularization)
|
||||
transfer = numerator / denominator
|
||||
return transfer.astype(np.complex64), freqs.astype(np.float32)
|
||||
|
||||
|
||||
def synthesize_reference(*, reference: np.ndarray, transfer: np.ndarray, sample_rate: int, nperseg: int, noverlap: int):
|
||||
_, _, ref_stft = signal.stft(reference, fs=sample_rate, nperseg=nperseg, noverlap=noverlap, boundary="zeros", padded=True)
|
||||
predicted_stft = ref_stft * transfer[:, None]
|
||||
_, predicted = signal.istft(predicted_stft, fs=sample_rate, nperseg=nperseg, noverlap=noverlap, input_onesided=True, boundary=True)
|
||||
return predicted.astype(np.float32)
|
||||
|
||||
|
||||
def phase_mapping(freqs: np.ndarray, transfer: np.ndarray, *, min_hz: float = 80.0, max_hz: float = 16000.0, bins: int = 24):
|
||||
valid = (freqs >= min_hz) & (freqs <= max_hz) & (np.abs(transfer) > 1e-9)
|
||||
if not np.any(valid):
|
||||
return tuple()
|
||||
selected_freqs = np.geomspace(max(min_hz, float(freqs[valid][0])), min(max_hz, float(freqs[valid][-1])), bins)
|
||||
rows = []
|
||||
for frequency in selected_freqs:
|
||||
index = int(np.argmin(np.abs(freqs - frequency)))
|
||||
magnitude = float(abs(transfer[index]))
|
||||
phase = float(np.angle(transfer[index]))
|
||||
rows.append((float(freqs[index]), phase, magnitude))
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
def pad_or_trim(samples: np.ndarray, length: int) -> np.ndarray:
|
||||
x = np.asarray(samples, dtype=np.float32).reshape(-1)
|
||||
if len(x) == length:
|
||||
return x
|
||||
if len(x) > length:
|
||||
return x[:length]
|
||||
out = np.zeros(length, dtype=np.float32)
|
||||
out[: len(x)] = x
|
||||
return out
|
||||
|
||||
|
||||
def rms(samples: np.ndarray) -> float:
|
||||
x = np.asarray(samples, dtype=np.float32)
|
||||
return float(np.sqrt(np.mean(x * x))) if x.size else 0.0
|
||||
|
|
@ -1,113 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RoomSuppressionConfig:
|
||||
block_size: int = 1024
|
||||
hop_size: int = 512
|
||||
transient_ratio: float = 2.5
|
||||
max_witness_attenuation_db: float = -18.0
|
||||
anchor_transient_attenuation_db: float = -6.0
|
||||
room_subtraction: float = 0.15
|
||||
envelope_floor: float = 1e-5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RoomSuppressionReport:
|
||||
frames: int
|
||||
anchor_channels: tuple[int, ...]
|
||||
witness_channels: tuple[int, ...]
|
||||
transient_blocks: int
|
||||
mean_witness_gain: float
|
||||
mean_anchor_gain: float
|
||||
|
||||
|
||||
def suppress_room_field(
|
||||
field: np.ndarray,
|
||||
anchor_channels: list[int] | tuple[int, ...],
|
||||
witness_channels: list[int] | tuple[int, ...],
|
||||
config: RoomSuppressionConfig | None = None,
|
||||
) -> tuple[np.ndarray, RoomSuppressionReport]:
|
||||
cfg = config or RoomSuppressionConfig()
|
||||
x = np.asarray(field, dtype=np.float32)
|
||||
if x.ndim != 2:
|
||||
raise ValueError("field must be frames-by-channels")
|
||||
anchors = tuple(int(channel) for channel in anchor_channels if 0 <= int(channel) < x.shape[1])
|
||||
witnesses = tuple(int(channel) for channel in witness_channels if 0 <= int(channel) < x.shape[1] and int(channel) not in anchors)
|
||||
if not anchors:
|
||||
raise ValueError("at least one anchor channel is required")
|
||||
if not witnesses:
|
||||
return x.copy(), RoomSuppressionReport(len(x), anchors, witnesses, 0, 1.0, 1.0)
|
||||
|
||||
y = np.zeros_like(x)
|
||||
weight = np.zeros(len(x), dtype=np.float32)
|
||||
witness_gain_sum = 0.0
|
||||
anchor_gain_sum = 0.0
|
||||
blocks = 0
|
||||
transient_blocks = 0
|
||||
min_witness_gain = db_to_amp(cfg.max_witness_attenuation_db)
|
||||
min_anchor_gain = db_to_amp(cfg.anchor_transient_attenuation_db)
|
||||
window = np.hanning(cfg.block_size).astype(np.float32)
|
||||
if not np.any(window):
|
||||
window = np.ones(cfg.block_size, dtype=np.float32)
|
||||
|
||||
for start in range(0, max(1, len(x) - cfg.block_size + 1), cfg.hop_size):
|
||||
end = min(len(x), start + cfg.block_size)
|
||||
block = x[start:end]
|
||||
win = window[: end - start, None]
|
||||
anchor_env = channel_rms(block[:, anchors])
|
||||
witness_env = channel_rms(block[:, witnesses])
|
||||
anchor_peak = channel_peak(block[:, anchors])
|
||||
witness_peak = channel_peak(block[:, witnesses])
|
||||
transient_score = max(witness_env / max(anchor_env, cfg.envelope_floor), witness_peak / max(anchor_peak, cfg.envelope_floor))
|
||||
is_transient = witness_env > cfg.envelope_floor and transient_score >= cfg.transient_ratio
|
||||
|
||||
witness_gain = min_witness_gain if is_transient else 1.0
|
||||
anchor_gain = min_anchor_gain if is_transient and anchor_env < witness_env else 1.0
|
||||
if is_transient:
|
||||
transient_blocks += 1
|
||||
witness_gain_sum += witness_gain
|
||||
anchor_gain_sum += anchor_gain
|
||||
blocks += 1
|
||||
|
||||
cleaned = block.copy()
|
||||
room_estimate = np.mean(block[:, witnesses], axis=1, keepdims=True)
|
||||
cleaned[:, witnesses] *= witness_gain
|
||||
if cfg.room_subtraction > 0.0:
|
||||
cleaned[:, anchors] -= cfg.room_subtraction * witness_gain * room_estimate
|
||||
cleaned[:, anchors] *= anchor_gain
|
||||
y[start:end] += cleaned * win
|
||||
weight[start:end] += win.reshape(-1)
|
||||
|
||||
active = weight > 1e-9
|
||||
y[active] = y[active] / weight[active, None]
|
||||
y[~active] = x[~active]
|
||||
report = RoomSuppressionReport(
|
||||
frames=len(x),
|
||||
anchor_channels=anchors,
|
||||
witness_channels=witnesses,
|
||||
transient_blocks=transient_blocks,
|
||||
mean_witness_gain=witness_gain_sum / max(1, blocks),
|
||||
mean_anchor_gain=anchor_gain_sum / max(1, blocks),
|
||||
)
|
||||
return y.astype(np.float32), report
|
||||
|
||||
|
||||
def channel_rms(block: np.ndarray) -> float:
|
||||
if block.size == 0:
|
||||
return 0.0
|
||||
return float(np.sqrt(np.mean(np.asarray(block, dtype=np.float32) ** 2)))
|
||||
|
||||
|
||||
def channel_peak(block: np.ndarray) -> float:
|
||||
if block.size == 0:
|
||||
return 0.0
|
||||
return float(np.max(np.abs(block)))
|
||||
|
||||
|
||||
def db_to_amp(db: float) -> float:
|
||||
return 10.0 ** (float(db) / 20.0)
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChirpletObservation:
|
||||
source_id: str
|
||||
frame_index: int
|
||||
delay_samples: float
|
||||
phase_radians: float
|
||||
score: float
|
||||
rate_scale: float = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncState:
|
||||
delay_samples: float = 0.0
|
||||
phase_radians: float = 0.0
|
||||
rate_scale: float = 1.0
|
||||
confidence: float = 0.0
|
||||
last_frame_index: int = -1
|
||||
|
||||
|
||||
class RuntimeSyncEstimator:
|
||||
"""Maintains per-source delay/SRO/phase state from known speaker chirplets."""
|
||||
|
||||
def __init__(self, min_score: float = 0.18, smoothing: float = 0.2):
|
||||
if not 0.0 <= smoothing <= 1.0:
|
||||
raise ValueError("smoothing must be between 0 and 1")
|
||||
self.min_score = min_score
|
||||
self.smoothing = smoothing
|
||||
self._states: dict[str, SyncState] = {}
|
||||
|
||||
def state_for(self, source_id: str) -> SyncState:
|
||||
return self._states.get(source_id, SyncState())
|
||||
|
||||
def update(self, observation: ChirpletObservation) -> SyncState:
|
||||
previous = self.state_for(observation.source_id)
|
||||
if observation.score < self.min_score:
|
||||
frozen = SyncState(
|
||||
delay_samples=previous.delay_samples,
|
||||
phase_radians=previous.phase_radians,
|
||||
rate_scale=previous.rate_scale,
|
||||
confidence=observation.score,
|
||||
last_frame_index=previous.last_frame_index,
|
||||
)
|
||||
self._states[observation.source_id] = frozen
|
||||
return frozen
|
||||
|
||||
alpha = self.smoothing
|
||||
updated = SyncState(
|
||||
delay_samples=blend(previous.delay_samples, observation.delay_samples, alpha, previous.confidence),
|
||||
phase_radians=blend(previous.phase_radians, observation.phase_radians, alpha, previous.confidence),
|
||||
rate_scale=blend(previous.rate_scale, observation.rate_scale, alpha, previous.confidence),
|
||||
confidence=observation.score,
|
||||
last_frame_index=observation.frame_index,
|
||||
)
|
||||
self._states[observation.source_id] = updated
|
||||
return updated
|
||||
|
||||
|
||||
def blend(previous: float, current: float, alpha: float, previous_confidence: float) -> float:
|
||||
if previous_confidence <= 0.0:
|
||||
return current
|
||||
return (1.0 - alpha) * previous + alpha * current
|
||||
|
|
@ -1,168 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
from typing import Iterable
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceEvent:
|
||||
event_id: int
|
||||
start_sample: int
|
||||
duration_samples: int
|
||||
position_m: tuple[float, float, float]
|
||||
direction_m: tuple[float, float, float]
|
||||
energy: float
|
||||
confidence: float
|
||||
kind: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VoiceFocusFrame:
|
||||
start_sample: int
|
||||
duration_samples: int
|
||||
anchor_weights: dict[int, float]
|
||||
witness_energy: float
|
||||
anchor_energy: float
|
||||
noise_ratio: float
|
||||
|
||||
|
||||
def analyze_source_field(
|
||||
field: np.ndarray,
|
||||
sample_rate: int,
|
||||
mic_positions: dict[int, tuple[float, float, float]],
|
||||
anchor_channels: Iterable[int],
|
||||
witness_channels: Iterable[int],
|
||||
*,
|
||||
block_size: int = 1024,
|
||||
hop_size: int = 512,
|
||||
transient_ratio: float = 2.5,
|
||||
min_event_energy: float = 1e-6,
|
||||
onset_ratio: float = 1.8,
|
||||
min_event_spacing_samples: int = 2048,
|
||||
) -> tuple[list[SourceEvent], list[VoiceFocusFrame]]:
|
||||
samples = np.asarray(field, dtype=np.float32)
|
||||
if samples.ndim != 2:
|
||||
raise ValueError("source field must be frames-by-channels")
|
||||
anchors = [int(channel) for channel in anchor_channels if int(channel) < samples.shape[1]]
|
||||
witnesses = [int(channel) for channel in witness_channels if int(channel) < samples.shape[1]]
|
||||
if not witnesses:
|
||||
return [], []
|
||||
block_size = int(block_size)
|
||||
hop_size = int(hop_size)
|
||||
if block_size <= 0 or hop_size <= 0:
|
||||
raise ValueError("block_size and hop_size must be positive")
|
||||
|
||||
events: list[SourceEvent] = []
|
||||
focus: list[VoiceFocusFrame] = []
|
||||
candidates = []
|
||||
window = np.hanning(block_size).astype(np.float32)
|
||||
previous_witness_energy = 0.0
|
||||
for start in range(0, max(0, samples.shape[0] - block_size + 1), hop_size):
|
||||
block = samples[start : start + block_size] * window[:, None]
|
||||
witness_energy_by_channel = {
|
||||
channel: rms_energy(block[:, channel])
|
||||
for channel in witnesses
|
||||
if channel in mic_positions
|
||||
}
|
||||
anchor_energy_by_channel = {channel: rms_energy(block[:, channel]) for channel in anchors}
|
||||
witness_energy = float(sum(witness_energy_by_channel.values()))
|
||||
anchor_energy = float(sum(anchor_energy_by_channel.values()))
|
||||
noise_ratio = witness_energy / max(anchor_energy, 1e-12)
|
||||
focus.append(
|
||||
VoiceFocusFrame(
|
||||
start_sample=start,
|
||||
duration_samples=block_size,
|
||||
anchor_weights=anchor_mix_weights(anchor_energy_by_channel),
|
||||
witness_energy=witness_energy,
|
||||
anchor_energy=anchor_energy,
|
||||
noise_ratio=noise_ratio,
|
||||
)
|
||||
)
|
||||
onset = witness_energy / max(previous_witness_energy, 1e-12)
|
||||
previous_witness_energy = witness_energy
|
||||
if witness_energy < min_event_energy or noise_ratio < transient_ratio or onset < onset_ratio:
|
||||
continue
|
||||
position, confidence = localize_energy_centroid(witness_energy_by_channel, mic_positions)
|
||||
candidates.append(
|
||||
(
|
||||
start,
|
||||
SourceEvent(
|
||||
event_id=-1,
|
||||
start_sample=start,
|
||||
duration_samples=block_size,
|
||||
position_m=position,
|
||||
direction_m=unit_vector(position),
|
||||
energy=witness_energy,
|
||||
confidence=confidence,
|
||||
kind="witness-dominant-transient",
|
||||
),
|
||||
)
|
||||
)
|
||||
events = suppress_nearby_events([event for _, event in candidates], int(min_event_spacing_samples))
|
||||
return events, focus
|
||||
|
||||
|
||||
def rms_energy(samples: np.ndarray) -> float:
|
||||
if samples.size == 0:
|
||||
return 0.0
|
||||
return float(np.mean(np.asarray(samples, dtype=np.float64) ** 2))
|
||||
|
||||
|
||||
def anchor_mix_weights(energies: dict[int, float]) -> dict[int, float]:
|
||||
if not energies:
|
||||
return {}
|
||||
floor = max(max(energies.values()) * 1e-6, 1e-12)
|
||||
total = sum(max(value, floor) for value in energies.values())
|
||||
return {channel: max(value, floor) / total for channel, value in sorted(energies.items())}
|
||||
|
||||
|
||||
def localize_energy_centroid(
|
||||
energies: dict[int, float],
|
||||
mic_positions: dict[int, tuple[float, float, float]],
|
||||
) -> tuple[tuple[float, float, float], float]:
|
||||
usable = [(channel, max(float(energy), 0.0)) for channel, energy in energies.items() if energy > 0.0]
|
||||
if not usable:
|
||||
return (0.0, 0.0, 0.0), 0.0
|
||||
weights = np.asarray([energy for _, energy in usable], dtype=np.float64)
|
||||
positions = np.asarray([mic_positions[channel] for channel, _ in usable], dtype=np.float64)
|
||||
total = float(np.sum(weights))
|
||||
centroid = np.sum(positions * weights[:, None], axis=0) / total
|
||||
dominance = float(np.max(weights) / total)
|
||||
spread = float(np.sqrt(np.average(np.sum((positions - centroid) ** 2, axis=1), weights=weights)))
|
||||
confidence = max(0.0, min(1.0, 0.35 + dominance - 0.15 * spread))
|
||||
return tuple(float(value) for value in centroid), confidence
|
||||
|
||||
|
||||
def suppress_nearby_events(events: list[SourceEvent], min_spacing_samples: int) -> list[SourceEvent]:
|
||||
if not events:
|
||||
return []
|
||||
min_spacing_samples = max(0, int(min_spacing_samples))
|
||||
kept: list[SourceEvent] = []
|
||||
for event in sorted(events, key=lambda item: item.energy, reverse=True):
|
||||
if any(abs(event.start_sample - existing.start_sample) < min_spacing_samples for existing in kept):
|
||||
continue
|
||||
kept.append(event)
|
||||
kept.sort(key=lambda item: item.start_sample)
|
||||
return [
|
||||
SourceEvent(
|
||||
event_id=index,
|
||||
start_sample=event.start_sample,
|
||||
duration_samples=event.duration_samples,
|
||||
position_m=event.position_m,
|
||||
direction_m=event.direction_m,
|
||||
energy=event.energy,
|
||||
confidence=event.confidence,
|
||||
kind=event.kind,
|
||||
)
|
||||
for index, event in enumerate(kept)
|
||||
]
|
||||
|
||||
|
||||
def unit_vector(position: tuple[float, float, float]) -> tuple[float, float, float]:
|
||||
norm = math.sqrt(sum(value * value for value in position))
|
||||
if norm <= 1e-12:
|
||||
return (0.0, 0.0, 0.0)
|
||||
return tuple(float(value / norm) for value in position)
|
||||
|
|
@ -87,16 +87,15 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"bridgeDemotion": {
|
||||
"python": [
|
||||
"calibration",
|
||||
"contract-tests",
|
||||
"device-discovery",
|
||||
"status",
|
||||
"compatibility-spout-diagnostics",
|
||||
"offline-analysis"
|
||||
"runtimePolicy": {
|
||||
"liveOnlyIn": [
|
||||
"Mimir.Runtime",
|
||||
"native-driver-workers",
|
||||
"native-reservoir",
|
||||
"Aquarium.Engine",
|
||||
"Faust"
|
||||
],
|
||||
"notPython": [
|
||||
"neverInCompatibilityEdges": [
|
||||
"dense-feature-extraction",
|
||||
"reservoir-reconciliation",
|
||||
"hot-dsp",
|
||||
|
|
|
|||
|
|
@ -1,96 +1,14 @@
|
|||
# Aquarium Spatial Audio
|
||||
# Aquarium Spatial Audio
|
||||
|
||||
## Objective
|
||||
Aquarium hosts the Mimir runtime UI and presents the synchronized program
|
||||
surface. Faust/native DSP owns the hot audio graph behind that surface.
|
||||
|
||||
Publish the live spatial audio field through the same typed state discipline as the splat renderer. Aquarium consumes the AmbiX bus and hands it to native Faust DSP; Mimir owns capture, sync, calibration, and stream timing.
|
||||
## Contract
|
||||
|
||||
## Current Mechanism
|
||||
- Mimir.Runtime exposes bounded audio buffers and stream health.
|
||||
- Native audio workers append mic, loopback, and network audio blocks.
|
||||
- Faust/native DSP consumes aligned blocks and emits stems plus spatial bed.
|
||||
- Aquarium shows controls and debug state, then routes final outputs toward OBS.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["aligned microphone field"] --> B["FOA encoder"]
|
||||
B --> C["AmbiX ACN/SN3D W,Y,Z,X blocks"]
|
||||
C --> D["localcast.audio.spatial_frame"]
|
||||
A --> M["localcast.audio.mic_field"]
|
||||
M --> N["Faust voice-separation graph"]
|
||||
A --> H["source-event analysis"]
|
||||
H --> I["localcast.audio.source_events"]
|
||||
D --> E["audio-state.msgpack / CultNet document_put"]
|
||||
M --> O["audio-mic-field.msgpack / CultNet document_put"]
|
||||
I --> J["audio-events.msgpack / CultNet document_put"]
|
||||
E --> F["Aquarium client"]
|
||||
O --> F
|
||||
J --> F
|
||||
K["visual-state.msgpack"] --> F
|
||||
F --> G["native Faust spatial DSP + volumetric renderer"]
|
||||
```
|
||||
|
||||
Live files:
|
||||
|
||||
- `calibration/runs/audio-state.msgpack`: latest typed AmbiX audio block.
|
||||
- `calibration/runs/audio-mic-field.msgpack`: latest aligned six-mic block for Faust voice separation.
|
||||
- `calibration/runs/audio-stream-status.msgpack`: audio publisher heartbeat.
|
||||
- `calibration/runs/audio-events.msgpack`: latest typed dialogue-focus and transient vector field.
|
||||
- `calibration/runs/av-sync-status.json`: current Aquarium/Spout publisher view of visual frame id, audio frame id, audio delta, and synchronized event overlay count.
|
||||
|
||||
Document type:
|
||||
|
||||
- `localcast.audio.spatial_frame`
|
||||
- schema id: `gamecult.localcast.audio.spatial_frame.v1`
|
||||
- key: `localcast.audio.spatial-frame.live`
|
||||
- payload: MessagePack array decoded as `CultSpatialAudioFrame`
|
||||
- audio format: interleaved `float32`, 48 kHz, AmbiX ACN/SN3D channels `W,Y,Z,X`
|
||||
|
||||
Source event document type:
|
||||
|
||||
- `localcast.audio.source_events`
|
||||
- schema id: `gamecult.localcast.audio.source_events.v1`
|
||||
- key: `localcast.audio.source-events.live`
|
||||
- payload: MessagePack array decoded as `CultAudioSourceEvents`
|
||||
- contents: dialogue anchor weights plus witness-dominant transient events with sample time, estimated room position, direction, energy, confidence, and kind.
|
||||
|
||||
Mic-field document type:
|
||||
|
||||
- `localcast.audio.mic_field`
|
||||
- schema id: `gamecult.localcast.audio.mic_field.v1`
|
||||
- key: `localcast.audio.mic-field.live`
|
||||
- payload: MessagePack array decoded as `CultAudioMicFieldFrame`
|
||||
- audio format: interleaved `float32`, 48 kHz, aligned mic channels
|
||||
- default channel order: `host-focusrite`, `co-streamer-focusrite`, `kiyo-0`, `kiyo-1`, `ps-eye-0`, `ps-eye-1`
|
||||
- graph id: `localcast.faust.voice_separation.v1`
|
||||
- Faust source: `faust/localcast_voice_separation.dsp`
|
||||
|
||||
AmbiX replay smoke command:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m localcast.diagnostics.spatial_audio --input .\calibration\runs\audio-full-sync-20260518-165751\field-foa-ambix.wav --loop --duration 5 --smoke-readback
|
||||
```
|
||||
|
||||
Faust mic-field replay smoke command:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m localcast.diagnostics.faust_mic_field --input .\calibration\runs\audio-full-sync-20260518-165751\field-cleaned.wav --loop --duration 5 --smoke-readback
|
||||
```
|
||||
|
||||
This exercises the old mic-field document shape. Production voice separation should read typed reservoir/CultNet data from the native live path; Python is not the hot publisher.
|
||||
|
||||
Source-event analysis command:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-source-events --profile .\calibration\runs\audio-field-loud-profile.json --input .\calibration\runs\<run-folder>\field-cleaned.wav --cache .\calibration\runs\audio-events.msgpack
|
||||
```
|
||||
|
||||
Synchronized Aquarium/Spout publisher command:
|
||||
|
||||
The old Python/OpenGL Spout diagnostic launcher has been deleted. Aquarium is
|
||||
the next OBS-facing publisher.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Aquarium owns rendering and Faust DSP, not microphone capture or clock correction.
|
||||
- Mimir publishes declared AmbiX blocks for the spatial bed and aligned six-mic blocks for Faust voice separation. Unaligned heterogeneous microphones still do not cross this boundary.
|
||||
- Mimir publishes source-event geometry separately from AmbiX audio; render effects do not have to infer transient positions from the sound bed.
|
||||
- Faust owns the voice-separation graph once the aligned mic field has crossed into Aquarium. Python may publish controls and telemetry, but it must not become the hot separation engine.
|
||||
- Aquarium/Spout packaging selects audio source events against each visual frame's `audio_alignment_time_ns`; OBS should receive the already synchronized output rather than trying to align independent media sources.
|
||||
- The audio frame carries `start_sample` and `audio_time_ns` so visual packets can align against the same bounded-latency timeline.
|
||||
- OBS may receive a rendered monitor output later, but OBS is not the spatial bus authority.
|
||||
The audio path should be inspectable from the app, but the app UI is not the DSP
|
||||
engine. Runtime state crosses as typed buffers, descriptors, and controls.
|
||||
|
|
|
|||
|
|
@ -1,276 +1,40 @@
|
|||
# Audio Field Spine
|
||||
# Audio Field
|
||||
|
||||
## Objective
|
||||
Mimir's audio field is six microphones, loopback/program reference, and two
|
||||
calibration speakers aligned into one presentation timeline.
|
||||
|
||||
Build the audio side around the real six-microphone rig: two Kiyo camera mics, two PS Eye camera mics, the local Focusrite ADC with a shielded cardioid near the host's face, and the neighbor Focusrite ADC with a shotgun mic pointed at the co-streamer.
|
||||
|
||||
The Focusrite channels are the dialogue anchors. The camera mics are spatial context, calibration evidence, and fallback texture. Treating all six as equal would be tidy on paper and stupid in the room, which is the classic way paper gets someone fired by physics.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
The repo has a profile and tool:
|
||||
|
||||
- `config/audio-field.example.json` declares each mic source, machine, device query, clock domain, field channel, quality priority, placeholder geometry, two local speaker channels, calibration sweep settings, and FOA AmbiX bus format.
|
||||
- `scripts/audio_field.py` validates shared or distributed profiles, lists PortAudio devices, checks local distributed sources, generates calibration sweeps, summarizes the sync plan, preserves shared-input capture helpers, and encodes an already aligned six-channel WAV into first-order AmbiX.
|
||||
|
||||
The default profile is `distributed-clocks`. The coherent field is not captured directly. It is assembled after delay and sampling-rate-offset alignment.
|
||||
|
||||
Latency is allowed. The live goal is bounded buffered real-time: hold enough audio to estimate delay and slow clock drift, emit blocks behind the live edge, and converge instead of chasing instant output with bad math. The profile owns that latency policy.
|
||||
|
||||
Runtime sync is not optional for the real show. Static sweep calibration gives the first estimate; the live system must keep updating delay, sampling-rate offset, polarity, and phase confidence as devices drift. Known speaker output is telemetry: every calibration chirplet or intentionally embedded probe gives the estimator a fresh phase-field observation.
|
||||
|
||||
If passive telemetry is not enough, the system should emit extra chirplets automatically. That is an optimization loop: spend the smallest audible probe budget that raises sync confidence enough to protect the field.
|
||||
|
||||
## Pipeline
|
||||
## Live Target
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["config/audio-field.json"] --> B["audio_field.py validate"]
|
||||
C["local Focusrite shielded cardioid"] --> D["local reference timeline"]
|
||||
E["neighbor Focusrite shotgun"] --> F["remote high-quality dialogue capture"]
|
||||
G["Kiyo + PS Eye camera mics"] --> H["spatial/context captures"]
|
||||
I["2 local speakers"] --> J["calibration sweep / pulse"]
|
||||
J --> D
|
||||
J --> F
|
||||
J --> H
|
||||
D --> K["delay + SRO alignment"]
|
||||
F --> K
|
||||
A["mic / loopback capture drivers"] --> B["Mimir.Runtime audio buffers"]
|
||||
C["speaker probe scheduler"] --> B
|
||||
B --> D["native alignment + phase state"]
|
||||
D --> E["Faust/native DSP"]
|
||||
E --> F["host voice"]
|
||||
E --> G["co-streamer voice"]
|
||||
E --> H["ambient / transients"]
|
||||
E --> I["loopback stems"]
|
||||
E --> J["spatial bed"]
|
||||
F --> K["OBS"]
|
||||
G --> K
|
||||
H --> K
|
||||
K --> L["bounded field cache"]
|
||||
P["known speaker chirplets"] --> Q["runtime delay/SRO/phase estimator"]
|
||||
R["confidence probe optimizer"] --> P
|
||||
D --> Q
|
||||
F --> Q
|
||||
H --> Q
|
||||
Q --> S["live phase-meaning extractor"]
|
||||
S --> T["phase-field meaning cache"]
|
||||
S --> K
|
||||
L --> M["aligned six-channel blocks"]
|
||||
M --> N["FOA encoder"]
|
||||
N --> O["AmbiX ACN/SN3D output"]
|
||||
I --> K
|
||||
J --> K
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
Create a local profile first:
|
||||
|
||||
```powershell
|
||||
Copy-Item .\config\audio-field.example.json .\config\audio-field.json
|
||||
```
|
||||
|
||||
List audio devices:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py devices
|
||||
```
|
||||
|
||||
Probe whether a Focusrite path accepts high-rate capture:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py probe-rates --device-query Scarlett --hostapi WASAPI --direction input --channels 1 --rate 48000 --rate 96000
|
||||
```
|
||||
|
||||
Probe the speaker output path separately:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py probe-rates --device-query Scarlett --hostapi WASAPI --direction output --channels 2 --rate 44100 --rate 48000 --rate 96000
|
||||
```
|
||||
|
||||
Validate the profile and local device matches:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py validate --profile .\config\audio-field.json --check-devices
|
||||
```
|
||||
|
||||
Summarize the clock domains and required alignment path:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py sync-plan --profile .\config\audio-field.json
|
||||
```
|
||||
|
||||
Generate a calibration sweep without touching hardware:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py make-stimulus --profile .\config\audio-field.json
|
||||
```
|
||||
|
||||
Create a distributed run folder that can accept one WAV per mic:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py init-run --profile .\config\audio-field.json
|
||||
```
|
||||
|
||||
Record all locally visible distributed mics for a deadline calibration pass:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-local-calibration --profile .\config\audio-field.json --seconds 10
|
||||
```
|
||||
|
||||
For passive runtime sync against ground-truth program output, capture the Scarlett loopback with the local mics:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-local-calibration --profile .\config\audio-field.json --seconds 20 --record-loopback --loopback-query Scarlett --loopback-rate 48000
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-reference-sync --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --window-seconds 4 --hop-seconds 1 --method normalized --min-score 0.08
|
||||
```
|
||||
|
||||
The loopback path is ground-truth content, but not automatically a perfect ground-truth clock. If WASAPI loopback reports discontinuities, use the stable windows and treat the rest as suspect.
|
||||
|
||||
For dense runtime calibration, emit a low-level multiband chirplet texture instead of one big sweep:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-probe-train --profile .\config\audio-field.json --seconds 8 --chirp-seconds 0.03 --chirps-per-second 16 --probe-band 180:500 --probe-band 600:1200 --probe-band 1500:3000 --probe-band 3500:7000 --probe-band 8000:14000 --probe-level-offset-db -18 --output-rate 44100 --loopback-rate 48000
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-probe-train --profile .\config\audio-field.json --run .\calibration\runs\<run-folder>
|
||||
```
|
||||
|
||||
`analyze-probe-train` is the offline live-fit evidence path: it uses each event's band-specific chirplet, gates weak loopback/mic detections, estimates phase-derived delay deltas across frequency bands, and updates a smoothed phase/frequency mapping. Coarse delays still include device latency; the volumetric room solve must fit latency, drift, phase response, and acoustic path jointly.
|
||||
|
||||
Replay extracted phase-field meaning from an aligned field and known program/loopback reference:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m localcast.diagnostics.audio_phase_field --field .\calibration\runs\<run-folder>\field-program-cleaned.wav --reference .\calibration\runs\<run-folder>\ground_truth_loopback.wav --cache .\calibration\runs\audio-phase-field.msgpack
|
||||
```
|
||||
|
||||
This is not a phase oscilloscope. Raw phase bands stay internal. The diagnostic document publishes consequences: per-source delay correction, distance-equivalent delta, coherence, fit error, confidence, reference-bleed estimate, suppression weight, correction energy, and whether the active probe optimizer should spend chirps.
|
||||
|
||||
Exercise the confidence loop by letting the replay schedule strategic active probes:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m localcast.diagnostics.audio_phase_field --field .\calibration\runs\<run-folder>\field-program-cleaned.wav --reference .\calibration\runs\<run-folder>\ground_truth_loopback.wav --cache .\calibration\runs\audio-phase-field.msgpack --maintain-confidence --ultrasonic-probes --play-probes
|
||||
```
|
||||
|
||||
`--maintain-confidence` converts low-confidence phase-field state into `ActiveProbeOptimizer` requests, writes emitted chirplets under `calibration/runs/active-probes`, and appends `active-probes.jsonl`. Probe files rotate through fixed slots and the manifest rotates at a byte cap, because a calibration loop that creates infinite tiny WAV files is just a storage leak with a physics degree. `--play-probes` sends the emitted chirplet to the selected output device through `sounddevice`; omit it for dry-run scheduling. `--ultrasonic-probes` uses the highest safe band under Nyquist, roughly `18.5-22 kHz` at 48 kHz. This can fail silently in the physical world if the speaker, mic, driver, or resampler refuses to carry that band; the confidence feedback is the judge, not the command line's self-esteem.
|
||||
|
||||
The old Python live local-capture bridge is quarantined as `localcast.diagnostics.audio_live_field`. It documents the deadline experiment, but production local mic and loopback capture now belongs in native workers that append typed sample handles through `LocalcastProducer`.
|
||||
|
||||
Record local mics while playing one speaker sweep. Use the output rate that the device probe says is real:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-local-calibration --profile .\config\audio-field.json --seconds 10 --play-sweep --speaker-channel 0 --output-rate 44100
|
||||
```
|
||||
|
||||
After dropping the neighbor Focusrite WAV into the run's `sources/` folder, estimate sweep arrivals and assemble the aligned field:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-distributed --profile .\config\audio-field.json --run .\calibration\runs\<run-folder>
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py assemble-aligned --profile .\config\audio-field.json --run .\calibration\runs\<run-folder>
|
||||
```
|
||||
|
||||
For the stream-day compensated field, use the sweep-derived response pass during assembly:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py assemble-aligned --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --compensate-response
|
||||
```
|
||||
|
||||
This estimates each mic's magnitude response from the calibration sweep relative to the reference Focusrite, smooths the inverse curve, clips it to bounded boost/cut limits, and writes `response-compensation.json`. It deliberately corrects magnitude only; phase stays owned by the timing/sync path.
|
||||
|
||||
Record the neighbor Focusrite shotgun directly into an existing distributed run over SSH/SFTP:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py record-remote-focusrite --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --seconds 10 --sample-rate 48000
|
||||
```
|
||||
|
||||
This records `Analogue 1 + 2 (Focusrite USB Audio)` on `192.168.1.84` with remote FFmpeg, pulls it back as `sources/mic_focusrite_neighbor.wav`, and updates the run manifest. Use this for calibration imports; the existing OBS SRT source is still the live monitoring/streaming path.
|
||||
|
||||
`analyze-distributed` now does a deadline-grade chirplet refinement by default: it uses the coarse sweep matched-filter peak as the initial time-of-arrival, then searches a small fractional-delay and chirp-rate neighborhood with chirplet atoms. Tune the local search when needed:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-distributed --profile .\config\audio-field.json --run .\calibration\runs\<run-folder> --chirplet-refine --search-samples 3 --fractional-steps 8 --rate-ppm 150
|
||||
```
|
||||
|
||||
This is not a full adaptive chirplet decomposition engine. It is the stream-day version: enough chirplet parameter search to get sub-sample timing refinement without turning calibration into a thesis defense in the middle of setup.
|
||||
|
||||
Encode an offline aligned six-channel WAV to FOA AmbiX:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py encode-foa --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-aligned.wav --output .\calibration\runs\<run-folder>\field-foa-ambix.wav
|
||||
```
|
||||
|
||||
Replay the same aligned six-channel field directly to the old mic-field document for Faust smoke tests:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m localcast.diagnostics.faust_mic_field --input .\calibration\runs\<run-folder>\field-cleaned.wav --loop --realtime --smoke-readback
|
||||
```
|
||||
|
||||
This writes `localcast.audio.mic_field` into `calibration/runs/audio-mic-field.msgpack` with channel roles and graph id `localcast.faust.voice_separation.v1`. It is a diagnostic replay path. The live path is native capture into the rolling reservoir, then Aquarium/Faust consumption.
|
||||
|
||||
Suppress room/transient witness energy before FOA encoding:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py suppress-room --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-aligned.wav --output .\calibration\runs\<run-folder>\field-cleaned.wav
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py encode-foa --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-cleaned.wav --output .\calibration\runs\<run-folder>\field-cleaned-foa-ambix.wav
|
||||
```
|
||||
|
||||
This first suppression pass treats the Focusrite dialogue anchors as wanted direct sources and the camera mics as room/transient witnesses. It attenuates witness-heavy broadband transients, lightly subtracts witness room energy from anchors, and writes a JSON report. It is deliberately a stream-side cleanup stage, not physical cancellation in the room.
|
||||
|
||||
Suppress known speaker/program bleed using output loopback as ground truth:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py suppress-reference --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-aligned.wav --reference .\calibration\runs\<run-folder>\ground_truth_loopback.wav --output .\calibration\runs\<run-folder>\field-program-suppressed.wav
|
||||
```
|
||||
|
||||
This is the music-as-both-enemy-and-teacher path. The reference program audio is transformed into a time/frequency transfer estimate per mic channel, reconstructed as predicted bleed, subtracted from the aligned field, and exported as phase/frequency mapping evidence. A future live loop should publish the known program stem as its own OBS/Aquarium channel while using the same ground truth to keep learning the room.
|
||||
|
||||
Estimate dialogue focus and volumetric transient events:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\audio_field.py analyze-source-events --profile .\config\audio-field.json --input .\calibration\runs\<run-folder>\field-cleaned.wav --cache .\calibration\runs\audio-events.msgpack
|
||||
```
|
||||
|
||||
This emits `localcast.audio.source_events` for Aquarium. Dialogue anchors produce voice-focus weights; camera/context mics produce witness-dominant transient events with sample time, estimated room position, direction, energy, and confidence. This is the boundary between a clean vocal bed and renderer-visible clutter: clicks, taps, and other spatial transients should become geometry instead of being smeared into the voice mix.
|
||||
|
||||
The `play-record` and `record-field` commands remain for a `shared-input-device` profile only. They deliberately refuse the distributed rig until an alignment stage emits one coherent six-channel WAV.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Each physical microphone declares its machine, device query, clock domain, field channel, geometry, gain, delay, polarity, directivity, and role.
|
||||
- The local Focusrite shielded cardioid is the default reference mic.
|
||||
- The neighbor Focusrite shotgun is the co-streamer dialogue anchor and should be captured losslessly for calibration.
|
||||
- Focusrite captures should use the best available native/exclusive path and high-rate calibration capture when practical, then resample into the field timeline after alignment.
|
||||
- Playback sample rate is its own device fact. Probe it separately; do not assume the Scarlett input and output paths accept the same rates through PortAudio/WASAPI.
|
||||
- Distributed-clock microphones must be aligned and resampled into one reference timeline before FOA encoding.
|
||||
- Output may run behind live input by the configured latency budget, but it must converge toward real-time instead of letting cache depth grow without bound.
|
||||
- Sweep arrival estimates should use chirplet refinement when calibration signal quality allows it; plain matched-filter peaks are a fallback, not the precision path.
|
||||
- Runtime sync updates delay/SRO/phase estimates from known speaker chirplets every block/frame, gated by confidence so a bad observation freezes rather than poisons the field.
|
||||
- Active chirplet probes are scheduled by an optimization loop, not by panic. It should prefer masked windows, respect minimum spacing and level caps, and maximize expected confidence gain per audible intrusion.
|
||||
- Ultrasonic probes are allowed only as a bounded optimization strategy. They must stay below Nyquist, remain level-capped, and prove themselves by raising measured confidence; hardware may distort or discard them.
|
||||
- Dense probe textures should be harmonically organized so any lower-band aliases land closer to musical relationships than arbitrary squeal. This is damage control, not a license to trust aliasing.
|
||||
- FOA output is AmbiX: ACN channel order, SN3D normalization, channels `W,Y,Z,X`.
|
||||
- The Faust voice-separation input is the aligned six-mic field, not the AmbiX collapse. Voice separation needs anchor and witness channels before spatial rendering destroys useful evidence.
|
||||
- Speaker calibration is a measurement path, not a generic monitor output.
|
||||
- Source-event geometry is published beside the AmbiX bed; render effects do not have to infer transient positions from mixed audio.
|
||||
- Phase/chirplet evidence is reduced into alignment, correction, suppression, and probe-control meaning before it crosses the live cache boundary. Raw phase is an estimator detail, not a renderer API.
|
||||
- Camera fusion may publish listener or source pose later, but it does not own audio channel timing.
|
||||
- Focusrite dialogue mics are the voice anchors.
|
||||
- Camera mics are spatial/context witnesses.
|
||||
- Loopback/program audio is timing evidence where available.
|
||||
- Distributed inputs must be aligned and resampled before they become program
|
||||
stems.
|
||||
- Probe signals are budgeted telemetry, not a permanent audio bed.
|
||||
- Faust/native DSP owns the hot separation and spatialization graph.
|
||||
|
||||
## Module Boundaries
|
||||
## Next Cut
|
||||
|
||||
The audio code is split so the hard parts can be tested without the room, drivers, or neighbor machine:
|
||||
|
||||
- `audio_field.buffering` owns source buffers and ordered field assembly.
|
||||
- `audio_field.latency` owns the bounded-delay real-time convergence policy.
|
||||
- `audio_field.ports` declares injectable capture, alignment, encoder, and sink protocols.
|
||||
- `audio_field.pipeline` wires those ports together without knowing whether the source is a real Focusrite, an SRT receiver, a WAV fixture, or a test double.
|
||||
- The next runtime estimator module should own chirplet observations, delay/SRO/phase state, confidence gates, and phase-field updates. It should feed the aligner; it should not be hidden inside the FOA encoder.
|
||||
- The active probe optimizer owns whether to emit extra chirplets. It reads sync confidence and probe budget, then decides when and where an intentional chirplet is worth the cost.
|
||||
- `audio_field.active_probe` owns the runtime join between phase-field confidence and emitted chirplet probes. It converts extracted source confidence into sync states, applies masking/spacing policy, writes bounded probe WAV slots plus a rotating manifest, and optionally plays them.
|
||||
- `audio_field.phase_meaning` owns live extraction of meaning from phase/chirplet evidence. It consumes known reference audio plus aligned mic windows, keeps the smoothed phase/frequency state internal, and emits only actionable state for alignment, suppression, and probe control.
|
||||
- Room suppression owns stream-side cleanup: dialogue anchors define desired direct energy, spatial/context mics act as witnesses for room and transient clutter, and the cleaned aligned field feeds FOA/Aquarium/Faust.
|
||||
- Source-event analysis owns non-vocal spatial facts: dialogue focus weights and localized transient vectors are published beside the AmbiX bed, not hidden inside it.
|
||||
- Aquarium/Faust owns the hot voice-separation graph after `localcast.audio.mic_field`; Mimir owns alignment, timing, roles, and control publication.
|
||||
- `scripts/audio_field.py` stays as the operator CLI and hardware probe surface.
|
||||
|
||||
This is the portfolio-piece line: each module owns one invariant, and the tests use mocks/fakes instead of asking a driver stack to please be emotionally available.
|
||||
|
||||
## First Cut Limits
|
||||
|
||||
The current encoder is a source-style FOA mix from calibrated microphone channels and declared orientations. It accepts an already aligned six-channel WAV. It does not capture or align independent USB/network clocks by itself, and it is not a full arbitrary-array sound-field reconstruction.
|
||||
|
||||
Next honest steps:
|
||||
|
||||
1. Confirm local Kiyo, PS Eye, local Focusrite, and local speaker device matches.
|
||||
2. Confirm the neighbor Focusrite capture path, preferably native/exclusive or the best FFmpeg/driver route available on that machine.
|
||||
3. Probe the local and neighbor Focusrites for 48 kHz and 96 kHz capture support through the best available driver path.
|
||||
4. Capture the two Focusrite anchors losslessly during calibration; prefer 96 kHz when driver/device support is real, then resample after sync.
|
||||
5. Replace placeholder mic/speaker geometry with measured world coordinates.
|
||||
6. Build the delay/SRO alignment stage that feeds `audio_field.buffering.FieldAssemblyCache`.
|
||||
7. Emit aligned six-channel blocks under the configured latency policy.
|
||||
8. Encode the first FOA AmbiX test only after that aligned WAV/block stream exists.
|
||||
Add native audio capture workers that append typed blocks into
|
||||
`Mimir.Runtime`, then expose buffer depth, clock state, delay estimates, and
|
||||
stem routing in Aquarium UI.
|
||||
|
|
|
|||
|
|
@ -1,245 +1,24 @@
|
|||
# Calibration Harness
|
||||
# Calibration
|
||||
|
||||
This is the first physical-device calibration spine for the expanded spatial rig.
|
||||
Calibration data is measured truth for the live runtime. It is not the runtime.
|
||||
|
||||
## Objective
|
||||
## Current Policy
|
||||
|
||||
Turn connected cameras, microphones, speakers, and near-field sensors into timestamped observations that can be calibrated into one world coordinate system.
|
||||
- Keep calibration artifacts under `calibration/` when they record real device
|
||||
identity, timing, geometry, or audio response.
|
||||
- Prefer vendor SDKs, native driver APIs, Media Foundation, DirectShow, libusb,
|
||||
LeapC, and GPU interop for new capture work.
|
||||
- Treat old measurements as evidence only when they still change a live
|
||||
decision.
|
||||
|
||||
## Current Mechanism
|
||||
## Needed Measurements
|
||||
|
||||
The harness uses a repo-local Python environment:
|
||||
- Leap stereo IR cadence and device timestamp behavior.
|
||||
- Per-camera intrinsics and fixed rig extrinsics.
|
||||
- Mic/speaker positions and polarity.
|
||||
- Loopback delay for local and co-streamer playback paths.
|
||||
- OBS presentation delay for bridge endpoints.
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -r .\requirements-calibration.txt
|
||||
```
|
||||
|
||||
Run discovery:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py discover
|
||||
```
|
||||
|
||||
Capture camera snapshots:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py snapshot --max-index 10
|
||||
```
|
||||
|
||||
List DirectShow devices and options through FFmpeg:
|
||||
|
||||
```powershell
|
||||
$ff = .\.venv\Scripts\python.exe -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"
|
||||
& $ff -hide_banner -list_devices true -f dshow -i dummy
|
||||
& $ff -hide_banner -list_options true -f dshow -i video="PS3 Eye Universal"
|
||||
```
|
||||
|
||||
Probe camera mode behavior:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py mode-probe --api msmf --index 0 --profile 320x240x120
|
||||
```
|
||||
|
||||
Smoke-test input devices:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py audio-smoke --duration 1.0
|
||||
```
|
||||
|
||||
Outputs are written under `calibration/runs/`, which is ignored by git. The manifest files are the disposable lab notebook for the live machine.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Observations must include device identity, API/backend, timestamp, and confidence or failure reason.
|
||||
- Calibration files may refer to devices by stable identity where possible, not only by fragile camera index.
|
||||
- The world model owns truth. Snapshots, audio probes, splat packets, and debug images are evidence.
|
||||
- Do not assume LeapUVC raw access and Ultraleap tracking coexist.
|
||||
- Do not assume camera-attached microphones share the camera video clock.
|
||||
|
||||
## First Cut
|
||||
|
||||
The first useful calibration target is not a full point cloud. It is:
|
||||
|
||||
1. identify which video devices can produce frames
|
||||
2. identify which microphone devices can produce samples
|
||||
3. capture snapshots from each accessible camera
|
||||
4. record RMS/peak data from each accessible mic
|
||||
5. fix driver/backend issues for devices that are attached but inaccessible
|
||||
|
||||
## First Probe On This Machine
|
||||
|
||||
Run artifacts:
|
||||
|
||||
- `calibration/runs/20260518T124230Z-discover/manifest.json`
|
||||
- `calibration/runs/20260518T124231Z-audio-smoke/manifest.json`
|
||||
- `calibration/runs/20260518T124257Z-snapshot/manifest.json`
|
||||
|
||||
Observed video access:
|
||||
|
||||
- `dshow:0` / `msmf:0`: LeapUVC raw stereo IR image, visible as green/magenta packed output.
|
||||
- `dshow:1` / `msmf:1`: Razer Kiyo-class RGB camera.
|
||||
- `dshow:2` / `msmf:2`: second Razer Kiyo-class RGB camera, likely Kiyo Pro.
|
||||
- `dshow:3`: first PS3 Eye through PS3 Eye Universal Driver / PS3EyeDirectShow.
|
||||
- `dshow:4`: second PS3 Eye through PS3 Eye Universal Driver / PS3EyeDirectShow.
|
||||
|
||||
Mode probe notes:
|
||||
|
||||
- Historical diagnostic only: `msmf:0` LeapUVC accepted a `320x240x120` request and reported about 115 fps, while the old OpenCV probe measured around 52 fps. Treat that as evidence that the sensor mode is plausible and that the diagnostic path is too soft for live timing. Mimir live ingest should talk directly to the driver path.
|
||||
- Kiyo RGB devices produce snapshots, but initial isolated mode probes against Kiyo indices timed out. Do not trust FPS configuration for Kiyos until a backend-specific capture path is chosen.
|
||||
- PS3 Eye default DirectShow capture works at `640x480` near 30 fps. High-FPS tracking modes are not proven yet; mode probes against the DirectShow filter can hang or collide with another open handle, so test them sequentially.
|
||||
|
||||
Observed audio access over WASAPI at 48 kHz:
|
||||
|
||||
- Scarlett Solo USB microphone
|
||||
- Razer Kiyo Pro microphone
|
||||
- Razer Kiyo microphone
|
||||
- both `USB Camera-B4.09.24.1` microphone devices, presumed PS3 Eye audio interfaces
|
||||
- Scarlett Solo speaker output
|
||||
|
||||
## ChArUco Target
|
||||
|
||||
A first calibration target has been generated:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\charuco_calibration.py board
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
- `calibration/targets/charuco-8x6-dict4x4-100.png`
|
||||
- `calibration/targets/charuco-8x6-dict4x4-100.json`
|
||||
|
||||
Capture intrinsics frames for a camera:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\charuco_calibration.py capture --api dshow --index 1 --frames 25
|
||||
```
|
||||
|
||||
Solve intrinsics from a capture run:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\charuco_calibration.py calibrate --images .\calibration\runs\<run-folder>
|
||||
```
|
||||
|
||||
## PS3 Eye Driver Cut
|
||||
|
||||
Use the open-driver path first. The current candidate is the opentrack PS3 Eye open driver route:
|
||||
|
||||
1. uninstall any old CL Eye / PS3 Eye video driver
|
||||
2. use Zadig on PS3 Eye interface `MI_00`
|
||||
3. install `libusb-win32` first
|
||||
4. if that fails, try `libusbK`
|
||||
5. re-run:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py discover --max-index 10
|
||||
.\.venv\Scripts\python.exe .\scripts\calibration_probe.py snapshot --max-index 10
|
||||
```
|
||||
|
||||
Do not install the driver over `MI_01`; that is the working generic USB audio interface.
|
||||
|
||||
CL Eye / Code Laboratories is historical reference material only. Do not make this repo depend on a paid, stale, or redistributed proprietary driver. Reverse engineering should stay inside interoperability research boundaries; the live machine should prefer the open driver.
|
||||
|
||||
opentrack/libusb status:
|
||||
|
||||
- Both PS3 Eye `MI_00` video interfaces are now bound as `libusb-win32 devices` and show `OK` in PnP.
|
||||
- `E:\Tools\opentrack\modules\ps3eye-mode-test.exe` sees the cameras well enough to enumerate good modes up to `320x240@205Hz` and `640x480@83Hz`.
|
||||
- Frame reads still fail with repeated `ps3eye: payload error, data[1]=78` and `can't read any frame`.
|
||||
|
||||
That means the next fault is not "missing driver"; it is driver/backend/USB streaming. opentrack's guide recommends `libusb-win32` first and `libusbK` as a fallback. PSMove's PS3 Eye documentation says WinUSB through Zadig has been tested with PS3EYEDriver on Windows. If libusb-win32 continues to enumerate modes but fail frames, try the fallback in this order on `MI_00` only:
|
||||
|
||||
1. `libusbK`
|
||||
2. `WinUSB`
|
||||
|
||||
After each driver swap, rerun:
|
||||
|
||||
```powershell
|
||||
& 'E:\Tools\opentrack\modules\ps3eye-mode-test.exe'
|
||||
& 'E:\Tools\opentrack\modules\ps3eye-frame-test.exe'
|
||||
```
|
||||
|
||||
Fallback results so far:
|
||||
|
||||
- `libusbK` with both Eyes direct to motherboard: all opentrack modes report `GOOD`, including `320x240@30`, but frame reads still fail with `payload error, data[1]=78/79` and `bad header`.
|
||||
- `WinUSB` with both live `MI_00` instances: opentrack mode test still reports all modes `GOOD`, but one camera open reports `Access is denied` and frame streaming still repeats `payload error, data[1]=78/79`.
|
||||
- `libusb-win32`, `libusbK`, and `WinUSB` have all failed frame reads through opentrack on this machine.
|
||||
|
||||
That path is currently rejected for frame capture on this machine. Keep it as a mode-enumeration reference, not the live capture path.
|
||||
|
||||
Working DirectShow path:
|
||||
|
||||
- Installed AllanCat `PS3 Eye Universal Driver` / `PS3EyeDirectShow` from `PS3EyeInstaller1.1.msi`.
|
||||
- Installed source filters:
|
||||
- `C:\Program Files\PS3 Eye Universal Driver\PS3EyeSourceFilter64.dll`
|
||||
- `C:\Program Files (x86)\PS3 Eye Universal Driver\PS3EyeSourceFilter.dll`
|
||||
- The filter's camera count is controlled by `ChangeCameraNumber.bat`, which unregisters/registers the source filter with `/i:<count>`.
|
||||
- With two cameras connected, register both filters for two cameras from an elevated shell:
|
||||
|
||||
```powershell
|
||||
$dll32 = 'C:\Program Files (x86)\PS3 Eye Universal Driver\PS3EyeSourceFilter.dll'
|
||||
$dll64 = 'C:\Program Files\PS3 Eye Universal Driver\PS3EyeSourceFilter64.dll'
|
||||
Start-Process regsvr32.exe -ArgumentList "/n /i:2 `"$dll32`"" -Verb RunAs -Wait
|
||||
Start-Process regsvr32.exe -ArgumentList "/n /i:2 `"$dll64`"" -Verb RunAs -Wait
|
||||
```
|
||||
|
||||
After registration, this machine exposes:
|
||||
|
||||
- `dshow:3`: PS3 Eye, default `640x480`, about 30 fps.
|
||||
- `dshow:4`: PS3 Eye, default `640x480`, about 30 fps.
|
||||
- Simultaneous three-second capture from indices 3 and 4 produced 90 frames each, about 29.8-30.0 fps.
|
||||
- DirectShow device names are `PS3 Eye Universal` and `PS3 Eye Universal2`; use these names when forcing high-rate modes through FFmpeg.
|
||||
|
||||
Known caveats:
|
||||
|
||||
- Historical diagnostic only: OpenCV `mode-probe` calls that set width/height/fps may time out against the PS3EyeDirectShow filter.
|
||||
- Parallel probes can race the same libusb/backend state and produce `Access is denied`; test PS3 Eye mode changes one handle at a time.
|
||||
- Historical diagnostic only: OpenCV by index did not negotiate high-rate PS3 Eye modes correctly. It can report a requested FPS while delivering the wrong shape or frame rate.
|
||||
- FFmpeg by DirectShow device name does negotiate the filter pins correctly. Verified modes:
|
||||
- single `PS3 Eye Universal` at `640x480@30/40/50/60`; `640x480@60` delivered about 56 fps over three seconds
|
||||
- single `PS3 Eye Universal` at `320x240@30/40/50/60`; `320x240@60` delivered 180 frames over three seconds
|
||||
- single `PS3 Eye Universal2` at `640x480@60` and `320x240@60`; both delivered about 59-60 fps
|
||||
- dual `640x480@60` delivered about 54-56 fps per Eye over five seconds
|
||||
- dual `320x240@60` delivered 300 frames per Eye over five seconds
|
||||
- Requests above 60 fps through the installed DirectShow filter do not increase delivered frame rate. `320x240@70` still delivered about 60 fps; `640x480@70` delivered about 51-52 fps.
|
||||
|
||||
Current tracking capture command shape:
|
||||
|
||||
```powershell
|
||||
$ff = .\.venv\Scripts\python.exe -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"
|
||||
& $ff -hide_banner -f dshow -video_size 320x240 -framerate 60 -pixel_format bgr24 -i video="PS3 Eye Universal" -an -f rawvideo -
|
||||
& $ff -hide_banner -f dshow -video_size 320x240 -framerate 60 -pixel_format bgr24 -i video="PS3 Eye Universal2" -an -f rawvideo -
|
||||
```
|
||||
|
||||
That command emits raw BGR frames to stdout. A real tracker should launch each FFmpeg capture as a child process, read fixed-size `320 * 240 * 3` frame packets, and timestamp packet arrival at the process boundary.
|
||||
|
||||
Next escalation is no longer "find any video path." It is:
|
||||
|
||||
- capture ChArUco intrinsics for `dshow:3` and `dshow:4` at the working default mode
|
||||
- use FFmpeg DirectShow capture for PS3 Eye tracking at `320x240@60`
|
||||
- patch/rebuild PS3EyeDirectShow if more than 60 fps is required; the installed filter advertises a practical 60 fps ceiling
|
||||
- keep Leap/Kiyos/PS3 Eyes split across USB root paths where possible
|
||||
|
||||
Also test with one PS3 Eye unplugged and each camera connected directly to a motherboard USB 2.0/3.x port, not through a hub. A libusb issue report shows PS3 Eye/opentrack access can break when certain USB-C hubs are present, even when the camera itself is not plugged into that hub.
|
||||
|
||||
USB topology note from this machine:
|
||||
|
||||
- The two PS3 Eyes, Razer Kiyo, Razer Kiyo Pro, and Leap Motion are effectively sharing the same external hub/root path.
|
||||
- After binding both PS3 Eye `MI_00` interfaces, one PS3 Eye composite device and one PS3 Eye audio interface showed `Unknown`, while both `MI_00` interfaces remained visible as `libusb-win32`.
|
||||
- Two `Unknown USB Device (Device Descriptor Request Failed)` entries were also present on the same hub path.
|
||||
|
||||
That makes the hub/root topology a live suspect. A USB3 hub does not make old USB2 high-bandwidth devices independent; USB2 traffic still shares the hub's USB2 side and transaction scheduling. iPiSoft's multiple-PS Eye guidance says a single USB2 hub is only acceptable for low-resolution capture, and opentrack's guide says to try another USB2/USB3 controller if the camera fails.
|
||||
|
||||
Practical next cut:
|
||||
|
||||
1. Test one PS3 Eye alone on the current hub.
|
||||
2. If it still fails, test one PS3 Eye alone on a different motherboard root port/controller.
|
||||
3. Once one streams, add the second PS3 Eye at low tracking mode first, e.g. `320x240@60`, then increase.
|
||||
4. Put Kiyos/Leap on a different hub/root path if possible.
|
||||
5. If no physical split is possible, plan for lower PS3 Eye rates and treat the hub as a scarce shared resource, not a magic blue rectangle.
|
||||
|
||||
Mirrored references:
|
||||
|
||||
- `research/visual-spatial-map/mirrors/opentrack-ps3-eye-open-driver-instructions.html`
|
||||
- `research/visual-spatial-map/mirrors/zadig-home.html`
|
||||
- `research/visual-spatial-map/mirrors/code-laboratories-cl-eye-driver.html`
|
||||
Calibration tooling should be native or vendor-backed from here. If a measurement
|
||||
cannot be reproduced without the deleted scripting stack, record the gap and
|
||||
rebuild the measurement path in the live language stack.
|
||||
|
|
|
|||
|
|
@ -1,212 +1,69 @@
|
|||
# Implementation Plan
|
||||
# Implementation Plan
|
||||
|
||||
## Current Cut Line
|
||||
|
||||
`docs/native-rebuild-plan.md` is now the active plan.
|
||||
Mimir is now a C# app/runtime plus native reservoir project. The live stream
|
||||
machine must be direct-driver and native-buffer first:
|
||||
|
||||
No more Python live hot path. No more OpenGL production Spout sink. No more JSON
|
||||
live data stores. Edge JSON may define CultNet schema or export diagnostics, but
|
||||
the real process/network data stays typed because every subsystem is under our
|
||||
control.
|
||||
- `src/Mimir.App` hosts Aquarium Engine for windowing, rendering, and the D3D12
|
||||
bridge.
|
||||
- `src/Mimir.Runtime` owns stream descriptors, source polling, direct push
|
||||
ingest, one rolling buffer per configured audio/video stream, and the
|
||||
synchronization hub Aquarium can inspect.
|
||||
- `native/reservoir` owns the lower native rolling-buffer invariant for
|
||||
Aquarium/Faust integration.
|
||||
- PowerShell/FFmpeg/SRT remains a bridge utility for LAN OBS feeds. It is not
|
||||
the synchronized program authority.
|
||||
|
||||
The native reservoir is now one time-ordered rolling buffer with typed views.
|
||||
The previous shared-edge typed rings proved the retention invariant; the new
|
||||
shape removes independent per-kind storage from the live foundation.
|
||||
|
||||
The near-term viable stream app is Aquarium-hosted: it ingests local or
|
||||
networked video/audio feeds as producers into the same five-second in-memory
|
||||
`LocalcastRuntime`, exposes debug/settings/output control through Aquarium UI,
|
||||
and emits synchronized OBS program video plus separately controllable audio
|
||||
stems. Mimir now owns its own C# solution while referencing Aquarium Engine as
|
||||
the windowing/rendering library and D3D12 bridge. `docs/viable-stream-app.md`
|
||||
is the current cut line for that app.
|
||||
|
||||
The v1 OBS bridge is now gated by a bounded smoke-test witness ledger. No
|
||||
plugin/native receiver expansion is justified until
|
||||
`calibration/runs/obs-v1-smoke-ledger.json` records sender capture, SRT receive,
|
||||
and OBS presentation timestamps for every planned endpoint with bounded drift,
|
||||
latency, and confidence.
|
||||
The old script stack is gone. Do not add a compatibility edge unless it protects
|
||||
a named invariant that the native runtime cannot protect yet.
|
||||
|
||||
## Implemented
|
||||
|
||||
- Mimir public identity and repo Face:
|
||||
- `README.md` now presents the project as Mimir: local sensors, coherent
|
||||
field.
|
||||
- `Mimir.png` is the user-repixelized 256px avatar source.
|
||||
- `assets/branding/mimir-avatar-256.png` is the project branding copy.
|
||||
- `.voidbot/voice/mimir.png` and `.voidbot/voice/identity.json` are the
|
||||
VoidBot-facing persona surfaces for the Mimir Face.
|
||||
- `.voidbot/state/mimir.cc` is the typed persistent Face state. It is seeded
|
||||
with durable birth memories for Mimir identity, native-reservoir target,
|
||||
ownership boundaries, audio-field discipline, and heartbeat agency pressure.
|
||||
- `docs/mimir-face.md` defines Mimir's jurisdiction, voice, heartbeat
|
||||
behavior, and inherited memories. VoidBot is only the mouth/scheduler.
|
||||
- Perfect Machine contract:
|
||||
- `docs/perfect-machine.md` defines the target native machine: one five-second spatiotemporal reservoir, Aquarium-owned dense visual fusion/material/brush rendering, Faust-owned hot audio DSP, OBS-owned broadcast controls, and Mimir-owned calibration/config/status.
|
||||
- `docs/viable-stream-app.md` defines the first useful application cut:
|
||||
Aquarium hosts the in-memory five-second runtime, owns runtime UI and
|
||||
output management, treats local/networked feeds as producers, and emits
|
||||
synchronized OBS program surfaces.
|
||||
- `Mimir.slnx` contains `src/Mimir.App` and `src/Mimir.Runtime`.
|
||||
`Mimir.App` launches `AquariumHost` from Aquarium Engine, and
|
||||
`Mimir.Runtime` supplies the Aquarium client runtime factory.
|
||||
- `Mimir.Runtime` now owns `MimirSynchronizationHub`,
|
||||
`MimirRollingStreamBuffer`, stream descriptors, and the `IMimirStreamSource`
|
||||
adapter seam. It initializes one bounded rolling buffer per configured
|
||||
audio/video stream and polls registered local/network sources each frame.
|
||||
Local devices should feed through native push adapters; process-backed
|
||||
sources are compatibility edges for network/diagnostic command ingest, not
|
||||
the six-camera capture foundation.
|
||||
- `MimirVideoFrameDescriptor` is the first video-frame hot-path descriptor:
|
||||
dimensions, pixel format, stride, device timestamp, and optional native/GPU
|
||||
handle. Leap stereo IR should enter Mimir through this native descriptor,
|
||||
with OpenCV kept out of the hot loop.
|
||||
- `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` define the
|
||||
live driver-facing seam. LeapUVC/libusb, LeapC images, Media Foundation,
|
||||
DirectShow, or GPU shared texture capture should plug in here.
|
||||
- `config/perfect-machine.example.json` declares the contract shape for six cameras, six microphones, reservoir typed views, native authorities, outputs, and the demotion of bridge scripts to tooling.
|
||||
- `native/reservoir` is the first native Rust crate. It implements one
|
||||
shared-edge five-second rolling buffer with typed views and proves that
|
||||
every kind expires from the newest live sample.
|
||||
- `native/reservoir/include/localcast_reservoir.h` exposes the initial
|
||||
Aquarium/Faust C ABI: opaque reservoir create/destroy, sample-handle push,
|
||||
edge/window queries, ring counts, and latest sample lookup by sensor hash.
|
||||
The ABI now exposes total rolling-buffer length and typed-view length.
|
||||
- `localcast_hash_source_id` owns stable FNV-1a source hashing for native
|
||||
producers; empty/null source ids produce zero and are rejected.
|
||||
- `localcast_producer_create_for_source` is the preferred producer constructor
|
||||
for adapters because it keeps source-id hashing inside the native ABI.
|
||||
- `LocalcastRuntime` wraps the current reservoir with typed native producer
|
||||
calls and total/typed read functions. It is the intended live spine for
|
||||
Aquarium/Faust bindings.
|
||||
- `LocalcastProducer` owns native ingress source identity and sequence
|
||||
assignment before appending live handles into `LocalcastRuntime`.
|
||||
- `LocalcastAudioBlockDescriptor` is the first typed payload descriptor for
|
||||
caller-owned float32 interleaved audio blocks. The reservoir stores only the
|
||||
descriptor pointer as a payload handle; audio memory remains owned by
|
||||
native/Faust producers.
|
||||
- `LocalcastRenderPacketDescriptor` gives render packets the same typed
|
||||
descriptor boundary: caller-owned point buffer, point count/stride, target
|
||||
size, source window, present time, audio-alignment time, and optional
|
||||
metadata handle.
|
||||
- `LocalcastRenderPoint` is the first fixed point-buffer element ABI for
|
||||
Aquarium decoding: stable-key hash, source timestamp, position, radius,
|
||||
color/alpha, and confidence.
|
||||
- Repo-local persistence machinery.
|
||||
- First architecture map.
|
||||
- Example config for one video source plus two audio sources.
|
||||
- Sender device discovery script.
|
||||
- Sender launch script with dry-run mode and per-source FFmpeg commands.
|
||||
- OBS receiver setup notes.
|
||||
- Neighbor sender deployment under `C:\Meta\Mimir`.
|
||||
- Madman's desktop start/stop launchers for the sender.
|
||||
- Receiver OBS scene has `Neighbor PC - Video` and `Neighbor PC - Focusrite` Media Sources.
|
||||
- Direct co-streamer loopback capture is now attempted with the repo WASAPI shim instead of Voicemeeter.
|
||||
- Receiver OBS scene has `Neighbor PC - System Audio` on SRT port `5102`.
|
||||
- Sender script uses `-nostdin` and repo-root logs so desktop launchers stay alive and diagnostics land in `C:\Meta\Mimir\logs`.
|
||||
- Sender video config is `1920x1080` for the interactive desktop. The `1024x768` SSH session size is not the streaming target.
|
||||
- Desktop `.cmd` launchers delegate to PowerShell wrappers so paths with spaces and apostrophes are handled in one place.
|
||||
- Audio-field sidecar profile and tool:
|
||||
- `config/audio-field.example.json` declares the actual distributed six-mic rig: two Kiyo mics, two PS Eye mics, local Focusrite shielded cardioid, neighbor Focusrite shotgun on the co-streamer, two local speakers, placeholder geometry, clock domains, capture policy, calibration sweep settings, and FOA AmbiX ACN/SN3D output.
|
||||
- `scripts/audio_field.py` lists devices, validates shared or distributed profiles, checks local distributed sources, generates calibration sweeps, summarizes clock-domain sync requirements, preserves shared-input capture helpers, and encodes already aligned offline WAVs to FOA.
|
||||
- `audio_field/` contains testable core modules for source buffering, bounded latency convergence, injectable capture/alignment/encoder/sink ports, and pipeline orchestration.
|
||||
- `docs/audio-field.md` maps the audio pipeline and its invariants.
|
||||
- Sensor-fusion render bridge:
|
||||
- `localcast.sensor_fusion.calibration_space` solves fixed-board ChArUco observations into camera poses in one common world frame.
|
||||
- `localcast.sensor_fusion.surface_features` matches cross-view features and triangulates calibrated surface tracks.
|
||||
- `localcast.sensor_fusion.render_bridge` emits render-frame packets with visual/audio timing metadata and Spout sender identity.
|
||||
- `localcast.diagnostics.visual_cache` stores diagnostic visual state as typed
|
||||
CultCache MessagePack documents. It is not the production live boundary.
|
||||
- `localcast.diagnostics.render_math` owns pure diagnostic render budgeting,
|
||||
camera projection, brush lowering, and CPU rasterization tests without an
|
||||
OpenGL or OpenCV requirement.
|
||||
- The Python/OpenGL Spout publisher and launcher have been deleted.
|
||||
Production Spout2 publication belongs to Aquarium.
|
||||
- `localcast.diagnostics.visual_producer` contains the old Python visual
|
||||
producer code. It is diagnostic/migration code, not production runtime, and
|
||||
no longer has a script launcher.
|
||||
- The live visual producer writes a multi-LOD scene cache with source kind and priority. Real Leap frames are promoted as the highest-priority visual timing/spatial evidence; Leap fallback frames remain lower-priority diagnostics.
|
||||
- Live clap calibration is wired into the visual producer. It keeps a rolling frame window from the Kiyo pair plus Leap, reads the live spatial audio frame for transient candidates, publishes `clap-events.msgpack`, injects clap calibration markers into the render frame, and writes clap evidence into the LOD cache. Kiyo stereo owns the current rough 3D solve; Leap owns the best visual timing witness until its geometric model is calibrated.
|
||||
- Clap peaks now update a per-camera clock sync model. The point-cloud builder can sample camera history buffers at `oracle_time - camera_offset` instead of using whichever frame arrived last.
|
||||
- The live visual producer now uses an explicit five-second spatiotemporal reservoir. RGB/Leap frame history expires from the newest shared sample, the multi-LOD cache only accepts evidence inside that same window, and `RenderFramePacket.source_time_min_ns/source_time_max_ns` declares the reservoir slice being rendered.
|
||||
- Multi-LOD cells now carry first-pass material estimates: weighted albedo plus roughness/metallic hints derived from source evidence. Aquarium should treat this as relightable material evidence to refine, not as the final BRDF solve.
|
||||
- The Spout/audio overlay boundary clamps stale visual packets to the current audio reservoir edge. If camera geometry ages out, it is dropped instead of being broadcast out of sync.
|
||||
- Live fallback-only RGB/Leap mode exists for deadline operation when OpenCV/MSMF/DirectShow reads block longer than the five-second reservoir. It keeps the reservoir and OBS output alive while real camera capture is moved to nonblocking ingress.
|
||||
- OpenCV camera reads now run behind `LatestFramePump` workers so blocking drivers cannot freeze the fusion hot loop. The live deadline command uses lower per-frame sample density (`--rgb-room-step 16 --leap-step 16 --points 64`) so the reservoir/TAA path stays fresh enough for Spout to render visual points inside the five-second budget.
|
||||
- `localcast.sensor_fusion.chirp_pose` converts live phase-field delay meaning for Kiyo/PS Eye microphone sources into camera-body range constraints and per-camera pose-correction estimates. It can load camera-mic and speaker geometry from the audio-field profile, with the example profile used as the live fallback until measured local geometry exists. The diagnostic visual producer can inject those constraints as `camera-chirp:*` and `camera-pose-correction:*` render points plus `chirp-camera-pose` LOD evidence.
|
||||
- Diagnostic render math still has a named `kiyo-mid-deru` virtual camera
|
||||
preset and point budget for CPU tests. Aquarium should own the production
|
||||
version of that policy.
|
||||
- `docs/obs-spout-streaming.md` documents OBS setup and the Aquarium replacement boundary.
|
||||
- `docs/typed-visual-state.md` documents the diagnostic CultCache file shape
|
||||
and the CultNet visual schema target.
|
||||
- OBS synchronized program surface:
|
||||
- `scripts/obs_smoke_test.py` creates the v1 OBS smoke-test endpoint plan,
|
||||
event template, and witness ledger.
|
||||
- `localcast.obs_smoke` owns the pure endpoint planning and ledger summary
|
||||
logic: per-stage timestamps, matched end-to-end latency, endpoint drift, and
|
||||
confidence.
|
||||
- `docs/obs-v1-smoke-test.md` is the runbook for collecting
|
||||
`sender_capture`, `srt_receive`, and `obs_present` evidence before receiver
|
||||
expansion.
|
||||
- `scripts/setup_obs_synced_program.py` derives OBS-controllable stems from an aligned program audio timeline: host voice, co-streamer voice, ambient, transients, co-streamer loopback, and local loopback.
|
||||
- `scripts/capture_co_streamer_surfaces.py` captures neighbor Focusrite and neighbor loopback with local loopback ground truth, estimates the late remote-family offset, and writes aligned co-streamer surfaces for the stem packer.
|
||||
- `scripts/wasapi-loopback-capture.ps1` is the direct primary-playback loopback path. It must run in the neighbor's interactive console session; SSH-only capture sees the device but receives no render packets.
|
||||
- The tool creates/updates local OBS Media Sources for those stems and mutes/disables raw unsynchronized inputs.
|
||||
- Strict mode disables every scene item except the synchronized Mimir program video and stem controls.
|
||||
- Live phase-field meaning:
|
||||
- `audio_field.phase_meaning` extracts actionable delay, coherence, confidence, suppression, correction-energy, and active-probe need from internal phase/chirplet evidence.
|
||||
- `localcast.audio.phase_field` is a typed CultCache document at `calibration/runs/audio-phase-field.msgpack`.
|
||||
- `localcast.diagnostics.audio_phase_field` can replay an aligned mic field plus known program/loopback reference into the phase-field document for diagnostics. It is not a live bridge authority.
|
||||
- `localcast.diagnostics.audio_phase_field` can write `audio-phase-field-status.json` during replay so estimator behavior remains inspectable while the native ingest path is built.
|
||||
- `audio_field.active_probe` wires low phase-field confidence into `ActiveProbeOptimizer`, emits bounded chirplet WAVs plus `active-probes.jsonl`, and can play probes through the default output device.
|
||||
- `localcast.diagnostics.audio_live_field` preserves the old local WASAPI/PortAudio capture experiment as diagnostic code only. Production local mic and loopback ingest belongs in native capture workers that append typed handles through `LocalcastProducer`.
|
||||
- Active probe maintenance only targets source ids backed by live local capture devices. Missing distributed channels remain stable placeholders in the mic/phase field, but they do not consume chirp budget.
|
||||
- Active probe artifacts are bounded: emitted chirps rotate through a fixed slot set and the manifest rotates at a byte cap. The calibration loop is allowed to be noisy; it is not allowed to become an unbounded filesystem leak.
|
||||
- Faust voice-separation boundary:
|
||||
- `localcast.audio.mic_field` publishes aligned six-mic float32 blocks at `calibration/runs/audio-mic-field.msgpack`.
|
||||
- `faust/localcast_voice_separation.dsp` is the first Aquarium-hosted graph surface for host voice, co-streamer voice, ambient, transient, and loopback stems.
|
||||
- `localcast.diagnostics.faust_mic_field` can replay aligned WAV blocks into the old mic-field document for smoke tests. It is not a live publisher.
|
||||
- Mimir public identity, branding, and Face memory.
|
||||
- `Mimir.slnx` with `src/Mimir.App` and `src/Mimir.Runtime`.
|
||||
- Aquarium host bootstrapping from `Mimir.App`.
|
||||
- `MimirSynchronizationHub`, `MimirRollingStreamBuffer`, stream descriptors, and
|
||||
`IMimirStreamSource`.
|
||||
- Configurable five-second default rolling buffers for local and network audio
|
||||
and video streams.
|
||||
- `MimirNativeIngestStreamSource` for direct push ingest into runtime buffers.
|
||||
- `MimirProcessStreamSource` for bridge/network command edges.
|
||||
- `MimirVideoFrameDescriptor` for dimensions, pixel format, stride, device
|
||||
timestamp, and native/GPU handle metadata.
|
||||
- `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` as the live
|
||||
driver-facing seam for Leap, Media Foundation, DirectShow, libusb, LeapC, or
|
||||
shared texture capture.
|
||||
- `native/reservoir` with one shared-edge rolling buffer, typed views, C ABI,
|
||||
source-id hashing, producer helpers, and typed audio/render payload
|
||||
descriptors.
|
||||
- Windows bridge scripts for sender discovery/start/stop and simple OBS Media
|
||||
Source ingest.
|
||||
- Documentation for OBS receiver setup, native rebuild boundaries, the viable
|
||||
stream app, and the Mimir Face.
|
||||
|
||||
## Temporary
|
||||
|
||||
- Audio and video are separate SRT endpoints. This preserves OBS mixing authority but may need latency tuning.
|
||||
- The OBS v1 smoke ledger currently owns the receiver expansion gate. Until a
|
||||
real run passes, endpoint coherence is unknown rather than assumed.
|
||||
- Audio defaults to AAC inside MPEG-TS for compatibility; test Opus later only if there is a concrete reason.
|
||||
- Desktop capture uses `gdigrab` first because it is broadly available. `ddagrab` is a candidate once the installed FFmpeg build is confirmed.
|
||||
- The scripts assume Windows sender and OBS receiver on the same LAN.
|
||||
- The Python visual producer is a diagnostic/migration fossil only. The OpenGL
|
||||
Spout sink has been deleted.
|
||||
- Python audio publishers are diagnostic fossils only. The AmbiX, phase-field,
|
||||
live-local-capture, and Faust mic-field publisher modules live under
|
||||
`localcast.diagnostics.*`; the live PowerShell launchers for phase-field and
|
||||
Faust mic-field publication have been deleted.
|
||||
- Audio and video may still traverse separate OBS/SRT endpoints during bridge
|
||||
testing so OBS can preserve independent controls.
|
||||
- Process-backed stream sources are only acceptable for network bridge feeds or
|
||||
diagnostics. Six-camera local ingest belongs behind direct capture drivers.
|
||||
- Calibration artifacts may remain on disk as evidence, but live state must be
|
||||
in memory inside Mimir/Aquarium/native runtime surfaces.
|
||||
|
||||
## Next
|
||||
|
||||
1. Delete remaining diagnostic command dependence on `localcast.diagnostics.visual_producer`,
|
||||
diagnostic JSON render-frame adapters, and diagnostic JSON LOD adapters.
|
||||
Reservoir-window clipping, Leap packed transforms, RGB reference splats, and
|
||||
clap calibration have been split out of the producer monolith.
|
||||
2. Bind Aquarium/Faust to the rolling-buffer `LocalcastRuntime`.
|
||||
Aquarium now has a safe-code native reservoir binding layer, injected frame
|
||||
source seam, and native `ILocalCastVisualFrameSource` that reads render
|
||||
packet handles through `ILocalCastNativeRuntime` with an injected payload
|
||||
decoder. It also has the matching safe-code audio block and render packet
|
||||
descriptor bindings, plus a render descriptor decoder that reads timing and
|
||||
target metadata from native payload handles and decodes the first native
|
||||
point-buffer ABI by default. Aquarium also exposes the native source-id hash
|
||||
wrapper and source-id producer constructor. The next Aquarium cut is wiring
|
||||
native runtime creation into the app path once a producer exists to feed it.
|
||||
3. Move camera/mic/loopback ingest into native capture workers that use
|
||||
`LocalcastProducer` to append typed sample handles.
|
||||
4. Move feature extraction, flow, cross-view matching, LOD reconciliation,
|
||||
material fitting, brush/splat rendering, and Spout2 publication into
|
||||
Aquarium GPU compute.
|
||||
5. Move mic alignment, room suppression, voice separation, Ambisonic/HOA
|
||||
spatialization, and stem generation into Faust/native DSP.
|
||||
6. Keep FFmpeg/SRT scripts as simple LAN ingest/capture utilities, not the
|
||||
synchronized program authority.
|
||||
7. Run the v1 OBS smoke test against the actual sender/receiver setup and keep
|
||||
the ledger as evidence before any receiver/plugin/native OBS expansion.
|
||||
1. Implement concrete direct capture drivers for Leap stereo IR first, then the
|
||||
other cameras.
|
||||
2. Feed those drivers into `MimirVideoCaptureDriverSource` and prove sustained
|
||||
frame cadence in the rolling buffers.
|
||||
3. Add native audio capture workers for local mic, loopback, and network audio
|
||||
feeds.
|
||||
4. Bind Aquarium UI to the synchronization hub so buffer depth, stream cadence,
|
||||
source timestamps, and output settings are visible and adjustable.
|
||||
5. Move GPU feature extraction, fusion, material fitting, render budgeting, and
|
||||
Spout2 publication into Aquarium.
|
||||
6. Move mic alignment, room suppression, voice separation, spatialization, and
|
||||
stem generation into Faust/native DSP.
|
||||
7. Keep the OBS bridge witness ledger as evidence before expanding receiver
|
||||
machinery.
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ Mimir must not:
|
|||
|
||||
- claim ownership over OBS composition, Aquarium rendering, Faust DSP, or FFmpeg
|
||||
capture;
|
||||
- revive Python live hot paths, OpenGL production Spout, or JSON live stores;
|
||||
- revive deleted script hot paths, OpenGL production Spout, or JSON live stores;
|
||||
- turn progress updates into lore fog;
|
||||
- preserve old work because it exists;
|
||||
- let heartbeat chatter become a substitute for shipped cuts.
|
||||
|
|
@ -71,7 +71,6 @@ Invariants:
|
|||
- FFmpeg owns simple capture, encode, and transport in V1 bridge mode.
|
||||
- Mimir/this repo owns configuration, calibration, launch/status, typed
|
||||
contracts, memory, and operational repeatability.
|
||||
- Python is tooling and diagnostics, not a live presentation hot path.
|
||||
- JSON is schema or diagnostic export, not live process/network data.
|
||||
- Missing synchronized feeds are explicit absence or placeholders, not stale or
|
||||
unsynchronized substitutions.
|
||||
|
|
@ -138,8 +137,8 @@ When VoidBot wakes Mimir for a heartbeat:
|
|||
|
||||
1. Read `state/map.yaml`, `notes/fresh-workspace-handoff.md`,
|
||||
`notes/current-system-map.md`, and `docs/implementation-plan.md`.
|
||||
2. Run `tools/localcast_state.py status`.
|
||||
3. Check `git status --short --branch`.
|
||||
2. Check `git status --short --branch`.
|
||||
3. Read the tail of `state/evidence.jsonl`.
|
||||
4. Report only meaningful drift, completed work, blockers, or next bounded
|
||||
moves.
|
||||
5. If nothing changed, say so briefly and name the next useful cut.
|
||||
|
|
@ -164,9 +163,9 @@ These are the lessons Mimir should remember at birth:
|
|||
- Icon explorations and prompts live under `assets/branding/`.
|
||||
- The strongest avatar direction was the voxel-mask Face: mythic, symmetrical,
|
||||
sensor-rooted, and readable as a profile image.
|
||||
- The Python/OpenGL Spout publisher was deleted. Do not revive it.
|
||||
- Python producers, CultCache files, and JSON adapters are diagnostics or
|
||||
migration fossils. They are not production runtime authority.
|
||||
- The deleted script-era presentation stack stays deleted. Do not revive it.
|
||||
- CultCache files and JSON adapters are diagnostics or migration fossils. They
|
||||
are not production runtime authority.
|
||||
- `native/reservoir` is the first native foundation. It now uses one
|
||||
time-ordered rolling buffer with typed views.
|
||||
- `LocalcastRuntime` is the intended live spine. `LocalcastProducer` owns source
|
||||
|
|
|
|||
|
|
@ -1,160 +1,71 @@
|
|||
# Native Rebuild Plan
|
||||
# Native Rebuild Plan
|
||||
|
||||
This is the cut line after the architectural teardown.
|
||||
|
||||
The live system must be rebuilt around one native rolling reservoir. Python and
|
||||
OpenGL are no longer acceptable live foundations. Python may remain as offline
|
||||
calibration, schema tests, device discovery, migration probes, and forensic
|
||||
tools only. If a future change needs Python or an OpenGL Spout sink in the live
|
||||
path, treat that as evidence the native boundary is missing, not as permission
|
||||
to extend the deadline bridge.
|
||||
This is the live cut line: Mimir is a direct-driver, native-buffer, Aquarium
|
||||
hosted stream machine.
|
||||
|
||||
## Objective
|
||||
|
||||
Make the second PC available in OBS as synchronized program video plus
|
||||
separately controllable audio while preserving the real ownership model:
|
||||
Make the room available in OBS as synchronized program video plus separately
|
||||
controllable audio while preserving ownership:
|
||||
|
||||
- Mimir owns config, calibration, contract tests, launch, status, and
|
||||
CultNet schema.
|
||||
- One native runtime owns live sample timing and retention.
|
||||
- Aquarium owns GPU visual fusion, material/brush/splat rendering, and Spout2
|
||||
publication.
|
||||
- Faust/native DSP owns hot audio alignment, suppression, voice separation,
|
||||
stems, and spatial bed generation.
|
||||
- Mimir owns configuration, calibration truth, runtime contracts, launch,
|
||||
status, and persistence.
|
||||
- Mimir.Runtime owns in-memory stream buffers and runtime synchronization.
|
||||
- Native capture workers own device reads and append typed sample handles.
|
||||
- Aquarium owns GPU fusion, rendering, D3D12 interop, UI, and Spout2 output.
|
||||
- Faust/native DSP owns hot audio alignment, suppression, separation, stems, and
|
||||
spatial bed generation.
|
||||
- OBS owns broadcast controls.
|
||||
|
||||
## Durable State Model
|
||||
|
||||
Durable state is declarative or evidentiary. It is not the live machine.
|
||||
|
||||
- `config/localcast.json`: LAN sender/receiver endpoints, OBS source names, and
|
||||
FFmpeg/NVENC settings for simple bridge mode.
|
||||
- `config/sensor-fusion.json`: measured camera identity, intrinsics, extrinsics,
|
||||
capture hints, and calibration timestamps.
|
||||
- `config/audio-field.json`: measured mic/speaker identity, geometry, clock
|
||||
domains, channel order, roles, gain, delay, and polarity.
|
||||
- CultNet schema JSON: edge schema only. The actual runtime documents are typed
|
||||
CultNet documents, not JSON data files.
|
||||
- Calibration artifacts: WAVs, images, manifests, solves, and evidence ledgers.
|
||||
- `state/*` and `notes/*`: rehydration memory for agents, never runtime truth.
|
||||
|
||||
## Runtime State Model
|
||||
|
||||
The runtime state is one native rolling buffer with a single edge.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
C["native capture workers"] --> R["LocalcastRuntime rolling reservoir"]
|
||||
A["audio capture / loopback workers"] --> R
|
||||
R --> Q["Aquarium GPU fusion + render"]
|
||||
C["direct camera drivers"] --> R["Mimir.Runtime buffers"]
|
||||
A["audio / loopback drivers"] --> R
|
||||
N["network feed producers"] --> R
|
||||
R --> Q["Aquarium UI + GPU fusion"]
|
||||
R --> F["Faust/native DSP"]
|
||||
Q --> S["Spout2 sender"]
|
||||
Q --> S["Spout2/program video"]
|
||||
F --> P["program stems + spatial bed"]
|
||||
S --> O["OBS"]
|
||||
P --> O
|
||||
R --> N["typed CultNet status/docs"]
|
||||
```
|
||||
|
||||
The reservoir stores sample handles in one time-ordered rolling buffer. Each
|
||||
sample has:
|
||||
The app-level runtime initializes one rolling buffer per configured audio or
|
||||
video stream, defaulting to five seconds. The lower native reservoir keeps the
|
||||
single-edge typed-handle invariant for Aquarium/Faust integration.
|
||||
|
||||
- kind: camera frame, camera feature, scene ray, surface claim, material claim,
|
||||
audio block, phase claim, event claim, render packet, or status claim
|
||||
- source id
|
||||
- source timestamp
|
||||
- arrival timestamp
|
||||
- sequence
|
||||
- payload handle
|
||||
- provenance flags, which must be zero for live reservoir samples
|
||||
|
||||
Typed ring views may exist as indexes over the rolling buffer, but they do not
|
||||
own retention. Expiry happens once, against the reservoir edge. No private
|
||||
history outlives the rolling buffer.
|
||||
|
||||
Payload memory belongs to the producing domain. Aquarium owns GPU image,
|
||||
feature, surface, material, and render payloads. Faust/native DSP owns audio
|
||||
buffers and stem payloads. The reservoir owns timing, identity, ordering,
|
||||
retention, and handle lookup.
|
||||
|
||||
Typed payload descriptors may cross the ABI when they clarify ownership without
|
||||
copying data. `LocalcastAudioBlockDescriptor` describes caller-owned interleaved
|
||||
float32 audio blocks for native/Faust producers; the reservoir stores its
|
||||
address as the payload handle and does not own the bytes.
|
||||
`LocalcastRenderPacketDescriptor` does the same for visual render packets:
|
||||
caller-owned point buffers and timing metadata are explicit, while Aquarium owns
|
||||
decode/upload/rendering.
|
||||
The first point-buffer element is `LocalcastRenderPoint`; it is deliberately
|
||||
small so a native producer can kill file-backed render-frame transport before
|
||||
the richer material/brush payloads arrive.
|
||||
Payload memory belongs to the producing domain. The reservoir and runtime own
|
||||
timing, identity, ordering, retention, and lookup. They do not pretend to own
|
||||
camera driver buffers, GPU textures, or DSP audio memory.
|
||||
|
||||
## Authoritative Boundaries
|
||||
|
||||
- Config/calibration crosses into runtime as immutable measured truth plus
|
||||
explicit profile version.
|
||||
- Capture workers cross into runtime by appending typed sample handles.
|
||||
- Aquarium crosses the reservoir boundary by sampling typed visual/audio timing
|
||||
handles and publishing a Spout2 texture.
|
||||
- Faust/native DSP crosses the reservoir boundary by sampling audio/phase/event
|
||||
handles and publishing typed stem/spatial-bed documents or OBS-facing audio
|
||||
surfaces.
|
||||
- CultNet carries typed process/network documents for status, control, and
|
||||
external consumers. JSON exists only to declare schema or export diagnostics.
|
||||
- OBS receives final program surfaces. It does not own synchronization or scene
|
||||
reconstruction.
|
||||
|
||||
## Derived, Not Stored
|
||||
|
||||
- Render packets are derived from reservoir claims.
|
||||
- LOD cells are derived from current reservoir contents.
|
||||
- Brush/splat packets are derived by Aquarium.
|
||||
- Audio event overlays are derived from event claims and presentation time.
|
||||
- Point budgets are derived from typed claim metadata, not string prefixes.
|
||||
- JSON heartbeat/status files are diagnostic exports only, if they survive at
|
||||
all.
|
||||
|
||||
## Delete Early
|
||||
|
||||
Delete or quarantine these before adding new live features:
|
||||
|
||||
- Python live producers.
|
||||
- Python live audio/visual hot loops.
|
||||
- OpenGL Spout renderer.
|
||||
- Synthetic/fallback visual evidence in the production path.
|
||||
- JSON render-frame and LOD stores as live data.
|
||||
- Renderer-owned semantic priority based on stable-key prefixes.
|
||||
- Multiple Python copies of reservoir-window clipping.
|
||||
- File mtime caches used as lifecycle or data freshness authority.
|
||||
- Config/calibration crosses into runtime as measured truth plus profile
|
||||
version.
|
||||
- Capture drivers cross into runtime by appending typed samples.
|
||||
- Aquarium consumes current visual/audio timing state and publishes the program
|
||||
video surface.
|
||||
- Faust/native DSP consumes audio/phase/event handles and publishes stems.
|
||||
- OBS receives final program surfaces. It does not own synchronization.
|
||||
|
||||
## Impossible By Construction
|
||||
|
||||
- A sample older than the reservoir window is visible to live consumers.
|
||||
- A diagnostic/fallback source enters a ground-truth reservoir kind.
|
||||
- A renderer invents scene priority from display names or string prefixes.
|
||||
- JSON becomes live data transport.
|
||||
- Python becomes the production hot path.
|
||||
- OpenGL becomes the production Spout sink.
|
||||
- A sample older than the rolling window is visible to live consumers.
|
||||
- A process bridge becomes the six-camera local capture foundation.
|
||||
- File polling becomes the native runtime API.
|
||||
- OBS broadcasts raw unsynchronized sources as the synchronized program.
|
||||
- Two modules own the reservoir edge.
|
||||
|
||||
## Migration Order
|
||||
|
||||
1. Freeze this plan in persistence and stop feature work on the Python/OpenGL
|
||||
bridge.
|
||||
2. Rewrite `native/reservoir` from typed independent rings to one rolling buffer
|
||||
with typed indexes/views.
|
||||
3. Add contract tests proving single-edge expiry, typed view queries, latest
|
||||
lookup, and impossible fallback admission.
|
||||
4. Add the minimal Aquarium/Faust C ABI over the rolling buffer.
|
||||
5. Move any remaining useful Python packet/schema code into diagnostics or
|
||||
contract tests.
|
||||
6. Keep the Python visual producer and compatibility adapters under
|
||||
`localcast.diagnostics` only until they can be deleted.
|
||||
7. Build the Aquarium-owned Spout publisher. Do not revive the Python/OpenGL
|
||||
path.
|
||||
8. Move audio hot path into Faust/native DSP behind typed reservoir handles.
|
||||
9. Keep FFmpeg/SRT scripts only as simple V1 LAN bridge and capture utilities.
|
||||
10. Delete dead compatibility files once no diagnostic command depends on them.
|
||||
|
||||
Small commits are allowed. Small evasions are not. If a commit preserves the
|
||||
deadline bridge by adding an adapter around it, it is probably feeding the old
|
||||
machine again.
|
||||
1. Keep the C# app/runtime as the public Mimir surface.
|
||||
2. Implement Leap stereo IR direct ingest first and measure sustained cadence.
|
||||
3. Add the remaining local camera drivers through the same source seam.
|
||||
4. Add native audio capture workers and feed aligned blocks to Faust/native DSP.
|
||||
5. Bind Aquarium UI to stream health, buffer depth, source timestamps, settings,
|
||||
and output management.
|
||||
6. Move GPU fusion and Spout2 publication fully into Aquarium.
|
||||
7. Keep FFmpeg/SRT scripts only as bridge utilities until direct program output
|
||||
makes them unnecessary.
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ The sender FFmpeg build does not expose a native `wasapi` input device, so it
|
|||
cannot directly capture primary playback by itself. `scripts\wasapi-loopback-capture.ps1`
|
||||
is the direct Core Audio loopback path. It works when launched in the logged-in
|
||||
console session and audio is actually rendering; SSH-only launches can open the
|
||||
endpoint but receive no render packets. `scripts\capture_co_streamer_surfaces.py`
|
||||
endpoint but receive no render packets. The native/co-streamer capture path
|
||||
therefore schedules the WASAPI loopback leg into the interactive session and
|
||||
pulls the resulting raw float PCM back for alignment.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,32 +1,8 @@
|
|||
# OBS Spout Streaming
|
||||
|
||||
## Current Status
|
||||
|
||||
The Python/OpenGL Spout sender has been deleted.
|
||||
|
||||
Mimir no longer carries a runnable OpenGL publication path. The only
|
||||
surviving pieces are diagnostic packet/brush math in
|
||||
`localcast.diagnostics.render_math` and typed diagnostic visual documents in
|
||||
`localcast.diagnostics.visual_cache`.
|
||||
# OBS Spout Streaming
|
||||
|
||||
Production Spout2 publication belongs to Aquarium.
|
||||
|
||||
## Target
|
||||
|
||||
```text
|
||||
native rolling reservoir
|
||||
-> Aquarium typed runtime state
|
||||
-> GPU feature/fusion/material/brush buffers
|
||||
-> D3D render target
|
||||
-> Spout2 sender texture
|
||||
-> OBS Spout2 Capture
|
||||
```
|
||||
|
||||
## Invariants
|
||||
|
||||
- OBS receives a named Spout2 texture from Aquarium, not Python/OpenGL.
|
||||
- Mimir may expose diagnostic typed documents and CPU render math, but
|
||||
it does not own the production renderer.
|
||||
- JSON remains a diagnostic/status surface only.
|
||||
- The neighbor SRT video feed is a timed media artifact and must share the same
|
||||
presentation ledger as Aquarium output and Faust audio.
|
||||
OBS should receive a named Spout2 texture from the Aquarium-hosted Mimir app.
|
||||
The bridge scripts can keep SRT Media Sources alive while direct output matures,
|
||||
but synchronized program video should come from Aquarium once the runtime has
|
||||
live camera buffers.
|
||||
|
|
|
|||
|
|
@ -1,85 +1,20 @@
|
|||
# OBS V1 Smoke Test
|
||||
|
||||
No plugin/native receiver work gets promoted until this ledger exists for the
|
||||
plain FFmpeg/SRT OBS path.
|
||||
The OBS bridge is allowed to remain only while it leaves evidence.
|
||||
|
||||
The smoke test is deliberately small:
|
||||
## Witness Ledger
|
||||
|
||||
- `sender_capture`: sender-side flash/chirp or packet-origin timestamp.
|
||||
- `srt_receive`: receiver-side stream arrival timestamp.
|
||||
- `obs_present`: OBS preview/recording presentation timestamp.
|
||||
- endpoint drift: media-time slope versus receiver monotonic time.
|
||||
- end-to-end latency: matched `eventId` from `sender_capture` to `obs_present`.
|
||||
- confidence: stage coverage, observation count, event confidence, latency, and drift.
|
||||
`calibration/runs/obs-v1-smoke-ledger.json` records bridge evidence:
|
||||
|
||||
The output ledger is `calibration/runs/obs-v1-smoke-ledger.json`. A passing
|
||||
ledger sets `gate.pluginOrNativeReceiverExpansionAllowed` to `true`. Anything
|
||||
else means the bridge is still talking without enough clocks. Adorable, but no.
|
||||
- sender capture timestamp;
|
||||
- receiver transport timestamp;
|
||||
- OBS presentation timestamp;
|
||||
- endpoint drift;
|
||||
- end-to-end latency;
|
||||
- confidence and operator notes.
|
||||
|
||||
## Run
|
||||
## Pass Condition
|
||||
|
||||
From the repo root:
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json plan
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json template-events
|
||||
```
|
||||
|
||||
Edit `calibration/runs/obs-v1-smoke-events.jsonl` with real observations from
|
||||
one bounded pass. Use the same `eventId` for the same visible flash or audible
|
||||
chirp as it moves through stages.
|
||||
|
||||
Then summarize:
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json summarize
|
||||
```
|
||||
|
||||
## Event Shape
|
||||
|
||||
Each line is one JSON object:
|
||||
|
||||
```json
|
||||
{
|
||||
"endpoint": "video",
|
||||
"stage": "obs_present",
|
||||
"eventId": "video-flash-001",
|
||||
"monotonicNs": 1000180000000,
|
||||
"wallTimeNs": null,
|
||||
"mediaTimeNs": 180000000,
|
||||
"confidence": 0.9,
|
||||
"note": "OBS recording frame containing flash"
|
||||
}
|
||||
```
|
||||
|
||||
Required stages are:
|
||||
|
||||
- `sender_capture`
|
||||
- `srt_receive`
|
||||
- `obs_present`
|
||||
|
||||
`monotonicNs` is mandatory because wall clocks lie casually. `wallTimeNs` is
|
||||
optional human correlation only. `mediaTimeNs` is optional for individual events,
|
||||
but drift confidence needs at least two receiver-side media-time observations.
|
||||
|
||||
## Thresholds
|
||||
|
||||
Defaults:
|
||||
|
||||
- maximum absolute endpoint drift: `100 ppm`
|
||||
- maximum end-to-end latency: `500 ms`
|
||||
|
||||
Override them when running the summary:
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\scripts\obs_smoke_test.py --config .\config\localcast.json --max-abs-drift-ppm 50 --max-latency-ms 350 summarize
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
`status: ok` means every planned endpoint has enough timestamp evidence for this
|
||||
bounded pass. It does not prove the native reservoir is done. It proves the v1
|
||||
OBS bridge has a clocked witness.
|
||||
|
||||
`status: fail` means stop bridge expansion and fix the missing or drifting
|
||||
stage first.
|
||||
Every planned endpoint needs matching evidence at all three stages before the
|
||||
receiver path grows new machinery. A visible source in OBS proves pixels arrived.
|
||||
It does not prove the program is synchronized.
|
||||
|
|
|
|||
|
|
@ -1,200 +1,80 @@
|
|||
# Perfect Machine
|
||||
# Perfect Machine
|
||||
|
||||
## Objective
|
||||
|
||||
Build one synchronized spatial stream machine from six cameras, six microphones,
|
||||
two speakers, Leap timing, Aquarium GPU rendering, Faust DSP, and OBS output.
|
||||
|
||||
The bridge scripts are not the product. They are scaffolding, launch surfaces,
|
||||
calibration tools, and compatibility probes. The live hot path belongs to native
|
||||
runtime code, GPU compute, and Faust.
|
||||
The product is not a pile of bridge scripts. The product is a coherent live
|
||||
field with explicit owners.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
The repo currently proves the contracts:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["camera/audio/phase/render producers"] --> B["LocalcastRuntime C ABI"]
|
||||
B --> C["5s native reservoir"]
|
||||
C --> D["Aquarium GPU + Faust DSP"]
|
||||
D --> E["Spout/audio stems"]
|
||||
E --> F["OBS"]
|
||||
A["direct capture / network producers"] --> B["Mimir.Runtime rolling buffers"]
|
||||
B --> C["native reservoir handles"]
|
||||
C --> D["Aquarium GPU + UI"]
|
||||
C --> E["Faust/native DSP"]
|
||||
D --> F["Spout2/program video"]
|
||||
E --> G["program stems"]
|
||||
F --> H["OBS"]
|
||||
G --> H
|
||||
```
|
||||
|
||||
The old CultCache/Python/Spout path remains a compatibility diagnostic. It is
|
||||
not the runtime API.
|
||||
|
||||
## Invariants
|
||||
|
||||
- One five-second spatiotemporal reservoir is the live authority.
|
||||
- The reservoir is keyed by one shared presentation clock.
|
||||
- Every sample has sensor id, local hardware time if available, arrival time,
|
||||
calibrated world transform, confidence, and provenance.
|
||||
- One five-second live window is the timing authority.
|
||||
- Every stream has a bounded rolling buffer.
|
||||
- Missing data is absence, not a stale substitute.
|
||||
- Late data can refine the reservoir while it is inside the five-second window.
|
||||
- Anything older than the live reservoir is offline calibration evidence, not
|
||||
broadcast geometry.
|
||||
- Audio clocks, camera clocks, Leap timing, remote video, and OBS presentation
|
||||
are reconciled before rendering.
|
||||
- Late data can refine the live window only while it remains inside the window.
|
||||
- Aquarium owns dense visual fusion, temporal accumulation, material fitting,
|
||||
brush/splat generation, final render target, and Spout publication.
|
||||
- Faust owns hot audio DSP: voice separation, room suppression, Ambisonic/HOA
|
||||
spatialization, and loopback/source stem generation.
|
||||
- Mimir owns configuration, calibration, typed contracts, launch,
|
||||
status, persistence, and compatibility surfaces.
|
||||
|
||||
## Native Runtime Shape
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["camera capture workers"] --> R["5s native reservoir"]
|
||||
B["mic/loopback capture workers"] --> R
|
||||
C["Leap worker"] --> R
|
||||
D["remote video/audio ingest"] --> R
|
||||
E["speaker probe scheduler"] --> R
|
||||
R --> F["clock/pose optimizer"]
|
||||
F --> R
|
||||
R --> G["Aquarium GPU fusion"]
|
||||
G --> H["multi-LOD surface/material field"]
|
||||
H --> I["brush/splat/TAA renderer"]
|
||||
R --> J["Faust DSP graph"]
|
||||
J --> K["program stems + spatial bed"]
|
||||
I --> L["Spout2 texture"]
|
||||
K --> M["OBS audio controls"]
|
||||
L --> N["OBS video source"]
|
||||
```
|
||||
rendering, D3D12 interop, UI, and Spout publication.
|
||||
- Faust/native DSP owns hot audio alignment, suppression, voice separation,
|
||||
spatialization, and stem generation.
|
||||
- Mimir owns configuration, calibration truth, runtime contracts, launch,
|
||||
status, and persistence.
|
||||
|
||||
## Reservoir Contract
|
||||
|
||||
The reservoir stores one time-ordered rolling buffer of sample handles, not one
|
||||
giant JSON-ish object and not independent per-kind histories. Typed views over
|
||||
that buffer expose the kinds consumers need.
|
||||
The native reservoir stores time-ordered sample handles with typed views. It
|
||||
owns retention and lookup, not payload memory. Producers append. Optimizers
|
||||
refine. Aquarium/Faust consume.
|
||||
|
||||
Required sample kinds / typed views:
|
||||
Required sample kinds include camera frames, camera features, scene rays,
|
||||
surface claims, material claims, audio blocks, phase claims, event claims, and
|
||||
render packets.
|
||||
|
||||
- `camera_frame`: raw or GPU-importable image handles plus timestamps.
|
||||
- `camera_feature`: keypoints, descriptors, optical flow, confidence, sensor id.
|
||||
- `scene_ray`: calibrated rays from feature observations.
|
||||
- `surface_claim`: triangulated or depth-estimated world samples.
|
||||
- `material_claim`: albedo, roughness, metallic/specular hints, view direction.
|
||||
- `audio_block`: aligned mic/loopback samples and per-source clock state.
|
||||
- `phase_claim`: delay/SRO/phase/coherence estimates from chirplets and program
|
||||
reference.
|
||||
- `event_claim`: claps, transients, gestures, active illumination pulses.
|
||||
- `render_packet`: selected brush/splat work for the current presentation frame.
|
||||
|
||||
The reservoir owns retention. Producers append. Optimizers refine. Renderers
|
||||
sample. No stage owns a private history that can outlive the reservoir.
|
||||
|
||||
`LocalcastRuntime` is the first native owner above the raw reservoir. It exposes
|
||||
typed producer calls for each sample kind so camera capture, audio capture,
|
||||
phase estimation, material fitting, event detection, and render planning all
|
||||
append into one shared five-second window without crossing a Python file cache.
|
||||
It also exposes total and typed-view reads so Aquarium/Faust can consume that
|
||||
same window without building private histories.
|
||||
|
||||
`LocalcastProducer` is the first native capture-worker boundary. It owns sample
|
||||
kind, source identity, and sequence assignment before appending live handles into
|
||||
`LocalcastRuntime`; hardware adapters should provide timestamps and payload
|
||||
handles, not reservoir authority.
|
||||
`LocalcastRuntime` and `LocalcastProducer` are the lower native boundary.
|
||||
`Mimir.Runtime` is the app-level synchronization surface that Aquarium hosts and
|
||||
debugs.
|
||||
|
||||
## Visual Fusion
|
||||
|
||||
Camera fusion is feature matching across the reservoir, not a latest-frame
|
||||
operation.
|
||||
|
||||
The visual path should:
|
||||
|
||||
- ingest all cameras continuously into pinned/native buffers referenced by
|
||||
reservoir sample handles;
|
||||
- extract features and flow on GPU where possible;
|
||||
- match every plausible cross-view feature within time and epipolar bounds;
|
||||
- use Leap as the strongest near-field timing/spatial witness when live;
|
||||
- estimate surface points, normals, confidence, and material observations;
|
||||
- keep multi-LOD cells resident for Aquarium compute reconciliation;
|
||||
- emit only the frame budget needed for OBS while TAA accumulates detail.
|
||||
|
||||
The live target is not "points per frame." The live target is evidence per
|
||||
reservoir window and how much of it Aquarium can reconcile before presentation.
|
||||
Camera fusion is cross-view evidence across the rolling window, not
|
||||
latest-frame display. Leap stereo IR is the timing ground-truth candidate. The
|
||||
driver path should deliver frame descriptors with device timestamps and native
|
||||
or GPU handles, then Aquarium should do feature extraction, flow, matching,
|
||||
material estimation, brush/splat budgeting, and final presentation on GPU.
|
||||
|
||||
## Audio Fusion
|
||||
|
||||
The audio path should:
|
||||
The audio path aligns all microphones and loopbacks into one presentation
|
||||
timeline, feeds Faust/native DSP with bounded blocks, and emits host voice,
|
||||
co-streamer voice, ambient, transients, local loopback, co-streamer loopback,
|
||||
and spatial bed as synchronized outputs.
|
||||
|
||||
- align all six microphones into one clocked field;
|
||||
- use Focusrite dialogue mics as voice anchors;
|
||||
- use camera mics as spatial/context witnesses;
|
||||
- use loopback/program audio as ground truth where available;
|
||||
- emit active probes only for channels that can observe them;
|
||||
- continuously update delay, SRO, phase, frequency response, and confidence;
|
||||
- feed Faust with aligned mic channels and control telemetry;
|
||||
- produce host voice, co-streamer voice, ambient, transients, local loopback,
|
||||
co-streamer loopback, and spatial bed as synchronized outputs.
|
||||
|
||||
Raw phase is internal. Meaning crosses the boundary.
|
||||
Raw estimator detail stays inside the audio runtime. Meaning crosses the
|
||||
boundary.
|
||||
|
||||
## Cut Line
|
||||
|
||||
Cut these from the hot path:
|
||||
|
||||
- Python dense rendering.
|
||||
- Python camera feature extraction in the presentation loop.
|
||||
- File polling as a native runtime API.
|
||||
- OBS-side sync between independent raw sources.
|
||||
- Stale geometry clamped into looking current.
|
||||
- Probe scheduling against placeholder channels.
|
||||
- file polling as a runtime API;
|
||||
- process capture as the six-camera local foundation;
|
||||
- OBS-side synchronization between raw sources;
|
||||
- stale geometry clamped into looking current;
|
||||
- probe scheduling against placeholder channels.
|
||||
|
||||
Keep these as tooling:
|
||||
|
||||
- Python calibration scripts.
|
||||
- Python contract tests.
|
||||
- Python device discovery.
|
||||
- Compatibility Spout sender for diagnostics.
|
||||
- Offline analysis and reproducible evidence ledgers.
|
||||
|
||||
## First Native Cut
|
||||
|
||||
1. Define the native reservoir ABI from `config/perfect-machine.example.json`.
|
||||
2. Build a native reservoir process or Aquarium module that owns the five-second
|
||||
rolling buffer.
|
||||
3. Move camera ingest into native capture workers that write reservoir samples.
|
||||
4. Move audio ingest/phase claims into the same presentation-clock reservoir.
|
||||
5. Let Aquarium consume reservoir surfaces/material claims directly on GPU.
|
||||
6. Let Faust consume reservoir audio blocks and source controls directly.
|
||||
7. Keep the old bridge only as a comparison and fallback surface.
|
||||
|
||||
## Native Work Started
|
||||
|
||||
`native/reservoir` is the first native crate. It implements the shared-edge
|
||||
five-second rolling reservoir invariant:
|
||||
|
||||
- append samples into one rolling buffer with typed views;
|
||||
- advance the reservoir edge from the newest sample;
|
||||
- evict all sample kinds against the same edge;
|
||||
- query the latest valid sample per sensor inside a typed view.
|
||||
|
||||
It now builds as `rlib`, `cdylib`, and `staticlib`, with a small C ABI declared
|
||||
in `native/reservoir/include/localcast_reservoir.h`:
|
||||
|
||||
- create/destroy an opaque `LocalcastReservoir`;
|
||||
- push timestamped sample metadata into a typed view of the rolling buffer;
|
||||
- advance/query the shared edge and window start;
|
||||
- query total length and typed-view length;
|
||||
- read samples by total rolling-buffer index or typed-view index;
|
||||
- query the latest sample for a sensor hash.
|
||||
- reject diagnostic/probe/fallback and unknown-flagged samples at the live
|
||||
reservoir boundary via sample provenance flags.
|
||||
- create/destroy an opaque `LocalcastRuntime`;
|
||||
- create/destroy opaque `LocalcastProducer` ingress helpers;
|
||||
- push live producer samples while the producer owns sequence/source metadata;
|
||||
- append typed camera/audio/phase/event/render handles through producer calls;
|
||||
- query a native runtime status struct with shared edge, window start, total
|
||||
count, and typed-view counts;
|
||||
- read runtime samples by total rolling-buffer index, typed-view index, and
|
||||
latest sensor hash.
|
||||
|
||||
The ABI carries `payload_handle`, not payload bytes. Aquarium owns image,
|
||||
feature, surface, material, and GPU memory interpretation. Faust/native DSP owns
|
||||
audio buffer interpretation. The reservoir owns only retention, sample kind,
|
||||
timestamp order, and the five-second shared-edge invariant.
|
||||
Keep PowerShell/FFmpeg/SRT only as bridge utility while native ingest matures.
|
||||
|
|
|
|||
|
|
@ -1,221 +1,31 @@
|
|||
# Sensor Fusion Architecture
|
||||
# Sensor Fusion Architecture
|
||||
|
||||
## Objective
|
||||
Visual fusion belongs in Aquarium over current Mimir runtime buffers.
|
||||
|
||||
Produce an aligned, timestamped point cloud from the local visual rig while allowing latency, buffering, and cache convergence. The live render path can lag behind capture; it may not lie about coordinate ownership.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
The rig currently has usable capture surfaces:
|
||||
|
||||
- PS3 Eyes through FFmpeg DirectShow device names `PS3 Eye Universal` and `PS3 Eye Universal2`, verified at dual `320x240@60`.
|
||||
- Kiyo-class RGB cameras through native Windows camera APIs such as Media
|
||||
Foundation or DirectShow for color evidence.
|
||||
- LeapUVC raw IR through native LeapUVC/libusb or LeapC image APIs for
|
||||
near-field timing evidence.
|
||||
- ChArUco tooling for intrinsics capture, but no shared fusion state yet.
|
||||
|
||||
That is capture. Capture is not a world model. The previous live producer also
|
||||
painted camera colors onto guessed body and room surfaces. That was useful
|
||||
deadline scaffolding, but it is not enough for detailed reconstruction.
|
||||
|
||||
## Invariants
|
||||
|
||||
- World coordinates own truth.
|
||||
- Capture adapters emit timestamped observations; they do not own fusion semantics.
|
||||
- Fusion core is pure and testable: calibrated camera models plus 2D observations in, 3D points/confidence out.
|
||||
- Point clouds and later brush/splat packets are cached render lowerings, not the canonical scene.
|
||||
- A missing high-detail update renders stale-but-bounded state until better evidence arrives.
|
||||
- The live temporal reservoir is five seconds wide, measured backward from the newest shared sample. Every camera, Leap, audio-derived calibration point, and LOD claim must either land inside that window or leave the live cache.
|
||||
|
||||
## Intended Change
|
||||
|
||||
The live pipeline now has two measurement-quality paths: sparse marker fusion
|
||||
for calibrated tracked objects and GPU-owned dense RGB stereo/flow for surface
|
||||
detail. A CPU dense stereo matcher exists only as a debug reference and is
|
||||
opt-in through `--cpu-dense-stereo`; production dense fusion may not route
|
||||
through Python loops. The provisional Kiyo geometry remains a lie detector, not
|
||||
truth, until `config/sensor-fusion.json` carries measured extrinsics.
|
||||
|
||||
The first pipeline slice adds these boundaries:
|
||||
## Live Flow
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Capture adapters"] --> B["FramePacket ring"]
|
||||
B --> C["Camera quality controller"]
|
||||
C --> D["manual exposure/gain/focus commands"]
|
||||
B --> E["Detection adapter"]
|
||||
E --> F["Observation2D"]
|
||||
B --> G["Dense stereo matcher"]
|
||||
H["SensorRig calibration"] --> I["Fusion core"]
|
||||
F --> I
|
||||
I --> J["TrackCache"]
|
||||
F --> Q["stochastic transient matcher"]
|
||||
Q --> R["scene-ray / LOD cache"]
|
||||
G --> K["RGB surface claims"]
|
||||
J --> L["PointCloud PLY"]
|
||||
J --> M["CultCache RenderFrame document"]
|
||||
R --> M
|
||||
K --> M
|
||||
M --> N["Spout sink / Aquarium GPU renderer"]
|
||||
N --> O["Spout2 sender texture"]
|
||||
O --> P["OBS Spout2 source"]
|
||||
A["direct camera drivers"] --> B["Mimir.Runtime video buffers"]
|
||||
C["Leap stereo IR driver"] --> B
|
||||
B --> D["native reservoir handles"]
|
||||
D --> E["Aquarium GPU feature extraction"]
|
||||
E --> F["cross-view matching + flow"]
|
||||
F --> G["surface/material claims"]
|
||||
G --> H["brush/splat render budget"]
|
||||
H --> I["Spout2/program video"]
|
||||
```
|
||||
|
||||
## Ownership
|
||||
## Invariants
|
||||
|
||||
- `localcast.sensor_fusion.core` owns calibrated camera models, 2D observations, DLT triangulation, reprojection gating, confidence scoring, point-cloud export, and track cache expiry.
|
||||
- `localcast.sensor_fusion.adapters` owns driver-facing frame ingress. Its first concrete adapter is an FFmpeg raw BGR reader for the PS3 Eye DirectShow path.
|
||||
- `localcast.sensor_fusion.calibration_space` owns fixed-board common-space calibration: ChArUco corner observations plus intrinsics become `CameraModel.world_from_sensor` transforms in one room frame.
|
||||
- `localcast.sensor_fusion.surface_features` owns cross-view feature observations, descriptor matching, and triangulated surface tracks. It consumes calibrated cameras; it does not invent camera geometry.
|
||||
- `localcast.sensor_fusion.stochastic_mapping` owns transient feature hypothesis sampling, image-pixel to scene-ray lowering, learned image-ray bias cells, and multi-LOD scene cache packets for later compute-shader reconciliation.
|
||||
- `localcast.sensor_fusion.camera_control` owns measurement-quality policy: luminance, clipping, contrast, and sharpness in; normalized exposure/gain/focus commands out. Driver adapters own translating those commands to native camera APIs, vendor tools, or no-op mocks.
|
||||
- `localcast.sensor_fusion.dense_stereo` owns a debug CPU reference for dense calibrated RGB surface claims. It is useful for tests and shader parity, but the live million-splat path belongs to Aquarium/GPU compute.
|
||||
- `localcast.sensor_fusion.active_illumination` owns deliberate light pulses as calibration telemetry. A Tuya bulb is an optional local-network actuator, not a rendering authority; its pulse timestamps are evidence for camera exposure/depth response.
|
||||
- `localcast.sensor_fusion.clap_calibration` owns deliberate clap detection: chirplet-synced audio transients nominate oracle timestamps, camera frame windows around that oracle look for motion derivatives, calibrated camera peaks triangulate the impact point, and only audio-plus-visual agreement becomes a clap calibration event.
|
||||
- `localcast.sensor_fusion.render_bridge` owns the in-process render-frame ABI: cached point claims plus target dimensions, Spout sender name, source timestamp range, intended visual presentation time, and ambisonic/audio alignment time.
|
||||
- `localcast.diagnostics.visual_cache` owns the typed CultCache document shape
|
||||
used by diagnostic visual-state files. Production visual state should cross
|
||||
the native/CultNet boundary directly, not through this Python file adapter.
|
||||
- `localcast.diagnostics.render_math` owns pure diagnostic render budgeting,
|
||||
camera projection, brush lowering, and CPU rasterization. It has unit tests
|
||||
and does not require a GPU context.
|
||||
- `scripts/sensor_fusion.py` owns CLI composition for offline observation files.
|
||||
- The Python/OpenGL Spout publisher has been deleted. No Mimir Python
|
||||
module owns OBS publication.
|
||||
- `config/sensor-fusion.example.json` owns the declarative rig shape: capture hints, intrinsics, extrinsics, latency, and fusion thresholds.
|
||||
|
||||
## Cache Discipline
|
||||
|
||||
This follows the same architectural lesson as `fractal-domains-cache-that-bites.md`: state begins as semantic claims in a named domain, then lowers into cheaper packets.
|
||||
|
||||
For this project:
|
||||
|
||||
```text
|
||||
sensor observation
|
||||
-> calibrated world ray
|
||||
-> triangulated marker claim
|
||||
-> stochastic transient hypothesis
|
||||
-> multi-LOD scene cache
|
||||
-> cached track
|
||||
-> render frame packet
|
||||
-> Aquarium brush/splat packet
|
||||
-> Spout sender texture
|
||||
-> OBS source
|
||||
```
|
||||
|
||||
The cache is not a bucket. `TrackCache` has a TTL and confidence update rule so the system can buffer and converge without pretending stale points are fresh. The live frame reservoir is explicitly five seconds wide: frame history expires from the newest shared sample, LOD evidence is clipped to that same interval, and each `RenderFramePacket` reports the exact source window. Later GPU buffers should mirror this shape: observation SoA, track SoA, material/BRDF estimate SoA, brush packet SoA.
|
||||
|
||||
`visual-lod-cache.json` is the diagnostic CPU-authored shape for the next
|
||||
compute pass. JSON serialization lives under `localcast.diagnostics.lod_json`,
|
||||
not in the mapping model. It groups stochastic/fused scene claims into multiple
|
||||
world-space voxel sizes, carrying center, radius, confidence, count, source-time
|
||||
bounds, and first-pass material estimates. The material channel is deliberately
|
||||
modest: weighted albedo plus roughness/metallic hints so Aquarium can start
|
||||
relighting brush/splat packets without treating screen-space color as the whole
|
||||
truth. A later shader pass should replace those hints with multi-view BRDF
|
||||
fitting inside the same reservoir.
|
||||
|
||||
## Test Boundaries
|
||||
|
||||
The core can be tested without cameras:
|
||||
|
||||
- synthetic cameras triangulate a known point
|
||||
- timestamp windows reject stale pairs
|
||||
- track cache expiry is deterministic
|
||||
- raw-frame adapter can be tested from an in-memory byte stream
|
||||
- fixed-board ChArUco observations solve camera poses into the expected common frame
|
||||
- matched surface descriptors triangulate to a known 3D point
|
||||
- stochastic transient matches triangulate descriptor-consistent rays and lower them into a multi-LOD scene cache
|
||||
- adaptive camera control responds to overexposure without live hardware
|
||||
- dense stereo turns shifted textured camera pairs into calibrated RGB surface claims
|
||||
|
||||
Those tests matter because camera drivers are not unit-test dependencies. They are weather.
|
||||
|
||||
## OBS And Spout Boundary
|
||||
|
||||
OBS should see a named Spout sender, not a camera window, file tail, or desktop capture. Current references confirm the ordinary Windows path: the Off World Live OBS Spout2 plugin receives Spout shared textures, while the Spout2 SDK is the app-side texture sharing surface.
|
||||
|
||||
The intended production handoff is:
|
||||
|
||||
```text
|
||||
Mimir TrackCache
|
||||
-> CultCache render-frame document
|
||||
-> Aquarium Engine typed runtime state
|
||||
-> GPU point/brush/splat buffer
|
||||
-> D3D render target
|
||||
-> Spout2 sender named "Mimir Point Cloud"
|
||||
-> OBS Spout2 Capture source
|
||||
```
|
||||
|
||||
`RenderFramePacket` is the diagnostic Python in-process shape. The diagnostic
|
||||
file boundary is a typed CultCache MessagePack document. Compatibility JSON
|
||||
read/write now lives under `localcast.diagnostics.render_frame_json`; the
|
||||
production packet module does not own file serialization. The production live
|
||||
boundary is native typed state plus CultNet `document_put`.
|
||||
|
||||
Clap calibration events use the same typed-state rule. A clap is not every sharp
|
||||
audio transient. The detector first finds a sharp broadband audio onset in the
|
||||
audio oracle timeline, then opens a short camera window around that timestamp
|
||||
and looks for high frame-derivative peaks per camera. At least the configured
|
||||
minimum number of cameras must agree; when a calibrated rig is available, their
|
||||
motion centroids are triangulated into a world-space impact point. The typed
|
||||
`localcast.calibration.clap_events` document carries stable event id, acoustic
|
||||
oracle time, visual observed time, timing uncertainty, confidence, world
|
||||
position, and the contributing camera peaks. Aquarium consumes those events as
|
||||
high-confidence calibration constraints beside ultrasonic chirplet room evidence.
|
||||
|
||||
The current streamable cut is:
|
||||
|
||||
```text
|
||||
CultCache render-frame document
|
||||
-> Aquarium typed runtime state
|
||||
-> D3D render target
|
||||
-> Spout2 sender
|
||||
-> OBS Spout2 Capture source
|
||||
```
|
||||
|
||||
This is deliberately a sink boundary, not a competing world model. Aquarium should replace the renderer body, not the capture/fusion/timing contract.
|
||||
|
||||
## Latency Contract
|
||||
|
||||
Latency is allowed. Drift is not.
|
||||
|
||||
Each render frame carries:
|
||||
|
||||
- `source_time_min_ns` and `source_time_max_ns`: the observation window that produced the cached points.
|
||||
- `present_time_ns`: when the visual frame wants to be presented after visual buffering.
|
||||
- `audio_alignment_time_ns`: the corresponding ambisonic output time.
|
||||
|
||||
That lets the final stream compositor buffer point-cloud visuals until they align with the bounded audio-field cache. The renderer may show a slightly older world if the packet is coherent and labeled. It may not quietly mix fresh audio with stale visual geometry and call that sync.
|
||||
|
||||
Current live deadline rule: `source_time_max_ns - source_time_min_ns` is five seconds. Late-arriving samples can fill the reservoir while they are inside that window; anything older is evidence for offline calibration, not the live program surface.
|
||||
|
||||
The Spout/audio overlay applies the same rule at the consumer boundary. If the visual producer or a camera driver stalls, OBS receives a packet clamped to the current audio edge with stale points removed. The current live fallback mode uses cached/synthetic RGB and Leap frames because the old diagnostic capture path measured slower than the reservoir; real cameras need nonblocking native-driver ingress feeding the same reservoir instead of blocking the producer loop.
|
||||
- Device timestamps beat arrival timestamps when available.
|
||||
- Leap is the first timing-camera candidate.
|
||||
- Process capture is a bridge edge, not the local six-camera foundation.
|
||||
- Aquarium owns GPU extraction, fusion, material fitting, and render budgeting.
|
||||
- Runtime buffers own retention and stream health, not scene reconstruction.
|
||||
|
||||
## Next Cut
|
||||
|
||||
1. Capture ChArUco intrinsics for each camera with `scripts/charuco_calibration.py calibrate`.
|
||||
2. Capture fixed-board observations from every camera and solve shared extrinsics with `scripts/solve_common_camera_space.py`.
|
||||
3. Use `scripts/triangulate_surface_features.py` on calibrated image pairs to prove real cross-view surface tracks before promoting the matcher into the live producer.
|
||||
4. Replace the synthetic stochastic transient observations in
|
||||
`localcast.diagnostics.visual_producer` with real native/Aquarium ORB/flow
|
||||
observations from driver-ingested PS3 Eye/Kiyo/Leap frames, then delete the
|
||||
Python diagnostic producer.
|
||||
5. Move dense matching and LOD reconciliation from CPU block search/JSON to GPU-resident stereo/flow and compute-shader cache reduction so the million-sample target is not murdered by Python loops.
|
||||
6. If a Tuya light is available on the local network, run `scripts/pulse_tuya_light.py` with its local key and align pulse timestamps against camera brightness response.
|
||||
7. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections.
|
||||
8. Record an observation run from the two PS3 Eyes into typed CultCache docs.
|
||||
9. Feed `RenderFramePacket` and the multi-LOD scene cache into Aquarium Engine.
|
||||
10. Publish the render target as a Spout2 sender and receive it in OBS.
|
||||
11. Delete compatibility JSON render-frame paths once no diagnostic script depends on them.
|
||||
|
||||
## References
|
||||
|
||||
- Multi-camera calibration and triangulation are the geometry spine. OpenCV may
|
||||
remain an offline calibration library; it is not live frame ingest. See
|
||||
`research/visual-spatial-map/summary.md`.
|
||||
- Jacob and Haeb-Umbach 2015 motivates audio-visual coordinate alignment. See `research/visual-spatial-map/mirrors/krekovic-2015-audio-visual-geometry-calibration.pdf`.
|
||||
- Kerbl et al. 2023 and RTG-SLAM motivate splats as render packets, not state ownership. See `research/visual-spatial-map/summary.md` and `research/gpu-fusion-splatting/summary.md`.
|
||||
- Spout2 and the OBS Spout2 plugin are the Windows/OBS texture-sharing bridge. See `research/spout-obs-bridge/summary.md`.
|
||||
- `E:\Projects\gamecult-site\GameCult\Blog\fractal-domains-cache-that-bites.md` supplies the cache discipline: semantic authority first, backend packet lowering second.
|
||||
Implement one concrete direct capture driver, feed `MimirVideoFrameDescriptor`
|
||||
samples into `MimirVideoCaptureDriverSource`, and measure sustained cadence over
|
||||
the default five-second window.
|
||||
|
|
|
|||
|
|
@ -1,119 +1,15 @@
|
|||
# Diagnostic Typed Visual State
|
||||
# Typed Visual State
|
||||
|
||||
## Objective
|
||||
Typed visual state now means native/runtime descriptors and Aquarium-readable
|
||||
payload handles, not file-polled render documents.
|
||||
|
||||
Keep the diagnostic visual file shape as typed CultCache documents and expose
|
||||
the production boundary as native CultNet document messages.
|
||||
## Boundary
|
||||
|
||||
JSON is no longer the authority for visual state. The diagnostic renderer
|
||||
consumes `calibration/runs/visual-state.msgpack`, which stores a
|
||||
`localcast.visual.render_frame` CultCache document. Production visual state must
|
||||
not be owned by this Python file adapter.
|
||||
- Capture drivers append frame descriptors.
|
||||
- The runtime owns stream buffering and health.
|
||||
- Native reservoir handles preserve shared timing and typed lookup.
|
||||
- Aquarium decodes visual payloads, runs GPU fusion, and publishes the program
|
||||
surface.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["diagnostics.visual_producer"] --> B["SensorRig.fuse"]
|
||||
B --> C["RenderFramePacket"]
|
||||
C --> D["CultRenderFrame"]
|
||||
X["audio-state.msgpack"] --> Y["audio event overlay"]
|
||||
Z["audio-events.msgpack"] --> Y
|
||||
D --> Y
|
||||
Y --> E["CultCache MessagePack store"]
|
||||
E --> F["diagnostic readers"]
|
||||
F --> G["render_math CPU checks"]
|
||||
G --> H["Aquarium replacement work"]
|
||||
```
|
||||
|
||||
Diagnostic files:
|
||||
|
||||
- `calibration/runs/visual-state.msgpack`: typed diagnostic visual frame state.
|
||||
- `calibration/runs/visual-stream-status.msgpack`: typed diagnostic stream
|
||||
status state.
|
||||
- `calibration/runs/stream-spout-status.json`: legacy heartbeat shape for quick
|
||||
terminal checks when a diagnostic publisher exists.
|
||||
- `calibration/runs/av-sync-status.json`: visual/audio sync heartbeat shape for
|
||||
Aquarium/native publishers.
|
||||
|
||||
## Document Types
|
||||
|
||||
`localcast.visual.render_frame`
|
||||
|
||||
- schema id: `gamecult.localcast.visual.render_frame.v1`
|
||||
- key: `localcast.visual.render-frame.live`
|
||||
- payload: MessagePack array, decoded as `CultRenderFrame`
|
||||
- owns: frame timing, Spout sender identity, target size, and render points
|
||||
|
||||
`localcast.visual.stream_status`
|
||||
|
||||
- schema id: `gamecult.localcast.visual.stream_status.v1`
|
||||
- key: `localcast.visual.stream-status.live`
|
||||
- payload: MessagePack array, decoded as `CultStreamStatus`
|
||||
- owns: sender heartbeat and renderer health
|
||||
|
||||
`localcast.calibration.clap_events`
|
||||
|
||||
- schema id: `gamecult.localcast.calibration.clap_events.v1`
|
||||
- key: `localcast.calibration.clap-events.live`
|
||||
- payload: MessagePack array, decoded as `CultClapEventsFrame`
|
||||
- owns: deliberate clap calibration events aligned against the audio timing oracle
|
||||
- fields: stable key, world position, acoustic oracle timestamp, visual observed timestamp, timing uncertainty in microseconds, visual/acoustic confidence, and contributing camera motion peaks
|
||||
|
||||
## CultNet Boundary
|
||||
|
||||
The API boundary is CultNet document replication, not ad hoc file polling:
|
||||
|
||||
```text
|
||||
CultNetDocumentPut(localcast.visual.render_frame)
|
||||
-> CultCache local store
|
||||
-> renderer frame source
|
||||
```
|
||||
|
||||
For the deadline rig, both producer and renderer share the local CultCache file.
|
||||
That arrangement is diagnostic scaffolding. Aquarium, native capture, and remote
|
||||
sensor nodes should publish the same typed document through CultNet
|
||||
`document_put` messages rather than treating a Python-polled file as live
|
||||
authority.
|
||||
|
||||
The live visual frame may contain multiple claim families. `dense-rgb:*` claims
|
||||
are calibrated two-camera RGB surface samples from the debug CPU stereo
|
||||
reference or, in the intended production path, Aquarium/GPU dense stereo and
|
||||
flow. `room-rgb:*` claims are camera-resolved room/background surface samples;
|
||||
`host-rgb:*` and `deru-rgb:*` claims are fallback RGB body/object surface
|
||||
samples; and `leap-motion:*` claims are high-rate LeapUVC packed-channel motion
|
||||
samples. Leap packed maps are split into explicit green, magenta, red, and blue
|
||||
channels before publication so the downstream accumulator can use Leap as the
|
||||
strongest timing/motion witness without pretending the packed image is one
|
||||
ordinary RGB camera.
|
||||
|
||||
Mimir does not own the final splat budget. It publishes dense typed
|
||||
claims with stable keys and timestamps; Aquarium owns temporal accumulation,
|
||||
renderer residency, and any GPU-side reduction needed to make million-splat
|
||||
frames presentable.
|
||||
|
||||
## Audio Synchronization
|
||||
|
||||
The deleted Python/OpenGL sender used to read `calibration/runs/audio-state.msgpack`
|
||||
and `calibration/runs/audio-events.msgpack` while rendering the diagnostic
|
||||
visual frame. That responsibility now belongs in Aquarium/native code: select
|
||||
source events against `RenderFramePacket.audio_alignment_time_ns`, add
|
||||
synchronized renderer-visible transient geometry, and write/publish sync status
|
||||
with visual frame id, audio frame id, audio delta, event counts, and remote
|
||||
video status.
|
||||
|
||||
The audio bed still travels as `localcast.audio.spatial_frame`; the visual render packet only receives renderer-visible transient geometry. That keeps the machine legible: audio owns sound, source-event analysis owns acoustic facts, Aquarium owns the final pixel/audio package for OBS.
|
||||
|
||||
The neighbor SRT video feed is also a timed media artifact. OBS/Aquarium must
|
||||
delay or present the remote video according to the same presentation clock as
|
||||
the Spout texture and AmbiX bed. This value is presentation delay, not only the
|
||||
SRT socket's `latency` parameter.
|
||||
|
||||
## Cut Line
|
||||
|
||||
- Keep: typed CultCache document contracts and MessagePack payloads.
|
||||
- Keep temporarily: JSON heartbeat for human shell checks.
|
||||
- Cut next: JSON render-frame polling now that it is isolated under diagnostics.
|
||||
- Do not add a second scene authority. Sensor fusion owns world claims; renderer owns pixels.
|
||||
- Do not make OBS synchronize separate sources. Aquarium receives synchronized visual/audio documents and emits the OBS-facing package.
|
||||
- Do not treat the neighbor SRT video feed as untimed scenery. It is a presentation artifact and belongs in the same sync status as audio and render frames.
|
||||
Any remaining file export should be treated as a diagnostic artifact, not as a
|
||||
live data path.
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ flowchart TD
|
|||
private buffers, or a parallel synchronization model.
|
||||
- Missing feeds become explicit absence or silent/blank placeholders inside the
|
||||
program model. Stale samples do not get stretched into looking current.
|
||||
- Python may inspect, calibrate, and test. It does not run the live hot path.
|
||||
- Calibration and diagnostics do not run the live hot path.
|
||||
|
||||
## First Viable Cut
|
||||
|
||||
|
|
@ -126,7 +126,7 @@ to the driver, GPU, and capture APIs.
|
|||
|
||||
Leap should be treated as the timing-camera candidate only when the native
|
||||
adapter preserves device timestamps or captures a monotonic timestamp
|
||||
immediately on frame receipt. Do not put OpenCV in the live ingest path.
|
||||
immediately on frame receipt.
|
||||
|
||||
## Cut Line
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
"""Mimir Python helpers."""
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
"""Diagnostic and migration-only surfaces.
|
||||
|
||||
Nothing in this package is production runtime authority.
|
||||
"""
|
||||
|
|
@ -1,452 +0,0 @@
|
|||
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[2]
|
||||
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 audio_field.profile import local_microphones, source_id_for_microphone # noqa: E402
|
||||
from localcast.sensor_fusion import camera_sensor_id_for_microphone # noqa: E402
|
||||
|
||||
|
||||
def load_profile(path: Path) -> dict:
|
||||
return json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
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="Diagnostic replay of the old local mic capture experiment into 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:
|
||||
live_source_ids = {source_id_for_microphone(mic) for group in groups.values() for mic in group["mics"]}
|
||||
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,
|
||||
eligible_source_ids={source_id for source_id in live_source_ids if source_id},
|
||||
)
|
||||
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()
|
||||
|
|
@ -1,256 +0,0 @@
|
|||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from scipy.io import wavfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
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.active_probe import ActiveConfidenceMaintainer # noqa: E402
|
||||
from audio_field.phase_meaning import LivePhaseMeaningExtractor # noqa: E402
|
||||
from audio_field.probe_bands import parse_probe_band, ultrasonic_probe_band # noqa: E402
|
||||
from audio_field.probe_optimizer import ActiveProbeOptimizer, ProbePolicy # 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 write_phase_runtime_status(
|
||||
path: Path,
|
||||
*,
|
||||
field: Path,
|
||||
reference: Path,
|
||||
frame_id: int,
|
||||
global_confidence: float,
|
||||
needs_active_probe: bool,
|
||||
emitted_probe,
|
||||
maintain_confidence: bool,
|
||||
play_probes: bool,
|
||||
) -> None:
|
||||
import json
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"input_mode": "wav-replay",
|
||||
"field": str(field),
|
||||
"reference": str(reference),
|
||||
"frame_id": int(frame_id),
|
||||
"global_confidence": float(global_confidence),
|
||||
"needs_active_probe": bool(needs_active_probe),
|
||||
"maintain_confidence": bool(maintain_confidence),
|
||||
"play_probes": bool(play_probes),
|
||||
"probe_feedback_mode": "open-loop-playback" if play_probes else "dry-run",
|
||||
"closed_loop_probe_capture": False,
|
||||
"last_probe": None
|
||||
if emitted_probe is None
|
||||
else {
|
||||
"source_id": emitted_probe.request.source_id,
|
||||
"reason": emitted_probe.request.reason,
|
||||
"urgency": emitted_probe.request.urgency,
|
||||
"path": str(emitted_probe.path),
|
||||
"emitted_monotonic_ns": emitted_probe.emitted_monotonic_ns,
|
||||
},
|
||||
"updated_monotonic_ns": time.monotonic_ns(),
|
||||
},
|
||||
indent=2,
|
||||
sort_keys=True,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
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="Diagnostic replay of 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("--status", type=Path, default=ROOT / "calibration" / "runs" / "audio-phase-field-status.json")
|
||||
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")
|
||||
parser.add_argument("--maintain-confidence", action="store_true")
|
||||
parser.add_argument("--target-confidence", type=float, default=0.65)
|
||||
parser.add_argument("--trigger-confidence", type=float, default=0.35)
|
||||
parser.add_argument("--min-probe-interval-frames", type=int, default=45)
|
||||
parser.add_argument("--probe-level-dbfs", type=float, default=-18.0)
|
||||
parser.add_argument("--probe-output-dir", type=Path, default=ROOT / "calibration" / "runs" / "active-probes")
|
||||
parser.add_argument("--probe-seconds", type=float, default=0.03)
|
||||
parser.add_argument("--probe-band", default="1800:9000")
|
||||
parser.add_argument("--ultrasonic-probes", action="store_true", help="Use a near-ultrasonic probe band below Nyquist.")
|
||||
parser.add_argument("--probe-pattern", choices=["single", "harmonic-dense"], default="single")
|
||||
parser.add_argument("--cram-harmonic-probes", action="store_true", help="Shortcut for dense near-ultrasonic harmonic probes.")
|
||||
parser.add_argument("--harmonic-root-hz", type=float, default=440.0)
|
||||
parser.add_argument("--harmonic-voices", type=int, default=36)
|
||||
parser.add_argument("--probe-channel", type=int, default=0)
|
||||
parser.add_argument("--probe-output-channels", type=int, default=2)
|
||||
parser.add_argument("--probe-unmasked", action="store_true", help="Allow probes even when the reference block is not masking them.")
|
||||
parser.add_argument("--play-probes", action="store_true", help="Play scheduled probes through the default output device.")
|
||||
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,
|
||||
)
|
||||
maintainer = None
|
||||
if args.maintain_confidence:
|
||||
use_ultrasonic = args.ultrasonic_probes or args.cram_harmonic_probes
|
||||
probe_pattern = "harmonic-dense" if args.cram_harmonic_probes else args.probe_pattern
|
||||
band_start, band_end = ultrasonic_probe_band(sample_rate) if use_ultrasonic else parse_probe_band(args.probe_band)
|
||||
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=not args.probe_unmasked,
|
||||
)
|
||||
),
|
||||
sample_rate=sample_rate,
|
||||
output_dir=args.probe_output_dir,
|
||||
duration_seconds=args.probe_seconds,
|
||||
start_hz=band_start,
|
||||
end_hz=band_end,
|
||||
channels=args.probe_output_channels,
|
||||
channel=args.probe_channel,
|
||||
pattern=probe_pattern,
|
||||
harmonic_root_hz=args.harmonic_root_hz,
|
||||
harmonic_voices=args.harmonic_voices,
|
||||
)
|
||||
|
||||
start_monotonic = time.monotonic()
|
||||
audio_origin_ns = time.monotonic_ns()
|
||||
frame_id = 0
|
||||
cursor = 0
|
||||
max_samples = min(len(reference_mono), len(field))
|
||||
last_status = 0.0
|
||||
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,
|
||||
),
|
||||
)
|
||||
emitted = None
|
||||
if maintainer is not None:
|
||||
emitted = maintainer.update(meaning, block_ref, force_masked=args.probe_unmasked)
|
||||
if emitted is not None and args.play_probes:
|
||||
play_probe_file(emitted.path)
|
||||
if time.monotonic() - last_status >= 1.0:
|
||||
write_phase_runtime_status(
|
||||
args.status,
|
||||
field=args.field,
|
||||
reference=args.reference,
|
||||
frame_id=meaning.frame_id,
|
||||
global_confidence=meaning.global_confidence,
|
||||
needs_active_probe=meaning.needs_active_probe,
|
||||
emitted_probe=emitted,
|
||||
maintain_confidence=args.maintain_confidence,
|
||||
play_probes=args.play_probes,
|
||||
)
|
||||
last_status = time.monotonic()
|
||||
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)
|
||||
|
||||
|
||||
def play_probe_file(path: Path) -> None:
|
||||
import sounddevice as sd
|
||||
|
||||
rate, data = wavfile.read(path)
|
||||
sd.play(data.astype(np.float32), int(rate), blocking=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,220 +0,0 @@
|
|||
"""Diagnostic live clap calibration against typed CultCache audio frames."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from audio_field.cultcache_audio import frame_to_numpy, get_live_spatial_audio_frame
|
||||
from localcast.diagnostics.visual_cache import get_live_clap_events, make_clap_events_frame, put_live_clap_events
|
||||
from localcast.sensor_fusion import (
|
||||
CameraClockSyncModel,
|
||||
CameraMotionPeak,
|
||||
ClapCalibrationEvent,
|
||||
ClapDetectorConfig,
|
||||
FusionConfig,
|
||||
SensorRig,
|
||||
TimestampedFrame,
|
||||
TimestampedFrameHistory,
|
||||
detect_clap_events,
|
||||
)
|
||||
from localcast.sensor_fusion.core import CameraModel
|
||||
from localcast.sensor_fusion.render_bridge import RenderPointPacket
|
||||
from localcast.sensor_fusion.reservoir_window import DEFAULT_RESERVOIR_NS
|
||||
from localcast.sensor_fusion.rgb_reference import rgb_dense_camera
|
||||
|
||||
|
||||
class LiveClapCalibrator:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
audio_cache: Path,
|
||||
clap_cache: Path,
|
||||
camera_width: int,
|
||||
camera_height: int,
|
||||
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, 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
|
||||
self.last_event_key: str | None = None
|
||||
left = rgb_dense_camera("kiyo-primary", -0.18, camera_width, camera_height)
|
||||
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=reservoir_ns),
|
||||
)
|
||||
self.config = ClapDetectorConfig(
|
||||
audio_window_samples=96,
|
||||
audio_hop_samples=24,
|
||||
audio_onset_ratio=2.0,
|
||||
min_audio_energy=1.0e-8,
|
||||
min_camera_motion_score=0.010,
|
||||
camera_window_ns=2_500_000_000,
|
||||
min_camera_count=2,
|
||||
min_event_spacing_ns=220_000_000,
|
||||
)
|
||||
self.events = ()
|
||||
self._restore_existing_events()
|
||||
|
||||
def _restore_existing_events(self) -> None:
|
||||
if not self.clap_cache.exists():
|
||||
return
|
||||
frame = get_live_clap_events(self.clap_cache)
|
||||
if frame is None or not frame.events:
|
||||
return
|
||||
events: list[ClapCalibrationEvent] = []
|
||||
for event in frame.events:
|
||||
peaks = tuple(
|
||||
CameraMotionPeak(
|
||||
sensor_id=str(peak.get("sensorId", "")),
|
||||
timestamp_ns=int(peak.get("timestampNs", 0)),
|
||||
uv=np.asarray(peak.get("uv", [0.0, 0.0]), dtype=np.float64),
|
||||
score=float(peak.get("score", 0.0)),
|
||||
)
|
||||
for peak in event.camera_peaks
|
||||
)
|
||||
restored = ClapCalibrationEvent(
|
||||
stable_key=event.stable_key,
|
||||
position_m=event.position_m,
|
||||
acoustic_oracle_ns=event.acoustic_oracle_ns,
|
||||
visual_observed_ns=event.visual_observed_ns,
|
||||
timing_uncertainty_us=event.timing_uncertainty_us,
|
||||
visual_confidence=event.visual_confidence,
|
||||
acoustic_confidence=event.acoustic_confidence,
|
||||
camera_peaks=peaks,
|
||||
)
|
||||
self.sync_model.observe_event(restored)
|
||||
events.append(restored)
|
||||
self.events = tuple(events)
|
||||
|
||||
def observe_frames(self, frames: dict[str, TimestampedFrame]) -> None:
|
||||
self.history.add_many(frames)
|
||||
|
||||
def update(self, frame_id: int) -> tuple[RenderPointPacket, ...]:
|
||||
audio = self._read_audio()
|
||||
if audio is None or audio.frame_id == self.last_audio_frame_id:
|
||||
return self._event_points(frame_id)
|
||||
self.last_audio_frame_id = audio.frame_id
|
||||
self.last_audio_time_ns = int(audio.audio_time_ns)
|
||||
block = frame_to_numpy(audio)
|
||||
events = detect_clap_events(
|
||||
block,
|
||||
audio.sample_rate,
|
||||
self.history.frames_by_sensor(),
|
||||
audio_time_ns=audio.audio_time_ns,
|
||||
start_sample=audio.start_sample,
|
||||
rig=self.rig,
|
||||
config=self.config,
|
||||
)
|
||||
if events:
|
||||
self.events = tuple(events)
|
||||
self.last_event_key = events[-1].stable_key
|
||||
for event in events:
|
||||
self.sync_model.observe_event(event)
|
||||
put_live_clap_events(self.clap_cache, make_clap_events_frame(frame_id=frame_id, events=events))
|
||||
elif not self.events:
|
||||
put_live_clap_events(self.clap_cache, make_clap_events_frame(frame_id=frame_id, events=()))
|
||||
return self._event_points(frame_id)
|
||||
|
||||
def _read_audio(self):
|
||||
if not self.audio_cache.exists():
|
||||
return None
|
||||
return get_live_spatial_audio_frame(self.audio_cache)
|
||||
|
||||
def oracle_time_ns(self, fallback_ns: int) -> int:
|
||||
return int(self.last_audio_time_ns if self.last_audio_time_ns is not None else fallback_ns)
|
||||
|
||||
def _event_points(self, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
points: list[RenderPointPacket] = []
|
||||
for event in self.events[-4:]:
|
||||
confidence = max(0.0, min(1.0, event.visual_confidence * event.acoustic_confidence))
|
||||
points.append(
|
||||
_render_point(
|
||||
f"clap-calibration:{event.stable_key}",
|
||||
np.asarray(event.position_m, dtype=np.float64),
|
||||
0.075,
|
||||
(0.15, 0.95, 1.0, 0.72),
|
||||
confidence,
|
||||
timestamp_ns,
|
||||
)
|
||||
)
|
||||
for peak in event.camera_peaks:
|
||||
camera = self.rig.cameras.get(peak.sensor_id)
|
||||
if peak.sensor_id == "leap":
|
||||
points.append(
|
||||
_render_point(
|
||||
f"clap-timing:{event.stable_key}:leap",
|
||||
np.asarray(event.position_m, dtype=np.float64) + np.array([0.0, -0.035, 0.12], dtype=np.float64),
|
||||
0.04,
|
||||
(0.45, 1.0, 0.72, 0.82),
|
||||
max(0.0, min(1.0, peak.score)),
|
||||
int(peak.timestamp_ns),
|
||||
)
|
||||
)
|
||||
continue
|
||||
if camera is None:
|
||||
continue
|
||||
ray = pixel_ray_point(camera, peak.uv, distance_m=1.2)
|
||||
points.append(
|
||||
_render_point(
|
||||
f"clap-ray:{event.stable_key}:{peak.sensor_id}",
|
||||
ray,
|
||||
0.026,
|
||||
(0.2, 0.85, 1.0, 0.42),
|
||||
max(0.0, min(1.0, peak.score)),
|
||||
int(peak.timestamp_ns),
|
||||
)
|
||||
)
|
||||
for estimate in self.sync_model.estimates():
|
||||
points.append(
|
||||
_render_point(
|
||||
f"camera-sync:{estimate.sensor_id}",
|
||||
sync_status_position(estimate.sensor_id),
|
||||
0.035,
|
||||
(0.45, 0.72, 1.0, 0.58),
|
||||
estimate.confidence,
|
||||
estimate.oracle_timestamp_ns,
|
||||
)
|
||||
)
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def sync_status_position(sensor_id: str) -> np.ndarray:
|
||||
positions = {
|
||||
"kiyo-primary": np.array([-0.18, -0.72, 1.28], dtype=np.float64),
|
||||
"kiyo-secondary": np.array([0.18, -0.72, 1.28], dtype=np.float64),
|
||||
"leap": np.array([0.0, -0.18, 0.76], dtype=np.float64),
|
||||
}
|
||||
return positions.get(sensor_id, np.zeros(3, dtype=np.float64))
|
||||
|
||||
|
||||
def pixel_ray_point(camera: CameraModel, uv: np.ndarray, *, distance_m: float) -> np.ndarray:
|
||||
point = np.asarray([float(uv[0]), float(uv[1]), 1.0], dtype=np.float64)
|
||||
direction_sensor = np.linalg.inv(camera.camera_matrix) @ point
|
||||
direction_sensor = direction_sensor / max(1.0e-12, np.linalg.norm(direction_sensor))
|
||||
direction_world = camera.world_from_sensor[:3, :3] @ direction_sensor
|
||||
direction_world = direction_world / max(1.0e-12, np.linalg.norm(direction_world))
|
||||
return camera.position_world + direction_world * float(distance_m)
|
||||
|
||||
|
||||
def _render_point(
|
||||
key: str,
|
||||
xyz: np.ndarray,
|
||||
radius_m: float,
|
||||
color: tuple[float, float, float, float],
|
||||
confidence: float,
|
||||
timestamp_ns: int,
|
||||
) -> RenderPointPacket:
|
||||
return RenderPointPacket(
|
||||
stable_key=key,
|
||||
xyz=np.asarray(xyz, dtype=np.float64),
|
||||
radius_m=radius_m,
|
||||
color_rgba=color,
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=timestamp_ns,
|
||||
)
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from scipy.io import wavfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from audio_field.cultcache_audio import ( # noqa: E402
|
||||
DEFAULT_MIC_FIELD_CHANNELS,
|
||||
get_live_mic_field_frame,
|
||||
make_mic_field_frame,
|
||||
put_live_mic_field_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 source_block(samples: np.ndarray, start_sample: int, frame_count: int, *, loop: bool) -> np.ndarray | None:
|
||||
if start_sample >= len(samples) and not loop:
|
||||
return None
|
||||
block = np.zeros((frame_count, samples.shape[1]), 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="Diagnostic replay of aligned mic channels as a Faust-ready input field.")
|
||||
parser.add_argument("--input", type=Path, default=ROOT / "calibration" / "runs" / "audio-program-live-20260518-180226" / "field-program-cleaned.wav")
|
||||
parser.add_argument("--cache", type=Path, default=ROOT / "calibration" / "runs" / "audio-mic-field.msgpack")
|
||||
parser.add_argument("--graph-id", default="localcast.faust.voice_separation.v1")
|
||||
parser.add_argument("--channel", action="append")
|
||||
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("--realtime", action="store_true")
|
||||
parser.add_argument("--smoke-readback", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
sample_rate, source = read_float_wav(args.input)
|
||||
channels = tuple(args.channel) if args.channel else DEFAULT_MIC_FIELD_CHANNELS
|
||||
if len(channels) != source.shape[1]:
|
||||
raise SystemExit(f"input has {source.shape[1]} channels but {len(channels)} channel ids were provided")
|
||||
|
||||
start_monotonic = time.monotonic()
|
||||
audio_origin_ns = time.monotonic_ns()
|
||||
frame_id = 0
|
||||
start_sample = 0
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
if args.duration is not None and now - start_monotonic >= args.duration:
|
||||
break
|
||||
block = source_block(source, 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_mic_field_frame(
|
||||
block,
|
||||
frame_id=frame_id,
|
||||
sample_rate=sample_rate,
|
||||
start_sample=start_sample,
|
||||
audio_time_ns=audio_time_ns,
|
||||
channels=channels,
|
||||
graph_id=args.graph_id,
|
||||
)
|
||||
put_live_mic_field_frame(args.cache, frame)
|
||||
if args.smoke_readback:
|
||||
loaded = get_live_mic_field_frame(args.cache)
|
||||
if loaded is None or loaded.frame_id != frame_id:
|
||||
raise SystemExit("Mic-field CultCache smoke readback failed")
|
||||
frame_id += 1
|
||||
start_sample += args.chunk_frames
|
||||
if args.realtime:
|
||||
target_time = start_monotonic + start_sample / sample_rate
|
||||
sleep_for = target_time - time.monotonic()
|
||||
if sleep_for > 0:
|
||||
time.sleep(sleep_for)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from localcast.sensor_fusion.stochastic_mapping import MultiLODSceneCache
|
||||
|
||||
|
||||
def write_lod_cache_json(path: Path, cache: MultiLODSceneCache) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(cache.to_dict(), indent=2), encoding="utf-8")
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from localcast.sensor_fusion.render_bridge import RenderFramePacket
|
||||
|
||||
|
||||
def write_render_frame_json(path: Path, frame: RenderFramePacket) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(frame.to_dict(), indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def load_render_frame_json(path: Path) -> RenderFramePacket:
|
||||
return RenderFramePacket.from_dict(json.loads(path.read_text(encoding="utf-8")))
|
||||
|
|
@ -1,474 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import math
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from localcast.sensor_fusion.render_bridge import RenderFramePacket, RenderPointPacket
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SpoutOutputConfig:
|
||||
sender_name: str = "Mimir Point Cloud"
|
||||
width: int = 1920
|
||||
height: int = 1080
|
||||
fps: float = 60.0
|
||||
point_scale: float = 1.0
|
||||
demo_point_count: int = 4096
|
||||
camera_preset: str = "kiyo-mid-deru"
|
||||
max_render_points: int = 5000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VirtualCamera:
|
||||
eye: tuple[float, float, float]
|
||||
target: tuple[float, float, float]
|
||||
up: tuple[float, float, float] = (0.0, 0.0, 1.0)
|
||||
fov_degrees: float = 62.0
|
||||
near_m: float = 0.05
|
||||
far_m: float = 50.0
|
||||
|
||||
@property
|
||||
def eye_np(self) -> np.ndarray:
|
||||
return np.asarray(self.eye, dtype=np.float64)
|
||||
|
||||
@property
|
||||
def target_np(self) -> np.ndarray:
|
||||
return np.asarray(self.target, dtype=np.float64)
|
||||
|
||||
@property
|
||||
def up_np(self) -> np.ndarray:
|
||||
return np.asarray(self.up, dtype=np.float64)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScreenBrushPacket:
|
||||
center_px: tuple[int, int]
|
||||
radii_px: tuple[int, int]
|
||||
rotation_deg: float
|
||||
color_rgba: tuple[int, int, int, int]
|
||||
depth: float = 0.0
|
||||
|
||||
|
||||
def demo_render_frame(now_s: float, config: SpoutOutputConfig) -> RenderFramePacket:
|
||||
count = max(1, int(config.demo_point_count))
|
||||
points: list[RenderPointPacket] = []
|
||||
for i in range(count):
|
||||
u = i / count
|
||||
ring = 0.15 + 1.15 * math.sqrt(u)
|
||||
theta = i * 2.399963229728653 + now_s * 0.45
|
||||
z = 1.2 + 0.55 * math.sin(i * 0.031 + now_s * 0.9)
|
||||
confidence = 0.35 + 0.65 * ((math.sin(i * 0.017 + now_s) + 1.0) * 0.5)
|
||||
color = (
|
||||
0.15 + 0.85 * confidence,
|
||||
0.35 + 0.35 * math.sin(theta + 1.7),
|
||||
0.70 + 0.25 * math.cos(theta),
|
||||
0.85,
|
||||
)
|
||||
points.append(
|
||||
RenderPointPacket(
|
||||
stable_key=f"demo-{i}",
|
||||
xyz=np.array([ring * math.cos(theta), ring * math.sin(theta), z], dtype=np.float64),
|
||||
radius_m=0.018 + 0.035 * confidence,
|
||||
color_rgba=color,
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=time.monotonic_ns(),
|
||||
)
|
||||
)
|
||||
now_ns = time.monotonic_ns()
|
||||
return RenderFramePacket(
|
||||
schema="localcast.sensor_fusion.render_frame.v1",
|
||||
frame_id=int(now_s * config.fps),
|
||||
created_monotonic_ns=now_ns,
|
||||
source_time_min_ns=now_ns,
|
||||
source_time_max_ns=now_ns,
|
||||
present_time_ns=now_ns,
|
||||
audio_alignment_time_ns=now_ns,
|
||||
spout_sender_name=config.sender_name,
|
||||
target_width=config.width,
|
||||
target_height=config.height,
|
||||
points=tuple(points),
|
||||
)
|
||||
|
||||
|
||||
def frame_to_vertex_array(frame: RenderFramePacket, point_scale: float = 1.0) -> np.ndarray:
|
||||
vertices = np.zeros((len(frame.points), 8), dtype=np.float32)
|
||||
for index, point in enumerate(frame.points):
|
||||
vertices[index, 0:3] = point.xyz.astype(np.float32)
|
||||
rgba = np.asarray(point.color_rgba, dtype=np.float32)
|
||||
confidence = max(0.0, min(1.0, float(point.confidence)))
|
||||
vertices[index, 3:7] = np.clip(rgba, 0.0, 1.0)
|
||||
vertices[index, 6] *= confidence
|
||||
vertices[index, 7] = max(0.002, float(point.radius_m) * point_scale)
|
||||
return vertices
|
||||
|
||||
|
||||
def frame_with_point_budget(
|
||||
frame: RenderFramePacket,
|
||||
max_points: int,
|
||||
camera_preset_name: str = "kiyo-mid-deru",
|
||||
) -> RenderFramePacket:
|
||||
if max_points <= 0 or len(frame.points) <= max_points:
|
||||
return frame
|
||||
pinned = sorted(
|
||||
(point for point in frame.points if is_pinned_render_point(point)),
|
||||
key=lambda point: (-render_priority(point, camera_preset_name), point.stable_key),
|
||||
)[:max_points]
|
||||
pinned_keys = {point.stable_key for point in pinned}
|
||||
remaining_budget = max(0, max_points - len(pinned))
|
||||
if remaining_budget <= 0:
|
||||
points = pinned
|
||||
return _frame_with_points(frame, points)
|
||||
priority_count = max(1, int(remaining_budget * 0.55))
|
||||
temporal_count = max(0, remaining_budget - priority_count)
|
||||
priority = sorted(
|
||||
(point for point in frame.points if point.stable_key not in pinned_keys),
|
||||
key=lambda point: (-render_priority(point, camera_preset_name), stable_hash(point.stable_key, 0)),
|
||||
)[:priority_count]
|
||||
selected_keys = pinned_keys | {point.stable_key for point in priority}
|
||||
remainder = [point for point in frame.points if point.stable_key not in selected_keys]
|
||||
temporal = sorted(
|
||||
remainder,
|
||||
key=lambda point: stable_hash(point.stable_key, frame.frame_id) / max(0.05, render_priority(point, camera_preset_name)),
|
||||
)[:temporal_count]
|
||||
points = pinned + priority + temporal
|
||||
points = sorted(points, key=lambda point: point.stable_key)
|
||||
return _frame_with_points(frame, points)
|
||||
|
||||
|
||||
def _frame_with_points(frame: RenderFramePacket, points: list[RenderPointPacket]) -> RenderFramePacket:
|
||||
return RenderFramePacket(
|
||||
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=frame.source_time_max_ns,
|
||||
present_time_ns=frame.present_time_ns,
|
||||
audio_alignment_time_ns=frame.audio_alignment_time_ns,
|
||||
spout_sender_name=frame.spout_sender_name,
|
||||
target_width=frame.target_width,
|
||||
target_height=frame.target_height,
|
||||
points=tuple(points),
|
||||
)
|
||||
|
||||
|
||||
def is_pinned_render_point(point: RenderPointPacket) -> bool:
|
||||
return point.stable_key.startswith(
|
||||
(
|
||||
"camera-chirp:",
|
||||
"camera-pose-correction:",
|
||||
"camera-sync:",
|
||||
"clap-calibration:",
|
||||
"clap-ray:",
|
||||
"clap-timing:",
|
||||
"audio-event-",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def point_prefix_counts(points: tuple[RenderPointPacket, ...] | list[RenderPointPacket]) -> dict[str, int]:
|
||||
counts: dict[str, int] = {}
|
||||
for point in points:
|
||||
prefix = point_prefix(point.stable_key)
|
||||
counts[prefix] = counts.get(prefix, 0) + 1
|
||||
return dict(sorted(counts.items()))
|
||||
|
||||
|
||||
def point_prefix(stable_key: str) -> str:
|
||||
if ":" in stable_key:
|
||||
return stable_key.split(":", 1)[0]
|
||||
if stable_key.startswith("audio-event-"):
|
||||
return "audio-event"
|
||||
return stable_key
|
||||
|
||||
|
||||
def stable_hash(key: str, salt: int) -> int:
|
||||
digest = hashlib.blake2s(f"{salt}:{key}".encode("utf-8"), digest_size=8).digest()
|
||||
return int.from_bytes(digest, "little")
|
||||
|
||||
|
||||
def render_priority(point: RenderPointPacket, camera_preset_name: str) -> float:
|
||||
key = point.stable_key
|
||||
confidence = max(0.0, min(1.0, float(point.confidence)))
|
||||
semantic = 1.0
|
||||
if key.startswith("clap-calibration:"):
|
||||
semantic = 3.2
|
||||
elif key.startswith(("camera-sync:", "camera-chirp:", "camera-pose-correction:")):
|
||||
semantic = 2.6
|
||||
elif key.startswith(("clap-ray:", "clap-timing:")):
|
||||
semantic = 2.2
|
||||
elif key.startswith("dense-rgb:"):
|
||||
semantic = 2.0
|
||||
elif key.startswith("leap-motion:"):
|
||||
semantic = 1.45
|
||||
elif key.startswith("room-rgb:"):
|
||||
semantic = 1.15
|
||||
elif key.startswith("stochastic:"):
|
||||
semantic = 0.36
|
||||
elif key.startswith("audio-event-"):
|
||||
semantic = 0.24
|
||||
elif key.startswith(("sensor:", "frustum:")):
|
||||
semantic = 0.12
|
||||
focus = render_focus_weight(point, camera_preset_name)
|
||||
return max(0.001, confidence * semantic * focus)
|
||||
|
||||
|
||||
def render_focus_weight(point: RenderPointPacket, camera_preset_name: str) -> float:
|
||||
if camera_preset_name != "kiyo-mid-deru":
|
||||
return 1.0
|
||||
xyz = np.asarray(point.xyz, dtype=np.float64)
|
||||
deru = np.array([0.48, 0.28, 1.24], dtype=np.float64)
|
||||
distance = float(np.linalg.norm((xyz - deru) * np.array([1.0, 1.0, 0.75], dtype=np.float64)))
|
||||
return 0.22 + 1.78 / (1.0 + distance * 1.85)
|
||||
|
||||
|
||||
def lower_frame_to_screen_brushes(
|
||||
frame: RenderFramePacket,
|
||||
width: int,
|
||||
height: int,
|
||||
point_scale: float = 1.0,
|
||||
camera: VirtualCamera | None = None,
|
||||
) -> tuple[ScreenBrushPacket, ...]:
|
||||
brushes: list[ScreenBrushPacket] = []
|
||||
view_proj = camera_matrix(0.0, width / max(1, height), camera)
|
||||
for point in frame.points:
|
||||
projected = project_world_to_screen(point.xyz, view_proj, width, height)
|
||||
if projected is None:
|
||||
continue
|
||||
px, py, depth, clip_w = projected
|
||||
radius_scale = semantic_radius_scale(point.stable_key)
|
||||
radius = max(2, int(round(float(point.radius_m) * point_scale * height * 1.45 * radius_scale / max(0.42, clip_w))))
|
||||
if px < -radius * 3 or px >= width + radius * 3 or py < -radius * 3 or py >= height + radius * 3:
|
||||
continue
|
||||
stable = hashlib.blake2s(point.stable_key.encode("utf-8"), digest_size=4).digest()
|
||||
angle = int.from_bytes(stable[:2], "little") / 65535.0 * 180.0
|
||||
semantic_stretch = 2.8 if point.stable_key.startswith(("frustum:", "ray:", "floor:", "wall:")) else 1.0
|
||||
stretch = semantic_stretch * (1.0 + (stable[2] / 255.0) * 1.45)
|
||||
radii = (max(2, int(round(radius * stretch))), radius)
|
||||
rgba = np.clip(np.asarray(point.color_rgba, dtype=np.float32), 0.0, 1.0)
|
||||
rgba[3] *= max(0.0, min(1.0, float(point.confidence)))
|
||||
rgba[3] *= semantic_alpha_scale(point.stable_key)
|
||||
color = tuple(int(v) for v in (rgba * 255.0)[:4])
|
||||
brushes.append(ScreenBrushPacket((px, py), radii, angle, color, depth))
|
||||
return tuple(sorted(brushes, key=lambda brush: brush.depth, reverse=True))
|
||||
|
||||
|
||||
def semantic_radius_scale(stable_key: str) -> float:
|
||||
if stable_key.startswith("audio-event-"):
|
||||
return 0.42
|
||||
if stable_key.startswith("stochastic:"):
|
||||
return 0.50
|
||||
return 1.0
|
||||
|
||||
|
||||
def semantic_alpha_scale(stable_key: str) -> float:
|
||||
if stable_key.startswith("audio-event-"):
|
||||
return 0.36
|
||||
if stable_key.startswith("stochastic:"):
|
||||
return 0.46
|
||||
return 1.0
|
||||
|
||||
|
||||
def rasterize_frame_rgba(
|
||||
frame: RenderFramePacket,
|
||||
width: int,
|
||||
height: int,
|
||||
point_scale: float = 1.0,
|
||||
camera: VirtualCamera | None = None,
|
||||
) -> np.ndarray:
|
||||
image = np.zeros((height, width, 4), dtype=np.uint8)
|
||||
image[:, :, 0] = 7
|
||||
image[:, :, 1] = 10
|
||||
image[:, :, 2] = 15
|
||||
image[:, :, 3] = 255
|
||||
draw_reconstruction_guides(image, camera)
|
||||
draw_floor_shadows(image, frame, point_scale, camera)
|
||||
canvas = image.astype(np.float32) / 255.0
|
||||
for brush in lower_frame_to_screen_brushes(frame, width, height, point_scale, camera):
|
||||
composite_gaussian_brush(canvas, brush)
|
||||
return np.clip(canvas * 255.0, 0.0, 255.0).astype(np.uint8)
|
||||
|
||||
|
||||
def composite_gaussian_brush(canvas: np.ndarray, brush: ScreenBrushPacket) -> None:
|
||||
height, width = canvas.shape[:2]
|
||||
cx, cy = brush.center_px
|
||||
rx, ry = max(1, brush.radii_px[0]), max(1, brush.radii_px[1])
|
||||
bound = int(math.ceil(max(rx, ry) * 1.35))
|
||||
x0 = max(0, cx - bound)
|
||||
x1 = min(width, cx + bound + 1)
|
||||
y0 = max(0, cy - bound)
|
||||
y1 = min(height, cy + bound + 1)
|
||||
if x0 >= x1 or y0 >= y1:
|
||||
return
|
||||
|
||||
yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)
|
||||
dx = xx - float(cx)
|
||||
dy = yy - float(cy)
|
||||
angle = math.radians(float(brush.rotation_deg))
|
||||
ca = math.cos(angle)
|
||||
sa = math.sin(angle)
|
||||
local_x = dx * ca + dy * sa
|
||||
local_y = -dx * sa + dy * ca
|
||||
q = (local_x / float(rx)) ** 2 + (local_y / float(ry)) ** 2
|
||||
mask = q < 1.0
|
||||
if not np.any(mask):
|
||||
return
|
||||
|
||||
# Compact Gaussian envelope: smooth center, finite edge, no solid paint bucket.
|
||||
falloff = 4.4
|
||||
edge = math.exp(-falloff)
|
||||
gaussian = np.exp(-falloff * q)
|
||||
envelope = np.clip((gaussian - edge) / max(1.0 - edge, 1e-6), 0.0, 1.0) ** 1.35
|
||||
envelope *= mask
|
||||
|
||||
src = np.asarray(brush.color_rgba, dtype=np.float32) / 255.0
|
||||
alpha = np.clip(envelope * src[3], 0.0, 0.96)
|
||||
if float(alpha.max()) <= 0.0:
|
||||
return
|
||||
target = canvas[y0:y1, x0:x1, :]
|
||||
target[:, :, :3] = src[:3] * alpha[:, :, None] + target[:, :, :3] * (1.0 - alpha[:, :, None])
|
||||
target[:, :, 3] = np.maximum(target[:, :, 3], alpha)
|
||||
|
||||
|
||||
def project_world_to_screen(
|
||||
xyz: np.ndarray,
|
||||
view_proj: np.ndarray,
|
||||
width: int,
|
||||
height: int,
|
||||
) -> tuple[int, int, float, float] | None:
|
||||
point = np.ones(4, dtype=np.float64)
|
||||
point[:3] = np.asarray(xyz, dtype=np.float64)
|
||||
clip = view_proj @ point
|
||||
if clip[3] <= 0.001:
|
||||
return None
|
||||
ndc = clip[:3] / clip[3]
|
||||
if ndc[0] < -1.35 or ndc[0] > 1.35 or ndc[1] < -1.35 or ndc[1] > 1.35:
|
||||
return None
|
||||
px = int(round((ndc[0] * 0.5 + 0.5) * width))
|
||||
py = int(round((0.5 - ndc[1] * 0.5) * height))
|
||||
return px, py, float(ndc[2]), float(clip[3])
|
||||
|
||||
|
||||
def draw_reconstruction_guides(image: np.ndarray, camera: VirtualCamera | None = None) -> None:
|
||||
try:
|
||||
import cv2
|
||||
except ModuleNotFoundError:
|
||||
return
|
||||
|
||||
height, width = image.shape[:2]
|
||||
view_proj = camera_matrix(0.0, width / max(1, height), camera)
|
||||
grid_color = (36, 50, 62, 255)
|
||||
wall_color = (24, 36, 50, 255)
|
||||
for x in np.linspace(-1.8, 1.8, 13):
|
||||
draw_world_line(image, view_proj, np.array([x, -1.0, 0.0]), np.array([x, 1.15, 0.0]), grid_color, 1)
|
||||
for y in np.linspace(-1.0, 1.15, 9):
|
||||
draw_world_line(image, view_proj, np.array([-1.8, y, 0.0]), np.array([1.8, y, 0.0]), grid_color, 1)
|
||||
for x in np.linspace(-1.8, 1.8, 9):
|
||||
draw_world_line(image, view_proj, np.array([x, 1.15, 0.0]), np.array([x, 1.15, 2.2]), wall_color, 1)
|
||||
for z in np.linspace(0.35, 2.1, 6):
|
||||
draw_world_line(image, view_proj, np.array([-1.8, 1.15, z]), np.array([1.8, 1.15, z]), wall_color, 1)
|
||||
|
||||
def draw_floor_shadows(
|
||||
image: np.ndarray,
|
||||
frame: RenderFramePacket,
|
||||
point_scale: float,
|
||||
camera: VirtualCamera | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
import cv2
|
||||
except ModuleNotFoundError:
|
||||
return
|
||||
|
||||
height, width = image.shape[:2]
|
||||
view_proj = camera_matrix(0.0, width / max(1, height), camera)
|
||||
for point in frame.points:
|
||||
xyz = np.asarray(point.xyz, dtype=np.float64)
|
||||
if xyz[2] <= 0.10 or point.stable_key.startswith(("sensor:", "frustum:")):
|
||||
continue
|
||||
shadow = xyz.copy()
|
||||
shadow[2] = 0.012
|
||||
projected = project_world_to_screen(shadow, view_proj, width, height)
|
||||
if projected is None:
|
||||
continue
|
||||
px, py, _, clip_w = projected
|
||||
radius = max(2, int(round(float(point.radius_m) * point_scale * height * 0.9 / max(0.42, clip_w))))
|
||||
shade = int(18 + 18 * max(0.0, min(1.0, float(point.confidence))))
|
||||
cv2.ellipse(image, (px, py), (radius * 2, max(1, radius // 2)), 0.0, 0.0, 360.0, (shade // 3, shade // 2, shade, 255), -1, cv2.LINE_AA)
|
||||
|
||||
|
||||
def draw_world_line(
|
||||
image: np.ndarray,
|
||||
view_proj: np.ndarray,
|
||||
start: np.ndarray,
|
||||
end: np.ndarray,
|
||||
color: tuple[int, int, int, int],
|
||||
thickness: int,
|
||||
) -> None:
|
||||
try:
|
||||
import cv2
|
||||
except ModuleNotFoundError:
|
||||
return
|
||||
|
||||
height, width = image.shape[:2]
|
||||
a = project_world_to_screen(start, view_proj, width, height)
|
||||
b = project_world_to_screen(end, view_proj, width, height)
|
||||
if a is None or b is None:
|
||||
return
|
||||
cv2.line(image, a[:2], b[:2], color, thickness=thickness, lineType=cv2.LINE_AA)
|
||||
|
||||
|
||||
|
||||
def camera_preset(name: str, now_s: float = 0.0) -> VirtualCamera:
|
||||
if name == "orbit":
|
||||
return VirtualCamera(
|
||||
eye=(2.4 * math.sin(now_s * 0.08), -3.4, 1.85 + 0.2 * math.cos(now_s * 0.11)),
|
||||
target=(0.0, 0.0, 1.15),
|
||||
fov_degrees=58.0,
|
||||
)
|
||||
if name == "kiyo-mid-deru":
|
||||
return VirtualCamera(
|
||||
eye=(0.05, -1.035, 1.64),
|
||||
target=(0.48, 0.28, 1.24),
|
||||
fov_degrees=64.0,
|
||||
)
|
||||
raise ValueError(f"unknown camera preset: {name}")
|
||||
|
||||
|
||||
def camera_matrix(now_s: float, aspect: float, camera: VirtualCamera | None = None) -> np.ndarray:
|
||||
view = camera_preset("orbit", now_s) if camera is None else camera
|
||||
return perspective(math.radians(view.fov_degrees), aspect, view.near_m, view.far_m) @ look_at(
|
||||
view.eye_np,
|
||||
view.target_np,
|
||||
view.up_np,
|
||||
)
|
||||
|
||||
|
||||
def look_at(eye: np.ndarray, target: np.ndarray, up: np.ndarray) -> np.ndarray:
|
||||
forward = target - eye
|
||||
forward = forward / np.linalg.norm(forward)
|
||||
side = np.cross(forward, up)
|
||||
side = side / np.linalg.norm(side)
|
||||
true_up = np.cross(side, forward)
|
||||
matrix = np.eye(4, dtype=np.float64)
|
||||
matrix[0, :3] = side
|
||||
matrix[1, :3] = true_up
|
||||
matrix[2, :3] = -forward
|
||||
translate = np.eye(4, dtype=np.float64)
|
||||
translate[:3, 3] = -eye
|
||||
return matrix @ translate
|
||||
|
||||
|
||||
def perspective(fov_y: float, aspect: float, near: float, far: float) -> np.ndarray:
|
||||
f = 1.0 / math.tan(fov_y * 0.5)
|
||||
matrix = np.zeros((4, 4), dtype=np.float64)
|
||||
matrix[0, 0] = f / aspect
|
||||
matrix[1, 1] = f
|
||||
matrix[2, 2] = (far + near) / (near - far)
|
||||
matrix[2, 3] = (2.0 * far * near) / (near - far)
|
||||
matrix[3, 2] = -1.0
|
||||
return matrix
|
||||
|
||||
|
||||
|
|
@ -1,154 +0,0 @@
|
|||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from scipy.io import wavfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
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="Diagnostic replay of AmbiX spatial audio blocks into typed CultCache state.")
|
||||
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="Mimir 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")
|
||||
parser.add_argument("--max-lag-ms", type=float, default=250.0)
|
||||
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
|
||||
realtime_start_sample = int((now - start_monotonic) * sample_rate)
|
||||
max_lag_samples = int(float(args.max_lag_ms) * sample_rate / 1000.0)
|
||||
if start_sample + args.chunk_frames < realtime_start_sample - max_lag_samples:
|
||||
start_sample = max(0, realtime_start_sample - (realtime_start_sample % args.chunk_frames))
|
||||
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()
|
||||
|
|
@ -1,393 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from localcast.sensor_fusion.render_bridge import RenderFramePacket, RenderPointPacket
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
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_RENDER_FRAME_KEY = "localcast.visual.render-frame.live"
|
||||
RENDER_FRAME_SCHEMA_ID = "gamecult.localcast.visual.render_frame.v1"
|
||||
STREAM_STATUS_KEY = "localcast.visual.stream-status.live"
|
||||
STREAM_STATUS_SCHEMA_ID = "gamecult.localcast.visual.stream_status.v1"
|
||||
CLAP_EVENTS_KEY = "localcast.calibration.clap-events.live"
|
||||
CLAP_EVENTS_SCHEMA_ID = "gamecult.localcast.calibration.clap_events.v1"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultRenderPoint:
|
||||
stable_key: str
|
||||
xyz: tuple[float, float, float]
|
||||
radius_m: float
|
||||
color_rgba: tuple[float, float, float, float]
|
||||
confidence: float
|
||||
source_timestamp_ns: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultRenderFrame:
|
||||
schema_version: str
|
||||
frame_id: int
|
||||
created_monotonic_ns: int
|
||||
source_time_min_ns: int
|
||||
source_time_max_ns: int
|
||||
present_time_ns: int
|
||||
audio_alignment_time_ns: int
|
||||
spout_sender_name: str
|
||||
target_width: int
|
||||
target_height: int
|
||||
points: tuple[CultRenderPoint, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultStreamStatus:
|
||||
sender_name: str
|
||||
frames_sent: int
|
||||
point_count: int
|
||||
frame_source: str
|
||||
updated_monotonic_ns: int
|
||||
last_error: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultClapEvent:
|
||||
stable_key: str
|
||||
position_m: tuple[float, float, float]
|
||||
acoustic_oracle_ns: int
|
||||
visual_observed_ns: int
|
||||
timing_uncertainty_us: float
|
||||
visual_confidence: float
|
||||
acoustic_confidence: float
|
||||
camera_peaks: tuple[dict[str, Any], ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultClapEventsFrame:
|
||||
schema_version: str
|
||||
frame_id: int
|
||||
created_monotonic_ns: int
|
||||
events: tuple[CultClapEvent, ...]
|
||||
|
||||
|
||||
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_point(point: CultRenderPoint) -> list[Any]:
|
||||
return [
|
||||
point.stable_key,
|
||||
list(point.xyz),
|
||||
point.radius_m,
|
||||
list(point.color_rgba),
|
||||
point.confidence,
|
||||
point.source_timestamp_ns,
|
||||
]
|
||||
|
||||
|
||||
def _decode_point(raw: Any) -> CultRenderPoint:
|
||||
return CultRenderPoint(
|
||||
stable_key=str(raw[0]),
|
||||
xyz=(float(raw[1][0]), float(raw[1][1]), float(raw[1][2])),
|
||||
radius_m=float(raw[2]),
|
||||
color_rgba=(float(raw[3][0]), float(raw[3][1]), float(raw[3][2]), float(raw[3][3])),
|
||||
confidence=float(raw[4]),
|
||||
source_timestamp_ns=int(raw[5]),
|
||||
)
|
||||
|
||||
|
||||
def _encode_render_frame(frame: CultRenderFrame) -> list[Any]:
|
||||
return [
|
||||
frame.schema_version,
|
||||
frame.frame_id,
|
||||
frame.created_monotonic_ns,
|
||||
frame.source_time_min_ns,
|
||||
frame.source_time_max_ns,
|
||||
frame.present_time_ns,
|
||||
frame.audio_alignment_time_ns,
|
||||
frame.spout_sender_name,
|
||||
frame.target_width,
|
||||
frame.target_height,
|
||||
[_encode_point(point) for point in frame.points],
|
||||
]
|
||||
|
||||
|
||||
def _decode_render_frame(raw: Any) -> CultRenderFrame:
|
||||
return CultRenderFrame(
|
||||
schema_version=str(raw[0]),
|
||||
frame_id=int(raw[1]),
|
||||
created_monotonic_ns=int(raw[2]),
|
||||
source_time_min_ns=int(raw[3]),
|
||||
source_time_max_ns=int(raw[4]),
|
||||
present_time_ns=int(raw[5]),
|
||||
audio_alignment_time_ns=int(raw[6]),
|
||||
spout_sender_name=str(raw[7]),
|
||||
target_width=int(raw[8]),
|
||||
target_height=int(raw[9]),
|
||||
points=tuple(_decode_point(point) for point in raw[10]),
|
||||
)
|
||||
|
||||
|
||||
def _encode_status(status: CultStreamStatus) -> list[Any]:
|
||||
return [
|
||||
status.sender_name,
|
||||
status.frames_sent,
|
||||
status.point_count,
|
||||
status.frame_source,
|
||||
status.updated_monotonic_ns,
|
||||
status.last_error,
|
||||
]
|
||||
|
||||
|
||||
def _decode_status(raw: Any) -> CultStreamStatus:
|
||||
return CultStreamStatus(
|
||||
sender_name=str(raw[0]),
|
||||
frames_sent=int(raw[1]),
|
||||
point_count=int(raw[2]),
|
||||
frame_source=str(raw[3]),
|
||||
updated_monotonic_ns=int(raw[4]),
|
||||
last_error=str(raw[5]),
|
||||
)
|
||||
|
||||
|
||||
def _encode_clap_event(event: CultClapEvent) -> list[Any]:
|
||||
return [
|
||||
event.stable_key,
|
||||
list(event.position_m),
|
||||
event.acoustic_oracle_ns,
|
||||
event.visual_observed_ns,
|
||||
event.timing_uncertainty_us,
|
||||
event.visual_confidence,
|
||||
event.acoustic_confidence,
|
||||
list(event.camera_peaks),
|
||||
]
|
||||
|
||||
|
||||
def _decode_clap_event(raw: Any) -> CultClapEvent:
|
||||
return CultClapEvent(
|
||||
stable_key=str(raw[0]),
|
||||
position_m=(float(raw[1][0]), float(raw[1][1]), float(raw[1][2])),
|
||||
acoustic_oracle_ns=int(raw[2]),
|
||||
visual_observed_ns=int(raw[3]),
|
||||
timing_uncertainty_us=float(raw[4]),
|
||||
visual_confidence=float(raw[5]),
|
||||
acoustic_confidence=float(raw[6]),
|
||||
camera_peaks=tuple(dict(item) for item in raw[7]),
|
||||
)
|
||||
|
||||
|
||||
def _encode_clap_events_frame(frame: CultClapEventsFrame) -> list[Any]:
|
||||
return [
|
||||
frame.schema_version,
|
||||
frame.frame_id,
|
||||
frame.created_monotonic_ns,
|
||||
[_encode_clap_event(event) for event in frame.events],
|
||||
]
|
||||
|
||||
|
||||
def _decode_clap_events_frame(raw: Any) -> CultClapEventsFrame:
|
||||
return CultClapEventsFrame(
|
||||
schema_version=str(raw[0]),
|
||||
frame_id=int(raw[1]),
|
||||
created_monotonic_ns=int(raw[2]),
|
||||
events=tuple(_decode_clap_event(item) for item in raw[3]),
|
||||
)
|
||||
|
||||
|
||||
RENDER_FRAME_DOCUMENT = define_document_type(
|
||||
"localcast.visual.render_frame",
|
||||
encode=_encode_render_frame,
|
||||
decode=_decode_render_frame,
|
||||
name=lambda frame: LIVE_RENDER_FRAME_KEY if isinstance(frame, CultRenderFrame) else None,
|
||||
payload_encoder=_pack,
|
||||
payload_decoder=_unpack,
|
||||
)
|
||||
|
||||
STREAM_STATUS_DOCUMENT = define_document_type(
|
||||
"localcast.visual.stream_status",
|
||||
encode=_encode_status,
|
||||
decode=_decode_status,
|
||||
name=lambda status: STREAM_STATUS_KEY if isinstance(status, CultStreamStatus) else None,
|
||||
payload_encoder=_pack,
|
||||
payload_decoder=_unpack,
|
||||
)
|
||||
|
||||
CLAP_EVENTS_DOCUMENT = define_document_type(
|
||||
"localcast.calibration.clap_events",
|
||||
encode=_encode_clap_events_frame,
|
||||
decode=_decode_clap_events_frame,
|
||||
name=lambda frame: CLAP_EVENTS_KEY if isinstance(frame, CultClapEventsFrame) 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_visual_cache_once(path: Path) -> CultCache:
|
||||
cache = (
|
||||
CultCache.builder()
|
||||
.register_document_type(RENDER_FRAME_DOCUMENT)
|
||||
.register_document_type(STREAM_STATUS_DOCUMENT)
|
||||
.register_document_type(CLAP_EVENTS_DOCUMENT)
|
||||
.add_generic_store(SingleFileMessagePackBackingStore(path))
|
||||
.build()
|
||||
)
|
||||
cache.pull_all_backing_stores()
|
||||
return cache
|
||||
|
||||
|
||||
def open_visual_cache(path: Path) -> CultCache:
|
||||
return _retry_cache_io(lambda: _open_visual_cache_once(path))
|
||||
|
||||
|
||||
def render_frame_to_cult(frame: RenderFramePacket) -> CultRenderFrame:
|
||||
return CultRenderFrame(
|
||||
schema_version=RENDER_FRAME_SCHEMA_ID,
|
||||
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=frame.source_time_max_ns,
|
||||
present_time_ns=frame.present_time_ns,
|
||||
audio_alignment_time_ns=frame.audio_alignment_time_ns,
|
||||
spout_sender_name=frame.spout_sender_name,
|
||||
target_width=frame.target_width,
|
||||
target_height=frame.target_height,
|
||||
points=tuple(
|
||||
CultRenderPoint(
|
||||
stable_key=point.stable_key,
|
||||
xyz=(float(point.xyz[0]), float(point.xyz[1]), float(point.xyz[2])),
|
||||
radius_m=point.radius_m,
|
||||
color_rgba=point.color_rgba,
|
||||
confidence=point.confidence,
|
||||
source_timestamp_ns=point.source_timestamp_ns,
|
||||
)
|
||||
for point in frame.points
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def cult_render_frame_to_packet(frame: CultRenderFrame) -> RenderFramePacket:
|
||||
return RenderFramePacket(
|
||||
schema="localcast.sensor_fusion.render_frame.v1",
|
||||
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=frame.source_time_max_ns,
|
||||
present_time_ns=frame.present_time_ns,
|
||||
audio_alignment_time_ns=frame.audio_alignment_time_ns,
|
||||
spout_sender_name=frame.spout_sender_name,
|
||||
target_width=frame.target_width,
|
||||
target_height=frame.target_height,
|
||||
points=tuple(
|
||||
RenderPointPacket(
|
||||
stable_key=point.stable_key,
|
||||
xyz=np.asarray(point.xyz, dtype=np.float64),
|
||||
radius_m=point.radius_m,
|
||||
color_rgba=point.color_rgba,
|
||||
confidence=point.confidence,
|
||||
source_timestamp_ns=point.source_timestamp_ns,
|
||||
)
|
||||
for point in frame.points
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def put_live_render_frame(path: Path, frame: RenderFramePacket) -> None:
|
||||
def operation() -> None:
|
||||
cache = open_visual_cache(path)
|
||||
cache.put(RENDER_FRAME_DOCUMENT, LIVE_RENDER_FRAME_KEY, render_frame_to_cult(frame))
|
||||
|
||||
_retry_cache_io(operation)
|
||||
|
||||
|
||||
def get_live_render_frame(path: Path) -> RenderFramePacket | None:
|
||||
def operation() -> RenderFramePacket | None:
|
||||
cache = open_visual_cache(path)
|
||||
frame = cache.get(RENDER_FRAME_DOCUMENT, LIVE_RENDER_FRAME_KEY)
|
||||
return None if frame is None else cult_render_frame_to_packet(frame)
|
||||
|
||||
return _retry_cache_io(operation)
|
||||
|
||||
|
||||
def put_stream_status(path: Path, status: CultStreamStatus) -> None:
|
||||
def operation() -> None:
|
||||
cache = open_visual_cache(path)
|
||||
cache.put(STREAM_STATUS_DOCUMENT, STREAM_STATUS_KEY, status)
|
||||
|
||||
_retry_cache_io(operation)
|
||||
|
||||
|
||||
def make_clap_events_frame(*, frame_id: int, events: list[Any] | tuple[Any, ...]) -> CultClapEventsFrame:
|
||||
return CultClapEventsFrame(
|
||||
schema_version=CLAP_EVENTS_SCHEMA_ID,
|
||||
frame_id=int(frame_id),
|
||||
created_monotonic_ns=time.monotonic_ns(),
|
||||
events=tuple(
|
||||
CultClapEvent(
|
||||
stable_key=str(event.stable_key),
|
||||
position_m=tuple(float(value) for value in event.position_m),
|
||||
acoustic_oracle_ns=int(event.acoustic_oracle_ns),
|
||||
visual_observed_ns=int(event.visual_observed_ns),
|
||||
timing_uncertainty_us=float(event.timing_uncertainty_us),
|
||||
visual_confidence=float(event.visual_confidence),
|
||||
acoustic_confidence=float(event.acoustic_confidence),
|
||||
camera_peaks=tuple(
|
||||
{
|
||||
"sensorId": peak.sensor_id,
|
||||
"timestampNs": int(peak.timestamp_ns),
|
||||
"uv": [float(peak.uv[0]), float(peak.uv[1])],
|
||||
"score": float(peak.score),
|
||||
}
|
||||
for peak in event.camera_peaks
|
||||
),
|
||||
)
|
||||
for event in events
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def put_live_clap_events(path: Path, frame: CultClapEventsFrame) -> None:
|
||||
def operation() -> None:
|
||||
cache = open_visual_cache(path)
|
||||
cache.put(CLAP_EVENTS_DOCUMENT, CLAP_EVENTS_KEY, frame)
|
||||
|
||||
_retry_cache_io(operation)
|
||||
|
||||
|
||||
def get_live_clap_events(path: Path) -> CultClapEventsFrame | None:
|
||||
def operation() -> CultClapEventsFrame | None:
|
||||
cache = open_visual_cache(path)
|
||||
return cache.get(CLAP_EVENTS_DOCUMENT, CLAP_EVENTS_KEY)
|
||||
|
||||
return _retry_cache_io(operation)
|
||||
|
|
@ -1,863 +0,0 @@
|
|||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from typing import BinaryIO
|
||||
|
||||
import numpy as np
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.sensor_fusion import (
|
||||
CameraModel,
|
||||
FusionConfig,
|
||||
Observation2D,
|
||||
RenderBridgeConfig,
|
||||
RenderFramePacket,
|
||||
RenderPointPacket,
|
||||
SensorRig,
|
||||
SurfaceFeatureObservation,
|
||||
CameraClockSyncModel,
|
||||
CameraChirpPoseConstraint,
|
||||
TimestampedFrame,
|
||||
TimestampedFrameHistory,
|
||||
camera_mic_geometry_from_audio_profile,
|
||||
constraints_from_phase_sources,
|
||||
estimate_pose_corrections,
|
||||
evidence_from_fusion_items,
|
||||
evidence_from_render_points,
|
||||
measure_frame_quality,
|
||||
multilod_cache_from_evidence,
|
||||
lower_points_to_render_frame,
|
||||
stochastic_transient_matches,
|
||||
speaker_geometry_from_audio_profile,
|
||||
)
|
||||
from localcast.diagnostics.visual_cache import (
|
||||
put_live_render_frame,
|
||||
)
|
||||
from localcast.diagnostics.clap_calibrator import LiveClapCalibrator
|
||||
from localcast.diagnostics.lod_json import write_lod_cache_json
|
||||
from localcast.sensor_fusion.camera_control import AdaptiveCameraController, OpenCvCameraSettingPort
|
||||
from localcast.sensor_fusion.adapters import LatestFramePump, OpenCvCaptureConfig, OpenCvFrameSource
|
||||
from localcast.sensor_fusion.reservoir_window import (
|
||||
DEFAULT_RESERVOIR_NS,
|
||||
evidence_in_reservoir,
|
||||
render_points_in_reservoir,
|
||||
)
|
||||
from localcast.sensor_fusion.leap_packed import leap_channel_motion_points, unpack_leap_packed_channels
|
||||
from localcast.sensor_fusion.rgb_reference import (
|
||||
rgb_body_splats,
|
||||
rgb_dense_camera,
|
||||
rgb_dense_stereo_splats,
|
||||
rgb_room_splats,
|
||||
)
|
||||
from audio_field.cultcache_audio import get_live_audio_phase_field, get_live_spatial_audio_frame
|
||||
|
||||
|
||||
def acquire_runtime_lock(path: Path) -> BinaryIO | None:
|
||||
import msvcrt
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle = path.open("a+b")
|
||||
handle.seek(0)
|
||||
handle.write(b"\0")
|
||||
handle.flush()
|
||||
handle.seek(0)
|
||||
try:
|
||||
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
except OSError:
|
||||
handle.close()
|
||||
return None
|
||||
return handle
|
||||
|
||||
|
||||
def latest_audio_time_ns(audio_cache: Path) -> int | None:
|
||||
if not audio_cache.exists():
|
||||
return None
|
||||
frame = get_live_spatial_audio_frame(audio_cache)
|
||||
if frame is None:
|
||||
return None
|
||||
return int(frame.audio_time_ns)
|
||||
|
||||
|
||||
def camera(sensor_id: str, x: float) -> CameraModel:
|
||||
return CameraModel(
|
||||
sensor_id=sensor_id,
|
||||
camera_matrix=np.array([[300.0, 0.0, 160.0], [0.0, 300.0, 120.0], [0.0, 0.0, 1.0]]),
|
||||
dist_coeffs=np.zeros(5),
|
||||
world_from_sensor=np.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, x],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]
|
||||
),
|
||||
width=320,
|
||||
height=240,
|
||||
)
|
||||
|
||||
|
||||
def synthetic_observations(rig: SensorRig, now_s: float, count: int) -> list[Observation2D]:
|
||||
left = rig.cameras["ps3eye_left"]
|
||||
right = rig.cameras["ps3eye_right"]
|
||||
timestamp = time.monotonic_ns()
|
||||
observations: list[Observation2D] = []
|
||||
targets = reconstruction_targets(now_s, count)
|
||||
for index, point in enumerate(targets):
|
||||
marker = f"synthetic-fused-{index}"
|
||||
observations.append(Observation2D("ps3eye_left", marker, timestamp, left.project_world(point), 0.95))
|
||||
observations.append(Observation2D("ps3eye_right", marker, timestamp, right.project_world(point), 0.92))
|
||||
return observations
|
||||
|
||||
|
||||
def stochastic_surface_observations(observations: list[Observation2D]) -> list[SurfaceFeatureObservation]:
|
||||
surface: list[SurfaceFeatureObservation] = []
|
||||
for obs in observations:
|
||||
marker_hash = abs(hash(obs.marker_id)) % 255
|
||||
descriptor = np.full(32, marker_hash, dtype=np.uint8)
|
||||
surface.append(
|
||||
SurfaceFeatureObservation(
|
||||
sensor_id=obs.sensor_id,
|
||||
feature_id=obs.marker_id,
|
||||
timestamp_ns=obs.timestamp_ns,
|
||||
uv=obs.uv,
|
||||
descriptor=descriptor,
|
||||
confidence=obs.confidence,
|
||||
)
|
||||
)
|
||||
return surface
|
||||
|
||||
|
||||
def transient_match_render_points(matches, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
points: list[RenderPointPacket] = []
|
||||
for match in matches:
|
||||
confidence = max(0.0, min(1.0, float(match.confidence)))
|
||||
points.append(
|
||||
render_point(
|
||||
f"stochastic:{match.stable_key}",
|
||||
match.xyz,
|
||||
0.018 + 0.020 * confidence,
|
||||
(1.0, 0.88, 0.32, 0.35 + 0.55 * confidence),
|
||||
confidence,
|
||||
timestamp_ns,
|
||||
)
|
||||
)
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def reconstruction_targets(now_s: float, count: int) -> list[np.ndarray]:
|
||||
"""Deadline stand-in for real detections: two people plus tracked room support."""
|
||||
body_count = max(32, int(count * 0.55))
|
||||
room_count = max(24, int(count * 0.25))
|
||||
marker_count = max(8, count - body_count - room_count)
|
||||
targets: list[np.ndarray] = []
|
||||
targets.extend(body_points("host", np.array([-0.42, 0.05, 0.0]), now_s, body_count // 2))
|
||||
targets.extend(body_points("deru", np.array([0.48, 0.28, 0.0]), now_s + 0.7, body_count - body_count // 2))
|
||||
targets.extend(room_support_points(now_s, room_count))
|
||||
targets.extend(marker_points(now_s, marker_count))
|
||||
return targets[: max(1, count)]
|
||||
|
||||
|
||||
def body_points(name: str, origin: np.ndarray, now_s: float, count: int) -> list[np.ndarray]:
|
||||
points: list[np.ndarray] = []
|
||||
golden = 2.399963229728653
|
||||
for index in range(max(1, count)):
|
||||
u = (index + 0.5) / max(1, count)
|
||||
theta = index * golden
|
||||
if u < 0.22:
|
||||
radius = 0.17 * np.sqrt(u / 0.22)
|
||||
z = 1.55 + 0.16 * np.sin(theta)
|
||||
local = np.array([radius * np.cos(theta), radius * np.sin(theta) * 0.72, z])
|
||||
elif u < 0.72:
|
||||
v = (u - 0.22) / 0.50
|
||||
radius = 0.23 * (1.0 - abs(v - 0.52) * 0.55)
|
||||
z = 0.72 + v * 0.72
|
||||
sway = 0.035 * np.sin(now_s * 1.4 + (0.0 if name == "host" else 1.2))
|
||||
local = np.array([radius * np.cos(theta) + sway, radius * np.sin(theta) * 0.52, z])
|
||||
else:
|
||||
v = (u - 0.72) / 0.28
|
||||
side = -1.0 if index % 2 == 0 else 1.0
|
||||
reach = 0.28 + 0.18 * np.sin(now_s * 1.7 + side)
|
||||
z = 1.16 - 0.25 * v
|
||||
local = np.array([side * reach * v, 0.06 * np.sin(theta), z])
|
||||
points.append(origin + local)
|
||||
return points
|
||||
|
||||
|
||||
def room_support_points(now_s: float, count: int) -> list[np.ndarray]:
|
||||
points: list[np.ndarray] = []
|
||||
for index in range(max(1, count)):
|
||||
u = (index + 0.5) / max(1, count)
|
||||
if index % 3 == 0:
|
||||
x = -1.65 + 3.3 * u
|
||||
y = -0.85 + 1.75 * ((index * 7) % max(1, count)) / max(1, count)
|
||||
z = 0.02
|
||||
elif index % 3 == 1:
|
||||
x = -1.65 + 3.3 * u
|
||||
y = 1.05
|
||||
z = 0.28 + 1.72 * ((index * 5) % max(1, count)) / max(1, count)
|
||||
else:
|
||||
x = -1.05 + 2.1 * ((index * 11) % max(1, count)) / max(1, count)
|
||||
y = -0.65 + 0.12 * np.sin(now_s + index)
|
||||
z = 0.85 + 0.95 * u
|
||||
points.append(np.array([x, y, z], dtype=np.float64))
|
||||
return points
|
||||
|
||||
|
||||
def marker_points(now_s: float, count: int) -> list[np.ndarray]:
|
||||
points: list[np.ndarray] = []
|
||||
for index in range(max(1, count)):
|
||||
theta = now_s * 0.9 + index * 2.399963229728653
|
||||
ring = 0.28 + 0.52 * ((index % 5) / 4.0)
|
||||
points.append(
|
||||
np.array(
|
||||
[
|
||||
ring * np.cos(theta),
|
||||
0.12 + ring * 0.42 * np.sin(theta * 0.7),
|
||||
1.08 + 0.42 * np.sin(theta + index * 0.37),
|
||||
],
|
||||
dtype=np.float64,
|
||||
)
|
||||
)
|
||||
return points
|
||||
|
||||
|
||||
def reconstruction_context_points(now_s: float, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
points: list[RenderPointPacket] = []
|
||||
cameras = [
|
||||
("ps3eye-left", (-0.78, -0.82, 1.34), (0.10, 0.72, 1.05), (0.2, 0.7, 1.0, 0.95)),
|
||||
("ps3eye-right", (0.78, -0.82, 1.34), (-0.10, 0.72, 1.05), (0.2, 0.7, 1.0, 0.95)),
|
||||
("kiyo", (-0.28, -1.05, 1.62), (-0.15, 0.45, 1.15), (1.0, 0.62, 0.25, 0.95)),
|
||||
("kiyo-pro", (0.38, -1.02, 1.66), (0.20, 0.48, 1.18), (1.0, 0.62, 0.25, 0.95)),
|
||||
("leap", (0.0, -0.18, 0.76), (0.0, 0.20, 1.05), (0.55, 1.0, 0.72, 0.95)),
|
||||
]
|
||||
for sensor, origin, target, color in cameras:
|
||||
origin_np = np.asarray(origin, dtype=np.float64)
|
||||
target_np = np.asarray(target, dtype=np.float64)
|
||||
points.append(render_point(f"sensor:{sensor}", origin_np, 0.055, color, 1.0, timestamp_ns))
|
||||
for ray_index, t in enumerate((0.28, 0.48, 0.68, 0.88)):
|
||||
p = origin_np + (target_np - origin_np) * t
|
||||
jitter = np.array([0.04 * np.sin(now_s + ray_index), 0.0, 0.035 * np.cos(now_s * 0.7 + ray_index)])
|
||||
points.append(render_point(f"frustum:{sensor}:{ray_index}", p + jitter, 0.014, color, 0.72, timestamp_ns))
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def render_point(
|
||||
key: str,
|
||||
xyz: np.ndarray,
|
||||
radius_m: float,
|
||||
color: tuple[float, float, float, float],
|
||||
confidence: float,
|
||||
timestamp_ns: int,
|
||||
) -> RenderPointPacket:
|
||||
return RenderPointPacket(
|
||||
stable_key=key,
|
||||
xyz=np.asarray(xyz, dtype=np.float64),
|
||||
radius_m=radius_m,
|
||||
color_rgba=color,
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=timestamp_ns,
|
||||
)
|
||||
|
||||
|
||||
def dim_fusion_points(points: tuple[RenderPointPacket, ...]) -> tuple[RenderPointPacket, ...]:
|
||||
muted: list[RenderPointPacket] = []
|
||||
for point in points:
|
||||
confidence = max(0.0, min(1.0, float(point.confidence)))
|
||||
muted.append(
|
||||
RenderPointPacket(
|
||||
stable_key=point.stable_key,
|
||||
xyz=point.xyz,
|
||||
radius_m=point.radius_m * 0.72,
|
||||
color_rgba=(0.46, 0.58, 0.72, 0.18 * confidence),
|
||||
confidence=confidence * 0.72,
|
||||
source_timestamp_ns=point.source_timestamp_ns,
|
||||
)
|
||||
)
|
||||
return tuple(muted)
|
||||
|
||||
|
||||
class RgbSplatSampler:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
api: str,
|
||||
primary_index: int,
|
||||
secondary_index: int,
|
||||
width: int,
|
||||
height: int,
|
||||
sample_step: int,
|
||||
room_step: int,
|
||||
dense_step: int,
|
||||
enable_cpu_dense_stereo: bool,
|
||||
adaptive_controls: bool,
|
||||
fallback_dir: Path,
|
||||
reservoir_ns: int = DEFAULT_RESERVOIR_NS,
|
||||
fallback_only: bool = False,
|
||||
) -> None:
|
||||
self.api = api
|
||||
self.primary_index = primary_index
|
||||
self.secondary_index = secondary_index
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.sample_step = max(4, int(sample_step))
|
||||
self.room_step = max(self.sample_step, int(room_step))
|
||||
self.dense_step = max(1, int(dense_step))
|
||||
self.enable_cpu_dense_stereo = enable_cpu_dense_stereo
|
||||
self.adaptive_controls = adaptive_controls
|
||||
self.fallback_dir = fallback_dir
|
||||
self.fallback_only = bool(fallback_only)
|
||||
self._captures: dict[int, object] = {}
|
||||
self._pumps: dict[int, LatestFramePump] = {}
|
||||
self._frames: dict[int, np.ndarray] = {}
|
||||
self._timestamped_frames: dict[str, TimestampedFrame] = {}
|
||||
self._history = TimestampedFrameHistory(max_frames=720, max_age_ns=reservoir_ns)
|
||||
self._controllers: dict[int, AdaptiveCameraController] = {}
|
||||
self._setting_ports: dict[int, OpenCvCameraSettingPort] = {}
|
||||
|
||||
def close(self) -> None:
|
||||
for capture in self._captures.values():
|
||||
try:
|
||||
capture.release()
|
||||
except Exception:
|
||||
pass
|
||||
self._captures.clear()
|
||||
|
||||
def splats(self, now_s: float, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
primary = self._read_frame(self.primary_index)
|
||||
secondary = self._read_frame(self.secondary_index)
|
||||
return self._splats_from_frames(primary, secondary, now_s, timestamp_ns)
|
||||
|
||||
def synced_splats(
|
||||
self,
|
||||
now_s: float,
|
||||
timestamp_ns: int,
|
||||
*,
|
||||
sync_model: CameraClockSyncModel,
|
||||
oracle_time_ns: int,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
self._read_frame(self.primary_index)
|
||||
self._read_frame(self.secondary_index)
|
||||
primary = self._history.nearest("kiyo-primary", sync_model.raw_time_for_oracle("kiyo-primary", oracle_time_ns))
|
||||
secondary = self._history.nearest("kiyo-secondary", sync_model.raw_time_for_oracle("kiyo-secondary", oracle_time_ns))
|
||||
return self._splats_from_frames(
|
||||
None if primary is None else primary.image,
|
||||
None if secondary is None else secondary.image,
|
||||
now_s,
|
||||
timestamp_ns,
|
||||
)
|
||||
|
||||
def _splats_from_frames(
|
||||
self,
|
||||
primary: np.ndarray | None,
|
||||
secondary: np.ndarray | None,
|
||||
now_s: float,
|
||||
timestamp_ns: int,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
points: list[RenderPointPacket] = []
|
||||
if self.enable_cpu_dense_stereo and primary is not None and secondary is not None:
|
||||
points.extend(rgb_dense_stereo_splats(primary, secondary, timestamp_ns, step=self.dense_step))
|
||||
if primary is not None:
|
||||
points.extend(rgb_room_splats("room-rgb:primary", primary, np.array([-0.42, 0.05, 0.0]), timestamp_ns, step=self.room_step))
|
||||
if not points:
|
||||
points.extend(rgb_body_splats("host-rgb", primary, np.array([-0.42, 0.05, 0.0]), now_s, timestamp_ns, side=-1.0, step=self.sample_step))
|
||||
if secondary is not None:
|
||||
points.extend(rgb_room_splats("room-rgb:secondary", secondary, np.array([0.48, 0.28, 0.0]), timestamp_ns, step=self.room_step))
|
||||
if not points:
|
||||
points.extend(rgb_body_splats("deru-rgb", secondary, np.array([0.48, 0.28, 0.0]), now_s + 0.6, timestamp_ns, side=1.0, step=self.sample_step))
|
||||
return tuple(points)
|
||||
|
||||
def latest_timestamped_frames(self) -> dict[str, TimestampedFrame]:
|
||||
return dict(self._timestamped_frames)
|
||||
|
||||
def _read_frame(self, index: int) -> np.ndarray | None:
|
||||
if self.fallback_only:
|
||||
return self._fallback_frame(index)
|
||||
pump = self._pumps.get(index)
|
||||
if pump is None:
|
||||
sensor_id = self._sensor_id(index)
|
||||
pump = LatestFramePump(
|
||||
lambda sensor_id=sensor_id, index=index: OpenCvFrameSource(
|
||||
OpenCvCaptureConfig(sensor_id=sensor_id, index=index, api=self.api, width=self.width, height=self.height)
|
||||
)
|
||||
)
|
||||
pump.start()
|
||||
self._pumps[index] = pump
|
||||
packet = pump.latest(max_age_ns=DEFAULT_RESERVOIR_NS)
|
||||
if packet is not None:
|
||||
frame = packet.image_bgr
|
||||
stamped = TimestampedFrame(packet.sensor_id, packet.timestamp_ns, frame.copy())
|
||||
self._timestamped_frames[packet.sensor_id] = stamped
|
||||
self._history.add(stamped)
|
||||
self._tune_capture(index, frame)
|
||||
self._frames[index] = frame
|
||||
return frame
|
||||
cached = self._frames.get(index)
|
||||
if cached is not None:
|
||||
return cached
|
||||
return self._fallback_frame(index)
|
||||
|
||||
def _tune_capture(self, index: int, frame: np.ndarray) -> None:
|
||||
controller = self._controllers.get(index)
|
||||
port = self._setting_ports.get(index)
|
||||
if controller is None or port is None:
|
||||
return
|
||||
command = controller.update(measure_frame_quality(frame))
|
||||
port.apply(command)
|
||||
|
||||
def _fallback_frame(self, index: int) -> np.ndarray | None:
|
||||
import cv2
|
||||
|
||||
candidates = [
|
||||
self.fallback_dir / f"rgb-probe-{self.api}-{index}.png",
|
||||
self.fallback_dir / f"rgb-probe-dshow-{index}.png",
|
||||
self.fallback_dir / f"rgb-probe-any-{index}.png",
|
||||
self.fallback_dir / f"rgb-probe-msmf-{index}.png",
|
||||
]
|
||||
for path in candidates:
|
||||
if path.exists():
|
||||
frame = cv2.imread(str(path))
|
||||
if frame is not None:
|
||||
sensor_id = self._sensor_id(index)
|
||||
stamped = TimestampedFrame(sensor_id, time.monotonic_ns(), frame.copy())
|
||||
self._timestamped_frames[sensor_id] = stamped
|
||||
self._history.add(stamped)
|
||||
return frame
|
||||
return None
|
||||
|
||||
def _sensor_id(self, index: int) -> str:
|
||||
if index == self.primary_index:
|
||||
return "kiyo-primary"
|
||||
if index == self.secondary_index:
|
||||
return "kiyo-secondary"
|
||||
return f"rgb-{index}"
|
||||
|
||||
|
||||
def cv2_api(name: str) -> int:
|
||||
import cv2
|
||||
|
||||
return {
|
||||
"any": 0,
|
||||
"dshow": cv2.CAP_DSHOW,
|
||||
"msmf": cv2.CAP_MSMF,
|
||||
}[name]
|
||||
|
||||
|
||||
class LiveChirpPoseMapper:
|
||||
def __init__(self, *, phase_cache: Path, audio_profile: Path | None = None) -> None:
|
||||
self.phase_cache = phase_cache
|
||||
self.camera_mics = None
|
||||
self.speakers = None
|
||||
if audio_profile is not None and audio_profile.exists():
|
||||
loaded_mics = camera_mic_geometry_from_audio_profile(audio_profile)
|
||||
loaded_speakers = speaker_geometry_from_audio_profile(audio_profile)
|
||||
self.camera_mics = loaded_mics or None
|
||||
self.speakers = loaded_speakers or None
|
||||
self.last_frame_id: int | None = None
|
||||
self.constraints: tuple[CameraChirpPoseConstraint, ...] = ()
|
||||
|
||||
def update(self, fallback_timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
if not self.phase_cache.exists():
|
||||
return self._constraint_points(fallback_timestamp_ns)
|
||||
field = get_live_audio_phase_field(self.phase_cache)
|
||||
if field is None:
|
||||
return self._constraint_points(fallback_timestamp_ns)
|
||||
if field.frame_id != self.last_frame_id:
|
||||
self.last_frame_id = field.frame_id
|
||||
self.constraints = constraints_from_phase_sources(
|
||||
field.sources,
|
||||
audio_time_ns=field.audio_time_ns,
|
||||
camera_mics=self.camera_mics,
|
||||
speakers=self.speakers,
|
||||
)
|
||||
return self._constraint_points(field.audio_time_ns)
|
||||
|
||||
def _constraint_points(self, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
points: list[RenderPointPacket] = []
|
||||
for constraint in self.constraints:
|
||||
points.extend(chirp_pose_constraint_points(constraint, timestamp_ns))
|
||||
for estimate in estimate_pose_corrections(self.constraints):
|
||||
points.extend(chirp_pose_correction_points(estimate, timestamp_ns))
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def chirp_pose_constraint_points(
|
||||
constraint: CameraChirpPoseConstraint,
|
||||
timestamp_ns: int,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
residual = float(constraint.range_residual_m)
|
||||
confidence = max(0.0, min(1.0, float(constraint.confidence)))
|
||||
camera = np.asarray(constraint.camera_position_m, dtype=np.float64)
|
||||
speaker = np.asarray(constraint.speaker_position_m, dtype=np.float64)
|
||||
direction = camera - speaker
|
||||
norm = float(np.linalg.norm(direction))
|
||||
if norm <= 1.0e-9:
|
||||
direction = np.array([0.0, 0.0, 1.0], dtype=np.float64)
|
||||
norm = 1.0
|
||||
unit = direction / norm
|
||||
corrected = speaker + unit * float(constraint.observed_range_m)
|
||||
midpoint = speaker + unit * (0.5 * (float(constraint.nominal_range_m) + float(constraint.observed_range_m)))
|
||||
residual_strength = min(1.0, abs(residual) / 0.25)
|
||||
return (
|
||||
render_point(
|
||||
f"{constraint.stable_key}:body",
|
||||
corrected,
|
||||
0.030 + 0.045 * residual_strength,
|
||||
(0.95, 0.78, 0.24, 0.38 + 0.42 * confidence),
|
||||
confidence,
|
||||
timestamp_ns,
|
||||
),
|
||||
render_point(
|
||||
f"{constraint.stable_key}:range",
|
||||
midpoint,
|
||||
0.012 + 0.030 * residual_strength,
|
||||
(1.0, 0.55, 0.18, 0.22 + 0.36 * confidence),
|
||||
confidence * 0.85,
|
||||
timestamp_ns,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def chirp_pose_correction_points(estimate, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
confidence = max(0.0, min(1.0, float(estimate.confidence)))
|
||||
start = np.asarray(estimate.position_m, dtype=np.float64)
|
||||
correction = np.asarray(estimate.correction_m, dtype=np.float64)
|
||||
end = start + correction
|
||||
magnitude = float(np.linalg.norm(correction))
|
||||
strength = min(1.0, magnitude / 0.25)
|
||||
alpha = 0.22 + 0.55 * strength * confidence
|
||||
return (
|
||||
render_point(
|
||||
f"camera-pose-correction:{estimate.sensor_id}:origin",
|
||||
start,
|
||||
0.022 + 0.045 * strength,
|
||||
(0.35, 0.78, 1.0, alpha),
|
||||
confidence,
|
||||
timestamp_ns,
|
||||
),
|
||||
render_point(
|
||||
f"camera-pose-correction:{estimate.sensor_id}:target",
|
||||
end,
|
||||
0.028 + 0.055 * strength,
|
||||
(1.0, 0.90, 0.30, alpha),
|
||||
confidence,
|
||||
timestamp_ns,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class LeapPackedMotionSampler:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
api: str,
|
||||
index: int,
|
||||
width: int,
|
||||
height: int,
|
||||
fps: float,
|
||||
step: int,
|
||||
fallback_dir: Path,
|
||||
fallback_only: bool = False,
|
||||
) -> None:
|
||||
self.api = api
|
||||
self.index = index
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.fps = fps
|
||||
self.step = max(4, int(step))
|
||||
self.fallback_dir = fallback_dir
|
||||
self.fallback_only = bool(fallback_only)
|
||||
self._capture = None
|
||||
self._pump: LatestFramePump | None = None
|
||||
self._previous_channels: dict[str, np.ndarray] = {}
|
||||
self._last_timestamp_ns: int | None = None
|
||||
self._last_frame_kind: str | None = None
|
||||
self._latest_timestamped_frame: TimestampedFrame | None = None
|
||||
self._fallback_index = 0
|
||||
|
||||
@property
|
||||
def last_timestamp_ns(self) -> int | None:
|
||||
return self._last_timestamp_ns
|
||||
|
||||
@property
|
||||
def last_frame_kind(self) -> str | None:
|
||||
return self._last_frame_kind
|
||||
|
||||
def latest_timestamped_frames(self) -> dict[str, TimestampedFrame]:
|
||||
if self._latest_timestamped_frame is None:
|
||||
return {}
|
||||
return {self._latest_timestamped_frame.sensor_id: self._latest_timestamped_frame}
|
||||
|
||||
def close(self) -> None:
|
||||
if self._capture is not None:
|
||||
try:
|
||||
self._capture.release()
|
||||
except Exception:
|
||||
pass
|
||||
self._capture = None
|
||||
|
||||
def motion_splats(self, timestamp_ns: int) -> tuple[RenderPointPacket, ...]:
|
||||
frame = self._read_frame()
|
||||
if frame is None:
|
||||
return ()
|
||||
self._last_timestamp_ns = time.monotonic_ns()
|
||||
self._latest_timestamped_frame = TimestampedFrame("leap", self._last_timestamp_ns, frame.copy())
|
||||
channels = unpack_leap_packed_channels(frame)
|
||||
points: list[RenderPointPacket] = []
|
||||
for channel_name, channel in channels.items():
|
||||
previous = self._previous_channels.get(channel_name)
|
||||
self._previous_channels[channel_name] = channel
|
||||
if previous is None or previous.shape != channel.shape:
|
||||
continue
|
||||
points.extend(leap_channel_motion_points(channel_name, channel, previous, self._last_timestamp_ns or timestamp_ns, step=self.step))
|
||||
return tuple(points)
|
||||
|
||||
def _read_frame(self) -> np.ndarray | None:
|
||||
if self.fallback_only:
|
||||
return self._fallback_frame()
|
||||
if self._pump is None:
|
||||
self._pump = LatestFramePump(
|
||||
lambda: OpenCvFrameSource(
|
||||
OpenCvCaptureConfig(
|
||||
sensor_id="leap",
|
||||
index=self.index,
|
||||
api=self.api,
|
||||
width=self.width,
|
||||
height=self.height,
|
||||
fps=self.fps,
|
||||
)
|
||||
)
|
||||
)
|
||||
self._pump.start()
|
||||
packet = self._pump.latest(max_age_ns=DEFAULT_RESERVOIR_NS)
|
||||
if packet is not None:
|
||||
self._last_frame_kind = "capture"
|
||||
return packet.image_bgr
|
||||
return self._fallback_frame()
|
||||
|
||||
def _fallback_frame(self) -> np.ndarray | None:
|
||||
import cv2
|
||||
|
||||
path = self.fallback_dir / "leap-probe.png"
|
||||
if path.exists():
|
||||
frame = cv2.imread(str(path))
|
||||
if frame is not None:
|
||||
self._last_frame_kind = "fallback-file"
|
||||
return frame
|
||||
return self._synthetic_motion_frame()
|
||||
|
||||
def _synthetic_motion_frame(self) -> np.ndarray:
|
||||
self._last_frame_kind = "fallback-synthetic"
|
||||
frame = np.zeros((self.height, self.width, 3), dtype=np.uint8)
|
||||
t = self._fallback_index
|
||||
self._fallback_index += 1
|
||||
cx = int((self.width * 0.30) + (self.width * 0.40) * ((np.sin(t * 0.37) + 1.0) * 0.5))
|
||||
cy = int((self.height * 0.30) + (self.height * 0.34) * ((np.cos(t * 0.41) + 1.0) * 0.5))
|
||||
y0 = max(0, cy - 4)
|
||||
y1 = min(self.height, cy + 5)
|
||||
x0 = max(0, cx - 4)
|
||||
x1 = min(self.width, cx + 5)
|
||||
frame[y0:y1, x0:x1, 1] = 220
|
||||
frame[max(0, y0 - 8) : min(self.height, y1 + 8), max(0, x0 - 8) : min(self.width, x1 + 8), 2] = 80
|
||||
frame[max(0, y0 - 12) : min(self.height, y1 + 12), max(0, x0 - 12) : min(self.width, x1 + 12), 0] = 55
|
||||
return frame
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Diagnostic replay of sensor-fusion render frames into typed CultCache state.")
|
||||
parser.add_argument("--cache", default=str(ROOT / "calibration" / "runs" / "visual-state.msgpack"))
|
||||
parser.add_argument("--fps", type=float, default=30.0)
|
||||
parser.add_argument("--points", type=int, default=256)
|
||||
parser.add_argument("--duration", type=float)
|
||||
parser.add_argument("--no-rgb", action="store_true")
|
||||
parser.add_argument("--rgb-api", choices=["any", "dshow", "msmf"], default="dshow")
|
||||
parser.add_argument("--rgb-fallback-only", action="store_true")
|
||||
parser.add_argument("--rgb-primary-index", type=int, default=1)
|
||||
parser.add_argument("--rgb-secondary-index", type=int, default=3)
|
||||
parser.add_argument("--rgb-width", type=int, default=640)
|
||||
parser.add_argument("--rgb-height", type=int, default=480)
|
||||
parser.add_argument("--rgb-sample-step", type=int, default=10)
|
||||
parser.add_argument("--rgb-room-step", type=int, default=28)
|
||||
parser.add_argument("--cpu-dense-stereo", action="store_true", help="Debug-only CPU stereo matcher. Production dense fusion belongs on the GPU.")
|
||||
parser.add_argument("--rgb-dense-step", type=int, default=16)
|
||||
parser.add_argument("--no-adaptive-camera-controls", action="store_true")
|
||||
parser.add_argument("--no-leap", action="store_true")
|
||||
parser.add_argument("--leap-api", choices=["any", "dshow", "msmf"], default="msmf")
|
||||
parser.add_argument("--leap-fallback-only", action="store_true")
|
||||
parser.add_argument("--leap-index", type=int, default=0)
|
||||
parser.add_argument("--leap-width", type=int, default=320)
|
||||
parser.add_argument("--leap-height", type=int, default=240)
|
||||
parser.add_argument("--leap-fps", type=float, default=120.0)
|
||||
parser.add_argument("--leap-step", type=int, default=12)
|
||||
parser.add_argument("--lod-cache", default=str(ROOT / "calibration" / "runs" / "visual-lod-cache.json"))
|
||||
parser.add_argument("--audio-cache", default=str(ROOT / "calibration" / "runs" / "audio-state.msgpack"))
|
||||
parser.add_argument("--phase-cache", default=str(ROOT / "calibration" / "runs" / "audio-phase-field.msgpack"))
|
||||
parser.add_argument("--audio-profile", default=str(ROOT / "config" / "audio-field.json"))
|
||||
parser.add_argument("--clap-cache", default=str(ROOT / "calibration" / "runs" / "clap-events.msgpack"))
|
||||
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=reservoir_ns),
|
||||
)
|
||||
render_config = RenderBridgeConfig(default_point_radius_m=0.035)
|
||||
interval = 1.0 / max(1.0, args.fps)
|
||||
start = time.monotonic()
|
||||
frame_id = 0
|
||||
cache_path = Path(args.cache)
|
||||
lod_cache_path = Path(args.lod_cache)
|
||||
lock = acquire_runtime_lock(cache_path.with_suffix(".producer.lock"))
|
||||
if lock is None:
|
||||
return
|
||||
rgb_sampler = None if args.no_rgb else RgbSplatSampler(
|
||||
api=args.rgb_api,
|
||||
primary_index=args.rgb_primary_index,
|
||||
secondary_index=args.rgb_secondary_index,
|
||||
width=args.rgb_width,
|
||||
height=args.rgb_height,
|
||||
sample_step=args.rgb_sample_step,
|
||||
room_step=args.rgb_room_step,
|
||||
dense_step=args.rgb_dense_step,
|
||||
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,
|
||||
fallback_only=args.rgb_fallback_only,
|
||||
)
|
||||
leap_sampler = None if args.no_leap else LeapPackedMotionSampler(
|
||||
api=args.leap_api,
|
||||
index=args.leap_index,
|
||||
width=args.leap_width,
|
||||
height=args.leap_height,
|
||||
fps=args.leap_fps,
|
||||
step=args.leap_step,
|
||||
fallback_dir=ROOT / "calibration" / "runs",
|
||||
fallback_only=args.leap_fallback_only,
|
||||
)
|
||||
clap_calibrator = None if args.no_clap_calibration else LiveClapCalibrator(
|
||||
audio_cache=Path(args.audio_cache),
|
||||
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":
|
||||
example_profile = audio_profile.with_name("audio-field.example.json")
|
||||
audio_profile = example_profile if example_profile.exists() else audio_profile
|
||||
chirp_pose_mapper = None if args.no_chirp_pose else LiveChirpPoseMapper(
|
||||
phase_cache=Path(args.phase_cache),
|
||||
audio_profile=audio_profile if audio_profile.exists() else None,
|
||||
)
|
||||
try:
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
if args.duration is not None and now - start >= args.duration:
|
||||
break
|
||||
observations = synthetic_observations(rig, now, args.points)
|
||||
result = rig.fuse(observations)
|
||||
transient_matches = () if args.no_stochastic_transients else stochastic_transient_matches(
|
||||
stochastic_surface_observations(observations),
|
||||
rig.cameras,
|
||||
max_descriptor_distance=0.0,
|
||||
max_reprojection_error_px=0.05,
|
||||
samples_per_observation=2,
|
||||
seed=frame_id,
|
||||
)
|
||||
frame = lower_points_to_render_frame(
|
||||
result.points,
|
||||
render_config,
|
||||
frame_id=frame_id,
|
||||
created_monotonic_ns=time.monotonic_ns(),
|
||||
)
|
||||
timestamp_ns = frame.source_time_max_ns
|
||||
leap_points = () if leap_sampler is None else leap_sampler.motion_splats(timestamp_ns)
|
||||
if clap_calibrator is not None:
|
||||
if rgb_sampler is not None:
|
||||
clap_calibrator.observe_frames(rgb_sampler.latest_timestamped_frames())
|
||||
if leap_sampler is not None:
|
||||
clap_calibrator.observe_frames(leap_sampler.latest_timestamped_frames())
|
||||
if leap_sampler is not None and leap_sampler.last_timestamp_ns is not None:
|
||||
timestamp_ns = max(timestamp_ns, leap_sampler.last_timestamp_ns)
|
||||
audio_edge_ns = latest_audio_time_ns(Path(args.audio_cache))
|
||||
reservoir_edge_ns = max(timestamp_ns, audio_edge_ns if audio_edge_ns is not None else timestamp_ns)
|
||||
leap_source_kind = (
|
||||
"leap-ground-truth"
|
||||
if leap_sampler is not None and leap_sampler.last_frame_kind == "capture"
|
||||
else "leap-fallback"
|
||||
)
|
||||
leap_source_priority = 3.0 if leap_source_kind == "leap-ground-truth" else 1.1
|
||||
rgb_points = ()
|
||||
if rgb_sampler is not None:
|
||||
if clap_calibrator is not None and clap_calibrator.sync_model.estimates():
|
||||
rgb_points = rgb_sampler.synced_splats(
|
||||
now,
|
||||
timestamp_ns,
|
||||
sync_model=clap_calibrator.sync_model,
|
||||
oracle_time_ns=clap_calibrator.oracle_time_ns(timestamp_ns),
|
||||
)
|
||||
else:
|
||||
rgb_points = rgb_sampler.splats(now, timestamp_ns)
|
||||
support_points = dim_fusion_points(tuple(frame.points)) if not rgb_points else ()
|
||||
stochastic_points = transient_match_render_points(transient_matches, timestamp_ns)
|
||||
clap_points = () if clap_calibrator is None else clap_calibrator.update(reservoir_edge_ns)
|
||||
chirp_pose_points = () if chirp_pose_mapper is None else chirp_pose_mapper.update(reservoir_edge_ns)
|
||||
render_points = render_points_in_reservoir(
|
||||
clap_points + chirp_pose_points + leap_points + rgb_points + stochastic_points + support_points,
|
||||
latest_timestamp_ns=reservoir_edge_ns,
|
||||
reservoir_ns=reservoir_ns,
|
||||
)
|
||||
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=reservoir_edge_ns,
|
||||
reservoir_ns=reservoir_ns,
|
||||
)
|
||||
source_time_min_ns, source_time_max_ns = reservoir_window_ns(reservoir_edge_ns, reservoir_ns)
|
||||
lod_cache = multilod_cache_from_evidence(
|
||||
evidence,
|
||||
levels=(0.01, 0.04, 0.16, 0.64),
|
||||
created_monotonic_ns=time.monotonic_ns(),
|
||||
)
|
||||
write_lod_cache_json(lod_cache_path, lod_cache)
|
||||
frame = RenderFramePacket(
|
||||
schema=frame.schema,
|
||||
frame_id=frame.frame_id,
|
||||
created_monotonic_ns=frame.created_monotonic_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,
|
||||
target_width=frame.target_width,
|
||||
target_height=frame.target_height,
|
||||
points=render_points,
|
||||
)
|
||||
put_live_render_frame(cache_path, frame)
|
||||
frame_id += 1
|
||||
sleep_for = interval - (time.monotonic() - now)
|
||||
if sleep_for > 0:
|
||||
time.sleep(sleep_for)
|
||||
finally:
|
||||
if rgb_sampler is not None:
|
||||
rgb_sampler.close()
|
||||
if leap_sampler is not None:
|
||||
leap_sampler.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,270 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
from statistics import median
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
NS_PER_MS = 1_000_000
|
||||
NS_PER_SECOND = 1_000_000_000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EndpointPlan:
|
||||
name: str
|
||||
kind: str
|
||||
port: int
|
||||
listener_url: str
|
||||
expected_latency_ms: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SmokeEvent:
|
||||
endpoint: str
|
||||
stage: str
|
||||
monotonic_ns: int
|
||||
wall_time_ns: int | None = None
|
||||
media_time_ns: int | None = None
|
||||
event_id: str | None = None
|
||||
confidence: float = 1.0
|
||||
note: str = ""
|
||||
|
||||
|
||||
def load_config_endpoints(config_path: Path) -> list[EndpointPlan]:
|
||||
config = json.loads(config_path.read_text(encoding="utf-8-sig"))
|
||||
receiver = config.get("receiver", {})
|
||||
base_port = int(receiver.get("basePort", 5100))
|
||||
expected_latency_ms = float(receiver.get("srtLatencyMicros", 120000)) / 1000.0
|
||||
passphrase = str(receiver.get("passphrase", "") or "")
|
||||
secret_suffix = "&passphrase=SET&pbkeylen=16" if passphrase else ""
|
||||
|
||||
endpoints: list[EndpointPlan] = []
|
||||
video = config.get("video") or {}
|
||||
if video.get("enabled", False):
|
||||
port = base_port + int(video.get("portOffset", 0))
|
||||
endpoints.append(
|
||||
EndpointPlan(
|
||||
name="video",
|
||||
kind="video",
|
||||
port=port,
|
||||
listener_url=f"srt://0.0.0.0:{port}?mode=listener&latency={int(expected_latency_ms * 1000)}&timeout=5000000{secret_suffix}",
|
||||
expected_latency_ms=expected_latency_ms,
|
||||
)
|
||||
)
|
||||
|
||||
for audio in config.get("audioSources", []) or []:
|
||||
name = str(audio.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
port = base_port + int(audio.get("portOffset", 0))
|
||||
endpoints.append(
|
||||
EndpointPlan(
|
||||
name=f"audio-{name}",
|
||||
kind="audio",
|
||||
port=port,
|
||||
listener_url=f"srt://0.0.0.0:{port}?mode=listener&latency={int(expected_latency_ms * 1000)}&timeout=5000000{secret_suffix}",
|
||||
expected_latency_ms=expected_latency_ms,
|
||||
)
|
||||
)
|
||||
return endpoints
|
||||
|
||||
|
||||
def event_from_json(raw: dict[str, Any]) -> SmokeEvent:
|
||||
return SmokeEvent(
|
||||
endpoint=str(raw["endpoint"]),
|
||||
stage=str(raw["stage"]),
|
||||
monotonic_ns=int(raw["monotonicNs"]),
|
||||
wall_time_ns=None if raw.get("wallTimeNs") is None else int(raw["wallTimeNs"]),
|
||||
media_time_ns=None if raw.get("mediaTimeNs") is None else int(raw["mediaTimeNs"]),
|
||||
event_id=None if raw.get("eventId") is None else str(raw["eventId"]),
|
||||
confidence=float(raw.get("confidence", 1.0)),
|
||||
note=str(raw.get("note", "")),
|
||||
)
|
||||
|
||||
|
||||
def read_events_jsonl(path: Path) -> list[SmokeEvent]:
|
||||
events: list[SmokeEvent] = []
|
||||
for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
events.append(event_from_json(json.loads(line)))
|
||||
except Exception as exc: # pragma: no cover - message quality path
|
||||
raise ValueError(f"{path}:{line_number}: invalid smoke event: {exc}") from exc
|
||||
return events
|
||||
|
||||
|
||||
def write_event_template(path: Path, endpoints: Iterable[EndpointPlan]) -> None:
|
||||
rows: list[dict[str, Any]] = []
|
||||
base = 1_000_000_000_000
|
||||
for index, endpoint in enumerate(endpoints):
|
||||
event_id = f"{endpoint.name}-flash-001" if endpoint.kind == "video" else f"{endpoint.name}-chirp-001"
|
||||
start = base + index * 10 * NS_PER_SECOND
|
||||
rows.extend(
|
||||
[
|
||||
{
|
||||
"endpoint": endpoint.name,
|
||||
"stage": "sender_capture",
|
||||
"eventId": event_id,
|
||||
"monotonicNs": start,
|
||||
"wallTimeNs": None,
|
||||
"mediaTimeNs": 0,
|
||||
"confidence": 1.0,
|
||||
"note": "Replace with sender-side flash/chirp capture timestamp.",
|
||||
},
|
||||
{
|
||||
"endpoint": endpoint.name,
|
||||
"stage": "srt_receive",
|
||||
"eventId": event_id,
|
||||
"monotonicNs": start + int(endpoint.expected_latency_ms * NS_PER_MS),
|
||||
"wallTimeNs": None,
|
||||
"mediaTimeNs": int(endpoint.expected_latency_ms * NS_PER_MS),
|
||||
"confidence": 0.8,
|
||||
"note": "Replace with first packet or probe observation at receiver.",
|
||||
},
|
||||
{
|
||||
"endpoint": endpoint.name,
|
||||
"stage": "obs_present",
|
||||
"eventId": event_id,
|
||||
"monotonicNs": start + int(endpoint.expected_latency_ms * NS_PER_MS * 1.5),
|
||||
"wallTimeNs": None,
|
||||
"mediaTimeNs": int(endpoint.expected_latency_ms * NS_PER_MS),
|
||||
"confidence": 0.8,
|
||||
"note": "Replace with OBS recording/preview observation.",
|
||||
},
|
||||
]
|
||||
)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8")
|
||||
|
||||
|
||||
def summarize_events(
|
||||
endpoints: Iterable[EndpointPlan],
|
||||
events: Iterable[SmokeEvent],
|
||||
*,
|
||||
max_abs_drift_ppm: float = 100.0,
|
||||
max_latency_ms: float = 500.0,
|
||||
) -> dict[str, Any]:
|
||||
endpoint_plans = {endpoint.name: endpoint for endpoint in endpoints}
|
||||
events_by_endpoint: dict[str, list[SmokeEvent]] = {name: [] for name in endpoint_plans}
|
||||
for event in events:
|
||||
events_by_endpoint.setdefault(event.endpoint, []).append(event)
|
||||
|
||||
summaries = []
|
||||
for name, endpoint in endpoint_plans.items():
|
||||
rows = sorted(events_by_endpoint.get(name, []), key=lambda item: item.monotonic_ns)
|
||||
stages = sorted({row.stage for row in rows})
|
||||
latencies_ms = _matched_latencies_ms(rows)
|
||||
drift_ppm = _endpoint_drift_ppm(rows)
|
||||
confidence = _endpoint_confidence(
|
||||
rows,
|
||||
latencies_ms=latencies_ms,
|
||||
drift_ppm=drift_ppm,
|
||||
max_abs_drift_ppm=max_abs_drift_ppm,
|
||||
max_latency_ms=max_latency_ms,
|
||||
)
|
||||
status = "ok" if confidence >= 0.8 else "suspect" if confidence >= 0.5 else "fail"
|
||||
summaries.append(
|
||||
{
|
||||
"endpoint": name,
|
||||
"kind": endpoint.kind,
|
||||
"port": endpoint.port,
|
||||
"listenerUrl": endpoint.listener_url,
|
||||
"expectedLatencyMs": endpoint.expected_latency_ms,
|
||||
"observedStages": stages,
|
||||
"eventCount": len(rows),
|
||||
"endToEndLatencyMs": _latency_summary(latencies_ms),
|
||||
"endpointDriftPpm": drift_ppm,
|
||||
"confidence": round(confidence, 3),
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
|
||||
overall_confidence = min((item["confidence"] for item in summaries), default=0.0)
|
||||
failed = [item["endpoint"] for item in summaries if item["status"] != "ok"]
|
||||
return {
|
||||
"schema": "gamecult.localcast.obs_v1_smoke_ledger.v1",
|
||||
"createdWallTime": datetime.now(timezone.utc).isoformat(),
|
||||
"gate": {
|
||||
"pluginOrNativeReceiverExpansionAllowed": not failed,
|
||||
"reason": "Every planned OBS-facing endpoint must have sender_capture, srt_receive, and obs_present evidence with bounded latency and drift.",
|
||||
},
|
||||
"thresholds": {
|
||||
"maxAbsDriftPpm": max_abs_drift_ppm,
|
||||
"maxLatencyMs": max_latency_ms,
|
||||
"requiredStages": ["sender_capture", "srt_receive", "obs_present"],
|
||||
},
|
||||
"endpoints": summaries,
|
||||
"overallConfidence": round(overall_confidence, 3),
|
||||
"status": "ok" if not failed and summaries else "fail",
|
||||
"blockedEndpoints": failed,
|
||||
}
|
||||
|
||||
|
||||
def _matched_latencies_ms(events: list[SmokeEvent]) -> list[float]:
|
||||
by_id: dict[str, dict[str, SmokeEvent]] = {}
|
||||
for event in events:
|
||||
if not event.event_id:
|
||||
continue
|
||||
by_id.setdefault(event.event_id, {})[event.stage] = event
|
||||
latencies: list[float] = []
|
||||
for stages in by_id.values():
|
||||
sender = stages.get("sender_capture")
|
||||
observed = stages.get("obs_present")
|
||||
if sender is None or observed is None:
|
||||
continue
|
||||
latencies.append((observed.monotonic_ns - sender.monotonic_ns) / NS_PER_MS)
|
||||
return latencies
|
||||
|
||||
|
||||
def _endpoint_drift_ppm(events: list[SmokeEvent]) -> float | None:
|
||||
timed = [event for event in events if event.media_time_ns is not None and event.stage in {"srt_receive", "obs_present"}]
|
||||
timed.sort(key=lambda item: item.monotonic_ns)
|
||||
if len(timed) < 2:
|
||||
return None
|
||||
first = timed[0]
|
||||
last = timed[-1]
|
||||
wall_delta = last.monotonic_ns - first.monotonic_ns
|
||||
media_delta = int(last.media_time_ns) - int(first.media_time_ns)
|
||||
if wall_delta <= 0:
|
||||
return None
|
||||
return round(((media_delta - wall_delta) / wall_delta) * 1_000_000.0, 3)
|
||||
|
||||
|
||||
def _latency_summary(latencies_ms: list[float]) -> dict[str, float | int | None]:
|
||||
if not latencies_ms:
|
||||
return {"count": 0, "median": None, "min": None, "max": None}
|
||||
return {
|
||||
"count": len(latencies_ms),
|
||||
"median": round(median(latencies_ms), 3),
|
||||
"min": round(min(latencies_ms), 3),
|
||||
"max": round(max(latencies_ms), 3),
|
||||
}
|
||||
|
||||
|
||||
def _endpoint_confidence(
|
||||
events: list[SmokeEvent],
|
||||
*,
|
||||
latencies_ms: list[float],
|
||||
drift_ppm: float | None,
|
||||
max_abs_drift_ppm: float,
|
||||
max_latency_ms: float,
|
||||
) -> float:
|
||||
if not events:
|
||||
return 0.0
|
||||
stages = {event.stage for event in events}
|
||||
required = {"sender_capture", "srt_receive", "obs_present"}
|
||||
stage_score = len(stages & required) / len(required)
|
||||
event_score = min(1.0, len(events) / 6.0)
|
||||
observation_score = max(0.0, min(1.0, sum(max(0.0, min(1.0, event.confidence)) for event in events) / len(events)))
|
||||
latency_score = 0.0
|
||||
if latencies_ms:
|
||||
worst = max(latencies_ms)
|
||||
latency_score = max(0.0, min(1.0, 1.0 - (worst / max_latency_ms)))
|
||||
drift_score = 0.0
|
||||
if drift_ppm is not None:
|
||||
drift_score = max(0.0, min(1.0, 1.0 - (abs(drift_ppm) / max_abs_drift_ppm)))
|
||||
return max(0.0, min(1.0, stage_score * 0.35 + event_score * 0.15 + observation_score * 0.15 + latency_score * 0.2 + drift_score * 0.15))
|
||||
|
|
@ -1,158 +0,0 @@
|
|||
"""Sensor fusion spine for the Mimir spatial rig."""
|
||||
|
||||
from .core import (
|
||||
CameraModel,
|
||||
FusionConfig,
|
||||
FusionResult,
|
||||
Observation2D,
|
||||
PointCloud,
|
||||
SensorRig,
|
||||
TrackCache,
|
||||
TriangulatedPoint,
|
||||
load_fusion_config,
|
||||
)
|
||||
from .render_bridge import RenderBridgeConfig, RenderFramePacket, RenderPointPacket, lower_points_to_render_frame
|
||||
from .camera_control import (
|
||||
AdaptiveCameraController,
|
||||
CameraControlCommand,
|
||||
CameraControlState,
|
||||
CameraQualityTarget,
|
||||
FrameQuality,
|
||||
measure_frame_quality,
|
||||
)
|
||||
from .dense_stereo import DenseStereoConfig, dense_stereo_points
|
||||
from .calibration_space import (
|
||||
BoardObservation,
|
||||
BoardSpec,
|
||||
CameraIntrinsics,
|
||||
CameraPoseSolve,
|
||||
camera_models_to_config,
|
||||
solve_camera_pose_from_fixed_board,
|
||||
solve_common_space_from_fixed_board,
|
||||
)
|
||||
from .surface_features import (
|
||||
SurfaceFeatureObservation,
|
||||
SurfaceFeatureTrack,
|
||||
match_surface_features,
|
||||
orb_surface_observations,
|
||||
triangulate_surface_tracks,
|
||||
)
|
||||
from .stochastic_mapping import (
|
||||
ImageRayBiasMap,
|
||||
LODCell,
|
||||
LODEvidencePoint,
|
||||
MultiLODSceneCache,
|
||||
RayBiasSample,
|
||||
SceneRay,
|
||||
TransientMatchHypothesis,
|
||||
evidence_from_fusion_items,
|
||||
evidence_from_render_points,
|
||||
multilod_cache_from_points,
|
||||
multilod_cache_from_evidence,
|
||||
pixel_scene_ray,
|
||||
stochastic_transient_matches,
|
||||
)
|
||||
from .audio_overlay import AudioVisualSyncStatus, overlay_audio_events
|
||||
from .media_artifacts import RemoteVideoArtifact, remote_video_artifact_for_present_time
|
||||
from .clap_calibration import (
|
||||
AudioTransientCandidate,
|
||||
CameraClockSyncModel,
|
||||
CameraMotionPeak,
|
||||
CameraSyncEstimate,
|
||||
ClapCalibrationEvent,
|
||||
ClapDetectorConfig,
|
||||
TimestampedFrameHistory,
|
||||
TimestampedFrame,
|
||||
detect_audio_transients,
|
||||
detect_camera_motion_peaks,
|
||||
detect_clap_events,
|
||||
)
|
||||
from .chirp_pose import (
|
||||
CameraChirpPoseConstraint,
|
||||
CameraMicGeometry,
|
||||
CameraPoseCorrectionEstimate,
|
||||
SpeakerGeometry,
|
||||
camera_mic_geometry_from_audio_profile,
|
||||
camera_sensor_id_for_microphone,
|
||||
constraints_from_phase_sources,
|
||||
default_camera_mic_geometry,
|
||||
default_speaker_geometry,
|
||||
estimate_pose_corrections,
|
||||
phase_source_id_for_microphone,
|
||||
speaker_geometry_from_audio_profile,
|
||||
)
|
||||
__all__ = [
|
||||
"CameraModel",
|
||||
"CameraIntrinsics",
|
||||
"BoardObservation",
|
||||
"BoardSpec",
|
||||
"CameraPoseSolve",
|
||||
"FusionConfig",
|
||||
"FusionResult",
|
||||
"Observation2D",
|
||||
"PointCloud",
|
||||
"SensorRig",
|
||||
"TrackCache",
|
||||
"TriangulatedPoint",
|
||||
"load_fusion_config",
|
||||
"RenderBridgeConfig",
|
||||
"RenderFramePacket",
|
||||
"RenderPointPacket",
|
||||
"AdaptiveCameraController",
|
||||
"CameraControlCommand",
|
||||
"CameraControlState",
|
||||
"CameraQualityTarget",
|
||||
"DenseStereoConfig",
|
||||
"FrameQuality",
|
||||
"SurfaceFeatureObservation",
|
||||
"SurfaceFeatureTrack",
|
||||
"ImageRayBiasMap",
|
||||
"LODCell",
|
||||
"LODEvidencePoint",
|
||||
"MultiLODSceneCache",
|
||||
"RayBiasSample",
|
||||
"SceneRay",
|
||||
"TransientMatchHypothesis",
|
||||
"AudioVisualSyncStatus",
|
||||
"AudioTransientCandidate",
|
||||
"CameraMotionPeak",
|
||||
"CameraClockSyncModel",
|
||||
"CameraSyncEstimate",
|
||||
"CameraChirpPoseConstraint",
|
||||
"CameraMicGeometry",
|
||||
"CameraPoseCorrectionEstimate",
|
||||
"SpeakerGeometry",
|
||||
"camera_mic_geometry_from_audio_profile",
|
||||
"camera_sensor_id_for_microphone",
|
||||
"ClapCalibrationEvent",
|
||||
"ClapDetectorConfig",
|
||||
"TimestampedFrame",
|
||||
"TimestampedFrameHistory",
|
||||
"RemoteVideoArtifact",
|
||||
"lower_points_to_render_frame",
|
||||
"dense_stereo_points",
|
||||
"camera_models_to_config",
|
||||
"match_surface_features",
|
||||
"measure_frame_quality",
|
||||
"orb_surface_observations",
|
||||
"evidence_from_fusion_items",
|
||||
"evidence_from_render_points",
|
||||
"multilod_cache_from_points",
|
||||
"multilod_cache_from_evidence",
|
||||
"overlay_audio_events",
|
||||
"pixel_scene_ray",
|
||||
"stochastic_transient_matches",
|
||||
"detect_audio_transients",
|
||||
"detect_camera_motion_peaks",
|
||||
"detect_clap_events",
|
||||
"constraints_from_phase_sources",
|
||||
"default_camera_mic_geometry",
|
||||
"default_speaker_geometry",
|
||||
"estimate_pose_corrections",
|
||||
"phase_source_id_for_microphone",
|
||||
"speaker_geometry_from_audio_profile",
|
||||
"remote_video_artifact_for_present_time",
|
||||
"solve_camera_pose_from_fixed_board",
|
||||
"solve_common_space_from_fixed_board",
|
||||
"triangulate_surface_tracks",
|
||||
]
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import time
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class LightPort(Protocol):
|
||||
def set_white(self, *, brightness_percent: int, color_temp_percent: int) -> None:
|
||||
...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IlluminationPulse:
|
||||
pulse_index: int
|
||||
start_monotonic_ns: int
|
||||
bright_until_monotonic_ns: int
|
||||
settle_until_monotonic_ns: int
|
||||
brightness_percent: int
|
||||
color_temp_percent: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IlluminationPulsePlan:
|
||||
pulse_count: int = 6
|
||||
bright_ms: int = 90
|
||||
settle_ms: int = 210
|
||||
brightness_percent: int = 100
|
||||
idle_brightness_percent: int = 18
|
||||
color_temp_percent: int = 50
|
||||
|
||||
@property
|
||||
def period_ms(self) -> int:
|
||||
return self.bright_ms + self.settle_ms
|
||||
|
||||
|
||||
class ActiveIlluminationController:
|
||||
def __init__(self, light: LightPort, plan: IlluminationPulsePlan):
|
||||
self.light = light
|
||||
self.plan = plan
|
||||
|
||||
def run(self, *, sleep=time.sleep, clock_ns=time.monotonic_ns) -> tuple[IlluminationPulse, ...]:
|
||||
pulses: list[IlluminationPulse] = []
|
||||
try:
|
||||
for index in range(max(0, self.plan.pulse_count)):
|
||||
start = clock_ns()
|
||||
self.light.set_white(
|
||||
brightness_percent=self.plan.brightness_percent,
|
||||
color_temp_percent=self.plan.color_temp_percent,
|
||||
)
|
||||
bright_until = start + self.plan.bright_ms * 1_000_000
|
||||
sleep(max(0.0, self.plan.bright_ms / 1000.0))
|
||||
self.light.set_white(
|
||||
brightness_percent=self.plan.idle_brightness_percent,
|
||||
color_temp_percent=self.plan.color_temp_percent,
|
||||
)
|
||||
settle_until = bright_until + self.plan.settle_ms * 1_000_000
|
||||
pulses.append(
|
||||
IlluminationPulse(
|
||||
pulse_index=index,
|
||||
start_monotonic_ns=start,
|
||||
bright_until_monotonic_ns=bright_until,
|
||||
settle_until_monotonic_ns=settle_until,
|
||||
brightness_percent=self.plan.brightness_percent,
|
||||
color_temp_percent=self.plan.color_temp_percent,
|
||||
)
|
||||
)
|
||||
sleep(max(0.0, self.plan.settle_ms / 1000.0))
|
||||
finally:
|
||||
self.light.set_white(
|
||||
brightness_percent=self.plan.idle_brightness_percent,
|
||||
color_temp_percent=self.plan.color_temp_percent,
|
||||
)
|
||||
return tuple(pulses)
|
||||
|
||||
|
||||
class TinytuyaLightPort:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
device_id: str,
|
||||
address: str,
|
||||
local_key: str,
|
||||
version: str = "3.3",
|
||||
dps_power: str = "20",
|
||||
dps_brightness: str = "22",
|
||||
dps_color_temp: str = "23",
|
||||
) -> None:
|
||||
import tinytuya
|
||||
|
||||
self.device = tinytuya.BulbDevice(device_id, address, local_key)
|
||||
self.device.set_version(float(version))
|
||||
self.dps_power = dps_power
|
||||
self.dps_brightness = dps_brightness
|
||||
self.dps_color_temp = dps_color_temp
|
||||
|
||||
def set_white(self, *, brightness_percent: int, color_temp_percent: int) -> None:
|
||||
brightness = _clamp_percent(brightness_percent)
|
||||
color_temp = _clamp_percent(color_temp_percent)
|
||||
if hasattr(self.device, "turn_on"):
|
||||
self.device.turn_on()
|
||||
self._set_value(self.dps_power, True)
|
||||
self._set_value(self.dps_brightness, int(round(brightness * 10)))
|
||||
self._set_value(self.dps_color_temp, int(round(color_temp * 10)))
|
||||
|
||||
def _set_value(self, dps: str, value: object) -> None:
|
||||
if hasattr(self.device, "set_value"):
|
||||
self.device.set_value(dps, value)
|
||||
return
|
||||
raise RuntimeError("tinytuya device does not expose set_value")
|
||||
|
||||
|
||||
def _clamp_percent(value: int) -> int:
|
||||
return max(0, min(100, int(value)))
|
||||
|
|
@ -1,235 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from typing import BinaryIO, Callable, Iterator, Protocol
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class FrameSource(Protocol):
|
||||
def frames(self) -> Iterator["FramePacket"]:
|
||||
...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FramePacket:
|
||||
sensor_id: str
|
||||
timestamp_ns: int
|
||||
sequence: int
|
||||
image_bgr: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FfmpegRawVideoConfig:
|
||||
sensor_id: str
|
||||
ffmpeg_exe: str
|
||||
device_name: str
|
||||
width: int
|
||||
height: int
|
||||
fps: int
|
||||
pixel_format: str = "bgr24"
|
||||
|
||||
@property
|
||||
def frame_bytes(self) -> int:
|
||||
if self.pixel_format != "bgr24":
|
||||
raise ValueError(f"Unsupported raw pixel format: {self.pixel_format}")
|
||||
return self.width * self.height * 3
|
||||
|
||||
def command(self) -> list[str]:
|
||||
return [
|
||||
self.ffmpeg_exe,
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"warning",
|
||||
"-f",
|
||||
"dshow",
|
||||
"-video_size",
|
||||
f"{self.width}x{self.height}",
|
||||
"-framerate",
|
||||
str(self.fps),
|
||||
"-pixel_format",
|
||||
self.pixel_format,
|
||||
"-i",
|
||||
f"video={self.device_name}",
|
||||
"-an",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-",
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OpenCvCaptureConfig:
|
||||
sensor_id: str
|
||||
index: int
|
||||
api: str
|
||||
width: int
|
||||
height: int
|
||||
fps: float | None = None
|
||||
|
||||
|
||||
class OpenCvFrameSource:
|
||||
"""OpenCV camera source. Use behind LatestFramePump for live loops."""
|
||||
|
||||
def __init__(self, config: OpenCvCaptureConfig):
|
||||
self.config = config
|
||||
self._capture = None
|
||||
|
||||
def __enter__(self) -> "OpenCvFrameSource":
|
||||
import cv2
|
||||
|
||||
capture = cv2.VideoCapture(self.config.index, cv2_api(self.config.api))
|
||||
if not capture.isOpened():
|
||||
try:
|
||||
capture.release()
|
||||
except Exception:
|
||||
pass
|
||||
raise RuntimeError(f"OpenCV capture did not open: {self.config}")
|
||||
capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.config.width)
|
||||
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.config.height)
|
||||
if self.config.fps is not None:
|
||||
capture.set(cv2.CAP_PROP_FPS, float(self.config.fps))
|
||||
capture.set(cv2.CAP_PROP_BUFFERSIZE, 1)
|
||||
self._capture = capture
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if self._capture is not None:
|
||||
try:
|
||||
self._capture.release()
|
||||
except Exception:
|
||||
pass
|
||||
self._capture = None
|
||||
|
||||
def frames(self) -> Iterator[FramePacket]:
|
||||
if self._capture is None:
|
||||
raise RuntimeError("OpenCvFrameSource must be used as a context manager")
|
||||
sequence = 0
|
||||
while True:
|
||||
ok, frame = self._capture.read()
|
||||
if not ok or frame is None:
|
||||
return
|
||||
yield FramePacket(
|
||||
sensor_id=self.config.sensor_id,
|
||||
timestamp_ns=time.monotonic_ns(),
|
||||
sequence=sequence,
|
||||
image_bgr=frame.copy(),
|
||||
)
|
||||
sequence += 1
|
||||
|
||||
|
||||
class LatestFramePump:
|
||||
"""Runs a blocking FrameSource in a daemon thread and exposes its latest frame."""
|
||||
|
||||
def __init__(self, source_factory: Callable[[], FrameSource]):
|
||||
self.source_factory = source_factory
|
||||
self._lock = threading.Lock()
|
||||
self._latest: FramePacket | None = None
|
||||
self._error: str | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
if self._thread is not None:
|
||||
return
|
||||
self._thread = threading.Thread(target=self._run, name="localcast-latest-frame-pump", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def latest(self, *, max_age_ns: int | None = None, now_ns: int | None = None) -> FramePacket | None:
|
||||
with self._lock:
|
||||
frame = self._latest
|
||||
if frame is None:
|
||||
return None
|
||||
if max_age_ns is not None:
|
||||
current = time.monotonic_ns() if now_ns is None else int(now_ns)
|
||||
if current - int(frame.timestamp_ns) > int(max_age_ns):
|
||||
return None
|
||||
return frame
|
||||
|
||||
@property
|
||||
def error(self) -> str | None:
|
||||
with self._lock:
|
||||
return self._error
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
with self.source_factory() as source: # type: ignore[attr-defined]
|
||||
for frame in source.frames():
|
||||
with self._lock:
|
||||
self._latest = frame
|
||||
self._error = None
|
||||
except Exception as exc:
|
||||
with self._lock:
|
||||
self._error = repr(exc)
|
||||
|
||||
|
||||
def cv2_api(name: str) -> int:
|
||||
import cv2
|
||||
|
||||
return {
|
||||
"any": 0,
|
||||
"dshow": cv2.CAP_DSHOW,
|
||||
"msmf": cv2.CAP_MSMF,
|
||||
}[name]
|
||||
|
||||
|
||||
class FfmpegRawVideoSource:
|
||||
"""Frame source adapter for DirectShow devices that FFmpeg negotiates better than OpenCV."""
|
||||
|
||||
def __init__(self, config: FfmpegRawVideoConfig):
|
||||
self.config = config
|
||||
self._process: subprocess.Popen[bytes] | None = None
|
||||
|
||||
def __enter__(self) -> "FfmpegRawVideoSource":
|
||||
self._process = subprocess.Popen(
|
||||
self.config.command(),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if self._process is None:
|
||||
return
|
||||
if self._process.poll() is None:
|
||||
self._process.terminate()
|
||||
try:
|
||||
self._process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._process.kill()
|
||||
self._process = None
|
||||
|
||||
def frames(self) -> Iterator[FramePacket]:
|
||||
if self._process is None or self._process.stdout is None:
|
||||
raise RuntimeError("FfmpegRawVideoSource must be used as a context manager")
|
||||
yield from read_raw_bgr_frames(
|
||||
self._process.stdout,
|
||||
sensor_id=self.config.sensor_id,
|
||||
width=self.config.width,
|
||||
height=self.config.height,
|
||||
frame_bytes=self.config.frame_bytes,
|
||||
)
|
||||
|
||||
|
||||
def read_raw_bgr_frames(
|
||||
stream: BinaryIO,
|
||||
sensor_id: str,
|
||||
width: int,
|
||||
height: int,
|
||||
frame_bytes: int,
|
||||
) -> Iterator[FramePacket]:
|
||||
sequence = 0
|
||||
while True:
|
||||
blob = stream.read(frame_bytes)
|
||||
if not blob or len(blob) < frame_bytes:
|
||||
return
|
||||
frame = np.frombuffer(blob, dtype=np.uint8).reshape((height, width, 3)).copy()
|
||||
yield FramePacket(
|
||||
sensor_id=sensor_id,
|
||||
timestamp_ns=time.monotonic_ns(),
|
||||
sequence=sequence,
|
||||
image_bgr=frame,
|
||||
)
|
||||
sequence += 1
|
||||
|
|
@ -1,183 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .render_bridge import RenderFramePacket, RenderPointPacket
|
||||
from .media_artifacts import RemoteVideoArtifact
|
||||
from .reservoir_window import DEFAULT_RESERVOIR_NS, render_points_in_reservoir
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from audio_field.cultcache_audio import CultAudioSourceEvents, CultSpatialAudioFrame # noqa: E402
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioVisualSyncStatus:
|
||||
visual_frame_id: int
|
||||
visual_present_time_ns: int
|
||||
audio_frame_id: int | None
|
||||
audio_time_ns: int | None
|
||||
audio_delta_ns: int | None
|
||||
source_event_count: int
|
||||
overlay_event_count: int
|
||||
remote_video: RemoteVideoArtifact | None
|
||||
synchronized: bool
|
||||
|
||||
|
||||
def overlay_audio_events(
|
||||
frame: RenderFramePacket,
|
||||
events: CultAudioSourceEvents | None,
|
||||
audio_frame: CultSpatialAudioFrame | None,
|
||||
*,
|
||||
window_ns: int = 120_000_000,
|
||||
radius_m: float = 0.045,
|
||||
max_events: int = 128,
|
||||
) -> tuple[RenderFramePacket, AudioVisualSyncStatus]:
|
||||
frame = clamp_frame_to_audio_reservoir(frame, audio_frame)
|
||||
if events is None:
|
||||
return frame, sync_status(frame, None, 0, 0, None, False)
|
||||
overlay = select_events_for_visual_frame(frame, events, audio_frame, int(window_ns), int(max_events))
|
||||
points = list(frame.points)
|
||||
for event in overlay:
|
||||
confidence = max(0.0, min(1.0, float(event.get("confidence", 0.5))))
|
||||
energy = max(0.0, float(event.get("energy", 0.0)))
|
||||
alpha = max(0.25, min(1.0, 0.35 + confidence * 0.65))
|
||||
intensity = max(0.25, min(1.0, 0.45 + energy * 8000.0))
|
||||
points.append(
|
||||
RenderPointPacket(
|
||||
stable_key=f"audio-event-{event.get('eventId', len(points))}",
|
||||
xyz=np.asarray(event.get("positionMeters", [0.0, 0.0, 1.2]), dtype=np.float64),
|
||||
radius_m=radius_m * (0.75 + confidence),
|
||||
color_rgba=(1.0, 0.35 + 0.45 * intensity, 0.15, alpha),
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=event_time_ns(event, events, audio_frame),
|
||||
)
|
||||
)
|
||||
return (
|
||||
RenderFramePacket(
|
||||
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=frame.source_time_max_ns,
|
||||
present_time_ns=frame.present_time_ns,
|
||||
audio_alignment_time_ns=frame.audio_alignment_time_ns,
|
||||
spout_sender_name=frame.spout_sender_name,
|
||||
target_width=frame.target_width,
|
||||
target_height=frame.target_height,
|
||||
points=tuple(points),
|
||||
),
|
||||
sync_status(frame, audio_frame, len(events.events), len(overlay), None, True),
|
||||
)
|
||||
|
||||
|
||||
def clamp_frame_to_audio_reservoir(
|
||||
frame: RenderFramePacket,
|
||||
audio_frame: CultSpatialAudioFrame | None,
|
||||
*,
|
||||
reservoir_ns: int = DEFAULT_RESERVOIR_NS,
|
||||
) -> RenderFramePacket:
|
||||
if audio_frame is None:
|
||||
return frame
|
||||
edge_ns = max(int(frame.source_time_max_ns), int(audio_frame.audio_time_ns))
|
||||
start_ns = edge_ns - int(reservoir_ns)
|
||||
points = render_points_in_reservoir(
|
||||
frame.points,
|
||||
latest_timestamp_ns=edge_ns,
|
||||
reservoir_ns=reservoir_ns,
|
||||
)
|
||||
return RenderFramePacket(
|
||||
schema=frame.schema,
|
||||
frame_id=frame.frame_id,
|
||||
created_monotonic_ns=frame.created_monotonic_ns,
|
||||
source_time_min_ns=start_ns,
|
||||
source_time_max_ns=edge_ns,
|
||||
present_time_ns=edge_ns,
|
||||
audio_alignment_time_ns=edge_ns,
|
||||
spout_sender_name=frame.spout_sender_name,
|
||||
target_width=frame.target_width,
|
||||
target_height=frame.target_height,
|
||||
points=points,
|
||||
)
|
||||
|
||||
|
||||
def select_events_for_visual_frame(
|
||||
frame: RenderFramePacket,
|
||||
events: CultAudioSourceEvents,
|
||||
audio_frame: CultSpatialAudioFrame | None,
|
||||
window_ns: int,
|
||||
max_events: int,
|
||||
) -> list[dict]:
|
||||
if audio_frame is None:
|
||||
return list(events.events[:max_events])
|
||||
selected = []
|
||||
half_window = max(1, window_ns // 2)
|
||||
for event in events.events:
|
||||
when_ns = event_time_ns(event, events, audio_frame)
|
||||
if abs(when_ns - frame.audio_alignment_time_ns) <= half_window:
|
||||
selected.append((abs(when_ns - frame.audio_alignment_time_ns), dict(event)))
|
||||
selected.sort(key=lambda item: item[0])
|
||||
return [event for _, event in selected[:max_events]]
|
||||
|
||||
|
||||
def event_time_ns(event: dict, events: CultAudioSourceEvents, audio_frame: CultSpatialAudioFrame | None) -> int:
|
||||
start_sample = int(event.get("startSample", 0))
|
||||
if audio_frame is None:
|
||||
return events.audio_time_ns + int((start_sample - events.start_sample) * 1_000_000_000 / events.sample_rate)
|
||||
event_span = max(1, int(events.frame_count))
|
||||
audio_mod = audio_frame.start_sample % event_span
|
||||
event_mod = start_sample % event_span
|
||||
delta_samples = event_mod - audio_mod
|
||||
half_span = event_span // 2
|
||||
if delta_samples > half_span:
|
||||
delta_samples -= event_span
|
||||
elif delta_samples < -half_span:
|
||||
delta_samples += event_span
|
||||
return audio_frame.audio_time_ns + int(delta_samples * 1_000_000_000 / audio_frame.sample_rate)
|
||||
|
||||
|
||||
def sync_status(
|
||||
frame: RenderFramePacket,
|
||||
audio_frame: CultSpatialAudioFrame | None,
|
||||
source_event_count: int,
|
||||
overlay_event_count: int,
|
||||
remote_video: RemoteVideoArtifact | None,
|
||||
synchronized: bool,
|
||||
) -> AudioVisualSyncStatus:
|
||||
audio_delta_ns = None if audio_frame is None else frame.audio_alignment_time_ns - audio_frame.audio_time_ns
|
||||
remote_ok = True if remote_video is None else remote_video.synchronized
|
||||
return AudioVisualSyncStatus(
|
||||
visual_frame_id=frame.frame_id,
|
||||
visual_present_time_ns=frame.present_time_ns,
|
||||
audio_frame_id=None if audio_frame is None else audio_frame.frame_id,
|
||||
audio_time_ns=None if audio_frame is None else audio_frame.audio_time_ns,
|
||||
audio_delta_ns=audio_delta_ns,
|
||||
source_event_count=source_event_count,
|
||||
overlay_event_count=overlay_event_count,
|
||||
remote_video=remote_video,
|
||||
synchronized=bool(synchronized and audio_frame is not None and remote_ok),
|
||||
)
|
||||
|
||||
|
||||
def with_remote_video_status(status: AudioVisualSyncStatus | None, remote_video: RemoteVideoArtifact | None) -> AudioVisualSyncStatus | None:
|
||||
if status is None:
|
||||
return None
|
||||
remote_ok = True if remote_video is None else remote_video.synchronized
|
||||
return AudioVisualSyncStatus(
|
||||
visual_frame_id=status.visual_frame_id,
|
||||
visual_present_time_ns=status.visual_present_time_ns,
|
||||
audio_frame_id=status.audio_frame_id,
|
||||
audio_time_ns=status.audio_time_ns,
|
||||
audio_delta_ns=status.audio_delta_ns,
|
||||
source_event_count=status.source_event_count,
|
||||
overlay_event_count=status.overlay_event_count,
|
||||
remote_video=remote_video,
|
||||
synchronized=bool(status.synchronized and remote_ok),
|
||||
)
|
||||
|
|
@ -1,167 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import CameraModel
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraIntrinsics:
|
||||
sensor_id: str
|
||||
camera_matrix: np.ndarray
|
||||
dist_coeffs: np.ndarray
|
||||
width: int
|
||||
height: int
|
||||
role: str = "tracking"
|
||||
latency_ms: float = 0.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BoardSpec:
|
||||
squares_x: int
|
||||
squares_y: int
|
||||
square_length_m: float
|
||||
|
||||
def object_point(self, corner_id: int) -> np.ndarray:
|
||||
cols = self.squares_x - 1
|
||||
if corner_id < 0 or corner_id >= cols * (self.squares_y - 1):
|
||||
raise ValueError(f"ChArUco corner id {corner_id} outside board")
|
||||
row = corner_id // cols
|
||||
col = corner_id % cols
|
||||
return np.array(
|
||||
[(col + 1) * self.square_length_m, (row + 1) * self.square_length_m, 0.0],
|
||||
dtype=np.float64,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BoardObservation:
|
||||
sensor_id: str
|
||||
timestamp_ns: int
|
||||
corner_ids: np.ndarray
|
||||
image_points: np.ndarray
|
||||
confidence: float = 1.0
|
||||
|
||||
@property
|
||||
def corner_count(self) -> int:
|
||||
return int(len(self.corner_ids))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraPoseSolve:
|
||||
sensor_id: str
|
||||
world_from_sensor: np.ndarray
|
||||
reprojection_error_px: float
|
||||
corner_count: int
|
||||
timestamp_ns: int
|
||||
|
||||
|
||||
def solve_camera_pose_from_fixed_board(
|
||||
intrinsics: CameraIntrinsics,
|
||||
board: BoardSpec,
|
||||
observation: BoardObservation,
|
||||
*,
|
||||
min_corners: int = 6,
|
||||
) -> CameraPoseSolve:
|
||||
if observation.sensor_id != intrinsics.sensor_id:
|
||||
raise ValueError("Observation sensor_id does not match intrinsics")
|
||||
if observation.corner_count < min_corners:
|
||||
raise ValueError(f"Need at least {min_corners} board corners; got {observation.corner_count}")
|
||||
|
||||
object_points = np.vstack([board.object_point(int(corner_id)) for corner_id in observation.corner_ids])
|
||||
image_points = np.asarray(observation.image_points, dtype=np.float64).reshape((-1, 2))
|
||||
if len(object_points) != len(image_points):
|
||||
raise ValueError("corner_ids and image_points must have matching length")
|
||||
|
||||
import cv2
|
||||
|
||||
ok, rvec, tvec = cv2.solvePnP(
|
||||
object_points,
|
||||
image_points,
|
||||
np.asarray(intrinsics.camera_matrix, dtype=np.float64),
|
||||
np.asarray(intrinsics.dist_coeffs, dtype=np.float64),
|
||||
flags=cv2.SOLVEPNP_ITERATIVE,
|
||||
)
|
||||
if not ok:
|
||||
raise ValueError(f"Could not solve pose for {intrinsics.sensor_id}")
|
||||
|
||||
rotation, _ = cv2.Rodrigues(rvec)
|
||||
sensor_from_world = np.eye(4, dtype=np.float64)
|
||||
sensor_from_world[:3, :3] = rotation
|
||||
sensor_from_world[:3, 3] = np.asarray(tvec, dtype=np.float64).reshape(3)
|
||||
world_from_sensor = np.linalg.inv(sensor_from_world)
|
||||
|
||||
projected, _ = cv2.projectPoints(
|
||||
object_points,
|
||||
rvec,
|
||||
tvec,
|
||||
np.asarray(intrinsics.camera_matrix, dtype=np.float64),
|
||||
np.asarray(intrinsics.dist_coeffs, dtype=np.float64),
|
||||
)
|
||||
error = float(np.mean(np.linalg.norm(projected.reshape((-1, 2)) - image_points, axis=1)))
|
||||
return CameraPoseSolve(
|
||||
sensor_id=intrinsics.sensor_id,
|
||||
world_from_sensor=world_from_sensor,
|
||||
reprojection_error_px=error,
|
||||
corner_count=observation.corner_count,
|
||||
timestamp_ns=observation.timestamp_ns,
|
||||
)
|
||||
|
||||
|
||||
def solve_common_space_from_fixed_board(
|
||||
intrinsics: Iterable[CameraIntrinsics],
|
||||
board: BoardSpec,
|
||||
observations: Iterable[BoardObservation],
|
||||
*,
|
||||
max_reprojection_error_px: float = 2.5,
|
||||
) -> tuple[dict[str, CameraModel], tuple[CameraPoseSolve, ...]]:
|
||||
intrinsics_by_id = {item.sensor_id: item for item in intrinsics}
|
||||
best_solves: dict[str, CameraPoseSolve] = {}
|
||||
for observation in observations:
|
||||
camera_intrinsics = intrinsics_by_id.get(observation.sensor_id)
|
||||
if camera_intrinsics is None:
|
||||
continue
|
||||
solve = solve_camera_pose_from_fixed_board(camera_intrinsics, board, observation)
|
||||
if solve.reprojection_error_px > max_reprojection_error_px:
|
||||
continue
|
||||
current = best_solves.get(solve.sensor_id)
|
||||
if current is None or (solve.corner_count, -solve.reprojection_error_px) > (current.corner_count, -current.reprojection_error_px):
|
||||
best_solves[solve.sensor_id] = solve
|
||||
|
||||
cameras: dict[str, CameraModel] = {}
|
||||
for sensor_id, solve in best_solves.items():
|
||||
item = intrinsics_by_id[sensor_id]
|
||||
cameras[sensor_id] = CameraModel(
|
||||
sensor_id=sensor_id,
|
||||
camera_matrix=np.asarray(item.camera_matrix, dtype=np.float64),
|
||||
dist_coeffs=np.asarray(item.dist_coeffs, dtype=np.float64),
|
||||
world_from_sensor=solve.world_from_sensor,
|
||||
width=item.width,
|
||||
height=item.height,
|
||||
role=item.role,
|
||||
latency_ms=item.latency_ms,
|
||||
)
|
||||
return cameras, tuple(best_solves.values())
|
||||
|
||||
|
||||
def camera_models_to_config(cameras: Iterable[CameraModel]) -> list[dict]:
|
||||
payload = []
|
||||
for camera in cameras:
|
||||
payload.append(
|
||||
{
|
||||
"id": camera.sensor_id,
|
||||
"role": camera.role,
|
||||
"intrinsics": {
|
||||
"width": camera.width,
|
||||
"height": camera.height,
|
||||
"camera_matrix": camera.camera_matrix.tolist(),
|
||||
"dist_coeffs": camera.dist_coeffs.tolist(),
|
||||
},
|
||||
"world_from_sensor": camera.world_from_sensor.tolist(),
|
||||
"latency_ms": camera.latency_ms,
|
||||
}
|
||||
)
|
||||
return payload
|
||||
|
|
@ -1,154 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FrameQuality:
|
||||
mean_luma: float
|
||||
dark_clip: float
|
||||
bright_clip: float
|
||||
contrast: float
|
||||
sharpness: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraControlState:
|
||||
exposure: float = 0.5
|
||||
gain: float = 0.25
|
||||
focus: float = 0.5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraControlCommand:
|
||||
exposure: float | None = None
|
||||
gain: float | None = None
|
||||
focus: float | None = None
|
||||
|
||||
@property
|
||||
def changed(self) -> bool:
|
||||
return self.exposure is not None or self.gain is not None or self.focus is not None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraQualityTarget:
|
||||
mean_luma: float = 0.52
|
||||
luma_deadband: float = 0.045
|
||||
max_bright_clip: float = 0.015
|
||||
max_dark_clip: float = 0.035
|
||||
min_sharpness: float = 0.035
|
||||
exposure_step: float = 0.035
|
||||
gain_step: float = 0.025
|
||||
focus_step: float = 0.020
|
||||
|
||||
|
||||
class CameraSettingPort(Protocol):
|
||||
def apply(self, command: CameraControlCommand) -> None:
|
||||
...
|
||||
|
||||
|
||||
def measure_frame_quality(frame_bgr: np.ndarray) -> FrameQuality:
|
||||
if frame_bgr.ndim != 3 or frame_bgr.shape[2] != 3:
|
||||
raise ValueError("frame_bgr must have shape HxWx3")
|
||||
frame = frame_bgr.astype(np.float32) / 255.0
|
||||
luma = 0.0722 * frame[:, :, 0] + 0.7152 * frame[:, :, 1] + 0.2126 * frame[:, :, 2]
|
||||
gx = np.diff(luma, axis=1)
|
||||
gy = np.diff(luma, axis=0)
|
||||
sharpness = float(np.mean(np.abs(gx)) + np.mean(np.abs(gy)))
|
||||
return FrameQuality(
|
||||
mean_luma=float(np.mean(luma)),
|
||||
dark_clip=float(np.mean(luma < 0.025)),
|
||||
bright_clip=float(np.mean(luma > 0.975)),
|
||||
contrast=float(np.percentile(luma, 95) - np.percentile(luma, 5)),
|
||||
sharpness=sharpness,
|
||||
)
|
||||
|
||||
|
||||
class AdaptiveCameraController:
|
||||
"""Small bounded controller for manual capture settings.
|
||||
|
||||
The controller owns measurement quality policy. It deliberately emits
|
||||
normalized commands; the driver adapter owns mapping those commands to
|
||||
OpenCV, DirectShow, vendor tools, or a no-op mock in tests.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
state: CameraControlState | None = None,
|
||||
target: CameraQualityTarget | None = None,
|
||||
) -> None:
|
||||
self.state = state or CameraControlState()
|
||||
self.target = target or CameraQualityTarget()
|
||||
self._focus_direction = 1.0
|
||||
|
||||
def update(self, quality: FrameQuality) -> CameraControlCommand:
|
||||
exposure = self.state.exposure
|
||||
gain = self.state.gain
|
||||
focus = self.state.focus
|
||||
|
||||
too_bright = quality.mean_luma > self.target.mean_luma + self.target.luma_deadband
|
||||
too_dark = quality.mean_luma < self.target.mean_luma - self.target.luma_deadband
|
||||
|
||||
if too_bright or quality.bright_clip > self.target.max_bright_clip:
|
||||
exposure -= self.target.exposure_step
|
||||
if quality.bright_clip > self.target.max_bright_clip * 2.0:
|
||||
gain -= self.target.gain_step
|
||||
elif too_dark or quality.dark_clip > self.target.max_dark_clip:
|
||||
exposure += self.target.exposure_step
|
||||
if exposure >= 0.92:
|
||||
gain += self.target.gain_step
|
||||
|
||||
if quality.sharpness < self.target.min_sharpness:
|
||||
focus += self._focus_direction * self.target.focus_step
|
||||
if focus <= 0.05 or focus >= 0.95:
|
||||
self._focus_direction *= -1.0
|
||||
|
||||
exposure = _clamp01(exposure)
|
||||
gain = _clamp01(gain)
|
||||
focus = _clamp01(focus)
|
||||
|
||||
command = CameraControlCommand(
|
||||
exposure=None if abs(exposure - self.state.exposure) < 1e-9 else exposure,
|
||||
gain=None if abs(gain - self.state.gain) < 1e-9 else gain,
|
||||
focus=None if abs(focus - self.state.focus) < 1e-9 else focus,
|
||||
)
|
||||
self.state = CameraControlState(exposure=exposure, gain=gain, focus=focus)
|
||||
return command
|
||||
|
||||
|
||||
class OpenCvCameraSettingPort:
|
||||
def __init__(self, capture: object) -> None:
|
||||
self.capture = capture
|
||||
|
||||
def apply(self, command: CameraControlCommand) -> None:
|
||||
if not command.changed:
|
||||
return
|
||||
import cv2
|
||||
|
||||
# Disable auto controls where OpenCV exposes the knobs, then apply a
|
||||
# normalized manual target. Driver backends differ; failed sets are
|
||||
# non-fatal because image quality feedback will continue next frame.
|
||||
try:
|
||||
self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)
|
||||
except Exception:
|
||||
pass
|
||||
if command.exposure is not None:
|
||||
_try_set(self.capture, cv2.CAP_PROP_EXPOSURE, -13.0 + command.exposure * 12.0)
|
||||
if command.gain is not None:
|
||||
_try_set(self.capture, cv2.CAP_PROP_GAIN, command.gain * 255.0)
|
||||
if command.focus is not None and hasattr(cv2, "CAP_PROP_FOCUS"):
|
||||
_try_set(self.capture, cv2.CAP_PROP_FOCUS, command.focus * 255.0)
|
||||
|
||||
|
||||
def _try_set(capture: object, prop: int, value: float) -> None:
|
||||
try:
|
||||
capture.set(prop, float(value))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _clamp01(value: float) -> float:
|
||||
return max(0.0, min(1.0, float(value)))
|
||||
|
|
@ -1,224 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Mapping, Sequence
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
SPEED_OF_SOUND_MPS = 343.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraMicGeometry:
|
||||
sensor_id: str
|
||||
source_id: str
|
||||
position_m: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SpeakerGeometry:
|
||||
speaker_id: str
|
||||
position_m: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraChirpPoseConstraint:
|
||||
stable_key: str
|
||||
sensor_id: str
|
||||
source_id: str
|
||||
speaker_id: str
|
||||
camera_position_m: np.ndarray
|
||||
speaker_position_m: np.ndarray
|
||||
nominal_range_m: float
|
||||
observed_range_m: float
|
||||
range_residual_m: float
|
||||
confidence: float
|
||||
timestamp_ns: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraPoseCorrectionEstimate:
|
||||
sensor_id: str
|
||||
position_m: np.ndarray
|
||||
correction_m: np.ndarray
|
||||
confidence: float
|
||||
constraint_count: int
|
||||
timestamp_ns: int
|
||||
|
||||
|
||||
def default_camera_mic_geometry() -> tuple[CameraMicGeometry, ...]:
|
||||
return (
|
||||
CameraMicGeometry("kiyo-primary", "kiyo-0", np.array([-0.18, -0.72, 1.28], dtype=np.float64)),
|
||||
CameraMicGeometry("kiyo-secondary", "kiyo-1", np.array([0.18, -0.72, 1.28], dtype=np.float64)),
|
||||
CameraMicGeometry("ps3eye-left", "ps-eye-0", np.array([-0.78, -0.82, 1.34], dtype=np.float64)),
|
||||
CameraMicGeometry("ps3eye-right", "ps-eye-1", np.array([0.78, -0.82, 1.34], dtype=np.float64)),
|
||||
)
|
||||
|
||||
|
||||
def default_speaker_geometry() -> tuple[SpeakerGeometry, ...]:
|
||||
return (
|
||||
SpeakerGeometry("local-speaker-left", np.array([-0.32, -1.08, 1.18], dtype=np.float64)),
|
||||
SpeakerGeometry("local-speaker-right", np.array([0.32, -1.08, 1.18], dtype=np.float64)),
|
||||
)
|
||||
|
||||
|
||||
def camera_mic_geometry_from_audio_profile(path: Path) -> tuple[CameraMicGeometry, ...]:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
rows: list[CameraMicGeometry] = []
|
||||
for mic in data.get("microphones", []):
|
||||
source_id = phase_source_id_for_microphone(mic)
|
||||
sensor_id = camera_sensor_id_for_microphone(mic)
|
||||
position = mic.get("positionMeters")
|
||||
if source_id is None or sensor_id is None or position is None:
|
||||
continue
|
||||
rows.append(CameraMicGeometry(sensor_id, source_id, np.asarray(position, dtype=np.float64)))
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
def speaker_geometry_from_audio_profile(path: Path) -> tuple[SpeakerGeometry, ...]:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
rows: list[SpeakerGeometry] = []
|
||||
for speaker in data.get("speakers", []):
|
||||
position = speaker.get("positionMeters")
|
||||
if position is None:
|
||||
continue
|
||||
rows.append(SpeakerGeometry(str(speaker.get("id", "")), np.asarray(position, dtype=np.float64)))
|
||||
return tuple(row for row in rows if row.speaker_id)
|
||||
|
||||
|
||||
def phase_source_id_for_microphone(mic: Mapping[str, object]) -> str | None:
|
||||
explicit = mic.get("phaseSourceId") or mic.get("sourceId")
|
||||
if explicit:
|
||||
return str(explicit)
|
||||
mic_id = str(mic.get("id", ""))
|
||||
known = {
|
||||
"mic_kiyo_left": "kiyo-0",
|
||||
"mic_kiyo_right": "kiyo-1",
|
||||
"mic_ps_eye_left": "ps-eye-0",
|
||||
"mic_ps_eye_right": "ps-eye-1",
|
||||
}
|
||||
return known.get(mic_id)
|
||||
|
||||
|
||||
def camera_sensor_id_for_microphone(mic: Mapping[str, object]) -> str | None:
|
||||
explicit = mic.get("cameraSensorId") or mic.get("sensorId")
|
||||
if explicit:
|
||||
return str(explicit)
|
||||
mic_id = str(mic.get("id", ""))
|
||||
known = {
|
||||
"mic_kiyo_left": "kiyo-primary",
|
||||
"mic_kiyo_right": "kiyo-secondary",
|
||||
"mic_ps_eye_left": "ps3eye-left",
|
||||
"mic_ps_eye_right": "ps3eye-right",
|
||||
}
|
||||
return known.get(mic_id)
|
||||
|
||||
|
||||
def constraints_from_phase_sources(
|
||||
sources: Sequence[Mapping[str, object]],
|
||||
*,
|
||||
audio_time_ns: int,
|
||||
camera_mics: Sequence[CameraMicGeometry] | None = None,
|
||||
speakers: Sequence[SpeakerGeometry] | None = None,
|
||||
max_abs_residual_m: float = 2.0,
|
||||
) -> tuple[CameraChirpPoseConstraint, ...]:
|
||||
"""Convert phase-field delay meaning into camera-body range constraints."""
|
||||
|
||||
camera_mics = default_camera_mic_geometry() if camera_mics is None else camera_mics
|
||||
speakers = default_speaker_geometry() if speakers is None else speakers
|
||||
mic_by_source = {item.source_id: item for item in camera_mics}
|
||||
if not speakers:
|
||||
return ()
|
||||
rows: list[CameraChirpPoseConstraint] = []
|
||||
for source in sources:
|
||||
source_id = str(source.get("sourceId", ""))
|
||||
mic = mic_by_source.get(source_id)
|
||||
if mic is None:
|
||||
continue
|
||||
confidence = max(0.0, min(1.0, float(source.get("confidence", 0.0))))
|
||||
if confidence <= 0.0:
|
||||
continue
|
||||
distance_delta_m = _source_distance_delta_m(source)
|
||||
if not np.isfinite(distance_delta_m):
|
||||
continue
|
||||
speaker = _nearest_speaker(mic.position_m, speakers)
|
||||
nominal = float(np.linalg.norm(mic.position_m - speaker.position_m))
|
||||
residual = float(max(-max_abs_residual_m, min(max_abs_residual_m, distance_delta_m)))
|
||||
observed = max(0.0, nominal + residual)
|
||||
rows.append(
|
||||
CameraChirpPoseConstraint(
|
||||
stable_key=f"camera-chirp:{mic.sensor_id}:{speaker.speaker_id}",
|
||||
sensor_id=mic.sensor_id,
|
||||
source_id=source_id,
|
||||
speaker_id=speaker.speaker_id,
|
||||
camera_position_m=mic.position_m.astype(np.float64),
|
||||
speaker_position_m=speaker.position_m.astype(np.float64),
|
||||
nominal_range_m=nominal,
|
||||
observed_range_m=observed,
|
||||
range_residual_m=residual,
|
||||
confidence=confidence,
|
||||
timestamp_ns=int(audio_time_ns),
|
||||
)
|
||||
)
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
def estimate_pose_corrections(
|
||||
constraints: Sequence[CameraChirpPoseConstraint],
|
||||
*,
|
||||
max_step_m: float = 0.35,
|
||||
) -> tuple[CameraPoseCorrectionEstimate, ...]:
|
||||
grouped: dict[str, list[CameraChirpPoseConstraint]] = {}
|
||||
for constraint in constraints:
|
||||
grouped.setdefault(constraint.sensor_id, []).append(constraint)
|
||||
estimates: list[CameraPoseCorrectionEstimate] = []
|
||||
for sensor_id, rows in grouped.items():
|
||||
vectors = []
|
||||
weights = []
|
||||
positions = []
|
||||
for row in rows:
|
||||
camera = np.asarray(row.camera_position_m, dtype=np.float64)
|
||||
speaker = np.asarray(row.speaker_position_m, dtype=np.float64)
|
||||
direction = camera - speaker
|
||||
norm = float(np.linalg.norm(direction))
|
||||
if norm <= 1.0e-9:
|
||||
continue
|
||||
unit = direction / norm
|
||||
confidence = max(0.0, min(1.0, float(row.confidence)))
|
||||
vectors.append(unit * float(row.range_residual_m))
|
||||
weights.append(max(1.0e-6, confidence))
|
||||
positions.append(camera)
|
||||
if not vectors:
|
||||
continue
|
||||
weighted = np.average(np.asarray(vectors, dtype=np.float64), axis=0, weights=np.asarray(weights, dtype=np.float64))
|
||||
magnitude = float(np.linalg.norm(weighted))
|
||||
if magnitude > max_step_m:
|
||||
weighted = weighted / magnitude * float(max_step_m)
|
||||
estimates.append(
|
||||
CameraPoseCorrectionEstimate(
|
||||
sensor_id=sensor_id,
|
||||
position_m=np.average(np.asarray(positions, dtype=np.float64), axis=0, weights=np.asarray(weights, dtype=np.float64)),
|
||||
correction_m=weighted.astype(np.float64),
|
||||
confidence=float(min(1.0, np.mean(weights))),
|
||||
constraint_count=len(vectors),
|
||||
timestamp_ns=max(row.timestamp_ns for row in rows),
|
||||
)
|
||||
)
|
||||
return tuple(sorted(estimates, key=lambda item: item.sensor_id))
|
||||
|
||||
|
||||
def _nearest_speaker(position_m: np.ndarray, speakers: Sequence[SpeakerGeometry]) -> SpeakerGeometry:
|
||||
return min(speakers, key=lambda speaker: float(np.linalg.norm(np.asarray(position_m) - speaker.position_m)))
|
||||
|
||||
|
||||
def _source_distance_delta_m(source: Mapping[str, object]) -> float:
|
||||
if "distanceDeltaMeters" in source:
|
||||
return float(source["distanceDeltaMeters"])
|
||||
if "delayMs" in source:
|
||||
return float(source["delayMs"]) * 0.001 * SPEED_OF_SOUND_MPS
|
||||
if "delaySamples" in source and "sampleRate" in source:
|
||||
return float(source["delaySamples"]) / max(1.0, float(source["sampleRate"])) * SPEED_OF_SOUND_MPS
|
||||
return float("nan")
|
||||
|
|
@ -1,325 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
from typing import Mapping, Sequence
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import Observation2D, SensorRig
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClapDetectorConfig:
|
||||
audio_window_samples: int = 256
|
||||
audio_hop_samples: int = 64
|
||||
audio_onset_ratio: float = 6.0
|
||||
min_audio_energy: float = 1.0e-5
|
||||
min_camera_motion_score: float = 0.035
|
||||
camera_window_ns: int = 35_000_000
|
||||
min_camera_count: int = 2
|
||||
min_event_spacing_ns: int = 180_000_000
|
||||
timing_uncertainty_us: float = 2.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioTransientCandidate:
|
||||
oracle_time_ns: int
|
||||
start_sample: int
|
||||
energy: float
|
||||
onset_ratio: float
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimestampedFrame:
|
||||
sensor_id: str
|
||||
timestamp_ns: int
|
||||
image: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraMotionPeak:
|
||||
sensor_id: str
|
||||
timestamp_ns: int
|
||||
uv: np.ndarray
|
||||
score: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClapCalibrationEvent:
|
||||
stable_key: str
|
||||
position_m: tuple[float, float, float]
|
||||
acoustic_oracle_ns: int
|
||||
visual_observed_ns: int
|
||||
timing_uncertainty_us: float
|
||||
visual_confidence: float
|
||||
acoustic_confidence: float
|
||||
camera_peaks: tuple[CameraMotionPeak, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraSyncEstimate:
|
||||
sensor_id: str
|
||||
offset_ns: int
|
||||
confidence: float
|
||||
updated_by_event: str
|
||||
observed_timestamp_ns: int
|
||||
oracle_timestamp_ns: int
|
||||
|
||||
|
||||
class CameraClockSyncModel:
|
||||
def __init__(self, smoothing: float = 0.35) -> None:
|
||||
self.smoothing = max(0.0, min(1.0, float(smoothing)))
|
||||
self._estimates: dict[str, CameraSyncEstimate] = {}
|
||||
|
||||
def observe_event(self, event: ClapCalibrationEvent) -> None:
|
||||
for peak in event.camera_peaks:
|
||||
raw_offset = int(event.acoustic_oracle_ns - peak.timestamp_ns)
|
||||
confidence = max(0.0, min(1.0, float(peak.score) * float(event.acoustic_confidence)))
|
||||
previous = self._estimates.get(peak.sensor_id)
|
||||
if previous is None:
|
||||
offset = raw_offset
|
||||
confidence = max(confidence, 1.0e-6)
|
||||
else:
|
||||
alpha = self.smoothing * confidence
|
||||
offset = round((1.0 - alpha) * previous.offset_ns + alpha * raw_offset)
|
||||
confidence = max(previous.confidence * 0.96, confidence)
|
||||
self._estimates[peak.sensor_id] = CameraSyncEstimate(
|
||||
sensor_id=peak.sensor_id,
|
||||
offset_ns=int(offset),
|
||||
confidence=float(confidence),
|
||||
updated_by_event=event.stable_key,
|
||||
observed_timestamp_ns=int(peak.timestamp_ns),
|
||||
oracle_timestamp_ns=int(event.acoustic_oracle_ns),
|
||||
)
|
||||
|
||||
def offset_ns(self, sensor_id: str) -> int:
|
||||
estimate = self._estimates.get(sensor_id)
|
||||
return 0 if estimate is None else estimate.offset_ns
|
||||
|
||||
def raw_time_for_oracle(self, sensor_id: str, oracle_time_ns: int) -> int:
|
||||
return int(oracle_time_ns) - self.offset_ns(sensor_id)
|
||||
|
||||
def estimates(self) -> tuple[CameraSyncEstimate, ...]:
|
||||
return tuple(sorted(self._estimates.values(), key=lambda item: item.sensor_id))
|
||||
|
||||
|
||||
class TimestampedFrameHistory:
|
||||
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:
|
||||
bucket = self._frames.setdefault(frame.sensor_id, [])
|
||||
if bucket and bucket[-1].timestamp_ns == frame.timestamp_ns:
|
||||
return
|
||||
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():
|
||||
self.add(frame)
|
||||
|
||||
def frames_by_sensor(self) -> dict[str, list[TimestampedFrame]]:
|
||||
return {sensor_id: list(frames) for sensor_id, frames in self._frames.items()}
|
||||
|
||||
def nearest(self, sensor_id: str, raw_time_ns: int) -> TimestampedFrame | None:
|
||||
frames = self._frames.get(sensor_id, [])
|
||||
if not frames:
|
||||
return None
|
||||
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,
|
||||
sample_rate: int,
|
||||
*,
|
||||
audio_time_ns: int,
|
||||
start_sample: int = 0,
|
||||
config: ClapDetectorConfig = ClapDetectorConfig(),
|
||||
) -> list[AudioTransientCandidate]:
|
||||
samples = np.asarray(field, dtype=np.float32)
|
||||
if samples.ndim == 1:
|
||||
samples = samples[:, None]
|
||||
if samples.ndim != 2:
|
||||
raise ValueError("audio field must be samples or samples-by-channels")
|
||||
if sample_rate <= 0:
|
||||
raise ValueError("sample_rate must be positive")
|
||||
window = int(config.audio_window_samples)
|
||||
hop = int(config.audio_hop_samples)
|
||||
if window <= 0 or hop <= 0:
|
||||
raise ValueError("audio windows must be positive")
|
||||
|
||||
candidates: list[AudioTransientCandidate] = []
|
||||
previous_energy = 0.0
|
||||
for offset in range(0, max(0, samples.shape[0] - window + 1), hop):
|
||||
block = samples[offset : offset + window]
|
||||
diff = np.diff(block, axis=0)
|
||||
energy = float(np.mean(block.astype(np.float64) ** 2))
|
||||
derivative_energy = float(np.mean(diff.astype(np.float64) ** 2)) if diff.size else 0.0
|
||||
onset = max(energy, derivative_energy) / max(previous_energy, 1.0e-12)
|
||||
previous_energy = max(energy, 1.0e-12)
|
||||
if energy < config.min_audio_energy or onset < config.audio_onset_ratio:
|
||||
continue
|
||||
sample = start_sample + offset
|
||||
oracle_time_ns = audio_time_ns + round((sample - start_sample) * 1_000_000_000 / sample_rate)
|
||||
confidence = max(0.0, min(1.0, 0.35 + math.log10(max(onset, 1.0)) * 0.28))
|
||||
candidates.append(AudioTransientCandidate(oracle_time_ns, sample, energy, onset, confidence))
|
||||
|
||||
return suppress_nearby_audio_candidates(candidates, config.min_event_spacing_ns)
|
||||
|
||||
|
||||
def detect_camera_motion_peaks(
|
||||
frames_by_sensor: Mapping[str, Sequence[TimestampedFrame]],
|
||||
oracle_time_ns: int,
|
||||
*,
|
||||
config: ClapDetectorConfig = ClapDetectorConfig(),
|
||||
) -> list[CameraMotionPeak]:
|
||||
peaks: list[CameraMotionPeak] = []
|
||||
for sensor_id, frames in frames_by_sensor.items():
|
||||
ordered = sorted(frames, key=lambda frame: frame.timestamp_ns)
|
||||
best: CameraMotionPeak | None = None
|
||||
for previous, current in zip(ordered, ordered[1:]):
|
||||
midpoint_ns = (previous.timestamp_ns + current.timestamp_ns) // 2
|
||||
if abs(midpoint_ns - oracle_time_ns) > config.camera_window_ns:
|
||||
continue
|
||||
if previous.image.shape[:2] != current.image.shape[:2]:
|
||||
continue
|
||||
score, uv = frame_motion_score(previous.image, current.image)
|
||||
if score < config.min_camera_motion_score:
|
||||
continue
|
||||
peak = CameraMotionPeak(sensor_id, midpoint_ns, uv, score)
|
||||
if best is None or peak.score > best.score:
|
||||
best = peak
|
||||
if best is not None:
|
||||
peaks.append(best)
|
||||
return sorted(peaks, key=lambda peak: peak.score, reverse=True)
|
||||
|
||||
|
||||
def detect_clap_events(
|
||||
field: np.ndarray,
|
||||
sample_rate: int,
|
||||
frames_by_sensor: Mapping[str, Sequence[TimestampedFrame]],
|
||||
*,
|
||||
audio_time_ns: int,
|
||||
rig: SensorRig | None = None,
|
||||
start_sample: int = 0,
|
||||
config: ClapDetectorConfig = ClapDetectorConfig(),
|
||||
) -> list[ClapCalibrationEvent]:
|
||||
events: list[ClapCalibrationEvent] = []
|
||||
for index, candidate in enumerate(
|
||||
detect_audio_transients(field, sample_rate, audio_time_ns=audio_time_ns, start_sample=start_sample, config=config)
|
||||
):
|
||||
peaks = detect_camera_motion_peaks(frames_by_sensor, candidate.oracle_time_ns, config=config)
|
||||
if len(peaks) < config.min_camera_count:
|
||||
continue
|
||||
position, visual_confidence = localize_clap(peaks, rig)
|
||||
if visual_confidence <= 0.0:
|
||||
continue
|
||||
visual_time_ns = round(sum(peak.timestamp_ns * peak.score for peak in peaks) / max(1.0e-12, sum(peak.score for peak in peaks)))
|
||||
timing_spread_us = max(abs(peak.timestamp_ns - candidate.oracle_time_ns) for peak in peaks) / 1000.0
|
||||
events.append(
|
||||
ClapCalibrationEvent(
|
||||
stable_key=f"clap:{candidate.oracle_time_ns}:{index}",
|
||||
position_m=position,
|
||||
acoustic_oracle_ns=candidate.oracle_time_ns,
|
||||
visual_observed_ns=visual_time_ns,
|
||||
timing_uncertainty_us=max(config.timing_uncertainty_us, timing_spread_us),
|
||||
visual_confidence=visual_confidence,
|
||||
acoustic_confidence=candidate.confidence,
|
||||
camera_peaks=tuple(peaks),
|
||||
)
|
||||
)
|
||||
return events
|
||||
|
||||
|
||||
def frame_motion_score(previous: np.ndarray, current: np.ndarray) -> tuple[float, np.ndarray]:
|
||||
a = to_luma(previous)
|
||||
b = to_luma(current)
|
||||
if a.shape != b.shape:
|
||||
raise ValueError(f"frame shape mismatch: {a.shape} vs {b.shape}")
|
||||
diff = np.abs(b - a)
|
||||
threshold = max(0.02, float(np.percentile(diff, 92)))
|
||||
mask = diff >= threshold
|
||||
if not np.any(mask):
|
||||
return 0.0, np.array([a.shape[1] * 0.5, a.shape[0] * 0.5], dtype=np.float64)
|
||||
weights = diff * mask
|
||||
yy, xx = np.indices(a.shape, dtype=np.float64)
|
||||
total = float(np.sum(weights))
|
||||
uv = np.array([float(np.sum(xx * weights) / total), float(np.sum(yy * weights) / total)], dtype=np.float64)
|
||||
score = float(np.mean(diff[mask]))
|
||||
return score, uv
|
||||
|
||||
|
||||
def localize_clap(peaks: Sequence[CameraMotionPeak], rig: SensorRig | None) -> tuple[tuple[float, float, float], float]:
|
||||
if rig is None:
|
||||
best = peaks[0]
|
||||
return (float(best.uv[0]), float(best.uv[1]), 0.0), max(0.0, min(1.0, best.score))
|
||||
observations = [
|
||||
Observation2D(peak.sensor_id, "clap-impact", peak.timestamp_ns, peak.uv, max(0.0, min(1.0, peak.score)))
|
||||
for peak in peaks
|
||||
if peak.sensor_id in rig.cameras
|
||||
]
|
||||
result = rig.fuse(observations)
|
||||
if not result.points:
|
||||
return (0.0, 0.0, 0.0), 0.0
|
||||
point = max(result.points, key=lambda item: item.confidence)
|
||||
return tuple(float(value) for value in point.xyz), float(point.confidence)
|
||||
|
||||
|
||||
def suppress_nearby_audio_candidates(
|
||||
candidates: list[AudioTransientCandidate],
|
||||
min_spacing_ns: int,
|
||||
) -> list[AudioTransientCandidate]:
|
||||
kept: list[AudioTransientCandidate] = []
|
||||
for candidate in sorted(candidates, key=lambda item: item.energy, reverse=True):
|
||||
if any(abs(candidate.oracle_time_ns - existing.oracle_time_ns) < min_spacing_ns for existing in kept):
|
||||
continue
|
||||
kept.append(candidate)
|
||||
return sorted(kept, key=lambda item: item.oracle_time_ns)
|
||||
|
||||
|
||||
def to_luma(frame: np.ndarray) -> np.ndarray:
|
||||
image = np.asarray(frame)
|
||||
if image.ndim == 2:
|
||||
return normalize_image(image)
|
||||
if image.ndim != 3 or image.shape[2] < 3:
|
||||
raise ValueError("camera frame must be grayscale or color image")
|
||||
rgb = image[:, :, :3].astype(np.float32)
|
||||
return normalize_image((0.2126 * rgb[:, :, 2]) + (0.7152 * rgb[:, :, 1]) + (0.0722 * rgb[:, :, 0]))
|
||||
|
||||
|
||||
def normalize_image(image: np.ndarray) -> np.ndarray:
|
||||
arr = np.asarray(image, dtype=np.float32)
|
||||
if arr.size == 0:
|
||||
raise ValueError("camera frame is empty")
|
||||
max_value = 255.0 if np.max(arr) > 1.5 else 1.0
|
||||
return np.clip(arr / max_value, 0.0, 1.0)
|
||||
|
|
@ -1,274 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
ArrayLike = Iterable[Iterable[float]] | Iterable[float]
|
||||
|
||||
|
||||
def _array(value: ArrayLike, shape: tuple[int, ...], name: str) -> np.ndarray:
|
||||
arr = np.asarray(value, dtype=np.float64)
|
||||
if arr.shape != shape:
|
||||
raise ValueError(f"{name} must have shape {shape}, got {arr.shape}")
|
||||
return arr
|
||||
|
||||
|
||||
def _normalize_homogeneous(point: np.ndarray) -> np.ndarray:
|
||||
if abs(point[-1]) < 1e-12:
|
||||
raise ValueError("Cannot normalize homogeneous point with near-zero W")
|
||||
return point[:-1] / point[-1]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraModel:
|
||||
"""Pinhole camera model with a world-from-camera transform."""
|
||||
|
||||
sensor_id: str
|
||||
camera_matrix: np.ndarray
|
||||
dist_coeffs: np.ndarray
|
||||
world_from_sensor: np.ndarray
|
||||
width: int
|
||||
height: int
|
||||
role: str = "tracking"
|
||||
latency_ms: float = 0.0
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "CameraModel":
|
||||
intrinsics = data.get("intrinsics", {})
|
||||
return CameraModel(
|
||||
sensor_id=data["id"],
|
||||
camera_matrix=_array(intrinsics["camera_matrix"], (3, 3), "camera_matrix"),
|
||||
dist_coeffs=np.asarray(intrinsics.get("dist_coeffs", []), dtype=np.float64),
|
||||
world_from_sensor=_array(data["world_from_sensor"], (4, 4), "world_from_sensor"),
|
||||
width=int(intrinsics["width"]),
|
||||
height=int(intrinsics["height"]),
|
||||
role=data.get("role", "tracking"),
|
||||
latency_ms=float(data.get("latency_ms", 0.0)),
|
||||
)
|
||||
|
||||
@property
|
||||
def sensor_from_world(self) -> np.ndarray:
|
||||
return np.linalg.inv(self.world_from_sensor)
|
||||
|
||||
@property
|
||||
def projection_matrix(self) -> np.ndarray:
|
||||
return self.camera_matrix @ self.sensor_from_world[:3, :]
|
||||
|
||||
@property
|
||||
def position_world(self) -> np.ndarray:
|
||||
return self.world_from_sensor[:3, 3]
|
||||
|
||||
def project_world(self, point_world: np.ndarray) -> np.ndarray:
|
||||
point = np.ones(4, dtype=np.float64)
|
||||
point[:3] = point_world
|
||||
uvw = self.projection_matrix @ point
|
||||
return _normalize_homogeneous(uvw)
|
||||
|
||||
def reprojection_error(self, point_world: np.ndarray, uv: np.ndarray) -> float:
|
||||
return float(np.linalg.norm(self.project_world(point_world) - uv))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Observation2D:
|
||||
sensor_id: str
|
||||
marker_id: str
|
||||
timestamp_ns: int
|
||||
uv: np.ndarray
|
||||
confidence: float = 1.0
|
||||
sequence: int | None = None
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "Observation2D":
|
||||
return Observation2D(
|
||||
sensor_id=data["sensor_id"],
|
||||
marker_id=data["marker_id"],
|
||||
timestamp_ns=int(data["timestamp_ns"]),
|
||||
uv=_array(data["uv"], (2,), "uv"),
|
||||
confidence=float(data.get("confidence", 1.0)),
|
||||
sequence=None if data.get("sequence") is None else int(data["sequence"]),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TriangulatedPoint:
|
||||
marker_id: str
|
||||
timestamp_ns: int
|
||||
xyz: np.ndarray
|
||||
confidence: float
|
||||
reprojection_error_px: float
|
||||
sensors: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FusionResult:
|
||||
points: tuple[TriangulatedPoint, ...]
|
||||
dropped: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class FusionConfig:
|
||||
max_pair_dt_ns: int = 25_000_000
|
||||
max_reprojection_error_px: float = 4.0
|
||||
min_confidence: float = 0.1
|
||||
cache_ttl_ns: int = 500_000_000
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "FusionConfig":
|
||||
return FusionConfig(
|
||||
max_pair_dt_ns=int(data.get("max_pair_dt_ns", 25_000_000)),
|
||||
max_reprojection_error_px=float(data.get("max_reprojection_error_px", 4.0)),
|
||||
min_confidence=float(data.get("min_confidence", 0.1)),
|
||||
cache_ttl_ns=int(data.get("cache_ttl_ns", 500_000_000)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SensorRig:
|
||||
cameras: dict[str, CameraModel]
|
||||
config: FusionConfig = field(default_factory=FusionConfig)
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "SensorRig":
|
||||
cameras = {item["id"]: CameraModel.from_dict(item) for item in data.get("cameras", [])}
|
||||
if len(cameras) < 2:
|
||||
raise ValueError("Sensor rig needs at least two cameras for triangulation")
|
||||
return SensorRig(cameras=cameras, config=FusionConfig.from_dict(data.get("fusion", {})))
|
||||
|
||||
def fuse(self, observations: Iterable[Observation2D]) -> FusionResult:
|
||||
grouped: dict[str, list[Observation2D]] = {}
|
||||
dropped: list[str] = []
|
||||
for obs in observations:
|
||||
if obs.sensor_id not in self.cameras:
|
||||
dropped.append(f"{obs.marker_id}: unknown sensor {obs.sensor_id}")
|
||||
continue
|
||||
if obs.confidence < self.config.min_confidence:
|
||||
dropped.append(f"{obs.marker_id}: low confidence from {obs.sensor_id}")
|
||||
continue
|
||||
grouped.setdefault(obs.marker_id, []).append(obs)
|
||||
|
||||
points: list[TriangulatedPoint] = []
|
||||
for marker_id, marker_obs in grouped.items():
|
||||
point = self._fuse_marker(marker_id, marker_obs)
|
||||
if point is None:
|
||||
dropped.append(f"{marker_id}: no valid camera pair")
|
||||
else:
|
||||
points.append(point)
|
||||
return FusionResult(points=tuple(points), dropped=tuple(dropped))
|
||||
|
||||
def _fuse_marker(self, marker_id: str, observations: list[Observation2D]) -> TriangulatedPoint | None:
|
||||
best: TriangulatedPoint | None = None
|
||||
ordered = sorted(observations, key=lambda item: item.confidence, reverse=True)
|
||||
for i, left in enumerate(ordered):
|
||||
for right in ordered[i + 1 :]:
|
||||
if left.sensor_id == right.sensor_id:
|
||||
continue
|
||||
dt = abs(left.timestamp_ns - right.timestamp_ns)
|
||||
if dt > self.config.max_pair_dt_ns:
|
||||
continue
|
||||
point = self._triangulate_pair(marker_id, left, right)
|
||||
if point is None:
|
||||
continue
|
||||
if best is None or point.confidence > best.confidence:
|
||||
best = point
|
||||
return best
|
||||
|
||||
def _triangulate_pair(
|
||||
self,
|
||||
marker_id: str,
|
||||
left: Observation2D,
|
||||
right: Observation2D,
|
||||
) -> TriangulatedPoint | None:
|
||||
cam_a = self.cameras[left.sensor_id]
|
||||
cam_b = self.cameras[right.sensor_id]
|
||||
xyz = triangulate_dlt(cam_a.projection_matrix, left.uv, cam_b.projection_matrix, right.uv)
|
||||
error_a = cam_a.reprojection_error(xyz, left.uv)
|
||||
error_b = cam_b.reprojection_error(xyz, right.uv)
|
||||
reprojection_error = (error_a + error_b) * 0.5
|
||||
if not math.isfinite(reprojection_error) or reprojection_error > self.config.max_reprojection_error_px:
|
||||
return None
|
||||
dt = abs(left.timestamp_ns - right.timestamp_ns)
|
||||
time_score = 1.0 - min(1.0, dt / max(1, self.config.max_pair_dt_ns))
|
||||
error_score = 1.0 - min(1.0, reprojection_error / max(1e-9, self.config.max_reprojection_error_px))
|
||||
confidence = float(min(left.confidence, right.confidence) * (0.5 + 0.5 * time_score) * (0.5 + 0.5 * error_score))
|
||||
return TriangulatedPoint(
|
||||
marker_id=marker_id,
|
||||
timestamp_ns=max(left.timestamp_ns, right.timestamp_ns),
|
||||
xyz=xyz,
|
||||
confidence=confidence,
|
||||
reprojection_error_px=float(reprojection_error),
|
||||
sensors=(left.sensor_id, right.sensor_id),
|
||||
)
|
||||
|
||||
|
||||
def triangulate_dlt(proj_a: np.ndarray, uv_a: np.ndarray, proj_b: np.ndarray, uv_b: np.ndarray) -> np.ndarray:
|
||||
"""Triangulate one point from two calibrated cameras using linear DLT."""
|
||||
|
||||
a = np.asarray(proj_a, dtype=np.float64)
|
||||
b = np.asarray(proj_b, dtype=np.float64)
|
||||
u0, v0 = np.asarray(uv_a, dtype=np.float64)
|
||||
u1, v1 = np.asarray(uv_b, dtype=np.float64)
|
||||
system = np.vstack(
|
||||
[
|
||||
u0 * a[2] - a[0],
|
||||
v0 * a[2] - a[1],
|
||||
u1 * b[2] - b[0],
|
||||
v1 * b[2] - b[1],
|
||||
]
|
||||
)
|
||||
_, _, vh = np.linalg.svd(system)
|
||||
return _normalize_homogeneous(vh[-1])
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrackCache:
|
||||
ttl_ns: int
|
||||
tracks: dict[str, TriangulatedPoint] = field(default_factory=dict)
|
||||
|
||||
def update(self, point: TriangulatedPoint) -> None:
|
||||
current = self.tracks.get(point.marker_id)
|
||||
if current is None or point.timestamp_ns >= current.timestamp_ns or point.confidence > current.confidence:
|
||||
self.tracks[point.marker_id] = point
|
||||
|
||||
def expire(self, now_ns: int) -> None:
|
||||
expired = [key for key, value in self.tracks.items() if now_ns - value.timestamp_ns > self.ttl_ns]
|
||||
for key in expired:
|
||||
del self.tracks[key]
|
||||
|
||||
def points(self) -> tuple[TriangulatedPoint, ...]:
|
||||
return tuple(sorted(self.tracks.values(), key=lambda item: item.marker_id))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PointCloud:
|
||||
points: tuple[TriangulatedPoint, ...]
|
||||
|
||||
def write_ply(self, path: Path) -> None:
|
||||
lines = [
|
||||
"ply",
|
||||
"format ascii 1.0",
|
||||
f"element vertex {len(self.points)}",
|
||||
"property float x",
|
||||
"property float y",
|
||||
"property float z",
|
||||
"property uchar red",
|
||||
"property uchar green",
|
||||
"property uchar blue",
|
||||
"property float confidence",
|
||||
"end_header",
|
||||
]
|
||||
for point in self.points:
|
||||
shade = int(max(0, min(255, round(point.confidence * 255))))
|
||||
x, y, z = point.xyz
|
||||
lines.append(f"{x:.9f} {y:.9f} {z:.9f} {shade} {shade} 255 {point.confidence:.6f}")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def load_fusion_config(path: Path) -> SensorRig:
|
||||
return SensorRig.from_dict(json.loads(path.read_text(encoding="utf-8")))
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import CameraModel, triangulate_dlt
|
||||
from .render_bridge import RenderPointPacket
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DenseStereoConfig:
|
||||
sample_step: int = 4
|
||||
block_radius: int = 3
|
||||
max_disparity_px: int = 96
|
||||
min_texture: float = 0.020
|
||||
min_ncc: float = 0.72
|
||||
max_reprojection_error_px: float = 6.0
|
||||
radius_m: float = 0.006
|
||||
|
||||
|
||||
def dense_stereo_points(
|
||||
*,
|
||||
prefix: str,
|
||||
left_frame_bgr: np.ndarray,
|
||||
right_frame_bgr: np.ndarray,
|
||||
left_camera: CameraModel,
|
||||
right_camera: CameraModel,
|
||||
timestamp_ns: int,
|
||||
config: DenseStereoConfig | None = None,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
"""Match textured pixels in a calibrated pair and emit RGB surface claims."""
|
||||
|
||||
cfg = config or DenseStereoConfig()
|
||||
left = _luma(left_frame_bgr)
|
||||
right = _luma(right_frame_bgr)
|
||||
height = min(left.shape[0], right.shape[0], left_camera.height, right_camera.height)
|
||||
width = min(left.shape[1], right.shape[1], left_camera.width, right_camera.width)
|
||||
radius = max(1, int(cfg.block_radius))
|
||||
step = max(1, int(cfg.sample_step))
|
||||
points: list[RenderPointPacket] = []
|
||||
|
||||
for row in range(radius, height - radius, step):
|
||||
for col in range(radius + 1, width - radius, step):
|
||||
patch = _patch(left, row, col, radius)
|
||||
texture = float(np.std(patch))
|
||||
if texture < cfg.min_texture:
|
||||
continue
|
||||
best_col, score = _best_horizontal_match(
|
||||
patch,
|
||||
right,
|
||||
row,
|
||||
col,
|
||||
radius,
|
||||
max_disparity_px=cfg.max_disparity_px,
|
||||
)
|
||||
if best_col is None or score < cfg.min_ncc:
|
||||
continue
|
||||
uv_left = np.array([float(col), float(row)], dtype=np.float64)
|
||||
uv_right = np.array([float(best_col), float(row)], dtype=np.float64)
|
||||
try:
|
||||
xyz = triangulate_dlt(left_camera.projection_matrix, uv_left, right_camera.projection_matrix, uv_right)
|
||||
except ValueError:
|
||||
continue
|
||||
if not np.all(np.isfinite(xyz)):
|
||||
continue
|
||||
error = 0.5 * (
|
||||
left_camera.reprojection_error(xyz, uv_left) + right_camera.reprojection_error(xyz, uv_right)
|
||||
)
|
||||
if error > cfg.max_reprojection_error_px:
|
||||
continue
|
||||
b, g, r = (left_frame_bgr[row, col].astype(np.float32) / 255.0).clip(0.0, 1.0)
|
||||
confidence = max(0.0, min(1.0, (score - cfg.min_ncc) / max(1e-6, 1.0 - cfg.min_ncc)))
|
||||
confidence = max(0.20, min(1.0, 0.35 + confidence * 0.55 + min(0.25, texture)))
|
||||
points.append(
|
||||
RenderPointPacket(
|
||||
stable_key=f"{prefix}:{row}:{col}:{best_col}",
|
||||
xyz=xyz.astype(np.float64),
|
||||
radius_m=cfg.radius_m,
|
||||
color_rgba=(float(r), float(g), float(b), 0.38 + 0.48 * confidence),
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=timestamp_ns,
|
||||
)
|
||||
)
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def _best_horizontal_match(
|
||||
left_patch: np.ndarray,
|
||||
right: np.ndarray,
|
||||
row: int,
|
||||
col: int,
|
||||
radius: int,
|
||||
*,
|
||||
max_disparity_px: int,
|
||||
) -> tuple[int | None, float]:
|
||||
best_col: int | None = None
|
||||
best_score = -1.0
|
||||
min_col = max(radius, col - max_disparity_px)
|
||||
max_col = min(right.shape[1] - radius - 1, col + max_disparity_px // 8)
|
||||
for candidate_col in range(min_col, max_col + 1):
|
||||
score = _ncc(left_patch, _patch(right, row, candidate_col, radius))
|
||||
if score > best_score:
|
||||
best_col = candidate_col
|
||||
best_score = score
|
||||
return best_col, best_score
|
||||
|
||||
|
||||
def _luma(frame_bgr: np.ndarray) -> np.ndarray:
|
||||
if frame_bgr.ndim != 3 or frame_bgr.shape[2] != 3:
|
||||
raise ValueError("frame_bgr must have shape HxWx3")
|
||||
frame = frame_bgr.astype(np.float32) / 255.0
|
||||
return 0.0722 * frame[:, :, 0] + 0.7152 * frame[:, :, 1] + 0.2126 * frame[:, :, 2]
|
||||
|
||||
|
||||
def _patch(image: np.ndarray, row: int, col: int, radius: int) -> np.ndarray:
|
||||
return image[row - radius : row + radius + 1, col - radius : col + radius + 1]
|
||||
|
||||
|
||||
def _ncc(a: np.ndarray, b: np.ndarray) -> float:
|
||||
aa = a.astype(np.float32) - float(np.mean(a))
|
||||
bb = b.astype(np.float32) - float(np.mean(b))
|
||||
denom = float(np.linalg.norm(aa) * np.linalg.norm(bb))
|
||||
if denom < 1e-9:
|
||||
return -1.0
|
||||
return float(np.sum(aa * bb) / denom)
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
"""Pure Leap packed-channel decoding and motion-point lowering."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .render_bridge import RenderPointPacket
|
||||
|
||||
|
||||
def unpack_leap_packed_channels(frame_bgr: np.ndarray) -> dict[str, np.ndarray]:
|
||||
frame = frame_bgr.astype(np.float32) / 255.0
|
||||
blue = frame[:, :, 0]
|
||||
green = frame[:, :, 1]
|
||||
red = frame[:, :, 2]
|
||||
magenta = np.maximum(red, blue)
|
||||
return {
|
||||
"green": green,
|
||||
"magenta": magenta,
|
||||
"red": red,
|
||||
"blue": blue,
|
||||
}
|
||||
|
||||
|
||||
def leap_channel_motion_points(
|
||||
channel_name: str,
|
||||
current: np.ndarray,
|
||||
previous: np.ndarray,
|
||||
timestamp_ns: int,
|
||||
*,
|
||||
step: int,
|
||||
) -> list[RenderPointPacket]:
|
||||
height, width = current.shape[:2]
|
||||
motion = np.abs(current - previous)
|
||||
threshold = max(0.035, float(np.percentile(motion, 94)))
|
||||
points: list[RenderPointPacket] = []
|
||||
for row in range(0, height, step):
|
||||
for col in range(0, width, step):
|
||||
value = float(motion[row, col])
|
||||
intensity = float(current[row, col])
|
||||
if value < threshold and intensity < 0.10:
|
||||
continue
|
||||
u = col / max(1, width - 1)
|
||||
v = row / max(1, height - 1)
|
||||
x = -0.46 + 0.92 * u
|
||||
y = -0.16 + 0.68 * (1.0 - v)
|
||||
z = 0.74 + 0.58 * (1.0 - v) + 0.12 * intensity
|
||||
confidence = max(0.28, min(1.0, value * 3.8 + intensity * 0.42))
|
||||
if channel_name == "green":
|
||||
color = (0.28, 1.0, 0.62, 0.86)
|
||||
elif channel_name == "magenta":
|
||||
color = (1.0, 0.26, 0.92, 0.80)
|
||||
elif channel_name == "red":
|
||||
color = (1.0, 0.22, 0.18, 0.42)
|
||||
else:
|
||||
color = (0.20, 0.42, 1.0, 0.42)
|
||||
points.append(
|
||||
RenderPointPacket(
|
||||
stable_key=f"leap-motion:{channel_name}:{row}:{col}",
|
||||
xyz=np.array([x, y, z], dtype=np.float64),
|
||||
radius_m=0.012 + 0.026 * confidence,
|
||||
color_rgba=color,
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=timestamp_ns,
|
||||
)
|
||||
)
|
||||
return points
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RemoteVideoArtifact:
|
||||
source_name: str
|
||||
url: str
|
||||
expected_latency_ns: int
|
||||
present_time_ns: int
|
||||
delta_ns: int
|
||||
synchronized: bool
|
||||
|
||||
|
||||
def remote_video_artifact_for_present_time(
|
||||
*,
|
||||
source_name: str,
|
||||
url: str,
|
||||
present_time_ns: int,
|
||||
observed_time_ns: int,
|
||||
expected_latency_ns: int,
|
||||
tolerance_ns: int = 120_000_000,
|
||||
) -> RemoteVideoArtifact:
|
||||
media_present_time = int(observed_time_ns) + int(expected_latency_ns)
|
||||
delta_ns = int(present_time_ns) - media_present_time
|
||||
return RemoteVideoArtifact(
|
||||
source_name=str(source_name),
|
||||
url=str(url),
|
||||
expected_latency_ns=int(expected_latency_ns),
|
||||
present_time_ns=media_present_time,
|
||||
delta_ns=delta_ns,
|
||||
synchronized=abs(delta_ns) <= int(tolerance_ns),
|
||||
)
|
||||
|
||||
|
|
@ -1,146 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import TriangulatedPoint
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RenderBridgeConfig:
|
||||
spout_sender_name: str = "Mimir Point Cloud"
|
||||
target_width: int = 1920
|
||||
target_height: int = 1080
|
||||
visual_delay_ns: int = 250_000_000
|
||||
audio_alignment_delay_ns: int = 250_000_000
|
||||
default_point_radius_m: float = 0.025
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "RenderBridgeConfig":
|
||||
return RenderBridgeConfig(
|
||||
spout_sender_name=data.get("spout_sender_name", "Mimir Point Cloud"),
|
||||
target_width=int(data.get("target_width", 1920)),
|
||||
target_height=int(data.get("target_height", 1080)),
|
||||
visual_delay_ns=int(data.get("visual_delay_ns", 250_000_000)),
|
||||
audio_alignment_delay_ns=int(data.get("audio_alignment_delay_ns", 250_000_000)),
|
||||
default_point_radius_m=float(data.get("default_point_radius_m", 0.025)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RenderPointPacket:
|
||||
stable_key: str
|
||||
xyz: np.ndarray
|
||||
radius_m: float
|
||||
color_rgba: tuple[float, float, float, float]
|
||||
confidence: float
|
||||
source_timestamp_ns: int
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"stable_key": self.stable_key,
|
||||
"xyz": [float(v) for v in self.xyz],
|
||||
"radius_m": float(self.radius_m),
|
||||
"color_rgba": [float(v) for v in self.color_rgba],
|
||||
"confidence": float(self.confidence),
|
||||
"source_timestamp_ns": int(self.source_timestamp_ns),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "RenderPointPacket":
|
||||
return RenderPointPacket(
|
||||
stable_key=str(data.get("stable_key", "")),
|
||||
xyz=np.asarray(data["xyz"], dtype=np.float64),
|
||||
radius_m=float(data.get("radius_m", 0.025)),
|
||||
color_rgba=tuple(float(v) for v in data.get("color_rgba", [1.0, 1.0, 1.0, 1.0])),
|
||||
confidence=float(data.get("confidence", 1.0)),
|
||||
source_timestamp_ns=int(data.get("source_timestamp_ns", 0)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RenderFramePacket:
|
||||
schema: str
|
||||
frame_id: int
|
||||
created_monotonic_ns: int
|
||||
source_time_min_ns: int
|
||||
source_time_max_ns: int
|
||||
present_time_ns: int
|
||||
audio_alignment_time_ns: int
|
||||
spout_sender_name: str
|
||||
target_width: int
|
||||
target_height: int
|
||||
points: tuple[RenderPointPacket, ...]
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"schema": self.schema,
|
||||
"frame_id": self.frame_id,
|
||||
"created_monotonic_ns": self.created_monotonic_ns,
|
||||
"source_time_min_ns": self.source_time_min_ns,
|
||||
"source_time_max_ns": self.source_time_max_ns,
|
||||
"present_time_ns": self.present_time_ns,
|
||||
"audio_alignment_time_ns": self.audio_alignment_time_ns,
|
||||
"spout_sender_name": self.spout_sender_name,
|
||||
"target_width": self.target_width,
|
||||
"target_height": self.target_height,
|
||||
"points": [point.to_dict() for point in self.points],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "RenderFramePacket":
|
||||
return RenderFramePacket(
|
||||
schema=str(data.get("schema", "")),
|
||||
frame_id=int(data.get("frame_id", 0)),
|
||||
created_monotonic_ns=int(data.get("created_monotonic_ns", 0)),
|
||||
source_time_min_ns=int(data.get("source_time_min_ns", 0)),
|
||||
source_time_max_ns=int(data.get("source_time_max_ns", 0)),
|
||||
present_time_ns=int(data.get("present_time_ns", 0)),
|
||||
audio_alignment_time_ns=int(data.get("audio_alignment_time_ns", 0)),
|
||||
spout_sender_name=str(data.get("spout_sender_name", "Mimir Point Cloud")),
|
||||
target_width=int(data.get("target_width", 1920)),
|
||||
target_height=int(data.get("target_height", 1080)),
|
||||
points=tuple(RenderPointPacket.from_dict(item) for item in data.get("points", [])),
|
||||
)
|
||||
|
||||
|
||||
def lower_points_to_render_frame(
|
||||
points: tuple[TriangulatedPoint, ...],
|
||||
config: RenderBridgeConfig,
|
||||
frame_id: int,
|
||||
created_monotonic_ns: int,
|
||||
) -> RenderFramePacket:
|
||||
if points:
|
||||
source_min = min(point.timestamp_ns for point in points)
|
||||
source_max = max(point.timestamp_ns for point in points)
|
||||
else:
|
||||
source_min = created_monotonic_ns
|
||||
source_max = created_monotonic_ns
|
||||
render_points = tuple(point_to_render_packet(point, config) for point in points)
|
||||
present_time = source_max + config.visual_delay_ns
|
||||
return RenderFramePacket(
|
||||
schema="localcast.sensor_fusion.render_frame.v1",
|
||||
frame_id=frame_id,
|
||||
created_monotonic_ns=created_monotonic_ns,
|
||||
source_time_min_ns=source_min,
|
||||
source_time_max_ns=source_max,
|
||||
present_time_ns=present_time,
|
||||
audio_alignment_time_ns=source_max + config.audio_alignment_delay_ns,
|
||||
spout_sender_name=config.spout_sender_name,
|
||||
target_width=config.target_width,
|
||||
target_height=config.target_height,
|
||||
points=render_points,
|
||||
)
|
||||
|
||||
|
||||
def point_to_render_packet(point: TriangulatedPoint, config: RenderBridgeConfig) -> RenderPointPacket:
|
||||
confidence = max(0.0, min(1.0, float(point.confidence)))
|
||||
return RenderPointPacket(
|
||||
stable_key=point.marker_id,
|
||||
xyz=point.xyz.astype(np.float64),
|
||||
radius_m=config.default_point_radius_m,
|
||||
color_rgba=(0.25 + 0.75 * confidence, 0.65, 1.0, confidence),
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=point.timestamp_ns,
|
||||
)
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
"""Shared reservoir-window clipping rules for visual evidence."""
|
||||
|
||||
from .render_bridge import RenderPointPacket
|
||||
|
||||
|
||||
DEFAULT_RESERVOIR_NS = 5_000_000_000
|
||||
|
||||
|
||||
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 render_points_in_reservoir(
|
||||
points: tuple[RenderPointPacket, ...],
|
||||
*,
|
||||
latest_timestamp_ns: int,
|
||||
reservoir_ns: int,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
start_ns, end_ns = reservoir_window_ns(latest_timestamp_ns, reservoir_ns)
|
||||
return tuple(point for point in points if start_ns <= int(point.source_timestamp_ns) <= end_ns)
|
||||
|
|
@ -1,213 +0,0 @@
|
|||
"""CPU reference RGB surface lowering used by diagnostics and tests."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import CameraModel
|
||||
from .dense_stereo import DenseStereoConfig, dense_stereo_points
|
||||
from .render_bridge import RenderPointPacket
|
||||
|
||||
|
||||
def rgb_dense_stereo_splats(
|
||||
primary_bgr: np.ndarray,
|
||||
secondary_bgr: np.ndarray,
|
||||
timestamp_ns: int,
|
||||
*,
|
||||
step: int,
|
||||
) -> tuple[RenderPointPacket, ...]:
|
||||
height, width = primary_bgr.shape[:2]
|
||||
secondary_height, secondary_width = secondary_bgr.shape[:2]
|
||||
width = min(width, secondary_width)
|
||||
height = min(height, secondary_height)
|
||||
left = rgb_dense_camera("kiyo-primary", -0.18, width, height)
|
||||
right = rgb_dense_camera("kiyo-secondary", 0.18, width, height)
|
||||
return dense_stereo_points(
|
||||
prefix="dense-rgb",
|
||||
left_frame_bgr=primary_bgr[:height, :width],
|
||||
right_frame_bgr=secondary_bgr[:height, :width],
|
||||
left_camera=left,
|
||||
right_camera=right,
|
||||
timestamp_ns=timestamp_ns,
|
||||
config=DenseStereoConfig(sample_step=step, block_radius=3, max_disparity_px=max(24, width // 3), radius_m=0.0045),
|
||||
)
|
||||
|
||||
|
||||
def rgb_dense_camera(sensor_id: str, x: float, width: int, height: int) -> CameraModel:
|
||||
focal = 0.82 * float(width)
|
||||
return CameraModel(
|
||||
sensor_id=sensor_id,
|
||||
camera_matrix=np.array(
|
||||
[
|
||||
[focal, 0.0, width * 0.5],
|
||||
[0.0, focal, height * 0.5],
|
||||
[0.0, 0.0, 1.0],
|
||||
],
|
||||
dtype=np.float64,
|
||||
),
|
||||
dist_coeffs=np.zeros(5),
|
||||
world_from_sensor=np.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, x],
|
||||
[0.0, 1.0, 0.0, -0.72],
|
||||
[0.0, 0.0, 1.0, 1.28],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
dtype=np.float64,
|
||||
),
|
||||
width=width,
|
||||
height=height,
|
||||
role="rgb_dense_stereo",
|
||||
latency_ms=45.0,
|
||||
)
|
||||
|
||||
|
||||
def rgb_body_splats(
|
||||
prefix: str,
|
||||
frame_bgr: np.ndarray,
|
||||
origin: np.ndarray,
|
||||
now_s: float,
|
||||
timestamp_ns: int,
|
||||
*,
|
||||
side: float,
|
||||
step: int,
|
||||
) -> list[RenderPointPacket]:
|
||||
height, width = frame_bgr.shape[:2]
|
||||
y0, y1, x0, x1 = person_crop(frame_bgr, side)
|
||||
crop_pixels = frame_bgr[y0:y1, x0:x1].astype(np.float32) / 255.0
|
||||
exposure = max(0.18, float(np.percentile(crop_pixels, 92))) if crop_pixels.size else 1.0
|
||||
points: list[RenderPointPacket] = []
|
||||
for row in range(y0, y1, step):
|
||||
for col in range(x0, x1, step):
|
||||
pixel = frame_bgr[row, col].astype(np.float32) / 255.0
|
||||
pixel = np.clip(np.power(np.clip(pixel / exposure, 0.0, 2.2), 0.72), 0.0, 1.0)
|
||||
luminance = float(0.0722 * pixel[0] + 0.7152 * pixel[1] + 0.2126 * pixel[2])
|
||||
saturation = float(np.max(pixel) - np.min(pixel))
|
||||
if luminance < 0.045 and saturation < 0.08:
|
||||
continue
|
||||
u = (col - x0) / max(1, x1 - x0 - 1)
|
||||
v = (row - y0) / max(1, y1 - y0 - 1)
|
||||
body = body_surface_point(u, v, side, now_s)
|
||||
thickness = 0.045 * np.sin((u * 11.0) + (v * 7.0) + now_s) + 0.030 * (luminance - 0.35)
|
||||
xyz = origin + body + np.array([0.0, thickness, 0.0])
|
||||
b, g, r = pixel
|
||||
alpha = max(0.34, min(0.92, 0.28 + luminance * 0.72 + saturation * 0.22))
|
||||
confidence = max(0.45, min(1.0, 0.55 + luminance * 0.35 + saturation * 0.25))
|
||||
radius = 0.014 + 0.020 * max(0.0, 1.0 - abs(v - 0.48) * 1.4)
|
||||
points.append(_render_point(f"{prefix}:{row}:{col}", xyz, radius, (float(r), float(g), float(b), alpha), confidence, timestamp_ns))
|
||||
return points
|
||||
|
||||
|
||||
def rgb_room_splats(
|
||||
prefix: str,
|
||||
frame_bgr: np.ndarray,
|
||||
camera_origin: np.ndarray,
|
||||
timestamp_ns: int,
|
||||
*,
|
||||
step: int,
|
||||
) -> list[RenderPointPacket]:
|
||||
height, width = frame_bgr.shape[:2]
|
||||
points: list[RenderPointPacket] = []
|
||||
body_crop = person_crop(frame_bgr, -1.0)
|
||||
for row in range(0, height, step):
|
||||
for col in range(0, width, step):
|
||||
if inside_person_crop(row, col, body_crop):
|
||||
continue
|
||||
pixel = frame_bgr[row, col].astype(np.float32) / 255.0
|
||||
luminance = float(0.0722 * pixel[0] + 0.7152 * pixel[1] + 0.2126 * pixel[2])
|
||||
saturation = float(np.max(pixel) - np.min(pixel))
|
||||
if luminance < 0.030 and saturation < 0.06:
|
||||
continue
|
||||
u = col / max(1, width - 1)
|
||||
v = row / max(1, height - 1)
|
||||
xyz = room_surface_point(u, v, camera_origin)
|
||||
b, g, r = np.clip(np.power(pixel, 0.78), 0.0, 1.0)
|
||||
alpha = max(0.16, min(0.58, 0.12 + luminance * 0.48 + saturation * 0.16))
|
||||
confidence = max(0.30, min(0.82, 0.38 + luminance * 0.32 + saturation * 0.18))
|
||||
points.append(_render_point(f"{prefix}:{row}:{col}", xyz, 0.024 + 0.018 * confidence, (float(r), float(g), float(b), alpha), confidence, timestamp_ns))
|
||||
return points
|
||||
|
||||
|
||||
def inside_person_crop(row: int, col: int, crop: tuple[int, int, int, int]) -> bool:
|
||||
y0, y1, x0, x1 = crop
|
||||
pad_y = max(6, (y1 - y0) // 18)
|
||||
pad_x = max(6, (x1 - x0) // 18)
|
||||
return y0 - pad_y <= row <= y1 + pad_y and x0 - pad_x <= col <= x1 + pad_x
|
||||
|
||||
|
||||
def room_surface_point(u: float, v: float, camera_origin: np.ndarray) -> np.ndarray:
|
||||
x = -1.75 + 3.5 * u
|
||||
if v > 0.70:
|
||||
floor_v = (v - 0.70) / 0.30
|
||||
y = -0.95 + 1.85 * (1.0 - floor_v)
|
||||
z = 0.018 + 0.05 * (1.0 - floor_v)
|
||||
elif v < 0.26:
|
||||
wall_v = v / 0.26
|
||||
y = 1.12
|
||||
z = 1.15 + 0.90 * (1.0 - wall_v)
|
||||
else:
|
||||
mid_v = (v - 0.26) / 0.44
|
||||
y = 1.05 - 0.55 * mid_v
|
||||
z = 1.12 - 0.55 * mid_v
|
||||
parallax = 0.10 * np.array([camera_origin[0], camera_origin[1], 0.0], dtype=np.float64)
|
||||
return np.array([x, y, z], dtype=np.float64) + parallax
|
||||
|
||||
|
||||
def person_crop(frame_bgr: np.ndarray, side: float) -> tuple[int, int, int, int]:
|
||||
height, width = frame_bgr.shape[:2]
|
||||
gray = np.max(frame_bgr, axis=2)
|
||||
threshold = max(18.0, float(np.percentile(gray, 63)))
|
||||
mask = gray > threshold
|
||||
if mask.any():
|
||||
ys, xs = np.nonzero(mask)
|
||||
x0 = max(0, int(np.percentile(xs, 8)) - width // 20)
|
||||
x1 = min(width, int(np.percentile(xs, 94)) + width // 20)
|
||||
y0 = max(0, int(np.percentile(ys, 4)) - height // 24)
|
||||
y1 = min(height, int(np.percentile(ys, 96)) + height // 24)
|
||||
else:
|
||||
x0, x1 = int(width * 0.18), int(width * 0.82)
|
||||
y0, y1 = int(height * 0.05), int(height * 0.95)
|
||||
if x1 - x0 < width * 0.25:
|
||||
center = int(width * (0.42 if side < 0 else 0.58))
|
||||
half = int(width * 0.24)
|
||||
x0, x1 = max(0, center - half), min(width, center + half)
|
||||
return y0, y1, x0, x1
|
||||
|
||||
|
||||
def body_surface_point(u: float, v: float, side: float, now_s: float) -> np.ndarray:
|
||||
theta = (u - 0.5) * np.pi * 1.15
|
||||
if v < 0.24:
|
||||
vv = v / 0.24
|
||||
radius_x = 0.18 * np.sin(max(0.03, vv) * np.pi)
|
||||
z = 1.42 + vv * 0.34
|
||||
x = radius_x * np.sin(theta) + 0.025 * np.sin(now_s)
|
||||
y = 0.02 * np.cos(theta)
|
||||
elif v < 0.78:
|
||||
vv = (v - 0.24) / 0.54
|
||||
width = 0.24 * (1.0 - abs(vv - 0.48) * 0.42)
|
||||
z = 0.74 + (1.0 - vv) * 0.68
|
||||
x = width * np.sin(theta)
|
||||
y = 0.055 * np.cos(theta)
|
||||
else:
|
||||
vv = (v - 0.78) / 0.22
|
||||
arm = side * (0.20 + 0.26 * abs(u - 0.5) * 2.0)
|
||||
x = arm * vv + 0.06 * np.sin(theta)
|
||||
y = 0.045 * np.cos(theta)
|
||||
z = 1.02 - 0.34 * vv
|
||||
return np.array([x, y, z], dtype=np.float64)
|
||||
|
||||
|
||||
def _render_point(
|
||||
key: str,
|
||||
xyz: np.ndarray,
|
||||
radius_m: float,
|
||||
color: tuple[float, float, float, float],
|
||||
confidence: float,
|
||||
timestamp_ns: int,
|
||||
) -> RenderPointPacket:
|
||||
return RenderPointPacket(
|
||||
stable_key=key,
|
||||
xyz=np.asarray(xyz, dtype=np.float64),
|
||||
radius_m=radius_m,
|
||||
color_rgba=color,
|
||||
confidence=confidence,
|
||||
source_timestamp_ns=timestamp_ns,
|
||||
)
|
||||
|
|
@ -1,427 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import CameraModel, TriangulatedPoint, triangulate_dlt
|
||||
from .surface_features import SurfaceFeatureObservation, descriptor_distance
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SceneRay:
|
||||
sensor_id: str
|
||||
timestamp_ns: int
|
||||
uv: np.ndarray
|
||||
origin: np.ndarray
|
||||
direction: np.ndarray
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransientMatchHypothesis:
|
||||
stable_key: str
|
||||
observations: tuple[SurfaceFeatureObservation, ...]
|
||||
xyz: np.ndarray
|
||||
confidence: float
|
||||
reprojection_error_px: float
|
||||
ray_disagreement_m: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RayBiasSample:
|
||||
sensor_id: str
|
||||
uv: np.ndarray
|
||||
residual_px: np.ndarray
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImageRayBiasMap:
|
||||
"""Learns a smooth per-sensor image-space correction from reprojection residuals."""
|
||||
|
||||
cell_size_px: int = 64
|
||||
smoothing: float = 0.2
|
||||
_cells: dict[tuple[str, int, int], tuple[np.ndarray, float]] = field(default_factory=dict)
|
||||
|
||||
def observe(self, sample: RayBiasSample) -> None:
|
||||
key = self._key(sample.sensor_id, sample.uv)
|
||||
previous = self._cells.get(key)
|
||||
residual = np.asarray(sample.residual_px, dtype=np.float64)
|
||||
confidence = max(0.0, min(1.0, float(sample.confidence)))
|
||||
if previous is None:
|
||||
self._cells[key] = (residual, confidence)
|
||||
return
|
||||
current, weight = previous
|
||||
alpha = self.smoothing * confidence
|
||||
updated = (1.0 - alpha) * current + alpha * residual
|
||||
self._cells[key] = (updated, max(weight * 0.98, confidence))
|
||||
|
||||
def correct_uv(self, sensor_id: str, uv: np.ndarray) -> np.ndarray:
|
||||
correction, _ = self._cells.get(self._key(sensor_id, uv), (np.zeros(2, dtype=np.float64), 0.0))
|
||||
return np.asarray(uv, dtype=np.float64) + correction
|
||||
|
||||
def _key(self, sensor_id: str, uv: np.ndarray) -> tuple[str, int, int]:
|
||||
point = np.asarray(uv, dtype=np.float64)
|
||||
return (str(sensor_id), int(point[0] // self.cell_size_px), int(point[1] // self.cell_size_px))
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"cellSizePx": self.cell_size_px,
|
||||
"smoothing": self.smoothing,
|
||||
"cells": [
|
||||
{
|
||||
"sensorId": sensor_id,
|
||||
"cellX": cell_x,
|
||||
"cellY": cell_y,
|
||||
"residualPx": [float(value) for value in residual],
|
||||
"confidence": float(confidence),
|
||||
}
|
||||
for (sensor_id, cell_x, cell_y), (residual, confidence) in sorted(self._cells.items())
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LODCell:
|
||||
level: int
|
||||
cell: tuple[int, int, int]
|
||||
center: tuple[float, float, float]
|
||||
radius_m: float
|
||||
confidence: float
|
||||
count: int
|
||||
source_time_min_ns: int
|
||||
source_time_max_ns: int
|
||||
source_priority: float = 1.0
|
||||
source_kind: str = "generic"
|
||||
material_albedo: tuple[float, float, float] = (1.0, 1.0, 1.0)
|
||||
material_roughness: float = 0.7
|
||||
material_metallic: float = 0.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MultiLODSceneCache:
|
||||
schema: str
|
||||
created_monotonic_ns: int
|
||||
levels: tuple[float, ...]
|
||||
cells: tuple[LODCell, ...]
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"schema": self.schema,
|
||||
"createdMonotonicNs": int(self.created_monotonic_ns),
|
||||
"levels": [float(level) for level in self.levels],
|
||||
"cells": [
|
||||
{
|
||||
"level": cell.level,
|
||||
"cell": list(cell.cell),
|
||||
"center": list(cell.center),
|
||||
"radiusM": cell.radius_m,
|
||||
"confidence": cell.confidence,
|
||||
"count": cell.count,
|
||||
"sourceTimeMinNs": cell.source_time_min_ns,
|
||||
"sourceTimeMaxNs": cell.source_time_max_ns,
|
||||
"sourcePriority": cell.source_priority,
|
||||
"sourceKind": cell.source_kind,
|
||||
"material": {
|
||||
"albedo": list(cell.material_albedo),
|
||||
"roughness": float(cell.material_roughness),
|
||||
"metallic": float(cell.material_metallic),
|
||||
},
|
||||
}
|
||||
for cell in self.cells
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def pixel_scene_ray(camera: CameraModel, uv: np.ndarray, timestamp_ns: int, confidence: float = 1.0) -> SceneRay:
|
||||
point = np.asarray([float(uv[0]), float(uv[1]), 1.0], dtype=np.float64)
|
||||
direction_sensor = np.linalg.inv(camera.camera_matrix) @ point
|
||||
direction_sensor = direction_sensor / max(1.0e-12, np.linalg.norm(direction_sensor))
|
||||
rotation = camera.world_from_sensor[:3, :3]
|
||||
direction_world = rotation @ direction_sensor
|
||||
direction_world = direction_world / max(1.0e-12, np.linalg.norm(direction_world))
|
||||
return SceneRay(
|
||||
sensor_id=camera.sensor_id,
|
||||
timestamp_ns=int(timestamp_ns),
|
||||
uv=np.asarray(uv, dtype=np.float64),
|
||||
origin=camera.position_world.astype(np.float64),
|
||||
direction=direction_world.astype(np.float64),
|
||||
confidence=float(confidence),
|
||||
)
|
||||
|
||||
|
||||
def stochastic_transient_matches(
|
||||
observations: Sequence[SurfaceFeatureObservation],
|
||||
cameras: dict[str, CameraModel],
|
||||
*,
|
||||
max_dt_ns: int = 25_000_000,
|
||||
max_descriptor_distance: float = 48.0,
|
||||
max_reprojection_error_px: float = 6.0,
|
||||
samples_per_observation: int = 4,
|
||||
seed: int = 0,
|
||||
) -> tuple[TransientMatchHypothesis, ...]:
|
||||
rng = np.random.default_rng(seed)
|
||||
usable = [obs for obs in observations if obs.sensor_id in cameras]
|
||||
hypotheses: list[TransientMatchHypothesis] = []
|
||||
for index, left in enumerate(usable):
|
||||
candidates = [
|
||||
right
|
||||
for right in usable
|
||||
if right.sensor_id != left.sensor_id
|
||||
and abs(right.timestamp_ns - left.timestamp_ns) <= max_dt_ns
|
||||
and descriptor_distance(left.descriptor, right.descriptor) <= max_descriptor_distance
|
||||
]
|
||||
if not candidates:
|
||||
continue
|
||||
rng.shuffle(candidates)
|
||||
for right in candidates[: max(1, int(samples_per_observation))]:
|
||||
hypothesis = triangulate_hypothesis(
|
||||
left,
|
||||
right,
|
||||
cameras,
|
||||
max_reprojection_error_px=max_reprojection_error_px,
|
||||
max_descriptor_distance=max_descriptor_distance,
|
||||
)
|
||||
if hypothesis is not None:
|
||||
hypotheses.append(hypothesis)
|
||||
return suppress_duplicate_hypotheses(hypotheses)
|
||||
|
||||
|
||||
def triangulate_hypothesis(
|
||||
left: SurfaceFeatureObservation,
|
||||
right: SurfaceFeatureObservation,
|
||||
cameras: dict[str, CameraModel],
|
||||
*,
|
||||
max_reprojection_error_px: float,
|
||||
max_descriptor_distance: float,
|
||||
) -> TransientMatchHypothesis | None:
|
||||
cam_a = cameras[left.sensor_id]
|
||||
cam_b = cameras[right.sensor_id]
|
||||
try:
|
||||
xyz = triangulate_dlt(cam_a.projection_matrix, left.uv, cam_b.projection_matrix, right.uv)
|
||||
except ValueError:
|
||||
return None
|
||||
error_a = cam_a.reprojection_error(xyz, left.uv)
|
||||
error_b = cam_b.reprojection_error(xyz, right.uv)
|
||||
error = float((error_a + error_b) * 0.5)
|
||||
if not np.isfinite(error) or error > max_reprojection_error_px:
|
||||
return None
|
||||
distance = descriptor_distance(left.descriptor, right.descriptor)
|
||||
descriptor_score = 1.0 - min(1.0, distance / max(1.0e-9, max_descriptor_distance))
|
||||
error_score = 1.0 - min(1.0, error / max(1.0e-9, max_reprojection_error_px))
|
||||
ray_distance = closest_ray_distance(
|
||||
pixel_scene_ray(cam_a, left.uv, left.timestamp_ns, left.confidence),
|
||||
pixel_scene_ray(cam_b, right.uv, right.timestamp_ns, right.confidence),
|
||||
)
|
||||
ray_score = 1.0 / (1.0 + ray_distance)
|
||||
confidence = float(min(left.confidence, right.confidence) * (0.4 + 0.3 * descriptor_score + 0.2 * error_score + 0.1 * ray_score))
|
||||
return TransientMatchHypothesis(
|
||||
stable_key=f"transient:{left.sensor_id}:{right.sensor_id}:{left.feature_id}:{right.feature_id}",
|
||||
observations=(left, right),
|
||||
xyz=xyz.astype(np.float64),
|
||||
confidence=confidence,
|
||||
reprojection_error_px=error,
|
||||
ray_disagreement_m=float(ray_distance),
|
||||
)
|
||||
|
||||
|
||||
def closest_ray_distance(left: SceneRay, right: SceneRay) -> float:
|
||||
p1 = left.origin
|
||||
d1 = left.direction
|
||||
p2 = right.origin
|
||||
d2 = right.direction
|
||||
cross = np.cross(d1, d2)
|
||||
denom = float(np.linalg.norm(cross))
|
||||
if denom <= 1.0e-9:
|
||||
return float(np.linalg.norm(np.cross(p2 - p1, d1)))
|
||||
return float(abs(np.dot(p2 - p1, cross)) / denom)
|
||||
|
||||
|
||||
def suppress_duplicate_hypotheses(hypotheses: Iterable[TransientMatchHypothesis]) -> tuple[TransientMatchHypothesis, ...]:
|
||||
best: dict[str, TransientMatchHypothesis] = {}
|
||||
for hypothesis in hypotheses:
|
||||
key = ":".join(sorted(obs.sensor_id for obs in hypothesis.observations)) + ":" + ":".join(sorted(obs.feature_id for obs in hypothesis.observations))
|
||||
current = best.get(key)
|
||||
if current is None or hypothesis.confidence > current.confidence:
|
||||
best[key] = hypothesis
|
||||
return tuple(sorted(best.values(), key=lambda item: item.confidence, reverse=True))
|
||||
|
||||
|
||||
def learn_ray_bias_from_points(
|
||||
cameras: dict[str, CameraModel],
|
||||
points: Iterable[TriangulatedPoint],
|
||||
bias_map: ImageRayBiasMap,
|
||||
) -> ImageRayBiasMap:
|
||||
for point in points:
|
||||
for sensor_id in point.sensors:
|
||||
camera = cameras.get(sensor_id)
|
||||
if camera is None:
|
||||
continue
|
||||
projected = camera.project_world(point.xyz)
|
||||
bias_map.observe(
|
||||
RayBiasSample(
|
||||
sensor_id=sensor_id,
|
||||
uv=projected,
|
||||
residual_px=np.zeros(2, dtype=np.float64),
|
||||
confidence=point.confidence,
|
||||
)
|
||||
)
|
||||
return bias_map
|
||||
|
||||
|
||||
def multilod_cache_from_points(
|
||||
points: Iterable[TriangulatedPoint | TransientMatchHypothesis],
|
||||
*,
|
||||
levels: tuple[float, ...] = (0.02, 0.08, 0.32),
|
||||
created_monotonic_ns: int = 0,
|
||||
) -> MultiLODSceneCache:
|
||||
items = list(points)
|
||||
cells: list[LODCell] = []
|
||||
for level_index, cell_size in enumerate(levels):
|
||||
buckets: dict[tuple[int, int, int], list] = {}
|
||||
for item in items:
|
||||
xyz = np.asarray(item.xyz, dtype=np.float64)
|
||||
key = tuple(int(np.floor(value / float(cell_size))) for value in xyz)
|
||||
buckets.setdefault(key, []).append(item)
|
||||
for key, bucket in buckets.items():
|
||||
weights = np.asarray([max(1.0e-6, float(item.confidence)) for item in bucket], dtype=np.float64)
|
||||
positions = np.asarray([np.asarray(item.xyz, dtype=np.float64) for item in bucket], dtype=np.float64)
|
||||
center = np.average(positions, axis=0, weights=weights)
|
||||
timestamps = [item_timestamp_ns(item) for item in bucket]
|
||||
cells.append(
|
||||
LODCell(
|
||||
level=level_index,
|
||||
cell=key,
|
||||
center=tuple(float(value) for value in center),
|
||||
radius_m=float(cell_size) * 0.5,
|
||||
confidence=float(np.mean(weights)),
|
||||
count=len(bucket),
|
||||
source_time_min_ns=min(timestamps),
|
||||
source_time_max_ns=max(timestamps),
|
||||
)
|
||||
)
|
||||
return MultiLODSceneCache(
|
||||
schema="localcast.sensor_fusion.multilod_scene_cache.v1",
|
||||
created_monotonic_ns=int(created_monotonic_ns),
|
||||
levels=tuple(float(level) for level in levels),
|
||||
cells=tuple(cells),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LODEvidencePoint:
|
||||
stable_key: str
|
||||
xyz: np.ndarray
|
||||
confidence: float
|
||||
timestamp_ns: int
|
||||
source_priority: float
|
||||
source_kind: str
|
||||
albedo: tuple[float, float, float] = (1.0, 1.0, 1.0)
|
||||
roughness: float = 0.7
|
||||
metallic: float = 0.0
|
||||
|
||||
|
||||
def multilod_cache_from_evidence(
|
||||
evidence: Iterable[LODEvidencePoint],
|
||||
*,
|
||||
levels: tuple[float, ...] = (0.02, 0.08, 0.32),
|
||||
created_monotonic_ns: int = 0,
|
||||
) -> MultiLODSceneCache:
|
||||
items = list(evidence)
|
||||
cells: list[LODCell] = []
|
||||
for level_index, cell_size in enumerate(levels):
|
||||
buckets: dict[tuple[int, int, int], list[LODEvidencePoint]] = {}
|
||||
for item in items:
|
||||
key = tuple(int(np.floor(float(value) / float(cell_size))) for value in np.asarray(item.xyz, dtype=np.float64))
|
||||
buckets.setdefault(key, []).append(item)
|
||||
for key, bucket in buckets.items():
|
||||
weights = np.asarray([max(1.0e-6, item.confidence * item.source_priority) for item in bucket], dtype=np.float64)
|
||||
positions = np.asarray([np.asarray(item.xyz, dtype=np.float64) for item in bucket], dtype=np.float64)
|
||||
center = np.average(positions, axis=0, weights=weights)
|
||||
priority = float(max(item.source_priority for item in bucket))
|
||||
source_kind = max(bucket, key=lambda item: item.source_priority).source_kind
|
||||
albedos = np.asarray([np.asarray(item.albedo, dtype=np.float64) for item in bucket], dtype=np.float64)
|
||||
albedo = np.average(albedos, axis=0, weights=weights)
|
||||
roughness = float(np.average([item.roughness for item in bucket], weights=weights))
|
||||
metallic = float(np.average([item.metallic for item in bucket], weights=weights))
|
||||
cells.append(
|
||||
LODCell(
|
||||
level=level_index,
|
||||
cell=key,
|
||||
center=tuple(float(value) for value in center),
|
||||
radius_m=float(cell_size) * 0.5,
|
||||
confidence=float(min(1.0, np.mean(weights))),
|
||||
count=len(bucket),
|
||||
source_time_min_ns=min(item.timestamp_ns for item in bucket),
|
||||
source_time_max_ns=max(item.timestamp_ns for item in bucket),
|
||||
source_priority=priority,
|
||||
source_kind=source_kind,
|
||||
material_albedo=tuple(float(np.clip(value, 0.0, 1.0)) for value in albedo),
|
||||
material_roughness=float(np.clip(roughness, 0.0, 1.0)),
|
||||
material_metallic=float(np.clip(metallic, 0.0, 1.0)),
|
||||
)
|
||||
)
|
||||
return MultiLODSceneCache(
|
||||
schema="localcast.sensor_fusion.multilod_scene_cache.v1",
|
||||
created_monotonic_ns=int(created_monotonic_ns),
|
||||
levels=tuple(float(level) for level in levels),
|
||||
cells=tuple(cells),
|
||||
)
|
||||
|
||||
|
||||
def evidence_from_render_points(points: Iterable, *, source_kind: str, source_priority: float) -> tuple[LODEvidencePoint, ...]:
|
||||
rows: list[LODEvidencePoint] = []
|
||||
for point in points:
|
||||
rgba = np.clip(np.asarray(getattr(point, "color_rgba", (1.0, 1.0, 1.0, 1.0)), dtype=np.float64), 0.0, 1.0)
|
||||
rows.append(
|
||||
LODEvidencePoint(
|
||||
stable_key=str(point.stable_key),
|
||||
xyz=np.asarray(point.xyz, dtype=np.float64),
|
||||
confidence=float(point.confidence),
|
||||
timestamp_ns=int(point.source_timestamp_ns),
|
||||
source_priority=float(source_priority),
|
||||
source_kind=str(source_kind),
|
||||
albedo=tuple(float(value) for value in rgba[:3]),
|
||||
roughness=roughness_from_rgba(rgba, source_kind=source_kind),
|
||||
metallic=0.0,
|
||||
)
|
||||
)
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
def evidence_from_fusion_items(
|
||||
items: Iterable[TriangulatedPoint | TransientMatchHypothesis],
|
||||
*,
|
||||
source_kind: str,
|
||||
source_priority: float,
|
||||
) -> tuple[LODEvidencePoint, ...]:
|
||||
rows: list[LODEvidencePoint] = []
|
||||
for item in items:
|
||||
rows.append(
|
||||
LODEvidencePoint(
|
||||
stable_key=str(getattr(item, "marker_id", getattr(item, "stable_key", "scene-claim"))),
|
||||
xyz=np.asarray(item.xyz, dtype=np.float64),
|
||||
confidence=float(item.confidence),
|
||||
timestamp_ns=item_timestamp_ns(item),
|
||||
source_priority=float(source_priority),
|
||||
source_kind=str(source_kind),
|
||||
)
|
||||
)
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
def item_timestamp_ns(item: TriangulatedPoint | TransientMatchHypothesis) -> int:
|
||||
if hasattr(item, "timestamp_ns"):
|
||||
return int(getattr(item, "timestamp_ns"))
|
||||
return int(max(obs.timestamp_ns for obs in item.observations))
|
||||
|
||||
|
||||
def roughness_from_rgba(rgba: np.ndarray, *, source_kind: str) -> float:
|
||||
rgb = np.asarray(rgba[:3], dtype=np.float64)
|
||||
saturation = float(np.max(rgb) - np.min(rgb))
|
||||
alpha = float(rgba[3]) if rgba.size > 3 else 1.0
|
||||
base = 0.82 if "rgb" in source_kind else 0.74
|
||||
roughness = base - 0.22 * saturation + 0.10 * (1.0 - alpha)
|
||||
return float(np.clip(roughness, 0.25, 0.95))
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .core import CameraModel, TriangulatedPoint, triangulate_dlt
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SurfaceFeatureObservation:
|
||||
sensor_id: str
|
||||
feature_id: str
|
||||
timestamp_ns: int
|
||||
uv: np.ndarray
|
||||
descriptor: np.ndarray
|
||||
color_bgr: tuple[int, int, int] = (255, 255, 255)
|
||||
confidence: float = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SurfaceFeatureTrack:
|
||||
track_id: str
|
||||
observations: tuple[SurfaceFeatureObservation, ...]
|
||||
|
||||
|
||||
def match_surface_features(
|
||||
left: Iterable[SurfaceFeatureObservation],
|
||||
right: Iterable[SurfaceFeatureObservation],
|
||||
*,
|
||||
max_descriptor_distance: float,
|
||||
max_dt_ns: int,
|
||||
) -> tuple[SurfaceFeatureTrack, ...]:
|
||||
tracks: list[SurfaceFeatureTrack] = []
|
||||
used_right: set[int] = set()
|
||||
right_items = list(right)
|
||||
for left_item in left:
|
||||
best_index = -1
|
||||
best_distance = float("inf")
|
||||
for index, right_item in enumerate(right_items):
|
||||
if index in used_right or right_item.sensor_id == left_item.sensor_id:
|
||||
continue
|
||||
if abs(right_item.timestamp_ns - left_item.timestamp_ns) > max_dt_ns:
|
||||
continue
|
||||
distance = descriptor_distance(left_item.descriptor, right_item.descriptor)
|
||||
if distance < best_distance:
|
||||
best_index = index
|
||||
best_distance = distance
|
||||
if best_index < 0 or best_distance > max_descriptor_distance:
|
||||
continue
|
||||
used_right.add(best_index)
|
||||
right_item = right_items[best_index]
|
||||
tracks.append(
|
||||
SurfaceFeatureTrack(
|
||||
track_id=f"{left_item.sensor_id}:{right_item.sensor_id}:{left_item.feature_id}:{right_item.feature_id}",
|
||||
observations=(left_item, right_item),
|
||||
)
|
||||
)
|
||||
return tuple(tracks)
|
||||
|
||||
|
||||
def triangulate_surface_tracks(
|
||||
tracks: Iterable[SurfaceFeatureTrack],
|
||||
cameras: dict[str, CameraModel],
|
||||
*,
|
||||
max_reprojection_error_px: float = 4.0,
|
||||
) -> tuple[TriangulatedPoint, ...]:
|
||||
points: list[TriangulatedPoint] = []
|
||||
for track in tracks:
|
||||
if len(track.observations) < 2:
|
||||
continue
|
||||
left, right = track.observations[:2]
|
||||
cam_a = cameras.get(left.sensor_id)
|
||||
cam_b = cameras.get(right.sensor_id)
|
||||
if cam_a is None or cam_b is None:
|
||||
continue
|
||||
try:
|
||||
xyz = triangulate_dlt(cam_a.projection_matrix, left.uv, cam_b.projection_matrix, right.uv)
|
||||
except ValueError:
|
||||
continue
|
||||
error_a = cam_a.reprojection_error(xyz, left.uv)
|
||||
error_b = cam_b.reprojection_error(xyz, right.uv)
|
||||
reprojection_error = float((error_a + error_b) * 0.5)
|
||||
if not np.isfinite(reprojection_error) or reprojection_error > max_reprojection_error_px:
|
||||
continue
|
||||
confidence = min(left.confidence, right.confidence) * max(0.0, 1.0 - reprojection_error / max_reprojection_error_px)
|
||||
points.append(
|
||||
TriangulatedPoint(
|
||||
marker_id=track.track_id,
|
||||
timestamp_ns=max(left.timestamp_ns, right.timestamp_ns),
|
||||
xyz=xyz,
|
||||
confidence=float(confidence),
|
||||
reprojection_error_px=reprojection_error,
|
||||
sensors=(left.sensor_id, right.sensor_id),
|
||||
)
|
||||
)
|
||||
return tuple(points)
|
||||
|
||||
|
||||
def orb_surface_observations(
|
||||
sensor_id: str,
|
||||
frame_bgr: np.ndarray,
|
||||
timestamp_ns: int,
|
||||
*,
|
||||
max_features: int = 2000,
|
||||
) -> tuple[SurfaceFeatureObservation, ...]:
|
||||
import cv2
|
||||
|
||||
gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
|
||||
detector = cv2.ORB_create(nfeatures=max_features)
|
||||
keypoints, descriptors = detector.detectAndCompute(gray, None)
|
||||
if descriptors is None:
|
||||
return ()
|
||||
observations: list[SurfaceFeatureObservation] = []
|
||||
height, width = frame_bgr.shape[:2]
|
||||
for index, (keypoint, descriptor) in enumerate(zip(keypoints, descriptors)):
|
||||
x = int(np.clip(round(keypoint.pt[0]), 0, width - 1))
|
||||
y = int(np.clip(round(keypoint.pt[1]), 0, height - 1))
|
||||
b, g, r = frame_bgr[y, x].tolist()
|
||||
observations.append(
|
||||
SurfaceFeatureObservation(
|
||||
sensor_id=sensor_id,
|
||||
feature_id=f"orb:{index}",
|
||||
timestamp_ns=timestamp_ns,
|
||||
uv=np.array([keypoint.pt[0], keypoint.pt[1]], dtype=np.float64),
|
||||
descriptor=descriptor.astype(np.uint8),
|
||||
color_bgr=(int(b), int(g), int(r)),
|
||||
confidence=float(min(1.0, keypoint.response * 40.0 + 0.25)),
|
||||
)
|
||||
)
|
||||
return tuple(observations)
|
||||
|
||||
|
||||
def descriptor_distance(left: np.ndarray, right: np.ndarray) -> float:
|
||||
a = np.asarray(left)
|
||||
b = np.asarray(right)
|
||||
if a.shape != b.shape:
|
||||
return float("inf")
|
||||
if a.dtype == np.uint8 and b.dtype == np.uint8:
|
||||
return float(np.unpackbits(np.bitwise_xor(a, b)).sum())
|
||||
delta = a.astype(np.float32) - b.astype(np.float32)
|
||||
return float(np.linalg.norm(delta))
|
||||
|
|
@ -2,9 +2,6 @@
|
|||
|
||||
This directory is for the hot path.
|
||||
|
||||
Mimir Python remains useful for calibration, launch, status, contract
|
||||
tests, and offline analysis. It does not own dense live fusion or DSP.
|
||||
|
||||
## Crates
|
||||
|
||||
- `reservoir`: the first native five-second spatiotemporal reservoir core. It
|
||||
|
|
@ -38,8 +35,7 @@ The reservoir ABI is intentionally small:
|
|||
|
||||
## Runtime ABI
|
||||
|
||||
`LocalcastRuntime` is the live spine that should replace the Python file-cache
|
||||
runtime path:
|
||||
`LocalcastRuntime` is the live spine for Aquarium/Faust integration:
|
||||
|
||||
- it owns one native reservoir;
|
||||
- it exposes typed producer functions for camera frames, camera features, scene
|
||||
|
|
|
|||
|
|
@ -1,34 +1,24 @@
|
|||
# Current System Map
|
||||
# Current System Map
|
||||
|
||||
Mimir is the public Face and product name for this repo. `localcast` remains
|
||||
the implementation surface where existing scripts, paths, schemas, and ABIs
|
||||
still use it.
|
||||
Mimir is the public Face and product name for this repo. A few lower native ABI
|
||||
names still use `localcast` until a deliberate rename cut exists.
|
||||
|
||||
The repo is intentionally thin. The target live machine is not the
|
||||
deadline bridge; it is the native rolling reservoir described in
|
||||
The live target is the native rolling field machine described in
|
||||
`docs/native-rebuild-plan.md`, `docs/perfect-machine.md`, and
|
||||
`config/perfect-machine.example.json`.
|
||||
|
||||
Mimir's persistent Face state is part of the operating machine:
|
||||
|
||||
- `docs/mimir-face.md` owns the Face doctrine, jurisdiction, heartbeat behavior,
|
||||
and inherited memory packet.
|
||||
- `.voidbot/voice/identity.json` and `.voidbot/voice/mimir.png` are the
|
||||
VoidBot-facing persona identity.
|
||||
- `.voidbot/state/mimir.cc` is typed persistent Face memory. VoidBot is the
|
||||
transport layer; Mimir owns continuity and repo-progress pressure.
|
||||
|
||||
## Perfect Machine Target
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["native camera workers"] --> R["single 5s rolling reservoir"]
|
||||
B["native mic/loopback workers"] --> R
|
||||
C["Leap timing/IR workers"] --> R
|
||||
D["remote video/audio workers"] --> R
|
||||
R --> E["Aquarium GPU fusion + material field"]
|
||||
R --> F["Faust DSP"]
|
||||
E --> G["Spout2 texture"]
|
||||
A["direct camera drivers"] --> R["Mimir.Runtime rolling buffers"]
|
||||
B["mic/loopback drivers"] --> R
|
||||
C["Leap timing/IR driver"] --> R
|
||||
D["network feed producers"] --> R
|
||||
R --> N["native reservoir handles"]
|
||||
N --> E["Aquarium GPU fusion + UI"]
|
||||
N --> F["Faust/native DSP"]
|
||||
E --> G["Spout2/program video"]
|
||||
F --> H["program stems + spatial bed"]
|
||||
G --> I["OBS"]
|
||||
H --> I
|
||||
|
|
@ -36,210 +26,77 @@ flowchart TD
|
|||
|
||||
Ownership:
|
||||
|
||||
- Mimir owns configuration, calibration, contract tests, launch, status, and persistence.
|
||||
- Aquarium owns dense visual fusion, material/brush/splat reconciliation, final render target, and Spout publication.
|
||||
- Faust owns hot audio DSP and program stem generation.
|
||||
- Mimir owns configuration, calibration truth, launch, status, persistence, and
|
||||
runtime contracts.
|
||||
- `Mimir.Runtime` owns app-level stream buffers and synchronization.
|
||||
- Native capture workers own device reads.
|
||||
- Aquarium owns dense visual fusion, material/brush/splat reconciliation,
|
||||
D3D12 interop, runtime UI, and Spout2 publication.
|
||||
- Faust/native DSP owns hot audio alignment, suppression, separation,
|
||||
spatialization, and stem generation.
|
||||
- OBS owns broadcast controls.
|
||||
- Python remains tooling only: calibration, contract tests, device discovery,
|
||||
offline analysis, and diagnostics. It is not the stream hot path.
|
||||
- OpenGL is not the production Spout sink. Aquarium owns production Spout2
|
||||
publication.
|
||||
- `native/reservoir` is the first native crate. It now uses one time-ordered
|
||||
rolling buffer with typed views. Retention has one owner.
|
||||
|
||||
Invariant: the five-second spatiotemporal reservoir is the live authority.
|
||||
Producers append sample handles through typed native calls, optimizers refine,
|
||||
Aquarium/Faust sample and interpret the pointed-to payloads. No private history
|
||||
outlives the reservoir, and typed views do not own retention. The reservoir does
|
||||
not pretend to own GPU image memory or Faust audio buffers. Edge JSON may
|
||||
declare schema or export diagnostics; live process/network data is typed
|
||||
CultNet documents.
|
||||
Invariant: the live window is bounded, in memory, and has one timing authority.
|
||||
No private history outlives the rolling buffer.
|
||||
|
||||
## Viable Stream App
|
||||
|
||||
`docs/viable-stream-app.md` defines the near-term app target while full native
|
||||
capture work continues. Aquarium hosts the running Mimir app, keeps the default
|
||||
five-second reservoir in memory, exposes debug/settings/output controls, and
|
||||
emits synchronized OBS program video plus separately controllable audio stems.
|
||||
Local and networked video/audio feeds are producers into that one runtime
|
||||
window; they do not own clocks or private synchronization buffers. Mimir owns
|
||||
`Mimir.slnx`; `src/Mimir.App` references Aquarium Engine as the host/windowing
|
||||
and D3D12 bridge, while `src/Mimir.Runtime` provides the Aquarium client runtime.
|
||||
`Mimir.Runtime` owns the first synchronization hub: one five-second default
|
||||
rolling buffer per configured audio/video stream, source polling through
|
||||
`IMimirStreamSource`, and runtime UI readouts for stream/buffer health.
|
||||
Local six-camera ingest should push native handles through
|
||||
`MimirNativeIngestStreamSource`; process-backed ingest remains a compatibility
|
||||
edge for network SRT or diagnostics. `MimirVideoFrameDescriptor` carries
|
||||
dimensions, pixel format, stride, device timestamp, and optional native/GPU
|
||||
handle metadata so Leap stereo IR can enter Mimir without OpenCV owning timing.
|
||||
`IMimirVideoCaptureDriver` is the driver-facing seam for LeapUVC/libusb, LeapC
|
||||
images, Media Foundation, DirectShow, or GPU shared textures. OpenCV is only an
|
||||
offline calibration or diagnostic library now.
|
||||
`docs/viable-stream-app.md` defines the near-term app target. Aquarium hosts the
|
||||
running Mimir app, keeps the default five-second runtime in memory, exposes
|
||||
debug/settings/output controls, and emits synchronized OBS program video plus
|
||||
separately controllable audio stems.
|
||||
|
||||
`Mimir.Runtime` currently provides:
|
||||
|
||||
- `MimirSynchronizationHub`;
|
||||
- `MimirRollingStreamBuffer`;
|
||||
- stream descriptors/settings;
|
||||
- `IMimirStreamSource`;
|
||||
- `MimirNativeIngestStreamSource`;
|
||||
- `MimirProcessStreamSource`;
|
||||
- `MimirVideoFrameDescriptor`;
|
||||
- `IMimirVideoCaptureDriver`;
|
||||
- `MimirVideoCaptureDriverSource`.
|
||||
|
||||
Process-backed sources are bridge/network edges. Local cameras should feed
|
||||
native descriptors with device timestamps and optional native/GPU handles.
|
||||
|
||||
## OBS Bridge Utility
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["config/localcast.json"] --> B["sender-start.ps1"]
|
||||
C["FFmpeg on sender"] --> D["Windows desktop capture"]
|
||||
C --> E["DirectShow audio capture"]
|
||||
D --> F["h264_nvenc encode"]
|
||||
E --> G["AAC encode"]
|
||||
F --> H["SRT MPEG-TS video endpoint"]
|
||||
G --> I["SRT MPEG-TS audio endpoint(s)"]
|
||||
D --> F["NVENC encode"]
|
||||
E --> G["audio encode"]
|
||||
F --> H["SRT video endpoint"]
|
||||
G --> I["SRT audio endpoint(s)"]
|
||||
H --> J["OBS Media Source"]
|
||||
I --> K["OBS Media Source per audio source"]
|
||||
J --> L["OBS scene composition"]
|
||||
K --> L
|
||||
```
|
||||
|
||||
## Ownership
|
||||
The bridge is useful because it is inspectable and already speaks OBS. It does
|
||||
not become the synchronized program authority.
|
||||
|
||||
- Config owns source identity, receiver address, ports, and encoding knobs.
|
||||
- FFmpeg owns capture, encoding, and network transport.
|
||||
- OBS owns source activation, layout, filters, monitoring, and recording/streaming.
|
||||
- This repo owns repeatability and memory.
|
||||
## Audio Field
|
||||
|
||||
## Why Not Plugin First
|
||||
The six-microphone path is separate from the bridge. The live version aligns mic
|
||||
and loopback blocks into one presentation timeline, feeds Faust/native DSP, and
|
||||
emits synchronized stems. Camera mics are spatial/context witnesses; Focusrite
|
||||
devices are dialogue anchors.
|
||||
|
||||
An OBS plugin would be justified if OBS could not ingest stable LAN streams, or if a plugin were needed to expose independent audio controls. V1 gets independent audio controls by making each source an OBS Media Source. That is boring. Boring is allowed to win when it is correct.
|
||||
## Visual Fusion
|
||||
|
||||
The next gate is not taste, it is evidence. `scripts/obs_smoke_test.py` and
|
||||
`localcast.obs_smoke` now define the v1 OBS smoke ledger:
|
||||
`calibration/runs/obs-v1-smoke-ledger.json`. Receiver/plugin/native expansion is
|
||||
blocked until each planned endpoint has `sender_capture`, `srt_receive`, and
|
||||
`obs_present` timestamp evidence, plus bounded drift, end-to-end latency, and
|
||||
confidence.
|
||||
Visual fusion belongs in Aquarium over current reservoir claims. Native capture
|
||||
workers provide frames; Aquarium owns feature extraction, matching, material
|
||||
fitting, render budgeting, and publication.
|
||||
|
||||
## Known Risks
|
||||
|
||||
- Windows audio source names vary by driver and localization.
|
||||
- Windows device names vary by driver and localization.
|
||||
- Some FFmpeg builds omit SRT or NVENC.
|
||||
- Separate endpoints can drift; local latency should be tuned before adding a synchronization layer.
|
||||
- OBS SRT reconnection behavior can be fussy. Use stable ports and source reactivation before treating port changes as a fix.
|
||||
|
||||
## Audio Field Sidecar
|
||||
|
||||
The six-microphone Ambisonic path is separate from the OBS endpoint path.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["config/audio-field.json"] --> B["scripts/audio_field.py"]
|
||||
C["local Focusrite shielded cardioid"] --> D["local reference timeline"]
|
||||
E["neighbor Focusrite shotgun"] --> F["remote dialogue capture"]
|
||||
G["Kiyo + PS Eye camera mics"] --> H["spatial/context captures"]
|
||||
I["2 speaker outputs"] --> J["calibration sweep"]
|
||||
J --> D
|
||||
J --> F
|
||||
J --> H
|
||||
R["confidence probe optimizer"] --> P["known speaker chirplets"]
|
||||
P --> Q["runtime delay/SRO/phase estimator"]
|
||||
D --> Q
|
||||
F --> Q
|
||||
H --> Q
|
||||
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"]
|
||||
M --> V["native mic-field producer"]
|
||||
V --> W["localcast.audio.mic_field"]
|
||||
W --> X["Aquarium Faust voice-separation graph"]
|
||||
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.
|
||||
- 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.
|
||||
- `localcast.diagnostics.audio_live_field`, `localcast.diagnostics.audio_phase_field`, `localcast.diagnostics.faust_mic_field`, and `localcast.diagnostics.spatial_audio` preserve the old Python audio publisher experiments as diagnostics only. Production mic, loopback, phase, stem, and spatial-bed ingest belongs in native/Faust workers that append typed sample handles through `LocalcastProducer`.
|
||||
- `audio-phase-field-status.json` is a diagnostic status export from the replay/experiment modules. The production phase runtime must report through typed CultNet/native status, not by making this JSON file the lifecycle authority.
|
||||
- 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 Mimir publishes `localcast.audio.mic_field`; Mimir owns alignment, timing, mic roles, graph id, and controls.
|
||||
|
||||
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. Speaker output chirplets are live telemetry; delay/SRO/phase state must update during runtime, not only during setup. Extra chirplets may be emitted automatically when confidence drops, but only under the active probe optimizer's budget. The local shielded cardioid and neighbor shotgun are the high-quality dialogue anchors; camera mics provide spatial/context evidence.
|
||||
|
||||
## Visual Fusion Cut Line
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["native camera/Leap sample handles"] --> R["rolling reservoir"]
|
||||
B["audio/phase/event handles"] --> R
|
||||
R --> C["Aquarium GPU feature/fusion/material/brush"]
|
||||
C --> D["Aquarium Spout2 sender"]
|
||||
R --> E["typed CultNet status/docs"]
|
||||
D --> F["OBS Spout2 Capture"]
|
||||
```
|
||||
|
||||
Ownership:
|
||||
|
||||
- Native capture workers own device reads and append handles. They do not own
|
||||
scene reconstruction.
|
||||
- The rolling reservoir owns the live edge, retention, ordering, and typed
|
||||
lookup.
|
||||
- `LocalcastProducer` owns source identity and sequence assignment before native
|
||||
capture workers append sample handles into `LocalcastRuntime`.
|
||||
- `LocalcastRuntime` owns the one live rolling window and exposes both producer
|
||||
pushes and consumer reads for Aquarium/Faust.
|
||||
- Aquarium owns dense visual fusion, material fitting, point/brush/splat
|
||||
lowering, render budgeting, and Spout2 publication.
|
||||
- CultNet typed documents carry status/control/process state. JSON is schema or
|
||||
diagnostic export only.
|
||||
- `localcast.diagnostics.visual_producer` is now diagnostic orchestration only.
|
||||
Reservoir-window clipping, Leap packed transforms, RGB reference splats, and
|
||||
diagnostic clap calibration have named modules outside the producer monolith.
|
||||
Python fallback producers and diagnostic CultCache/JSON file adapters remain
|
||||
diagnostics/migration fossils. They must not be extended as production
|
||||
surfaces.
|
||||
- `localcast.diagnostics.render_frame_json` and
|
||||
`localcast.diagnostics.lod_json` are explicit compatibility adapters; model
|
||||
modules do not own file serialization.
|
||||
- `localcast.diagnostics.render_math` is the pure, testable diagnostic renderer
|
||||
math that survived deletion of the OpenGL publisher.
|
||||
|
||||
Invariant: fallback/demo evidence cannot enter ground-truth reservoir kinds.
|
||||
Render packets, LOD cells, brush packets, and overlays are derived from reservoir
|
||||
claims. The renderer cannot invent scene priority from string prefixes.
|
||||
|
||||
## OBS Program Surface
|
||||
|
||||
OBS should not expose raw unsynchronized ingest as broadcast controls once a synchronized audio/video program is available.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["aligned audio program timeline"] --> B["setup_obs_synced_program.py"]
|
||||
B --> C["Host Voice stem"]
|
||||
B --> D["CoStreamer Voice stem"]
|
||||
B --> E["Ambient stem"]
|
||||
B --> F["Transients stem"]
|
||||
B --> G["CoStreamer Loopback stem"]
|
||||
B --> H["Local Loopback stem"]
|
||||
I["CultCache visual/audio timing"] --> J["Spout/Aquarium program video"]
|
||||
C --> K["OBS synchronized scene"]
|
||||
D --> K
|
||||
E --> K
|
||||
F --> K
|
||||
G --> K
|
||||
H --> K
|
||||
J --> K
|
||||
```
|
||||
|
||||
Ownership:
|
||||
|
||||
- `scripts/setup_obs_synced_program.py` owns packaging aligned program audio into OBS-controllable stems and muting/disabling raw unsynchronized OBS inputs.
|
||||
- `scripts/capture_co_streamer_surfaces.py` owns the late-arriving neighbor surface import: it captures neighbor Focusrite and neighbor loopback over SSH while recording local loopback, estimates the remote-family offset, and writes aligned co-streamer surfaces for the OBS stem packer.
|
||||
- `scripts/wasapi-loopback-capture.ps1` owns the direct primary-playback loopback path. It bypasses virtual mixers and asks Windows Core Audio for the default render endpoint loopback stream. It must run in the neighbor's interactive console session to receive render packets.
|
||||
- OBS owns final source volume, track assignment, filters, and stream/record output.
|
||||
- Aquarium/Spout owns synchronized program video, not raw remote desktop capture.
|
||||
|
||||
Invariant: raw SRT ingest, Desktop Audio, Mic/Aux, and other non-program scene items may exist for diagnostics, but they must be disabled or muted when broadcasting the synchronized program. Missing synchronized feeds should appear as explicit silent placeholders, not as live unsynchronized substitutes. The co-streamer Focusrite, co-streamer loopback, and remote video are the latest-arriving surface family; their measured delay should set the presentation buffer horizon instead of being patched in after the local field. Do not reintroduce Voicemeeter as the loopback authority without a concrete invariant; prefer direct WASAPI loopback or a sender FFmpeg build with native WASAPI input.
|
||||
|
||||
Smoke-test invariant: a visible stream in OBS is not proof of coherence. The v1
|
||||
bridge must leave a witness ledger with per-stage timestamps, endpoint drift,
|
||||
end-to-end latency, and confidence before the receiver surface grows new
|
||||
machinery.
|
||||
- Separate bridge endpoints can drift.
|
||||
- OBS SRT reconnection behavior can be fussy.
|
||||
- Direct driver work must prove sustained cadence before it becomes timing
|
||||
authority.
|
||||
|
|
|
|||
|
|
@ -1,162 +1,55 @@
|
|||
# Fresh Workspace Handoff
|
||||
# Fresh Workspace Handoff
|
||||
|
||||
This is the short re-entry packet for `E:\Projects\Mimir`.
|
||||
|
||||
Do not trust this file for the exact live HEAD. Exact branch, HEAD, and dirty state are volatile. Always ask git.
|
||||
Do not trust this file for exact branch, HEAD, or dirty state. Ask git.
|
||||
|
||||
## Rehydrate
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' .\tools\localcast_state.py status
|
||||
Get-Content .\state\map.yaml
|
||||
Get-Content .\notes\fresh-workspace-handoff.md
|
||||
Get-Content .\notes\current-system-map.md
|
||||
Get-Content .\docs\implementation-plan.md
|
||||
git status --short --branch
|
||||
git log --oneline -5
|
||||
Get-Content .\state\map.yaml
|
||||
Get-Content .\notes\current-system-map.md
|
||||
Get-Content .\docs\implementation-plan.md
|
||||
Get-Content .\state\evidence.jsonl -Tail 8
|
||||
```
|
||||
|
||||
## Current Shape
|
||||
|
||||
- Public brand/Face is Mimir. Implementation surfaces still use `localcast`
|
||||
until a deliberate package/schema rename cut exists.
|
||||
- Public brand/Face is Mimir.
|
||||
- Mimir's Face doctrine lives in `docs/mimir-face.md`.
|
||||
- Mimir's 256px avatar source is `Mimir.png`; project copy is
|
||||
`assets/branding/mimir-avatar-256.png`; VoidBot persona copy is
|
||||
`.voidbot/voice/mimir.png`.
|
||||
- Mimir is registered in VoidBot's private repo-Face registry alongside Nibu and
|
||||
Aqua. Repo-local Face identity/state live at `.voidbot/voice/identity.json`
|
||||
and `.voidbot/state/mimir.cc`.
|
||||
- Birth runner completed in plan mode under `.voidbot/birth`; the typed
|
||||
repo-Face state has already been seeded with durable Mimir birth memories and
|
||||
a heartbeat agency pressure.
|
||||
- V1 uses FFmpeg plus OBS Media Source over SRT.
|
||||
- Sender-side video encoding is `h264_nvenc`.
|
||||
- Audio sources are separate SRT endpoints so OBS can mix them separately.
|
||||
- The live synchronized program path is being rebuilt. The Python/OpenGL
|
||||
deadline Spout bridge has been deleted.
|
||||
- `docs/native-rebuild-plan.md` is the current cut plan.
|
||||
- `docs/viable-stream-app.md` is the near-term stream target: Aquarium hosts
|
||||
the in-memory five-second runtime and operator UI, local/networked feeds append
|
||||
as producers, and OBS receives synchronized program outputs rather than raw
|
||||
feed sync.
|
||||
- `Mimir.slnx` is the repo-owned C# app surface. `src/Mimir.App` references
|
||||
Aquarium Engine as the windowing/rendering/D3D12 host and loads
|
||||
`src/Mimir.Runtime` as the Aquarium client runtime assembly.
|
||||
- `src/Mimir.Runtime` now wraps Aquarium's LocalCast visual runtime in
|
||||
`MimirRuntime` and owns `MimirSynchronizationHub`: one configurable rolling
|
||||
buffer per audio/video stream, defaulting to five seconds. Stream ids can be
|
||||
declared with `MIMIR_LOCAL_VIDEO_STREAMS`, `MIMIR_LOCAL_AUDIO_STREAMS`,
|
||||
`MIMIR_NETWORK_VIDEO_STREAMS`, and `MIMIR_NETWORK_AUDIO_STREAMS`; real capture
|
||||
adapters feed buffers through `IMimirStreamSource`. Local six-camera ingest
|
||||
should use native push adapters such as `MimirNativeIngestStreamSource`, not
|
||||
FFmpeg stdout/process capture except as a network or diagnostic edge.
|
||||
`MimirVideoFrameDescriptor` now carries video shape, pixel format, stride,
|
||||
device timestamp, and optional native/GPU handle metadata for close-to-metal
|
||||
frame ingest; Leap stereo IR is the timing-camera candidate for this path.
|
||||
`IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` are the live
|
||||
driver seam; future LeapUVC/libusb, LeapC image, Media Foundation, DirectShow,
|
||||
or GPU shared-texture adapters should plug in there. OpenCV is no longer a
|
||||
live ingest target.
|
||||
- The reservoir is now one native time-ordered rolling buffer with typed
|
||||
indexes/views. The previous typed-ring crate is gone.
|
||||
- Native reservoir samples carry provenance flags; diagnostic/fallback samples
|
||||
are rejected at both the raw reservoir push and `LocalcastRuntime` typed
|
||||
producer boundary.
|
||||
- `LocalcastRuntime` now exposes producer pushes and consumer reads.
|
||||
`LocalcastProducer` owns source identity and sequence assignment for native
|
||||
capture workers.
|
||||
- `localcast_hash_source_id` owns stable FNV-1a source-id hashing for native
|
||||
producer creation.
|
||||
- `localcast_producer_create_for_source` is the preferred producer constructor
|
||||
for adapters with source-id bytes.
|
||||
- `LocalcastAudioBlockDescriptor` is the first typed audio payload descriptor:
|
||||
caller-owned float32 interleaved audio blocks cross the ABI by descriptor
|
||||
pointer, while the reservoir still owns only timing/retention metadata.
|
||||
- `LocalcastRenderPacketDescriptor` now gives render packets the same typed
|
||||
descriptor boundary for caller-owned point buffers and presentation timing.
|
||||
- `LocalcastRenderPoint` is the fixed first point-buffer ABI for Aquarium
|
||||
decoding.
|
||||
- Aquarium-Engine commit `4d5aec7` adds the first safe-code C# binding layer for
|
||||
this native ABI. It is not yet wired into `LocalCastRuntime` as the live
|
||||
source.
|
||||
- Aquarium-Engine commit `8798908` makes `LocalCastRuntime` consume an injected
|
||||
`ILocalCastVisualFrameSource`; the remaining Aquarium cut is a native source
|
||||
implementation over the binding.
|
||||
- Aquarium-Engine commit `687845c` adds that native frame source. It still needs
|
||||
the real payload decoder/runtime creation path before file polling can be
|
||||
removed from the default runtime.
|
||||
- Aquarium-Engine commit `34694e6` adds the matching safe-code C# binding and
|
||||
layout tests for `LocalcastAudioBlockDescriptor` and the native audio-block
|
||||
producer helper.
|
||||
- Aquarium-Engine commit `9eb40cf` adds the matching safe-code C# binding and
|
||||
layout tests for `LocalcastRenderPacketDescriptor` and the native
|
||||
render-packet producer helper.
|
||||
- Aquarium-Engine commit `cfb48d7` adds `LocalCastNativeRenderDescriptorDecoder`,
|
||||
which reads render descriptor timing/target metadata from native payload
|
||||
handles while keeping point-buffer decoding injectable.
|
||||
- Aquarium-Engine commit `f4c5988` adds `LocalCastNativeRenderPoint` and native
|
||||
point-buffer decoding for the render descriptor decoder.
|
||||
- Aquarium-Engine commit `924aa2f` exposes `LocalCastNativeSourceId.HashUtf8`
|
||||
as the safe wrapper over native source-id hashing.
|
||||
- Aquarium-Engine commit `c06d4cb` makes `LocalCastNativeVisualFrameSource`
|
||||
use the descriptor plus native point-buffer decoder by default.
|
||||
- Aquarium-Engine commit `3316895` exposes `CreateProducer(kind, sourceId)` so
|
||||
producer source hashing goes through native `localcast_producer_create_for_source`.
|
||||
- Aquarium-Engine commit `0f610d0` makes native render packets a direct GPU
|
||||
fusion input: `LocalCastNativeVisualFrameSource` exposes caller-owned
|
||||
`LocalcastRenderPoint` buffers, `LocalCastRuntime` publishes that buffer
|
||||
instead of managed seeds when present, and D3D12 uploads the native point bytes
|
||||
for the LocalCast fusion compute shader.
|
||||
- Edge JSON is schema/diagnostic only. Runtime network/process data should remain typed CultNet documents.
|
||||
- Python live producers and diagnostic CultCache/JSON file adapters are
|
||||
diagnostics, not production foundations. The OpenGL Spout sink has been
|
||||
deleted. Aquarium owns production Spout publication.
|
||||
- Python audio phase/live/Faust publishers have been moved under
|
||||
`localcast.diagnostics.*`, their live PowerShell launchers have been deleted,
|
||||
and reusable mic-profile/probe-band helpers now live in `audio_field`.
|
||||
Production audio ingest must use native capture workers and
|
||||
`LocalcastProducer`.
|
||||
- The AmbiX spatial-audio Python publisher is also quarantined as
|
||||
`localcast.diagnostics.spatial_audio`.
|
||||
- Neighbor sender is deployed at `C:\Meta\Mimir` on `192.168.1.84`.
|
||||
- Madman's desktop has `Start Mimir Sender.cmd` and `Stop Mimir Sender.cmd`.
|
||||
- Receiver OBS scene collection has `Neighbor PC - Video`, `Neighbor PC - Focusrite`, and `Neighbor PC - System Audio` Media Sources added.
|
||||
- V1 OBS bridge expansion is now gated by
|
||||
`calibration/runs/obs-v1-smoke-ledger.json`. The harness is
|
||||
`scripts/obs_smoke_test.py`, pure summary logic lives in
|
||||
`localcast.obs_smoke`, and the runbook is `docs/obs-v1-smoke-test.md`.
|
||||
A passing ledger needs `sender_capture`, `srt_receive`, and `obs_present`
|
||||
evidence for every planned endpoint, with endpoint drift, end-to-end latency,
|
||||
and confidence.
|
||||
- Sender uses SoundVolumeView for default device selection. Voicemeeter is no longer the loopback authority; co-streamer playback loopback uses the direct WASAPI shim scheduled into the neighbor console session.
|
||||
- Sender script was patched after failed transmission: live FFmpeg commands now include `-nostdin`, logs go under `C:\Meta\Mimir\logs`, and interactive video capture size is `1920x1080`.
|
||||
- Madman's desktop launchers call PowerShell wrappers: `scripts\start-localcast-desktop.ps1` and `scripts\stop-localcast-desktop.ps1`.
|
||||
- SSH-launched video capture fails with `gdigrab` error 5; test video from Madman's interactive desktop launcher.
|
||||
- VoidBot persona/state live under `.voidbot/voice/` and `.voidbot/state/`.
|
||||
Commit `.voidbot` dirt in a separate state commit whenever it appears.
|
||||
- V1 still has FFmpeg/SRT/OBS bridge utilities for LAN ingest.
|
||||
- The live stream app is C# plus Aquarium: `Mimir.slnx` contains
|
||||
`src/Mimir.App` and `src/Mimir.Runtime`.
|
||||
- `src/Mimir.App` hosts Aquarium Engine as the windowing/rendering/D3D12 bridge.
|
||||
- `src/Mimir.Runtime` owns `MimirSynchronizationHub`, configurable five-second
|
||||
rolling buffers, stream descriptors, source adapters, direct native ingest,
|
||||
and the video capture driver seam.
|
||||
- Local six-camera ingest should use direct driver adapters. Process-backed
|
||||
sources are bridge/network edges only.
|
||||
- Leap stereo IR is the first timing-camera candidate for direct ingest.
|
||||
- `native/reservoir` owns the lower shared-edge typed-handle invariant for
|
||||
Aquarium/Faust binding work.
|
||||
- Aquarium owns production GPU fusion, UI, and Spout2 publication.
|
||||
- Faust/native DSP owns hot audio alignment, separation, spatialization, and
|
||||
synchronized stems.
|
||||
- OBS receives final program surfaces; it does not own synchronization.
|
||||
|
||||
## Current Pressure
|
||||
|
||||
The useful next work is foundation surgery, not hardware feature expansion:
|
||||
|
||||
- build native capture workers that fill typed audio/render buffers through
|
||||
`LocalcastProducer`
|
||||
- bind Faust/native audio workers to the rolling-buffer `LocalcastRuntime`
|
||||
- build native mic/loopback/phase producers over `LocalcastProducer`; do not
|
||||
restore Python audio live launchers
|
||||
- delete the remaining diagnostic `visual_producer` command once native/Aquarium
|
||||
producer paths cover it; core reservoir clipping, Leap packed transforms, RGB
|
||||
reference splats, and diagnostic clap calibration have already been split out
|
||||
- bind Aquarium/Faust against the native runtime/producer ABI instead of
|
||||
reviving the deleted Python/OpenGL publisher
|
||||
- route future visual/audio runtime work through Aquarium/Faust/native runtime plus typed CultNet docs
|
||||
- keep FFmpeg/SRT bridge scripts only as simple LAN ingest and capture utilities
|
||||
- run the v1 OBS smoke-test witness ledger against the real sender/receiver
|
||||
before adding any OBS plugin/native receiver expansion
|
||||
- Implement the first concrete Leap direct capture driver and measure cadence.
|
||||
- Add remaining camera drivers through `IMimirVideoCaptureDriver`.
|
||||
- Add native audio capture workers for mic, loopback, and network audio feeds.
|
||||
- Bind Aquarium UI to stream health, buffer depth, timestamps, settings, and
|
||||
output management.
|
||||
- Keep PowerShell/FFmpeg/SRT as bridge utilities until native program output
|
||||
replaces them.
|
||||
|
||||
## Immediate Re-entry Instruction
|
||||
|
||||
Do not revive the Python/OpenGL bridge. Rehydrate, read
|
||||
`docs/native-rebuild-plan.md`, then run the v1 OBS smoke-test witness ledger
|
||||
before receiver expansion. After that clock evidence exists, cut toward native
|
||||
workers, Aquarium/Faust bindings, and typed CultNet boundaries.
|
||||
Read `docs/native-rebuild-plan.md`, then make the smallest direct-driver or
|
||||
runtime-buffer cut that improves the live Mimir machine. Do not restore deleted
|
||||
script infrastructure because a stale doc once missed it.
|
||||
|
|
|
|||
|
|
@ -1,9 +0,0 @@
|
|||
opencv-contrib-python
|
||||
tinytuya
|
||||
sounddevice
|
||||
soundcard
|
||||
scipy
|
||||
imageio-ffmpeg
|
||||
PyOpenGL
|
||||
SpoutGL
|
||||
msgpack
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
# Bibliography: Ambisonic AquaSynth Audio Field
|
||||
|
||||
Mirrored copies live under `research/ambisonic-aquasynth/mirrors/`.
|
||||
|
||||
## Core Ambisonics
|
||||
|
||||
- [ICST Ambisonics, "Ambisonics Formats Explained: A-Format, B-Format, FuMa, AmbiX, FOA and HOA"](https://ambisonics.ch/learn/ambisonics-formats/)
|
||||
Mirror: `mirrors/icst-ambisonics-formats.html`
|
||||
|
||||
- [RingBuffer, "Understanding Ambisonics"](https://ringbuffer.org/spatial_audio/ambisonics/understanding-ambisonics/)
|
||||
Mirror: `mirrors/ringbuffer-understanding-ambisonics.html`
|
||||
|
||||
- Leo McCormack, Archontis Politis, Raimundo Gonzalez, Tapio Lokki, Ville Pulkki, ["Parametric Ambisonic Encoding of Arbitrary Microphone Arrays"](https://doi.org/10.1109/TASLP.2022.3182857), IEEE/ACM TASLP, 2022.
|
||||
Open access landing page: [Aaltodoc](https://aaltodoc.aalto.fi/items/cb74eb6f-dd96-4bde-826c-f77f837a42d8)
|
||||
Mirrored PDF: `mirrors/mccormack-2022-parametric-ambisonic-encoding.pdf`
|
||||
|
||||
## Faust / Production Tooling
|
||||
|
||||
- [Faust Libraries, `hoa.lib`](https://faustlibraries.grame.fr/libs/hoa/)
|
||||
Mirror: `mirrors/faust-hoa-lib.html`
|
||||
|
||||
- [IEM Plug-in Suite](https://plugins.iem.at/)
|
||||
Mirror: `mirrors/iem-plugin-suite.html`
|
||||
|
||||
- [IEM Plug-in Suite, "Compatibility with other Suites"](https://plugins.iem.at/docs/compatibility/)
|
||||
Mirror: `mirrors/iem-compatibility.html`
|
||||
|
||||
- [SPARTA, "Overview"](https://leomccormack.github.io/sparta-site/docs/plugins/overview/)
|
||||
Mirror: `mirrors/sparta-overview.html`
|
||||
|
||||
## Capture, Clocking, Transport
|
||||
|
||||
- [FFmpeg Devices Documentation](https://www.ffmpeg.org/ffmpeg-devices.html)
|
||||
Mirror: `mirrors/ffmpeg-devices.html`
|
||||
|
||||
- [JACK Audio Connection Kit API Overview](https://jackaudio.org/api/index.html)
|
||||
Mirror: `mirrors/jack-api-overview.html`
|
||||
|
||||
- [JACK Audio Connection Kit, "Using JACK on Windows"](https://jackaudio.org/faq/jack_on_windows.html)
|
||||
Mirror: `mirrors/jack-on-windows.html`
|
||||
|
||||
- [RME Manuals, "Using multiple HDSPe AoX cards"](https://docs.rme-audio.com/aoxd/705-1c_multiple_cards_win/)
|
||||
Mirror: `mirrors/rme-multiple-cards-sync.html`
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because one or more lines are too long
|
|
@ -1,188 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en-us">
|
||||
|
||||
<head>
|
||||
<meta name="generator" content="Hugo 0.119.0">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title> Compatibility with other Suites </title>
|
||||
|
||||
|
||||
<meta name="description" content="What Ambisonic format is used? Which plug-ins can I combine?">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<meta name="author" content="Daniel Rudrich">
|
||||
|
||||
|
||||
<meta property="og:title" content="Compatibility with other Suites" />
|
||||
<meta property="og:description" content="What Ambisonic format is used? Which plug-ins can I combine?" />
|
||||
<meta property="og:type" content="article" />
|
||||
<meta property="og:url" content="https://plugins.iem.at/docs/compatibility/" /><meta property="og:image" content="https://plugins.iem.at/images/IEMPluginSuiteLogo.png"/><meta property="article:section" content="docs" />
|
||||
<meta property="article:published_time" content="2020-11-05T09:26:04+01:00" />
|
||||
<meta property="article:modified_time" content="2020-11-05T09:26:04+01:00" />
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<meta property="og:image" content="images/IEMPluginSuiteLogo.png">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<link rel="canonical" href="https://plugins.iem.at/docs/compatibility/">
|
||||
|
||||
<link rel="shortcut icon" type="image/png" href="images/favicon_96x96.png">
|
||||
|
||||
|
||||
<link href="https://plugins.iem.at/css/font.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/kube.min.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/kube.legenda.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/highlight.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/master.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/kube.demo.css" rel="stylesheet" type="text/css">
|
||||
|
||||
<link href="https://plugins.iem.at/css/custom.css" rel="stylesheet" type="text/css">
|
||||
|
||||
<script src="https://plugins.iem.at/js/jquery-3.5.1.min.js" type="text/javascript">
|
||||
</script>
|
||||
|
||||
<script type="text/javascript" src="https://plugins.iem.at/js/tocbot.min.js"></script>
|
||||
</head>
|
||||
|
||||
|
||||
<body class="page-kube">
|
||||
<header> <div class="show-sm">
|
||||
<div id="nav-toggle-box">
|
||||
<div id="nav-toggle-brand">
|
||||
<a href="https://plugins.iem.at/">IEM Plug-in Suite</a>
|
||||
</div><a data-component="toggleme" data-target="#top" href="#" id="nav-toggle"><i class="kube-menu"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hide-sm" id="top">
|
||||
<div id="top-brand">
|
||||
<a href="https://plugins.iem.at/" title="home">IEM Plug-in Suite</a>
|
||||
</div>
|
||||
|
||||
<nav id="top-nav-main">
|
||||
<ul>
|
||||
|
||||
|
||||
<li><a href="https://plugins.iem.at/download/" >Download</a></li>
|
||||
|
||||
<li><a href="https://plugins.iem.at/docs/" >Documentation</a></li>
|
||||
|
||||
<li><a href="https://plugins.iem.at/faq/" >FAQ</a></li>
|
||||
|
||||
<li><a href="https://plugins.iem.at/contact/" >Contact</a></li>
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
<div id="nav-toggle" style="text-align: center;">
|
||||
<a href="https://atmoky.com"><img src="https://plugins.iem.at/images/atmokyfriends.png" width="200"></a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main>
|
||||
<div id="main">
|
||||
<div id="hero">
|
||||
<h1> Compatibility with other Suites </h1>
|
||||
<p class="hero-lead">
|
||||
This guide tells you information about the used Ambisonic format and the compatibility with other plug-ins suites.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div id="kube-component" class="content">
|
||||
|
||||
<nav id="contents">
|
||||
<ol class="js-toc">
|
||||
</ol>
|
||||
</nav>
|
||||
<script type="text/javascript">
|
||||
document.addEventListener("DOMContentLoaded",
|
||||
function(){
|
||||
tocbot.init({
|
||||
|
||||
tocSelector: '.js-toc',
|
||||
|
||||
contentSelector: '.content',
|
||||
|
||||
headingSelector: 'h3'
|
||||
})
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<h3 id="the-short-facts">The short facts</h3>
|
||||
<p>The IEM Plug-in Suite uses the AmbiX convention, that is <strong>ACN channel ordering</strong> and <strong>SN3D normalization</strong>. That is the current standard, which most plug-in suites use. Some older suites use the Furse-Malham (<strong>FuMa</strong>) format, in order to use them with AmbiX, you’ll need to convert their signals to AmbiX and vice versa.</p>
|
||||
<p>Here’s a short and non-complete list of plug-in suites which also use the AmbiX convetion and can be used directly with the IEM Plug-in Suite:</p>
|
||||
<ul>
|
||||
<li>Matthias Kronlachner’s ambix plugin suite</li>
|
||||
<li>SPARTA / Compass plug-in suites</li>
|
||||
<li>SSA-Plugins</li>
|
||||
<li>BlueRippleSound plug-ins</li>
|
||||
<li>…</li>
|
||||
</ul>
|
||||
<h3 id="ambix-format">AmbiX format</h3>
|
||||
<p>The AmbiX format is the current standard for Ambisonics. It handles two important things: the <strong>channel ordering</strong> and the <strong>normalization</strong>. Both are related to the spherical harmonics, the math behind Ambisonics. Let’s take a look!</p>
|
||||
<h5 id="channel-ordering-acn">Channel ordering: ACN</h5>
|
||||
<p>The channel ordering used in the Ambix Format is called <code>ACN</code> which stands for <code>Ambisonic Channel Order</code>. What a greate name! The difference to the <code>FuMa</code> odering is that the channels aren’t ordered alphabetically any more. Here the first oder components for both FuMa and ACN:
|
||||
<code>FuMa</code>: WXYZ
|
||||
<code>ACN</code>: WYZX</p>
|
||||
<p>(<code>W</code> is the omni-directional signal; <code>X</code>, <code>Y</code>, and <code>Z</code> the figure-of-eights in x, y, and z direction)</p>
|
||||
<p>So why that non-sense? Well, let’s say it’s math… However, in combination with the SN3D normalization it has a neat property, which will we come to in a minute (or second for the fast readers)!</p>
|
||||
<h5 id="sn3d-normalization">SN3D Normalization</h5>
|
||||
<p>Semi-normalization is used in the AmbiX format. This one makes sure that when you encode a source, the levels of all channels won’t exceed the one in the first (omni, W) channel. In general, this is quite handy, so that clipping doesn’t occur in your DAW.</p>
|
||||
<p><strong>Note</strong>: in a mix, the levels <strong>can</strong> exceed the one of the omni-channel!</p>
|
||||
<p>N3D normalization on the other side will boost the signals in each order, which will lead to very high levels let’s say in the 7th order components in channels 50-64. So why would N3D be any good? Well, the math only works in N3D. For a matter of fact, things like beamforming or decoding (which is the same actually), will happen in N3D. But you as a user don’t have to take care of that, the plug-ins will internally apply a conversion if necessary, no worries :-)</p>
|
||||
<h5 id="encoding-a-signal-using-the-iem-plug-in-suite">Encoding a signal using the IEM Plug-in Suite</h5>
|
||||
<p>Per default, signals will be encoded with <strong>SN3D</strong> and <strong>ACN</strong>. You <em>can</em> set the normalization to <strong>N3D</strong> in most plug-ins, but you shouldn’t, as then the signals won’t be AmbiX compatible any more. Please do that only, if you know what you are doing :-)</p>
|
||||
<p>When using spherical harmonics, the coefficient (factor/weight) for the omni-channel is usualy <code>1/sqrt(4*pi)</code> which is something like <code>0.282094792</code>. In all encoders, the encoding coefficients will be adjusted so that the omni channel will have <strong>unity gain</strong>.</p>
|
||||
<p>On the other side, when decoding, e.g. with the <code>**Probe**Decoder</code> the weights are adjusted, so that encoding into one direction and decoding with the same direction will lead to <strong>unity</strong> a<strong>gain</strong>.</p>
|
||||
<h5 id="the-neat-property">The neat property!</h5>
|
||||
<p>Using <strong>SN3D</strong> and <strong>ACN</strong>, in other words <strong>AmbiX</strong>, the first two channels of your Ambisonic signals will hold mid/side signals, which you can simply decode with a mid/side decoder, like the one which comes with Reaper. So a very very simple StereoDecoder would be exactlyt that. Neat, right?</p>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer>
|
||||
<footer id="footer">
|
||||
<nav>
|
||||
<ul>
|
||||
<li><span>Plug-in Suite by IEM - Institute of Electronic Music and Acoustics</span></li>
|
||||
<li>
|
||||
<a href="https://iem.at/">IEM.at</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://plugins.iem.at/docs/">Docs</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<p>Website created with <a href="https://gohugo.io">Hugo</a> using the <a href="https://github.com/jeblister/kube">kube</a> theme.</p>
|
||||
</footer>
|
||||
|
||||
</footer>
|
||||
|
||||
|
||||
<script src="https://plugins.iem.at/js/kube.js" type="text/javascript">
|
||||
</script>
|
||||
<script src="https://plugins.iem.at/js/kube.legenda.js" type="text/javascript">
|
||||
</script>
|
||||
<script src="https://plugins.iem.at/js/master.js" type="text/javascript">
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,258 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en-us">
|
||||
|
||||
<head>
|
||||
<meta name="generator" content="Hugo 0.119.0">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title> IEM Plug-in Suite </title>
|
||||
|
||||
|
||||
<meta name="description" content="The IEM Plug-in Suite is a free and Open-Source audio plugin suite including Ambisonic plug-ins up to 7th order created by staff and students of the <br/> Institute of Electronic Music and Acoustics.">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<meta name="author" content="Daniel Rudrich">
|
||||
|
||||
|
||||
<meta property="og:title" content="IEM Plug-in Suite" />
|
||||
<meta property="og:description" content="The IEM Plug-in Suite is a free and Open-Source audio plugin suite including Ambisonic plug-ins up to 7th order created by staff and students of the <br/> Institute of Electronic Music and Acoustics." />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://plugins.iem.at/" /><meta property="og:image" content="https://plugins.iem.at/images/IEMPluginSuiteLogo.png"/>
|
||||
|
||||
|
||||
|
||||
<meta property="og:image" content="images/IEMPluginSuiteLogo.png">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<link rel="canonical" href="https://plugins.iem.at/">
|
||||
|
||||
<link rel="shortcut icon" type="image/png" href="images/favicon_96x96.png">
|
||||
|
||||
|
||||
<link href="https://plugins.iem.at/css/font.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/kube.min.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/kube.legenda.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/highlight.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/master.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://plugins.iem.at/css/kube.demo.css" rel="stylesheet" type="text/css">
|
||||
|
||||
<link href="https://plugins.iem.at/css/custom.css" rel="stylesheet" type="text/css">
|
||||
|
||||
<script src="https://plugins.iem.at/js/jquery-3.5.1.min.js" type="text/javascript">
|
||||
</script>
|
||||
|
||||
<script type="text/javascript" src="https://plugins.iem.at/js/tocbot.min.js"></script>
|
||||
</head>
|
||||
|
||||
|
||||
<body class="page-kube">
|
||||
<header> <div class="show-sm">
|
||||
<div id="nav-toggle-box">
|
||||
<div id="nav-toggle-brand">
|
||||
<a href="https://plugins.iem.at/">IEM Plug-in Suite</a>
|
||||
</div><a data-component="toggleme" data-target="#top" href="#" id="nav-toggle"><i class="kube-menu"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hide-sm" id="top">
|
||||
<div id="top-brand">
|
||||
<a href="https://plugins.iem.at/" title="home">IEM Plug-in Suite</a>
|
||||
</div>
|
||||
|
||||
<nav id="top-nav-main">
|
||||
<ul>
|
||||
|
||||
|
||||
<li><a href="https://plugins.iem.at/download/" >Download</a></li>
|
||||
|
||||
<li><a href="https://plugins.iem.at/docs/" >Documentation</a></li>
|
||||
|
||||
<li><a href="https://plugins.iem.at/faq/" >FAQ</a></li>
|
||||
|
||||
<li><a href="https://plugins.iem.at/contact/" >Contact</a></li>
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
<div id="nav-toggle" style="text-align: center;">
|
||||
<a href="https://atmoky.com"><img src="https://plugins.iem.at/images/atmokyfriends.png" width="200"></a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main>
|
||||
|
||||
<div id="main">
|
||||
<div id="hero">
|
||||
<img alt="IEM Plug-in Suite" src="images/IEMPluginSuiteLogo.png" width="450">
|
||||
<h1>IEM Plug-in Suite</h1>
|
||||
<p>The IEM Plug-in Suite is a free and Open-Source audio plugin suite including Ambisonic plug-ins up to 7th order created by staff and students of the <br/> Institute of Electronic Music and Acoustics.</p>
|
||||
</div>
|
||||
|
||||
<div id="action-buttons">
|
||||
<a class="button primary big" href="download/">Download</a>
|
||||
<a class="button outline big" href="https://git.iem.at/audioplugins/IEMPluginSuite/tags/v1.15.0">Release Page</a>
|
||||
<a class="button outline big" href="https://git.iem.at/audioplugins/IEMPluginSuite" onclick="_gaq.push(['_trackEvent', 'kube', 'github', '1.0.0']);">Source Code</a>
|
||||
<p>Latest Version v1.15.0, 10th April 2025</p>
|
||||
</div>
|
||||
|
||||
<div class="message focus open" data-component="message" data-loaded="true">
|
||||
<h5>NOTE: Breaking changes!</h5> Version v1.15.0 and v1.3.0 have introduced some breaking changes! Projects using one of the previous versions might not work as expected. For more information see the <a href="docs/breakingchanges/">Breaking changes article</a> and/or the <a href="https://git.iem.at/audioplugins/IEMPluginSuite/blob/master/ChangeLog.md">ChangeLog</a>.
|
||||
</div>
|
||||
|
||||
<div id="main">
|
||||
<h3 class="section" id="h-featured">Featured Plug-ins</h3>
|
||||
<nav data-component="tabs" data-live=".tab-live" id="livetabs"></nav>
|
||||
<div class="tab-live" data-title="DualDelay" id="tab-DualDelay">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/DualDelay.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>DualDelay</h5>
|
||||
<p>The <b>Dual</b>Delay has been one of the first plug-ins in the IEM Suite. Therefore it was time for a big makeover! It has been optimized to suite needs of composers and musicians by adding a sync-to-DAW function, a tap delay button as well as moving from milliseconds to BPM with multiplies for setting times. As cherry on top, it doesn't only support a rotation of the signal, but also warping!</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-live" data-title="GranularEncoder" id="tab-GranularEncoder">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/GranularEncoder.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>GranularEncoder</h5>
|
||||
<p>The <b>Granular</b>Encoder is an Ambisonic granular synthesis plug-in. That's right, it is the first Ambisonic synthesizer plug-in released in the suite! The best thing about it: you can use any mono or stereo audio signal, and turn it into an enveloping sound scene, or crush the signal into microscopic sonic particles!</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-live" data-title="MultiBandCompressor" id="tab-MultiBandCompressor">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/MultiBandCompressor.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>MultiBandCompressor</h5>
|
||||
<p>The <b>MultiBand</b>Compressor is a very handy tool in your project's mastering stage! It works like a stereo multi-band compressor, however, it will make sure the spatial image is not altered! The Ambisonic input signal is split up into four bands, which can be compressed individually.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-live" data-title="StereoEncoder" id="tab-StereoEncoder">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/StereoEncoder.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>StereoEncoder</h5>
|
||||
<p>Use the <b>Stereo</b>Encoder plug-in to encode mono or stereo audio signals into the Ambisonic domain - up to 7th order. The interface lets you easily set the orientation, width and rotation of the stereo pair. With a simple double-click onto the SpherePanner you can change the display to a linear elevation, which gives you a higher accuracy towards the horizon.</p>
|
||||
<p>With help of the Quaternion input, you can use use data from orientation trackers (e.g. headtrackers) to steer your source into the right direction.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-live" data-title="RoomEncoder" id="tab-RoomEncoder">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/RoomEncoder.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>RoomEncoder</h5>
|
||||
<p>The <b>Room</b>Encoder is so far the most complex and computation-intensive plug-in within the IEM plug-in suite. It allows you to put a source and a listener into a virtual shoebox-shaped room and render over 200 wall reflections. Perfect to enhance the externalization of binaural playback.</p>
|
||||
<p>You can move the source and the listener freely within the room, which will automatically generate Doppler-shift effects. Use the overall reflection coefficient and the low-shelve and high-shelve filters to change the character of the reflections.</p>
|
||||
<p><b>But thats not all:</b> The RoomEncoder can make use of DirectivitySignals as an input signal. This means that your source can have a frequency-dependent and time-variable directivity. The <b>Directivity</b>Shaper plugin is a good tool to create various directivities.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-live" data-title="AllRADecoder" id="tab-AllRADecoder">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/AllRADecoder.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>AllRADecoder</h5>
|
||||
<p>With the AllRADecoder you can design an Ambisonic decoder for an any desired loudspeaker layout using the AllRAD approach.</p>
|
||||
<p>The resulting decoder is automatically applied to the incoming Ambisonic audio stream, so it can be directly inserted into a decoder track of your audio project. You might also want to use it as a standalone application to design a decoder and write it into a JSON configuration file for the use in other plug-ins (e.g. <b>Simple</b>Decoder).</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-live" data-title="EnergyVisualizer" id="tab-EnergyVisualizer">
|
||||
<div class="row gutters">
|
||||
<div class="col-6"><img src="images/featured/EnergyVisualizer.png"></div>
|
||||
<div class="col-6">
|
||||
<h5>EnergyVisualizer</h5>
|
||||
<p>This plug-in is perfect for metering the spatial image. The <b>Energy</b>Visualizer visualizes the energy distribution on the sphere of the Ambisonic input signal. The energy levels are color-coded according to the color map. The Ambisonic Signal is decoded using 480 virtual loudspeakers with a subsequent RMS calculation and OpenGL visualization.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div id="kube-features">
|
||||
<div class="row gutters">
|
||||
<div class="col col-4 item">
|
||||
<figure>
|
||||
<img alt="Higher Order Ambisonics" height="60" src="https://plugins.iem.at/images/ambisonics_60px.png" width="60">
|
||||
</figure>
|
||||
<h3>One Plug-In - Seven Orders</h3>
|
||||
<p>Support for up to <b>7th</b> order Ambisonics, selectable <b>within</b> each plug-in.</p>
|
||||
|
||||
</div>
|
||||
<div class="col col-4 item">
|
||||
<figure>
|
||||
<img alt="Open-Source" height="30" src="images/openSource.png">
|
||||
</figure>
|
||||
<h3>Open-Source</h3>
|
||||
<p>Free to use, free to change. Contribute!</p>
|
||||
</div>
|
||||
<div class="col col-4 item">
|
||||
<figure>
|
||||
<img alt="Cross-platform" height="60" src="https://plugins.iem.at/images/crossPlatform.png">
|
||||
</figure>
|
||||
<h3>Cross-platform</h3>
|
||||
<p>Compiled Plug-ins available for macOS, Windows and Linux.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row gutters">
|
||||
<div class="col col-4 item">
|
||||
<h4>Made with JUCE</h4>
|
||||
<p>Created with the <a href="https://juce.com">JUCE</a> framework.</p>
|
||||
</div>
|
||||
<div class="col col-4 item">
|
||||
<h4>Created by staff and students</h4>
|
||||
<p>The plug-ins result from the institute's current research and student projects.</p>
|
||||
</div>
|
||||
<div class="col col-4 item">
|
||||
<h4>License</h4>
|
||||
<p>The IEM Plug-in Suite is licensed under the <a href="https://www.gnu.org/licenses/">GPLv3</a> License.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer> <footer id="footer">
|
||||
<nav>
|
||||
<ul>
|
||||
<li><span>Plug-in Suite by IEM - Institute of Electronic Music and Acoustics</span></li>
|
||||
<li>
|
||||
<a href="https://iem.at/">IEM.at</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://plugins.iem.at/docs/">Docs</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<p>Website created with <a href="https://gohugo.io">Hugo</a> using the <a href="https://github.com/jeblister/kube">kube</a> theme.</p>
|
||||
</footer>
|
||||
</footer>
|
||||
|
||||
|
||||
<script src="https://plugins.iem.at/js/kube.js" type="text/javascript">
|
||||
</script>
|
||||
<script src="https://plugins.iem.at/js/kube.legenda.js" type="text/javascript">
|
||||
</script>
|
||||
<script src="https://plugins.iem.at/js/master.js" type="text/javascript">
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,176 +0,0 @@
|
|||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.9.1"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>JACK-AUDIO-CONNECTION-KIT: JACK Audio Connection Kit</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
<script type="text/javascript" src="dynsections.js"></script>
|
||||
<link href="search/search.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="search/searchdata.js"></script>
|
||||
<script type="text/javascript" src="search/search.js"></script>
|
||||
<script type="text/javascript">
|
||||
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
|
||||
$(document).ready(function() { init_search(); });
|
||||
/* @license-end */
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="projectalign" style="padding-left: 0.5em;">
|
||||
<div id="projectname">JACK-AUDIO-CONNECTION-KIT
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.9.1 -->
|
||||
<script type="text/javascript">
|
||||
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
|
||||
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
|
||||
/* @license-end */
|
||||
</script>
|
||||
<div id="navrow1" class="tabs">
|
||||
<ul class="tablist">
|
||||
<li class="current"><a href="index.html"><span>Main Page</span></a></li>
|
||||
<li><a href="pages.html"><span>Related Pages</span></a></li>
|
||||
<li><a href="modules.html"><span>Modules</span></a></li>
|
||||
<li><a href="annotated.html"><span>Data Structures</span></a></li>
|
||||
<li><a href="files.html"><span>Files</span></a></li>
|
||||
<li>
|
||||
<div id="MSearchBox" class="MSearchBoxInactive">
|
||||
<span class="left">
|
||||
<img id="MSearchSelect" src="search/mag_sel.svg"
|
||||
onmouseover="return searchBox.OnSearchSelectShow()"
|
||||
onmouseout="return searchBox.OnSearchSelectHide()"
|
||||
alt=""/>
|
||||
<input type="text" id="MSearchField" value="Search" accesskey="S"
|
||||
onfocus="searchBox.OnSearchFieldFocus(true)"
|
||||
onblur="searchBox.OnSearchFieldFocus(false)"
|
||||
onkeyup="searchBox.OnSearchFieldChange(event)"/>
|
||||
</span><span class="right">
|
||||
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.svg" alt=""/></a>
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div><!-- top -->
|
||||
<!-- window showing the filter options -->
|
||||
<div id="MSearchSelectWindow"
|
||||
onmouseover="return searchBox.OnSearchSelectShow()"
|
||||
onmouseout="return searchBox.OnSearchSelectHide()"
|
||||
onkeydown="return searchBox.OnSearchSelectKey(event)">
|
||||
</div>
|
||||
|
||||
<!-- iframe showing the search results (closed by default) -->
|
||||
<div id="MSearchResultsWindow">
|
||||
<iframe src="javascript:void(0)" frameborder="0"
|
||||
name="MSearchResults" id="MSearchResults">
|
||||
</iframe>
|
||||
</div>
|
||||
|
||||
<div class="PageDoc"><div class="header">
|
||||
<div class="headertitle">
|
||||
<div class="title">JACK Audio Connection Kit </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><h1><a class="anchor" id="intro"></a>
|
||||
Introduction</h1>
|
||||
<p>JACK is a low-latency audio server, written for any operating system that is reasonably POSIX compliant. It currently exists for Linux, OS X, Solaris, FreeBSD and Windows. It can connect several client applications to an audio device, and allow them to share audio with each other. Clients can run as separate processes like normal applications, or within the JACK server as "plugins".</p>
|
||||
<p>JACK was designed from the ground up for professional audio work, and its design focuses on two key areas: synchronous execution of all clients, and low latency operation.</p>
|
||||
<dl class="section see"><dt>See also</dt><dd><a href="http://jackaudio.org">http://jackaudio.org</a></dd></dl>
|
||||
<h1><a class="anchor" id="jack_overview"></a>
|
||||
JACK Overview</h1>
|
||||
<p>Traditionally it has been hard if not impossible to write audio applications that can share data with each other. In addition, configuring and managing audio interface hardware has often been one of the most complex aspect of writing audio software.</p>
|
||||
<p>JACK changes all this by providing an API that does several things: </p><pre class="fragment">1. provides a high level abstraction for programmers that
|
||||
removes the audio interface hardware from the picture and
|
||||
allows them to concentrate on the core functionality of
|
||||
their software.
|
||||
|
||||
2. allows applications to send and receive audio data to/from
|
||||
each other as well as the audio interface. There is no
|
||||
difference in how an application sends or receives
|
||||
data regardless of whether it comes from/goes to another application
|
||||
or an audio interface.
|
||||
</pre><p> For programmers with experience of several other audio APIs such as PortAudio, Apple's CoreAudio, Steinberg's VST and ASIO as well as many others, JACK presents a familiar model: your program provides a "callback" function that will be executed at the right time. Your callback can send and receive data as well as do other signal processing tasks. You are not responsible for managing audio interfaces or threading, and there is no "format negotiation": all audio data within JACK is represented as 32 bit floating point values.</p>
|
||||
<p>For those with experiences rooted in the Unix world, JACK presents a somewhat unfamiliar API. Most Unix APIs are based on the read/write model spawned by the "everything is a file" abstraction that Unix is rightly famous for. The problem with this design is that it fails to take the realtime nature of audio interfaces into account, or more precisely, it fails to force application developers to pay sufficient attention to this aspect of their task. In addition, it becomes rather difficult to facilitate inter-application audio routing when different programs are not all running synchronously.</p>
|
||||
<p>Using JACK within your program is very simple, and typically consists of just:</p>
|
||||
<ul>
|
||||
<li>calling <a class="el" href="group__ClientFunctions.html#gabbd2041bca191943b6ef29a991a131c5">jack_client_open()</a> to connect to the JACK server.</li>
|
||||
<li>registering "ports" to enable data to be moved to and from your application.</li>
|
||||
<li>registering a "process callback" which will be called at the right time by the JACK server.</li>
|
||||
<li>telling JACK that your application is ready to start processing data.</li>
|
||||
</ul>
|
||||
<p>There is a lot more that you can do with JACK's interfaces, but for many applications, this is all that is needed. The simple_client.c example demonstrates a complete (simple!) JACK application that just copies the signal arriving at its input port to its output port. Similarly, inprocess.c shows how to write an internal client "plugin" that runs within the JACK server process.</p>
|
||||
<h1><a class="anchor" id="reference"></a>
|
||||
Reference</h1>
|
||||
<p>The JACK programming interfaces are described in several header files. We present them here broken into useful categories to make the API a little clearer:</p>
|
||||
<ul>
|
||||
<li><a class="el" href="group__ClientFunctions.html">Creating & manipulating clients</a></li>
|
||||
<li><a class="el" href="group__ClientCallbacks.html">Setting Client Callbacks</a></li>
|
||||
<li><a class="el" href="group__ClientThreads.html">Creating and managing client threads</a></li>
|
||||
<li><a class="el" href="group__ServerControl.html">Controlling & querying JACK server operation</a></li>
|
||||
<li><a class="el" href="group__PortFunctions.html">Creating & manipulating ports</a></li>
|
||||
<li><a class="el" href="group__PortSearching.html">Looking up ports</a></li>
|
||||
<li><a class="el" href="group__LatencyFunctions.html">Managing and determining latency</a></li>
|
||||
<li><a class="el" href="group__TimeFunctions.html">Handling time</a></li>
|
||||
<li><a class="el" href="group__TransportControl.html">Transport and Timebase control</a></li>
|
||||
<li><a class="el" href="group__ErrorOutput.html">Controlling error/information output</a></li>
|
||||
<li><a class="el" href="group__NonCallbackAPI.html">The non-callback API</a></li>
|
||||
<li><a class="el" href="group__MIDIAPI.html">Reading and writing MIDI data</a></li>
|
||||
<li><a class="el" href="group__SessionClientFunctions.html">Session API for clients.</a></li>
|
||||
<li><a class="el" href="group__WeakLinkage.html">managing support for newer/older versions of JACK</a></li>
|
||||
<li><a class="el" href="group__ControlAPI.html">the API for starting and controlling a JACK server</a></li>
|
||||
<li><a class="el" href="group__Metadata.html">Metadata API.</a></li>
|
||||
</ul>
|
||||
<p>The full API is described in:</p>
|
||||
<ul>
|
||||
<li><a class="el" href="jack_8h.html"><jack/jack.h></a> is the main JACK interface.</li>
|
||||
<li><a class="el" href="statistics_8h.html"><jack/statistics.h></a> provides interfaces for monitoring the performance of a running JACK server.</li>
|
||||
<li><a class="el" href="intclient_8h.html"><jack/intclient.h></a> allows loading and unloading JACK internal clients.</li>
|
||||
<li><a class="el" href="ringbuffer_8h.html"><jack/ringbuffer.h></a> defines a simple API for using lock-free ringbuffers. These are a good way to pass data between threads, when streaming realtime data to slower media, like audio file playback or recording.</li>
|
||||
<li><a class="el" href="transport_8h.html"><jack/transport.h></a> defines a simple transport control mechanism for starting, stopping and repositioning clients. This is described in the <a class="el" href="transport-design.html">JACK Transport Design</a> document.</li>
|
||||
<li><a class="el" href="types_8h.html"><jack/types.h></a> defines the main JACK data types.</li>
|
||||
<li><a class="el" href="thread_8h.html"><jack/thread.h></a> functions standardize thread creation for JACK and its clients.</li>
|
||||
<li><a class="el" href="midiport_8h.html"><jack/midiport.h></a> functions to handle reading and writing of MIDI data to a port</li>
|
||||
<li><a class="el" href="session_8h.html"><jack/session.h></a> functions that form the JACK session API</li>
|
||||
<li><a class="el" href="control_8h.html"><jack/control.h></a> the API for starting and controlling a JACK server</li>
|
||||
<li><a class="el" href="metadata_8h.html"><jack/metadata.h></a> the API for managing metadata about objects within JACK (clients and ports)</li>
|
||||
</ul>
|
||||
<p>In addition, the tools directory provides numerous examples of simple JACK clients that nevertheless use the API to do something useful. It includes</p>
|
||||
<ul>
|
||||
<li>a metronome.</li>
|
||||
<li>a recording client that can capture any number of channels from any JACK sources and store them as an audio file.</li>
|
||||
<li>command line clients to control the transport mechanism, change the buffer size and more. <br />
|
||||
</li>
|
||||
<li>commands to load and unload JACK internal clients.</li>
|
||||
<li>tools for checking the status of a running JACK system.</li>
|
||||
</ul>
|
||||
<p>and many more.</p>
|
||||
<h1><a class="anchor" id="porting"></a>
|
||||
Porting</h1>
|
||||
<p>JACK is designed to be portable to any system supporting the relevant POSIX and ANSI C standards. It currently runs under GNU/Linux, Mac OS X and Berkeley Unix on several different processor architectures. If you want to port JACK to another platform, please read the <a class="el" href="porting-guide.html">Porting JACK</a> document.</p>
|
||||
<h1><a class="anchor" id="license"></a>
|
||||
License</h1>
|
||||
<p>Copyright (C) 2001-2019 by Paul Davis, Stephane Letz, Jack O'Quinn, Torben Hohn, Filipe Coelho and others.</p>
|
||||
<p>JACK is free software; you can redistribute it and/or modify it under the terms of the GNU GPL and LGPL licenses as published by the Free Software Foundation, <a href="http://www.gnu.org">http://www.gnu.org</a>. The JACK server uses the GPL, as noted in the source file headers. However, the JACK library is licensed under the LGPL, allowing proprietary programs to link with it and use JACK services. You should have received a copy of these Licenses along with the program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p>
|
||||
<p>This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. </p>
|
||||
</div></div><!-- PageDoc -->
|
||||
</div><!-- contents -->
|
||||
<!-- start footer part -->
|
||||
<hr class="footer"/><address class="footer"><small>
|
||||
Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.1
|
||||
</small></address>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,183 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset='utf-8' />
|
||||
<meta name="description" content="JACK Audio Connection Kit | Using JACK on Windows" />
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="/assets/css/style.css">
|
||||
<link rel="alternate" type="application/atom+xml" href="/atom.xml" title="JACK Audio News">
|
||||
<title>Using JACK on Windows | JACK Audio Connection Kit</title>
|
||||
<!-- Favicon Generator Icons -->
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/assets/icons/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/assets/icons/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/assets/icons/favicon-16x16.png">
|
||||
<link rel="manifest" href="/assets/icons/site.webmanifest">
|
||||
<link rel="shortcut icon" href="/assets/icons/favicon.ico">
|
||||
<meta name="msapplication-TileColor" content="#212121">
|
||||
<meta name="msapplication-config" content="/assets/icons/browserconfig.xml">
|
||||
<meta name="theme-color" content="#212121">
|
||||
</head>
|
||||
<body>
|
||||
<!-- HEADER -->
|
||||
<div id="header_wrap" class="outer">
|
||||
<header class="inner">
|
||||
<a id="forkme_banner" href="https://github.com/jackaudio">View on GitHub</a>
|
||||
<a href="https://jackaudio.org">
|
||||
<img src="/assets/images/logo.png"
|
||||
alt="JACK Logo - Home" border="0">
|
||||
</a>
|
||||
<nav>
|
||||
<a href="/"> Home </a> |
|
||||
<a href="/news/"> News </a> |
|
||||
<a href="/applications/"> Applications </a> |
|
||||
<a href="/faq/"> FAQ </a> |
|
||||
<a href="https://github.com/jackaudio/jackaudio.github.com/wiki"> WIKI </a> |
|
||||
<a href="/api/"> API </a> |
|
||||
<a href="/downloads/"> Downloads </a> |
|
||||
<a href="/community.html"> Community Network </a>
|
||||
</nav>
|
||||
</header>
|
||||
</div>
|
||||
<!-- MAIN CONTENT -->
|
||||
<div id="main_content_wrap" class="outer">
|
||||
<section id="main_content" class="inner">
|
||||
<h1 id="using-jack-on-windows">Using JACK on Windows</h1>
|
||||
|
||||
<h2 id="introduction">Introduction</h2>
|
||||
|
||||
<p>As on other platforms, JACK on Windows is a multi-purpose audio server that
|
||||
connects audio and MIDI streams using the Windows system drivers.
|
||||
It connects (OUTPUT) to those audio drivers using the PortAudio project
|
||||
(so JACK can connect using dsound, wmme, ASIO, etc) depending on what
|
||||
the soundcard’s drivers support.</p>
|
||||
|
||||
<p>JACK provides an Audio, MIDI and transport API (Application Programming Interface)
|
||||
that can be used natively by audio application developers.
|
||||
There are already some existing <em>native</em> JACK Windows applications
|
||||
(that is, audio applications that use the JACK API directly).
|
||||
Through the API, JACK on Windows offers native JACK connections (INPUT),
|
||||
and the JACK-Router ASIO driver (INPUT) that offers an ASIO linker to the JACK Server.</p>
|
||||
|
||||
<p>So any ASIO application will be able to use the JACK-Router ASIO driver to
|
||||
connect to JACK, and JACK can then be used to route that audio to other
|
||||
applications connected to the JACK Server, or out to the system sound device.</p>
|
||||
|
||||
<p>Several applications have native JACK support:</p>
|
||||
|
||||
<ul>
|
||||
<li><a href="https://ardour.org/">Ardour</a></li>
|
||||
<li><a href="https://www.bitwig.com/">Bitwig Studio</a></li>
|
||||
<li><a href="https://kx.studio/Applications:Carla">Carla Plugin Host</a></li>
|
||||
<li><a href="https://github.com/sampov2/foo-yc20">Foo YC20</a></li>
|
||||
<li><a href="https://harrisonconsoles.com/product/mixbus/">Harisson MixBus</a></li>
|
||||
<li><a href="https://jamulus.io">Jamulus</a> (starting from Version 3.8.1 as separate build)</li>
|
||||
<li><a href="https://lmms.io/">LMMS</a> (starting from v1.3)</li>
|
||||
<li><a href="http://musescore.org/">MuseScore</a></li>
|
||||
<li><a href="http://users.notam02.no/~kjetism/radium/">Radium</a></li>
|
||||
<li><a href="https://www.zrythm.org/en/">Zrythm</a></li>
|
||||
</ul>
|
||||
|
||||
<p>Native JACK applications can make use of the full power of the JACK audio and
|
||||
MIDI connection system (for instance, they can open or close JACK connections
|
||||
from within the application, rather than having to set an ASIO driver to use
|
||||
use JACK-Router).
|
||||
Also, the use of natively provided JACK ports provides the ability to sync
|
||||
audio streams between applications.</p>
|
||||
|
||||
<p>The JACK-Router ASIO driver is “only” there so that users are able to use ASIO
|
||||
applications in the Windows context of JACK, but this connection obviously has
|
||||
some limitations that native applications won’t have.</p>
|
||||
|
||||
<p>JACK uses a ‘Server <-> Client’ architecture to supply the audio connection
|
||||
between your sound device and the ASIO application(s).
|
||||
When the JACK Server is running, the JACK-Router driver is then able to create
|
||||
connections between clients (ASIO applications) and the JACK Server.
|
||||
These connections can be seen in the QjackCtl -> Graph screen.</p>
|
||||
|
||||
<p>If the JACK Server is not running, then JACK-Router will not be available to
|
||||
your ASIO application(s), and an error report may be shown.</p>
|
||||
|
||||
<p>By default, JACK-Router is set to provide 4 Input and 4 Output connections.
|
||||
This setting can be customized to suite your needs by editing the
|
||||
JackRouter.ini file within your
|
||||
<code class="language-plaintext highlighter-rouge">C:\Program Files\JACK\jack-router\win32</code> (or <code class="language-plaintext highlighter-rouge">C:\Program Files\JACK\jack-router\win64</code>
|
||||
folder depending of the JACK 32 or 64-bit version).
|
||||
In Windows Explorer, right click on the file and choose the ‘Edit’ option.
|
||||
Change the settings in the [IO] portion of the file.</p>
|
||||
|
||||
<h2 id="installation-and-configuration">Installation and Configuration</h2>
|
||||
|
||||
<ol>
|
||||
<li>
|
||||
<p>Download the JACK2 installer for Windows from the <a href="/downloads/">download page.</a></p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Use the installer. Either the 32-bit or the 64-bit one (which still allows 32-bit clients).</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Pick “Full installation (with JACK-Router)” during installation.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>From the Windows Start menu, locate the QjackCtl application and run it.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>On the QjackCtl application, click “Setup” and adjust “Interface”, “Sample Rate” and “Frames/Period” as needed for your device/sound-card.
|
||||
Do not change settings you do not understand.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Click on OK to close the Setup dialog.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Click on “Start” to start the JACK Server with the parameters you just set up.</p>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p>When the JACK Server is running the JACK-Router ASIO interface will be
|
||||
available to all ASIO capable applications.</p>
|
||||
|
||||
<h2 id="uninstalling-jack">Uninstalling JACK</h2>
|
||||
|
||||
<p>Just open the “Programs and Features” in the Windows Control Panel and
|
||||
remove “JACK2 version …” from there.
|
||||
This will uninstall the JACK Server, JACK-Router and QjackCtl.</p>
|
||||
|
||||
<h2 id="connecting-audio-applications">Connecting Audio Applications</h2>
|
||||
|
||||
<ol>
|
||||
<li>
|
||||
<p>Start the JACK Server using QjackCtl</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>With the Jack Audio Server started, the JackRouter ASIO driver
|
||||
will be available for your ASIO supported applications.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Within your audio application, select JACK-Router as the audio device.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Within QjackCtl, click the “Graph” button.</p>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p>You can route the output of ASIO applications into the inputs of other ASIO
|
||||
applications (like a VST host application), and then connect the audio output
|
||||
of that application to your system output (or a combination of both).</p>
|
||||
|
||||
<p>Multiple channel audio is also supported, but may require more configuration
|
||||
than the simple setup described here.</p>
|
||||
|
||||
</section>
|
||||
</div>
|
||||
<!-- FOOTER -->
|
||||
<div id="footer_wrap" class="outer">
|
||||
<footer class="inner">
|
||||
<p class="copyright" style="text-align:left">Slate theme maintained by
|
||||
<a href="https://github.com/pages-themes">pages-themes</a>
|
||||
<span style="float:right">This site is open source.
|
||||
<a href="https://github.com/jackaudio/jackaudio.github.com/edit/master/faq/jack_on_windows.md">
|
||||
Improve this page</a>
|
||||
</span>
|
||||
</p>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
|
@ -1,478 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# " lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Understanding Ambisonics | RingBuffer</title>
|
||||
<link href="../../../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
|
||||
<link href="../../../assets/css/ipython.min.css" rel="stylesheet" type="text/css">
|
||||
<link href="../../../assets/css/nikola_ipython.css" rel="stylesheet" type="text/css">
|
||||
<link href="https://fonts.googleapis.com/css?family=Playfair+Display:700,900" rel="stylesheet">
|
||||
<meta name="theme-color" content="#5670d4">
|
||||
<meta name="generator" content="Nikola (getnikola.com)">
|
||||
<link rel="alternate" type="application/rss+xml" title="RSS" href="../../../rss.xml">
|
||||
<link rel="canonical" href="http://ringbuffer.org/spatial_audio/ambisonics/understanding-ambisonics/">
|
||||
<script type="text/x-mathjax-config">
|
||||
MathJax.Hub.Config({
|
||||
tex2jax: {
|
||||
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
|
||||
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
|
||||
processEscapes: true
|
||||
},
|
||||
displayAlign: 'center', // Change this to 'left' if you want left-aligned equations.
|
||||
"HTML-CSS": {
|
||||
styles: {'.MathJax_Display': {"margin": 0}}
|
||||
}
|
||||
});
|
||||
</script><!--[if lt IE 9]><script src="../../../assets/js/html5.js"></script><![endif]--><link rel="stylesheet" href="../../../assets/hvc/pkgindex.css">
|
||||
<meta name="author" content="Henrik von Coler">
|
||||
<link rel="prev" href="../../history/williams-mix/" title="John Cage's Williams Mix" type="text/html">
|
||||
<link rel="next" href="../../../computer_music_basics/physical_computing/puredata_ldr/" title="Pure Data: Light Dependent Resistor" type="text/html">
|
||||
<meta property="og:site_name" content="RingBuffer">
|
||||
<meta property="og:title" content="Understanding Ambisonics">
|
||||
<meta property="og:url" content="http://ringbuffer.org/spatial_audio/ambisonics/understanding-ambisonics/">
|
||||
<meta property="og:description" content="Mid–Side Stereo: 1D Ambisonics
|
||||
Mid–Side (MS) stereo can be understood as a one-dimensional decomposition
|
||||
of a sound field along a single horizontal axis and works with the same principle as Ambisonics">
|
||||
<meta property="og:type" content="article">
|
||||
<!-- <meta property="article:published_time" content="2022-04-28T14:00:00Z"> -->
|
||||
</head>
|
||||
<body>
|
||||
<a href="#content" class="sr-only sr-only-focusable">Skip to main content</a>
|
||||
|
||||
<!-- Header and menu bar -->
|
||||
<div class="container">
|
||||
<header class="blog-header py-3"><div class="row nbb-header align-items-center">
|
||||
<div class="col-md-3 col-xs-2 col-sm-2" style="width: auto;">
|
||||
<button class="navbar-toggler navbar-light bg-light nbb-navbar-toggler" type="button" data-toggle="collapse" data-target=".bs-nav-collapsible" aria-controls="bs-navbar" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse bs-nav-collapsible bootblog4-search-form-holder">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6 col-xs-10 col-sm-10 bootblog4-brand" style="width: auto;">
|
||||
<a class="navbar-brand blog-header-logo text-dark" href="http://ringbuffer.org/">
|
||||
|
||||
<!-- <span id="blog-title">RingBuffer</span> -->
|
||||
<img src="../../../images/ringbuffer_BANNER.png" alt="LOGO" class="center"></a>
|
||||
</div>
|
||||
<div class="col-md-3 justify-content-end align-items-center bs-nav-collapsible collapse flex-collapse bootblog4-right-nav">
|
||||
<nav class="navbar navbar-light bg-white"><ul class="navbar-nav bootblog4-right-nav"></ul></nav>
|
||||
</div>
|
||||
</div>
|
||||
</header><nav class="navbar navbar-expand-md navbar-light bg-white static-top"><div class="collapse navbar-collapse bs-nav-collapsible" id="bs-navbar">
|
||||
<ul class="navbar-nav nav-fill d-flex w-100">
|
||||
<li class="nav-item">
|
||||
<a href="../../../computer-music-basics" class="nav-link">Computer Music Basics</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="../../../dsp" class="nav-link">DSP</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="../../../sound-synthesis-introduction" class="nav-link">Sound Synthesis Introduction</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="../../../spatial-audio" class="nav-link">Spatial Audio</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="../../../music_interaction_systems" class="nav-link">Music Interaction Systems</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="../../../building-instruments-in-faust" class="nav-link">Faust</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="../../../sound-synthesis-cpp" class="nav-link">C++</a>
|
||||
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<!-- /.navbar-collapse -->
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="container" id="content" role="main">
|
||||
<div class="body-content">
|
||||
<!--Body content-->
|
||||
|
||||
|
||||
<article class="post-text h-entry hentry postpage" itemscope="itemscope" itemtype="http://schema.org/Article"><header><h1 class="p-name entry-title" itemprop="headline name"><a href="." class="u-url">Understanding Ambisonics</a></h1>
|
||||
|
||||
<div class="metadata">
|
||||
<p class="byline author vcard p-author h-card">
|
||||
<span class="byline-name fn p-name" itemprop="author">
|
||||
<a class="u-url" href="../../../authors/henrik-von-coler/">Henrik von Coler</a>
|
||||
</span>
|
||||
</p>
|
||||
|
||||
|
||||
<p class="dateline">
|
||||
<a href="." rel="bookmark">
|
||||
<time class="published dt-published" datetime="2022-04-28" itemprop="datePublished" title="2022-04-28">
|
||||
2022-04-28
|
||||
</time></a>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
</header><div class="e-content entry-content" itemprop="articleBody text">
|
||||
<section id="midside-stereo-1d-ambisonics"><h2>Mid–Side Stereo: 1D Ambisonics</h2>
|
||||
<p>Mid–Side (MS) stereo can be understood as a one-dimensional decomposition
|
||||
of a sound field along a single horizontal axis and works with the same principle as Ambisonics.
|
||||
MS represents the sound field using:</p>
|
||||
<ul class="simple">
|
||||
<li><p><strong>M (Mid)</strong> — an <strong>cardioid (or omnidirectional) component</strong></p></li>
|
||||
<li><p><strong>S (Side)</strong> — a <strong>bidirectional (figure-of-eight) component</strong> along the left–right axis</p></li>
|
||||
</ul>
|
||||
<figure class="align-center" style="width: 100%"><img alt="/images/spatial/mid_side.png" src="../../../images/spatial/mid_side.png" style="width: 40%;"><figcaption><p><em>MS configuration with omni (blue) and figure of 8 (greed/red).</em></p>
|
||||
</figcaption></figure><p>This structure already mirrors the first-order Ambisonic idea of
|
||||
decomposing the sound field into <strong>orthogonal basis functions</strong>.</p>
|
||||
<hr class="docutils">
|
||||
<section id="ms-encoding"><h3>MS Encoding</h3>
|
||||
<p>Given conventional stereo signals <span class="math">\(L\)</span> and <span class="math">\(R\)</span>:</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
M = \frac{L + R}{2}
|
||||
\end{equation*}
|
||||
</div>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
S = \frac{L - R}{2}
|
||||
\end{equation*}
|
||||
</div>
|
||||
<p>The inverse decoding is:</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
L = M + S
|
||||
\end{equation*}
|
||||
</div>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
R = M - S
|
||||
\end{equation*}
|
||||
</div>
|
||||
</section><hr class="docutils">
|
||||
<section id="interpretation"><h3>Interpretation</h3>
|
||||
<ul class="simple">
|
||||
<li><p><span class="math">\(M\)</span> corresponds to an <strong>omnidirectional pressure term</strong></p></li>
|
||||
<li><p><span class="math">\(S\)</span> corresponds to a <strong>dipole aligned left–right</strong></p></li>
|
||||
</ul>
|
||||
<p><strong>The phases of the dipole encode the spatial information.</strong></p>
|
||||
<p>Mathematically, this is equivalent to a <strong>1D first-order harmonic expansion</strong>:</p>
|
||||
<ul class="simple">
|
||||
<li><p><span class="math">\(M \leftrightarrow Y_0^0\)</span> (monopole)</p></li>
|
||||
<li><p><span class="math">\(S \leftrightarrow Y_1^{\pm1}\)</span> (horizontal dipole)</p></li>
|
||||
</ul>
|
||||
<p>In first-order Ambisonics (ACN/SN3D), the related components are:</p>
|
||||
<ul class="simple">
|
||||
<li><p><span class="math">\(W\)</span> — omnidirectional</p></li>
|
||||
<li><p><span class="math">\(Y\)</span> — left/right dipole</p></li>
|
||||
</ul></section><hr class="docutils">
|
||||
<section id="matrix-form"><h3>Matrix Form</h3>
|
||||
<p>MS encoding can also be written as a matrix transform:</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
\begin{bmatrix}
|
||||
M \\
|
||||
S
|
||||
\end{bmatrix}
|
||||
=
|
||||
\frac{1}{2}
|
||||
\begin{bmatrix}
|
||||
1 & 1 \\
|
||||
1 & -1
|
||||
\end{bmatrix}
|
||||
\begin{bmatrix}
|
||||
L \\
|
||||
R
|
||||
\end{bmatrix}
|
||||
\end{equation*}
|
||||
</div>
|
||||
<p>and decoding:</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
\begin{bmatrix}
|
||||
L \\
|
||||
R
|
||||
\end{bmatrix}
|
||||
=
|
||||
\begin{bmatrix}
|
||||
1 & 1 \\
|
||||
1 & -1
|
||||
\end{bmatrix}
|
||||
\begin{bmatrix}
|
||||
M \\
|
||||
S
|
||||
\end{bmatrix}
|
||||
\end{equation*}
|
||||
</div>
|
||||
</section></section><hr class="docutils">
|
||||
<section id="a-vs-b-format"><h2>A vs B Format</h2>
|
||||
<p><strong>A-format</strong> refers to the raw microphone capsule signals (e.g., tetrahedral mic outputs) when capturing 3D sound fields.
|
||||
This format is mic-specific and not interchangeable. To further process it, it usually needs to be converted to B-format.
|
||||
A→B conversion matrices are microphone-model-specific, considering capsule geometry and calibration.
|
||||
Microphone vendors need to supply the decoder.</p>
|
||||
<figure class="align-center" style="width: 100%"><img alt="/images/spatial/ambisonics/ambisonics_capsule.png" src="../../../images/spatial/ambisonics/ambisonics_capsule.png" style="width: 30%;"></figure><p><strong>B-format</strong> is made up of the spherical-harmonic components of the sound field.
|
||||
This is the standard Ambisonics format with defined channel order and normalization.
|
||||
B-format is portable and can be reproduced on any rendering system (loudspeaker setups, binaural), following standardized decoding algorithms.</p>
|
||||
</section><hr class="docutils">
|
||||
<section id="spherical-harmonics"><h2>Spherical Harmonics</h2>
|
||||
<p>Basic Ambisonics does not define a sound filed through positions, but through angles of incedence.
|
||||
Ambisonics is based on a decomposition of a sound field into <em>spherical harmonics</em> and dates back to Gerzon's theory of Peryphony (Gerzon, 1973).
|
||||
These spherical harmonics encode a sound field into to different axes,
|
||||
The number of Ambisonics channels $N$ is equal to the number of spherical harmonics.
|
||||
It can be calculated for a given order $M$ with the following formula:</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
N = (M+1)^2
|
||||
\end{equation*}
|
||||
</div>
|
||||
<p>Figure 1 shows the first 16 spherical harmonics. The first row ($N=1$) is the omnidirectional sound pressure
|
||||
for the order $M=0$.</p>
|
||||
<ul class="simple">
|
||||
<li><p>Rows 1-2 together represent the $N=4$ spherical harmonics of the first order Ambisonics signal.</p></li>
|
||||
<li><p>Rows 1-3 correspond to $M=2$, respectively $N=9$.</p></li>
|
||||
<li><p>Rows 1-4 to the third order Ambisonics signal with $N=16$ spherical harmonics.</p></li>
|
||||
</ul>
|
||||
<p>First order ambisonics is sufficient to encode a threedimensional sound field.
|
||||
The higher the Ambisonics order, the more precise the directional encoding and the better the localization of virtual sound sources.</p>
|
||||
<figure class="align-center" style="width: 100%"><img alt="/images/spatial/ambisonics/third-order-ambisonics.png" src="../../../images/spatial/ambisonics/third-order-ambisonics.png" style="width: 600px;"><figcaption><p>Fig. 1: Spherical harmonics up to order 3 <a class="brackets" href="#footnote-1" id="footnote-reference-1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>.</p>
|
||||
</figcaption></figure><aside class="footnote-list brackets"><aside class="footnote brackets" id="footnote-1" role="doc-footnote"><span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#footnote-reference-1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p><a class="reference external" href="https://commons.wikimedia.org/wiki/Category:Spherical_harmonics#/media/File:Spherical_Harmonics_deg3.png">https://commons.wikimedia.org/wiki/Category:Spherical_harmonics#/media/File:Spherical_Harmonics_deg3.png</a></p>
|
||||
</aside></aside></section><hr class="docutils">
|
||||
<section id="common-b-format-conventions"><h2>Common B-format Conventions</h2>
|
||||
<p>B-format conventions define the relation between Ambisonic channel order and spherical harmonics.
|
||||
There are different conventions for the sequence of the individual signals,
|
||||
as well as for the normalization.</p>
|
||||
<table>
|
||||
<caption>Ambisonics conventions (Common B-format variants)</caption>
|
||||
<thead><tr>
|
||||
<th>Convention</th>
|
||||
<th>Type</th>
|
||||
<th>Channel order (1st order)</th>
|
||||
<th>Normalization</th>
|
||||
<th>Notes / Where used</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<strong>FuMa</strong> (Furse–Malham)</td>
|
||||
<td>B-format (FOA)</td>
|
||||
<td><code>W, X, Y, Z</code></td>
|
||||
<td>FuMa (“maxN” style; <code>W</code> is scaled by <code>1/√2</code>)</td>
|
||||
<td>Legacy 1st-order B-format used in older DAWs and toolchains; awkward for higher orders (≥2).</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>AmbiX</strong></td>
|
||||
<td>B-format (FOA/HOA)</td>
|
||||
<td>
|
||||
<code>ACN</code> order → <code>[0:W, 1:Y, 2:Z, 3:X]</code>
|
||||
</td>
|
||||
<td><strong>SN3D</strong></td>
|
||||
<td>De-facto modern production standard (Reaper+AmbiX, many VR/AR SDKs, YouTube VR). Portable and HOA-friendly.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>ACN/N3D</strong></td>
|
||||
<td>B-format (FOA/HOA)</td>
|
||||
<td>
|
||||
<code>ACN</code> order → <code>[0:W, 1:Y, 2:Z, 3:X]</code>
|
||||
</td>
|
||||
<td>
|
||||
<strong>N3D</strong> (orthonormal)</td>
|
||||
<td>Common in research and HOA libraries; convenient for math/analysis and per-order processing.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<!-- Handy mappings (not part of the table, keep if useful):
|
||||
- FuMa ↔ AmbiX (FOA):
|
||||
• Gain: W_AmbiX = √2 · W_FuMa; X,Y,Z identical.
|
||||
• Order: FuMa [W,X,Y,Z] vs. AmbiX [W,Y,Z,X].
|
||||
- SN3D ↔ N3D (any order ℓ): Yℓm|N3D = √(2ℓ+1) · Yℓm|SN3D.
|
||||
--></section><hr class="docutils">
|
||||
<section id="ambisonic-formats"><h2>Ambisonic Formats</h2>
|
||||
<p>An Ambisonics B Format file or signal carries all $N$ spherical harmonics.
|
||||
Figure 2 shows a first order B Format signal.</p>
|
||||
<figure class="align-center" style="width: 100%"><img alt="/images/spatial/ambisonics/first-order-signal.png" src="../../../images/spatial/ambisonics/first-order-signal.png" style="width: 100%;"><figcaption><p>Fig. 2: Four channels of a first order Ambisonics signal.</p>
|
||||
</figcaption></figure><figure class="align-center" style="width: 100%"><img alt="/images/spatial/ambisonics/first-order-harmonics.png" src="../../../images/spatial/ambisonics/first-order-harmonics.png" style="width: 50%;"><figcaption><p>Fig. 2: Spherical harmonics of a first order Ambisonics signal.</p>
|
||||
</figcaption></figure></section><hr class="docutils">
|
||||
<section id="acn-normalizations-and-1st-order-mappings"><h2>ACN, Normalizations, and 1st-Order Mappings</h2>
|
||||
<p><strong>ACN (Ambisonic Channel Numbering)</strong></p>
|
||||
<p>The channel index <span class="math">\(n\)</span> is</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
n = \ell(\ell+1) + m, \qquad \ell = 0..L,\ \ m = -\ell..\ell.
|
||||
\end{equation*}
|
||||
</div>
|
||||
<p>For <strong>1st order</strong> (<span class="math">\(\ell = 0,1\)</span>), the ACN indices map to channels as</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
[\,0:\ Y_0^0 = W,\quad 1:\ Y_1^{-1} = Y,\quad 2:\ Y_1^{0} = Z,\quad 3:\ Y_1^{1} = X\,].
|
||||
\end{equation*}
|
||||
</div>
|
||||
<section id="normalizations"><h3>Normalizations</h3>
|
||||
<ul>
|
||||
<li><p><strong>SN3D</strong> (“semi-normalized”): <span class="math">\(Y_0^0 = 1\)</span>. Widely used in production (AmbiX).</p></li>
|
||||
<li>
|
||||
<p><strong>N3D</strong> (fully normalized): spherical harmonics are orthonormal over the unit sphere, i.e.,</p>
|
||||
<div class="math">
|
||||
\begin{equation*}
|
||||
\int_{S^2} Y_n^m(\Omega)\, Y_{n'}^{m'}(\Omega)\, d\Omega
|
||||
= \delta_{nn'}\,\delta_{mm'}
|
||||
\end{equation*}
|
||||
</div>
|
||||
<p>This normalization yields consistent energy per order and simplifies theoretical work, analysis, and algorithm design in higher-order Ambisonics; however, the order-dependent scaling can increase peak amplitudes in higher orders, requiring additional headroom or gain compensation to avoid clipping in practical implementations.</p>
|
||||
</li>
|
||||
<li><p><strong>FuMa</strong> (legacy): distinct scaling; notably <span class="math">\(W_{\text{FuMa}} = \tfrac{1}{\sqrt{2}}\,W_{\text{SN3D}}\)</span>.</p></li>
|
||||
</ul></section><section id="st-order-mappings-fuma-ambix-acnsn3d"><h3>1st-Order Mappings (FuMa ↔ AmbiX/ACN–SN3D)</h3>
|
||||
<p><strong>Channel order</strong></p>
|
||||
<ul class="simple">
|
||||
<li><p>FuMa order: <code>[W, X, Y, Z]</code></p></li>
|
||||
<li><p>AmbiX (ACN/SN3D) order: <code>[W, Y, Z, X]</code> (i.e., ACN indices <code>[0,1,2,3] -> [W,Y,Z,X]</code>)</p></li>
|
||||
</ul></section><hr class="docutils">
|
||||
<section id="references"><h3>References</h3>
|
||||
<div class="publication-list">
|
||||
<h4>2019</h4>
|
||||
<ul><li class="publication" style="padding-bottom: 1em;">Franz Zotter and Matthias Frank.
|
||||
<em><span class="bibtex-protected">Ambisonics: A Practical 3D Audio Theory for Recording, Studio Production, Sound Reinforcement, and Virtual Reality</span></em>.
|
||||
Springer, 2019.<br>[<a href="http://ringbuffer.org/papers/zotter2019ambisonics.html">details</a>]
|
||||
[<a href="javascript:void(0)" onclick="
|
||||
(function(target, id) {
|
||||
if ($('#' + $.escapeSelector(id)).css('display') == 'block')
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).hide('fast');
|
||||
$(target).text('BibTeX▼')
|
||||
}
|
||||
else
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).show('fast');
|
||||
$(target).text('BibTeX▲')
|
||||
}
|
||||
})(this, 'bibtex-zotter2019ambisonics');">BibTeX▼</a>]
|
||||
<div id="bibtex-zotter2019ambisonics" style="display:none"><pre>@book{zotter2019ambisonics,
|
||||
author = "Zotter, Franz and Frank, Matthias",
|
||||
publisher = "Springer",
|
||||
title = "{Ambisonics: A Practical 3D Audio Theory for Recording, Studio Production, Sound Reinforcement, and Virtual Reality}",
|
||||
year = "2019"
|
||||
}
|
||||
</pre></div>
|
||||
</li></ul>
|
||||
<h4>2015</h4>
|
||||
<ul><li class="publication" style="padding-bottom: 1em;">Matthias Frank, Franz Zotter, and Alois Sontacchi.
|
||||
<a href="http://ringbuffer.org/papers/frank2015producing.html"><strong>Producing 3d audio in ambisonics.</strong></a>
|
||||
In <em>Audio Engineering Society Conference: 57th International Conference: The Future of Audio Entertainment Technology–Cinema, Television and the Internet</em>. Audio Engineering Society, 2015.<br>[<a href="http://ringbuffer.org/papers/frank2015producing.html">details</a>]
|
||||
[<a href="javascript:void(0)" onclick="
|
||||
(function(target, id) {
|
||||
if ($('#' + $.escapeSelector(id)).css('display') == 'block')
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).hide('fast');
|
||||
$(target).text('BibTeX▼')
|
||||
}
|
||||
else
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).show('fast');
|
||||
$(target).text('BibTeX▲')
|
||||
}
|
||||
})(this, 'bibtex-frank2015producing');">BibTeX▼</a>]
|
||||
<div id="bibtex-frank2015producing" style="display:none"><pre>@inproceedings{frank2015producing,
|
||||
author = "Frank, Matthias and Zotter, Franz and Sontacchi, Alois",
|
||||
title = "Producing 3D audio in ambisonics",
|
||||
booktitle = "Audio Engineering Society Conference: 57th International Conference: The Future of Audio Entertainment Technology--Cinema, Television and the Internet",
|
||||
year = "2015",
|
||||
organization = "Audio Engineering Society"
|
||||
}
|
||||
</pre></div>
|
||||
</li></ul>
|
||||
<h4>2009</h4>
|
||||
<ul><li class="publication" style="padding-bottom: 1em;">Frank Melchior, Andreas Gr<span class="bibtex-protected">ä</span>fe, and Andreas Partzsch.
|
||||
<a href="http://ringbuffer.org/papers/melchior2009spatial.html"><strong>Spatial audio authoring for ambisonics reproduction.</strong></a>
|
||||
In <em>Proc. of the Ambisonics Symposium</em>. 2009.<br>[<a href="http://ringbuffer.org/papers/melchior2009spatial.html">details</a>]
|
||||
[<a href="javascript:void(0)" onclick="
|
||||
(function(target, id) {
|
||||
if ($('#' + $.escapeSelector(id)).css('display') == 'block')
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).hide('fast');
|
||||
$(target).text('BibTeX▼')
|
||||
}
|
||||
else
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).show('fast');
|
||||
$(target).text('BibTeX▲')
|
||||
}
|
||||
})(this, 'bibtex-melchior2009spatial');">BibTeX▼</a>]
|
||||
<div id="bibtex-melchior2009spatial" style="display:none"><pre>@inproceedings{melchior2009spatial,
|
||||
author = {Melchior, Frank and Gr{\"a}fe, Andreas and Partzsch, Andreas},
|
||||
title = "Spatial audio authoring for Ambisonics reproduction",
|
||||
booktitle = "Proc. of the Ambisonics Symposium",
|
||||
year = "2009"
|
||||
}
|
||||
</pre></div>
|
||||
</li></ul>
|
||||
<h4>1973</h4>
|
||||
<ul><li class="publication" style="padding-bottom: 1em;">Michael A. Gerzon.
|
||||
<a href="http://ringbuffer.org/papers/gerzon1973periphony.html"><strong><span class="bibtex-protected">Periphony: With-Height Sound Reproduction</span>.</strong></a>
|
||||
<em>Journal of the Audio Engineering Society</em>, 21(1):2–10, 1973.<br>[<a href="http://ringbuffer.org/papers/gerzon1973periphony.html">details</a>]
|
||||
[<a href="javascript:void(0)" onclick="
|
||||
(function(target, id) {
|
||||
if ($('#' + $.escapeSelector(id)).css('display') == 'block')
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).hide('fast');
|
||||
$(target).text('BibTeX▼')
|
||||
}
|
||||
else
|
||||
{
|
||||
$('#' + $.escapeSelector(id)).show('fast');
|
||||
$(target).text('BibTeX▲')
|
||||
}
|
||||
})(this, 'bibtex-gerzon1973periphony');">BibTeX▼</a>]
|
||||
<div id="bibtex-gerzon1973periphony" style="display:none"><pre>@article{gerzon1973periphony,
|
||||
author = "Gerzon, Michael A.",
|
||||
journal = "Journal of the Audio Engineering Society",
|
||||
number = "1",
|
||||
pages = "2--10",
|
||||
title = "{Periphony: With-Height Sound Reproduction}",
|
||||
volume = "21",
|
||||
year = "1973"
|
||||
}
|
||||
</pre></div>
|
||||
</li></ul>
|
||||
</div></section></section>
|
||||
</div>
|
||||
<aside class="postpromonav"><nav><ul class="pager hidden-print">
|
||||
<!-- <li class="previous"> --><!-- <a href="/spatial_audio/history/williams-mix/" rel="prev" title="John Cage's Williams Mix">Previous post</a> --><!-- </li> --><!-- <li class="next">
|
||||
<a href="/computer_music_basics/physical_computing/puredata_ldr/" rel="next" title="Pure Data: Light Dependent Resistor">Next post</a>
|
||||
</li> -->
|
||||
</ul></nav></aside><script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML" integrity="sha384-3lJUsx1TJHt7BA4udB5KPnDrlkO8T6J6v/op7ui0BbCjvZ9WqV4Xm6DTP6kQ/iBH" crossorigin="anonymous"></script><script type="text/x-mathjax-config">
|
||||
MathJax.Hub.Config({
|
||||
tex2jax: {
|
||||
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
|
||||
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
|
||||
processEscapes: true
|
||||
},
|
||||
displayAlign: 'center', // Change this to 'left' if you want left-aligned equations.
|
||||
"HTML-CSS": {
|
||||
styles: {'.MathJax_Display': {"margin": 0}}
|
||||
}
|
||||
});
|
||||
</script></article><!--End of body content--><footer id="footer"><center>
|
||||
<hr>
|
||||
<br>
|
||||
</center>
|
||||
<br></footer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script src="../../../assets/js/all-nocdn.js"></script><script>
|
||||
baguetteBox.run('div#content', {
|
||||
ignoreClass: 'islink',
|
||||
captions: function(element) {
|
||||
return element.getElementsByTagName('img')[0].alt;
|
||||
}});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,331 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Using multiple HDSPe AoX cards :: RME Manuals</title>
|
||||
<link rel="canonical" href="https://docs.rme-audio.com/aoxd/705-1c_multiple_cards_win/">
|
||||
<link rel="prev" href="../704-1c_operation_asio/">
|
||||
<link rel="next" href="../706-1c_digicheck_win/">
|
||||
<meta name="description" content=""Requirements when using more than one HDSPe AoX-D"">
|
||||
<meta name="keywords" content="multiple, several, aggregate, combine, asio, windows">
|
||||
<meta name="generator" content="Antora 3.1.14">
|
||||
<link rel="stylesheet" href="../../_/css/site.css">
|
||||
<script>(function (w, d, s, l, i) {
|
||||
w[l] = w[l] || []; w[l].push({
|
||||
'gtm.start':
|
||||
new Date().getTime(), event: 'gtm.js'
|
||||
}); var f = d.getElementsByTagName(s)[0],
|
||||
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
|
||||
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
|
||||
})(window, document, 'script', 'dataLayer', 'GTM-K7Q74RF');</script>
|
||||
</head>
|
||||
<body class="article">
|
||||
<!-- Google Tag Manager (noscript) -->
|
||||
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-K7Q74RF"
|
||||
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
|
||||
<!-- End Google Tag Manager (noscript) -->
|
||||
<script async id="search-script" src="../../_/js/vendor/rsearch.js"
|
||||
data-app-id="6I7K1NDPUD" data-api-key="a9fd16b8374ad54610afd2baa40b9ab9"
|
||||
data-index-name="dev_aoxd" data-stylesheet="../../_/css/vendor/docsearch.css"
|
||||
data-product-home="/aoxd/" data-product-title="RME HDSPe AoX-D User's Guide">
|
||||
</script>
|
||||
<header class="header">
|
||||
<nav class="navbar">
|
||||
<div id="navbar-brand" class="navbar-brand">
|
||||
<div class="navbar-item navbar-brand-logo hide-on-search"></div>
|
||||
<a class="navbar-item navbar-title hide-on-search" href="https://docs.rme-audio.com" id="navbar-title">RME Manuals</a>
|
||||
</div>
|
||||
<div id="search-fullwidth" class="navbar-search">
|
||||
<form class="navbar-item search">
|
||||
<input type="text" placeholder="Search" class="query" id="search-input">
|
||||
<button type="button" class="search"><span>Search [S]</span></button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="body">
|
||||
<div class="nav-container" data-component="aoxd" data-version="">
|
||||
<aside class="nav">
|
||||
<div class="panels">
|
||||
<div class="nav-panel-menu is-active" data-panel="menu">
|
||||
<nav class="nav-menu">
|
||||
<h3 class="title"><a href="../">RME HDSPe AoX-D User's Guide</a></h3>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="0">
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../015-1c_introduction/">Introduction</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../015-2r_package_contents/">Package Contents</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../015-3r_system_requirements/">System Requirements</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../015-4c_brief_description/">Brief Description and Characteristics</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../015-5t_hardware_installation/">Hardware Installation</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../015-6c_hardware_overview/">Hardware Overview</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../015-7r_blockdiagram/">Signal Flow Diagram</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<a class="nav-link" href="../095-1r_accessories/">Accessories</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../070-1c_support/">Warranty and Support</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../070-2r_support_contacts/">Support Contacts</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../700-1c_operation_usage_windows/">Usage under Windows</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../701-1c_drivers/">Driver and Firmware (Windows)</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../702-1c_configuration_win/">Configuring the HDSPe AoX-D</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../703-1c_operation_usage_win/">Operation and Usage</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../704-1c_operation_asio/">Operation under ASIO</a>
|
||||
</li>
|
||||
<li class="nav-item is-current-page" data-depth="2">
|
||||
<a class="nav-link" href="./">Using multiple HDSPe AoX cards</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../706-1c_digicheck_win/">DIGICheck Software Overview</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../710-1c_operation_usage_macos/">Usage under macOS</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../711-1c_drivers_mac/">Driver and Firmware (macOS)</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../712-1c_configuration_mac/">Configuring the HDSPe AoX-D</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../720-1c_connectors/">Connections</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../720-2c_network/">Network Ports</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../720-3c_headphones/">Line - Headphones</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../720-4r_phones_specifications/">Phones Specifications</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../720-5c_aesebu/">AES/EBU</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../720-6c_midi/">MIDI</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../720-7r_dsub_pinout/">D-Sub 9 Connector Pinout</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../800-1c_totalmix/">Routing and Monitoring with TotalMix</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../810-1c_totalmix_user_interface/">The User Interface</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../811-1c_channel_strip/">The Channel Strip</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../812-1c_control_room/">Control Room Strip</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../813-1c_control/">Control Strip</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../815-1c_preferences/">Preferences</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../816-1c_settings/">Settings</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../817-1c_hotkeys_usage/">Hotkeys and Usage</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../818-1c_menu_options/">Menu 'Options'</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../819-1c_menu_window/">Menu Window</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../830-1c_matrix/">The Matrix</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../840-1c_asio_direct_monitoring/">ASIO Direct Monitoring (Windows)</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../850-1c_midi_remote_tmfx/">MIDI Remote Overview</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="1">
|
||||
<button class="nav-item-toggle"></button>
|
||||
<a class="nav-link" href="../500-1c_annex/">Annex</a>
|
||||
<ul class="nav-list">
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../520-2r_ce/">CE Compliance</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../520-3r_fcc/">FCC Compliance</a>
|
||||
</li>
|
||||
<li class="nav-item" data-depth="2">
|
||||
<a class="nav-link" href="../520-4r_weee/">Note on Disposal</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<main class="article">
|
||||
<div class="toolbar" role="navigation">
|
||||
<button class="nav-toggle"></button>
|
||||
<a href="../../shared/" class="home-link"></a>
|
||||
<nav class="breadcrumbs" aria-label="breadcrumbs">
|
||||
<ul>
|
||||
<li><a href="../">RME HDSPe AoX-D User's Guide</a></li>
|
||||
<li><a href="../700-1c_operation_usage_windows/">Usage under Windows</a></li>
|
||||
<li><a href="./">Using multiple HDSPe AoX cards</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
<div class="content">
|
||||
<article class="doc">
|
||||
<h1 class="page">Using multiple HDSPe AoX cards</h1>
|
||||
<div class="paragraph">
|
||||
<p>The current driver supports the operation of up to three HDSPe AoX cards.
|
||||
It is possible to use both HDSPe AoX-M and HDSPe AoX-D at the same time.
|
||||
To ensure proper functionality, all cards must remain synchronized, either through a valid sync source via word clock or by using <strong>Auto-Sync</strong> with synchronized signals.</p>
|
||||
</div>
|
||||
<h2 id="_synchronization_setup" class="discrete">Synchronization Setup</h2>
|
||||
<div class="paragraph">
|
||||
<p>To maintain precise synchronization between multiple cards, internal connectors are available.
|
||||
The cards should be synchronized to the leader card by connecting the corresponding <strong>SYNC</strong> headers on the card with the supplied cable.
|
||||
Ensure that the clock modes for all cards are configured correctly in their respective <strong>Settings</strong> dialogs.</p>
|
||||
</div>
|
||||
<div class="ulist">
|
||||
<ul>
|
||||
<li>
|
||||
<p>When all units are supplied with a synchronous clock signal (i.e., all units display <strong>Sync</strong> in their <strong>Settings</strong> dialogs), all channels across the cards can be utilized simultaneously.
|
||||
This setup is particularly streamlined under ASIO, as the ASIO driver combines all cards into a single interface.</p>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<h2 id="_totalmix_with_multiple_cards" class="discrete">TotalMix with multiple cards</h2>
|
||||
<div class="paragraph">
|
||||
<p><strong>TotalMix</strong> is integrated into the hardware of each HDSPe AoX-D, allowing for up to three independent mixers when using three cards.
|
||||
However, these mixers are separate and do not support data exchange between cards.
|
||||
As a result, a global mixer for all units is not available.</p>
|
||||
</div>
|
||||
<div class="admonitionblock tip">
|
||||
<table>
|
||||
<tr>
|
||||
<td class="icon">
|
||||
<i class="fa icon-tip" title="Tip"></i>
|
||||
</td>
|
||||
<td class="content">
|
||||
If required, submixes could be aggregated from different cards using the optional MADI ports.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
<form action="https://submit-form.com/zq8cJcer0V5_Gt-P_RyS5" class="feedback" id="FeedbackForm">
|
||||
<div class="form-wrapper.show">
|
||||
<div class="question">
|
||||
<p>Was this topic helpful?</p>
|
||||
<div class="buttons">
|
||||
<button aria-expanded="false" type="button" id="feedback_yes"
|
||||
class="button button--secondary button--compact feedback--yes">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
||||
<path d="M0 0h24v24H0V0z" fill="none" />
|
||||
<path
|
||||
d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button aria-expanded="false" type="button" id="feedback_no"
|
||||
class="button button--secondary button--compact feedback--no">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
||||
<path d="M0 0h24v24H0z" fill="none" />
|
||||
<path
|
||||
d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="form-success" class="form-success">Thank you!</div>
|
||||
<div id="form-message" class="form-message">
|
||||
<p>
|
||||
Thank you for letting us know.
|
||||
</p>
|
||||
<p>
|
||||
Please tell us what you were looking for:
|
||||
</p>
|
||||
<input type="text" name="URL" value="/aoxd/705-1c_multiple_cards_win/" hidden="true" />
|
||||
<input type="text" name="honig_topf_48xz8" class="honig_topf_48xz8" />
|
||||
<input type="text" name="sweetFormField" class="honig_topf_48xz8" />
|
||||
<textarea name="message" class="form-input full" placeholder="Your message" maxlength="5000" required></textarea>
|
||||
<p> Your E-Mail (in case you would like us to contact you):</p>
|
||||
<input type="email" name="email" class="form-input form-input--wide" placeholder="your.email@rme-audio.de">
|
||||
<button type="submit" class="submitForm" id="submitForm">Submit your feedback!</button>
|
||||
</div>
|
||||
<p id="js-form-response"></p>
|
||||
</div>
|
||||
</form>
|
||||
<nav class="pagination">
|
||||
<span class="prev"><a href="../704-1c_operation_asio/">Operation under ASIO</a></span>
|
||||
<span class="next"><a href="../706-1c_digicheck_win/">DIGICheck Software Overview</a></span>
|
||||
</nav>
|
||||
</article>
|
||||
<aside class="toc sidebar" data-title="Contents" data-levels="2">
|
||||
<div class="toc-menu"></div>
|
||||
</aside>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<footer class="footer">
|
||||
<p>©2025 RME / m2lab Ltd.</p>
|
||||
</footer>
|
||||
<script src="../../_/js/site.js"></script>
|
||||
<script async src="../../_/js/vendor/highlight.js"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1,83 +0,0 @@
|
|||
# Ambisonic AquaSynth Field: Distilled Research
|
||||
|
||||
## Objective
|
||||
|
||||
Consolidate four live microphones -- shielded cardioid, Deru shotgun, and two camera mics -- into one synchronized spatial audio scene that can feed an AquaSynth Faust DSP graph, while also placing dynamic synth patch outputs in 3D.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
Mimir currently treats audio as independent OBS-ingestable endpoints: one FFmpeg process per audio source, one SRT port per source, and OBS owns the mix. That is coherent for manual OBS mixing, but it is the wrong ownership model for a single spatial field. An ambisonic bus needs clocked multichannel audio before spatial encoding, then effects, then decode/render.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Capture sync must be owned before spatial encoding. Drift correction after the fact can make playback tolerable, but it does not create a physically coherent sound field.
|
||||
- The ambisonic representation must declare order, channel count, channel order, normalization, sample rate, and render target.
|
||||
- The Faust graph should receive one declared spatial bus, not four unsynchronized mono stories wearing a coat.
|
||||
- Microphone geometry and directivity must be explicit if microphone feeds are treated as a captured field.
|
||||
- Synth outputs are easier: each synth voice is a mono or stereo source with explicit azimuth/elevation/radius metadata, then encoded into the same ambisonic bus.
|
||||
|
||||
## Main Finding
|
||||
|
||||
Four arbitrary microphones are not automatically a first-order ambisonic microphone. ICST distinguishes A-format as microphone-specific raw capsule output and B-format as the production/exchange sound-field representation; A-format must be converted before it is a usable ambisonic master [ICST]. A tetrahedral ambisonic mic works because capsule geometry and calibration are part of the device model. Your mic set is heterogeneous: cardioid, shotgun, and camera mics have different positions, directivities, gains, noise floors, latency, and likely clocks.
|
||||
|
||||
McCormack et al. show that arbitrary microphone arrays can be encoded into Ambisonics, but even conventional linear encoding is limited by geometry, sensor placement, regularization, spatial aliasing, and bandwidth; their proposed parametric method uses spatial analysis, filtering, source/ambient decomposition, and measured or modeled array behavior [McCormack 2022]. Translation: this is research-grade if we want "real recovered sound field," not a cute four-channel matrix.
|
||||
|
||||
## Recommended Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["4 physical mic feeds"] --> B["Clocked multichannel capture"]
|
||||
B --> C["Calibration: gain, delay, polarity, noise, geometry"]
|
||||
C --> D["Scene encoder"]
|
||||
E["Dynamic synth patch voices"] --> F["Position metadata: azimuth, elevation, radius"]
|
||||
F --> G["Faust HOA/FOA source encoders"]
|
||||
D --> H["Ambisonic bus"]
|
||||
G --> H
|
||||
H --> I["AquaSynth Faust spatial DSP"]
|
||||
I --> J["Decoder / renderer: binaural, stereo, OBS, speakers"]
|
||||
```
|
||||
|
||||
## Practical Path
|
||||
|
||||
1. Capture all four microphones through one clock domain.
|
||||
Prefer one multichannel audio interface or a driver/server that exposes one synchronized device. RME's documentation for multiple cards is blunt that cards need a shared sync source or sync headers to remain synchronized [RME]. JACK's design centers synchronous client execution and low-latency inter-application routing, and on Windows it can bridge ASIO clients through JACK-Router [JACK API; JACK Windows]. FFmpeg DirectShow can open multiple devices and says opening them on the same input "should improve synchronism," but that is not the same as proving sample-accurate shared-clock capture [FFmpeg Devices].
|
||||
|
||||
2. Pick the honest spatial model.
|
||||
For v1, do source-based ambisonic scene building: treat each mic as a directional source at a measured position, with calibration delays and gains. This produces a usable spatial mix, not a physically exact reconstruction. For v2, investigate measured arbitrary-array encoding if the room-capture realism matters enough to justify calibration sweeps and signal analysis.
|
||||
|
||||
3. Use ambiX unless a tool forces otherwise.
|
||||
ICST and IEM both identify ambiX as ACN channel ordering with SN3D normalization, and IEM explicitly uses that convention [ICST; IEM Compatibility]. This should be the default interchange format for the bus.
|
||||
|
||||
4. Start with FOA, design the graph for HOA.
|
||||
First-order Ambisonics is 4 channels. Higher order uses `(order + 1)^2` channels and gives sharper spatial resolution at higher routing and CPU cost [ICST]. Faust `hoa.lib` provides encoders, decoders, rotators, optimizers, and 3D encoders; `encoder3D(N, x, a, e)` directly fits dynamic synth voices [Faust hoa.lib]. The graph should parameterize order so FOA can ship first without boxing out HOA.
|
||||
|
||||
5. Keep OBS as render target, not spatial authority.
|
||||
If this path becomes live, OBS should ingest the rendered output or selected post-DSP stems. OBS should not be asked to preserve the ambisonic field while separately mixing the pre-field microphones. That splits authority and invites drift.
|
||||
|
||||
## Cut Line
|
||||
|
||||
Cut or suspend the old one-port-per-audio-source model for any microphone that participates in the ambisonic field. It can remain for plain OBS monitor sources, but the spatial bus must be one synchronized capture path.
|
||||
|
||||
Do not build a bespoke arbitrary-array encoder first. Use Faust `hoa.lib` for source encoding and established tooling like IEM/SPARTA for verification. Only consider a custom array encoder after we have measured mic geometry, clock behavior, impulse responses, and proven that source-based encoding is not enough.
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Are the two camera mics available as embedded channels from one capture device, or as separate USB/device clocks?
|
||||
- Do we have a multichannel interface that can ingest all four mics into one ASIO device?
|
||||
- Is AquaSynth currently a Faust host, a generated plugin target, or a separate graph compiler/runtime?
|
||||
- Is the desired output binaural headphone monitoring, stereo OBS program audio, surround speakers, or a stored ambisonic master?
|
||||
- Do we need the room itself reconstructed, or do we need a convincing controllable spatial mix for performance?
|
||||
|
||||
## Citations
|
||||
|
||||
- [ICST] ICST Ambisonics, "Ambisonics Formats Explained: A-Format, B-Format, FuMa, AmbiX, FOA and HOA." Mirror: `mirrors/icst-ambisonics-formats.html`.
|
||||
- [RingBuffer] RingBuffer, "Understanding Ambisonics." Mirror: `mirrors/ringbuffer-understanding-ambisonics.html`.
|
||||
- [McCormack 2022] McCormack, Politis, Gonzalez, Lokki, and Pulkki, "Parametric Ambisonic Encoding of Arbitrary Microphone Arrays," IEEE/ACM TASLP, 2022. Mirror: `mirrors/mccormack-2022-parametric-ambisonic-encoding.pdf`.
|
||||
- [Faust hoa.lib] Faust Libraries, `hoa.lib`. Mirror: `mirrors/faust-hoa-lib.html`.
|
||||
- [IEM] IEM Plug-in Suite. Mirror: `mirrors/iem-plugin-suite.html`.
|
||||
- [IEM Compatibility] IEM Plug-in Suite, "Compatibility with other Suites." Mirror: `mirrors/iem-compatibility.html`.
|
||||
- [SPARTA] SPARTA, "Overview." Mirror: `mirrors/sparta-overview.html`.
|
||||
- [FFmpeg Devices] FFmpeg Devices Documentation. Mirror: `mirrors/ffmpeg-devices.html`.
|
||||
- [JACK API] JACK Audio Connection Kit API Overview. Mirror: `mirrors/jack-api-overview.html`.
|
||||
- [JACK Windows] JACK Audio Connection Kit, "Using JACK on Windows." Mirror: `mirrors/jack-on-windows.html`.
|
||||
- [RME] RME Manuals, "Using multiple HDSPe AoX cards." Mirror: `mirrors/rme-multiple-cards-sync.html`.
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
# Bibliography: Feedback As Continuous Calibration
|
||||
|
||||
Mirrored copies live under `research/feedback-calibration/mirrors/`.
|
||||
|
||||
## Echo / Feedback System Identification
|
||||
|
||||
- S. Goetze, M. Kallinger, A. Mertins, and K. Kammeyer, "System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller," HSCMA 2008.
|
||||
Mirror: `mirrors/goetze-2008-aec-listening-room-compensation.html`
|
||||
|
||||
- F. Lindstrom, C. Schueldt, and I. Claesson, "Efficient Multichannel NLMS Implementation for Acoustic Echo Cancellation," EURASIP Journal on Audio, Speech, and Music Processing, 2007.
|
||||
Mirror: `mirrors/lindstrom-2007-efficient-multichannel-nlms.html`
|
||||
|
||||
- J.-M. Valin, "A New Robust Frequency Domain Echo Canceller With Closed-Loop Learning Rate Adaptation," arXiv:1602.08609, 2016.
|
||||
Mirror: `mirrors/valin-2016-frequency-domain-echo-canceller-learning-rate.pdf`
|
||||
|
||||
- "Double-Talk Robust Acoustic Echo Cancellation," EUSIPCO 2021.
|
||||
Mirror: `mirrors/eusipco-2021-double-talk-robust-aec.pdf`
|
||||
|
||||
- Apple Machine Learning Research, "Double-talk Robust Multichannel Acoustic Echo Cancellation Using Least Squares MIMO Adaptive Filtering," 2020.
|
||||
Mirror: `mirrors/apple-mimo-adaptive-echo-cancellation.html`
|
||||
|
||||
## Online Room / Acoustic Impulse Response Estimation
|
||||
|
||||
- J. Nikunen and T. Virtanen, "Estimation of Time-Varying Room Impulse Responses of Multiple Sound Sources from Observed Mixture and Isolated Source Signals," ICASSP 2018.
|
||||
Mirror: `mirrors/nikunen-virtanen-2018-time-varying-rir.pdf`
|
||||
|
||||
- T. Haubner, A. Brendel, and W. Kellermann, "Online Acoustic System Identification Exploiting Kalman Filtering and an Adaptive Impulse Response Subspace Model," arXiv:2105.03337, 2021.
|
||||
Mirror: `mirrors/haubner-2021-online-acoustic-system-identification.pdf`
|
||||
|
||||
## Notes
|
||||
|
||||
MathWorks AEC and Filtered-X LMS examples were consulted via browser snippets/opened page content, but direct mirroring was blocked by access controls from PowerShell. They are not relied on as mirrored primary artifacts in the summary.
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
|
@ -1,881 +0,0 @@
|
|||
|
||||
|
||||
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="de" class="nexus-font-support">
|
||||
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<meta name="google" content="nositelinkssearchbox"/>
|
||||
<meta name="tdm-reservation" content="0">
|
||||
<title>
|
||||
System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller
|
||||
- Universität zu Lübeck</title>
|
||||
|
||||
|
||||
|
||||
|
||||
<link rel='alternate' hreflang='en-gb' href='https://research.uni-luebeck.de/en/publications/system-identification-for-multi-channel-listening-room-compensati/' /><link rel='alternate' hreflang='de-de' href='https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/' />
|
||||
|
||||
<meta property="og:site_name" content="Universität zu Lübeck">
|
||||
|
||||
|
||||
<meta property="og:title" content="System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller"/>
|
||||
|
||||
|
||||
<meta property="og:url" content="https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/">
|
||||
<meta property="og:locale" content="de_DE">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<meta property="og:image" content="https://research.uni-luebeck.de/skin/headerImage/">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<meta property="og:type" content="article">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<link rel="stylesheet" href="/assets/application-119d61ec31b02051205711822747d1ca.css" />
|
||||
<!-- OneTrust Cookies Consent Notice start -->
|
||||
<script async src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js" type="text/javascript" charset="UTF-8" data-domain-script="d0404472-8daf-4764-aeb6-b4242ae76a56" data-document-language="true"></script>
|
||||
<script type="text/javascript">
|
||||
function OptanonWrapper() { }
|
||||
</script>
|
||||
<!-- OneTrust Cookies Consent Notice end -->
|
||||
|
||||
<link rel="shortcut icon" href="/skin/favIcon/"/>
|
||||
|
||||
<link href="/skin/css/" rel="stylesheet"/>
|
||||
|
||||
<script src="/skin/script/" type="text/javascript"></script>
|
||||
<script type="text/javascript" src="/assets/application-34cc2221eabdb23f03948cb449f4d1ca.js" ></script>
|
||||
<!--[if lt IE 9]>
|
||||
<script type="text/javascript" src="/assets/html5shiv.min-ca5300beead9a4a9d2c9c584a9016410.js" ></script>
|
||||
<script type="text/javascript" src="/assets/respond.min-678d372b349e434d9923e1b591f14a1e.js" ></script>
|
||||
<![endif]-->
|
||||
|
||||
|
||||
|
||||
<meta name="citation_title" content="System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller"></meta><meta name="citation_inbook_title" content="2008 Hands-Free Speech Communication and Microphone Arrays"></meta><meta name="citation_author" content="S. Goetze"></meta><meta name="citation_author" content="M. Kallinger"></meta><meta name="citation_author" content="A. Mertins"></meta><meta name="citation_author_institution" content="Institut für Signalverarbeitung"></meta><meta name="citation_author_email" content="alfred.mertins@uni-luebeck.de"></meta><meta name="citation_author" content="K. Kammeyer"></meta><meta name="citation_publication_date" content="2008/05/01"></meta><meta name="citation_doi" content="10.1109/HSCMA.2008.4538727"></meta><meta name="citation_language" content="Englisch"></meta><meta name="citation_publisher" content="IEEE"></meta><meta name="citation_firstpage" content="224"></meta><meta name="citation_lastpage" content="227"></meta><meta name="citation_conference_title" content="2008 Hands-free Speech Communication and Microphone Arrays"></meta>
|
||||
<script src="/assets/Chart.min-27bff060c3e539ceb22e763c8f2e9e10.js"></script>
|
||||
<script src="/assets/jquery.content-chart-9c09bb79ba3fc3829b6478d0e114f737.js"></script>
|
||||
|
||||
|
||||
|
||||
<!-- Google Analytics: No account ID (G) found -->
|
||||
<!-- SiteCatalyst not enabled -->
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body class="" data-page="publications">
|
||||
|
||||
<div id="aria-polite" aria-live="polite"></div>
|
||||
<div id="aria-assertive" aria-live="assertive"></div>
|
||||
|
||||
<a href="#main-navigation" class="sr-only sr-only-focusable">Zur Hauptnavigation wechseln</a>
|
||||
|
||||
<a href="#main-search" class="sr-only sr-only-focusable">Zur Suche wechseln</a>
|
||||
|
||||
<a href="#main-content" class="sr-only sr-only-focusable">Zum Hauptinhalt wechseln</a>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<header class="header" id="page-header">
|
||||
<div class="primary ">
|
||||
<div class="container">
|
||||
|
||||
<a href="/de/" class="logo">
|
||||
|
||||
<span class="sr-only">Universität zu Lübeck Home</span>
|
||||
<img src="/skin/headerImage/" alt="Universität zu Lübeck Logo"/>
|
||||
|
||||
</a>
|
||||
|
||||
<ul class="header-tools ">
|
||||
|
||||
|
||||
<li class="language-dropdown dropdown">
|
||||
<button data-toggle="dropdown" class="language_btn" aria-label="Sprache auswählen" aria-expanded="false">
|
||||
<i class="icon icon-globe" aria-hidden="true"></i></button>
|
||||
|
||||
<div class="dropdown-container">
|
||||
<ul class='language-selector dropdown-menu'><li><a href="/en/publications/system-identification-for-multi-channel-listening-room-compensati/" lang="en">English</a></li><li class='selected'><a href="/de/publications/system-identification-for-multi-channel-listening-room-compensati/" aria-current="true" lang="de">Deutsch</a></li></ul>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="header-search">
|
||||
|
||||
<form action="/de/searchAll/index/system-identification-for-multi-channel-listening-room-compensati/" method="get"
|
||||
class="search-form" id="search-everything">
|
||||
|
||||
<div class="global-search-wrapper">
|
||||
<div class="global-search mini">
|
||||
<div class="field-button-wrapper">
|
||||
<div class="search-cell search-field">
|
||||
<label for="main-search" class="sr-only">Inhalt suchen unter Universität zu Lübeck</label>
|
||||
<input id="main-search" class="search-field" value="" name="search"
|
||||
placeholder="Suchen …"/>
|
||||
</div>
|
||||
|
||||
<div class="search-submit">
|
||||
<button type="submit" aria-label="Suchen">
|
||||
<i class="icon icon-magnifying-glass" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<script>
|
||||
$(function () {
|
||||
var searchForm = $("#search-everything");
|
||||
var searchField = $(".search-field", searchForm);
|
||||
searchForm.on("submit", function () {
|
||||
var field = searchField.find("input");
|
||||
var searchString = field.val();
|
||||
|
||||
// No enter key submit nothing :-)
|
||||
if (!searchString) return false;
|
||||
|
||||
if (searchString.length >= 200) {
|
||||
searchForm.attr("method", "post");
|
||||
searchForm.attr("action", "/de/concepts/copypaste/");
|
||||
field.attr("name", "text");
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="subMenu">
|
||||
<div class="secondary">
|
||||
<div class="container">
|
||||
<nav id="main-navigation" aria-label="Hauptnavigation" class="content-navigation three-third">
|
||||
<ul data-value="Mehr" role="menubar" aria-label="Hauptnavigation">
|
||||
<li class="" role="none">
|
||||
<a href="/de/" role="menuitem" tabindex="-1">Home</a>
|
||||
</li>
|
||||
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/organisations/"><span>Einrichtungen</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/persons/"><span>Personen</span></a>
|
||||
</li>
|
||||
|
||||
<li class="selected" role="none">
|
||||
<a class="portal_link" tabindex="0" role="menuitem" href="/de/publications/"><span>Publikationen</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/projects/"><span>Projekte</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/prizes/"><span>Preise</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/impacts/"><span>Spin-Offs</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/clippings/"><span>Medien</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/activities/"><span>Aktivitäten</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" tabindex="-1" role="menuitem" href="/de/datasets/"><span>Forschungsdatensätze</span></a>
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</header>
|
||||
|
||||
<main id="page-content">
|
||||
|
||||
<div class="page-section page-section-publications page-section-publications-view ">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<section
|
||||
class="page-section-header page-section-header-publications page-section-header-publications-view
|
||||
no-backdrop-image"
|
||||
data-stickyheader=""
|
||||
style="">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="introduction no-metrics">
|
||||
<div class="rendering"><h1><span>System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller</span></h1></div>
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_associatespersonsclassifiedportal rendering_contributiontobookanthology rendering_associatespersonsclassifiedportal rendering_contributiontobookanthology_associatespersonsclassifiedportal"><p class="relations persons">S. Goetze, M. Kallinger, <a rel="Person" href="https://research.uni-luebeck.de/de/persons/alfred-mertins/" class="link person"><span>A. Mertins</span></a>, K. Kammeyer</div>
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_associatesorganisationsportal rendering_contributiontobookanthology rendering_associatesorganisationsportal rendering_contributiontobookanthology_associatesorganisationsportal"><ul class="relations organisations"><li class="department"><a rel="Organisation" href="https://research.uni-luebeck.de/de/organisations/institute-of-signal-processing/" class="link"><span>Institut für Signalverarbeitung</span></a></li></ul></div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="publication-metrics" role="region" aria-label="Publikationsmetrik">
|
||||
|
||||
<div class="metrics-container">
|
||||
|
||||
<div class="metrics-wrap metrics-top one">
|
||||
|
||||
<div class="metric scopus-citations">
|
||||
|
||||
<a target="_blank" href="https://www.scopus.com/inward/citedby.url?scp=50449102952&partnerID=8YFLogxK" aria-label="Quelle: Scopus: 7">
|
||||
|
||||
<span class="count">7</span>
|
||||
|
||||
<span class="sr-only"> Link öffnet neuen Tab</span> </a>
|
||||
|
||||
<span class="label">Zitate (Scopus)</span>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<div class="metrics-wrap metrics-bottom ">
|
||||
|
||||
<div class="metric metric-plum-x">
|
||||
<a href="https://plu.mx/plum/a/?doi=10.1109/HSCMA.2008.4538727" class="plumx-plum-print-popup" data-on-empty="plumXError" data-on-fail="plumXError" data-on-success="plumXSuccess" data-popup="left" data-hide-when-empty="true" data-site="plum"
|
||||
data-badge="false"></a>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="metric metric-altmetric">
|
||||
|
||||
<div data-badge-popover="top" data-badge-type="donut" data-doi="10.1109/HSCMA.2008.4538727" data-hide-no-mentions="true" data-link-target='_blank'
|
||||
class="altmetric-embed"></div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="subMenu">
|
||||
<div class="content-profile-navigation">
|
||||
<div class="container">
|
||||
<nav role="navigation">
|
||||
<ul role="menubar">
|
||||
<li class="selected" role="none">
|
||||
<a class="portal_link" role="menuitem" href="/de/publications/system-identification-for-multi-channel-listening-room-compensati/"><span>
|
||||
<i class="icon icon-publication" aria-hidden="true"></i>
|
||||
<span class="label">Übersicht </span>
|
||||
</span></a>
|
||||
</li>
|
||||
|
||||
<li class="" role="none">
|
||||
<a class="portal_link" role="menuitem" href="/de/publications/system-identification-for-multi-channel-listening-room-compensati/fingerprints/"><span>
|
||||
<i class="icon icon-fingerprint" aria-hidden="true"></i>
|
||||
<span class="label">Fingerprint</span>
|
||||
</span></a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
<div id="main-content"
|
||||
class="page-section-content page-section-content-publications page-section-content-publications-view ">
|
||||
|
||||
<section class="page-section content-relation-section">
|
||||
<div class="container">
|
||||
<div class="clearfix">
|
||||
<div class="content-content publication-content">
|
||||
|
||||
|
||||
<h2 class="subheader">Abstract</h2>
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_abstractportal rendering_contributiontobookanthology rendering_abstractportal rendering_contributiontobookanthology_abstractportal"><div class="textblock">Modern hands-free telecommunication devices jointly apply several subsystems, e.g. for noise reduction (NR), acoustic echo cancellation (AEC) and listening-room compensation (LRC). In this contribution the combination of an equalizer for listening room compensation and an acoustic echo canceller is analyzed. Inverse filtering of room impulse responses (RIRs) is a challenging task since they are, in general, mixed phase systems having hundreds of zeros inside and outside near the unit circle in the z-domain. Furthermore, a reliable estimate of the RIR which shall be inverted is important. Since RIRs are time-variant due to possible changes of the acoustic environment, they have to be identified adaptively. If an AEC (or any other adaptive method) is used to identify the time variant room impulse responses the estimate's distance to the real RIRs may be too high for a satisfying equalization, especially in periods of initial convergence of the AEC or after RIR changes. Therefore, we propose to estimate the convergence state of the AEC and to incorporate this knowledge into the equalizer design.</div></div>
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_detailsportal rendering_contributiontobookanthology rendering_detailsportal rendering_contributiontobookanthology_detailsportal"><div class="conference"><table class="properties"><tbody><tr class="language"><th scope="row">Originalsprache</th><td>Englisch</td></tr><tr><th scope="row">Titel</th><td>2008 Hands-Free Speech Communication and Microphone Arrays</td></tr><tr><th scope="row">Seitenumfang</th><td>4</td></tr><tr><th scope="row">Herausgeber (Verlag)</th><td><a rel="Publisher" href="#" class="link"><span>IEEE</span></a></td></tr><tr><th scope="row">Erscheinungsdatum</th><td><span class="date">01.05.2008</span></td></tr><tr><th scope="row">Seiten</th><td>224-227</td></tr><tr><th scope="row">Aufsatznummer</th><td>4538727</td></tr><tr class="isbn-print"><th scope="row">ISBN (Print)</th><td>978-1-4244-2337-8</td></tr><tr class="isbn-elektronisch"><th scope="row">ISBN (elektronisch)</th><td>978-1-4244-2338-5</td></tr><tr class="digital_object_identifiers"><th scope="row">DOIs</th><td><ul class="relations digital_object_identifiers"><li><a onclick="window.open(this.href, '_blank','noopener,noreferrer'); return false;" href="https://doi.org/10.1109/HSCMA.2008.4538727" class="link"><span>https://doi.org/10.1109/HSCMA.2008.4538727</span></a> </li></ul></td></tr><tr class="status"><th scope="row">Publikationsstatus</th><td><span class="prefix">Veröffentlicht - </span><span class="date">01.05.2008</span></td></tr><tr class="event"><th scope="row">Veranstaltung</th><td><a rel="Event" href="#" class="link"><span><span class="prefix">2008 Hands-free Speech Communication and Microphone Arrays</span></a> - Trento, Italien<br />Dauer: <span class="date">06.05.2008</span> → <span class="date">08.05.2008</span><br />Konferenznummer: 73345</span></td></tr></tbody></table></div></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="sdgs-content-page">
|
||||
<h2 id="sdg-title" class="subheader">UN SDGs</h2>
|
||||
<p class="sdg-text">Dieser Output leistet einen Beitrag zu folgendem(n) Ziel(en) für nachhaltige Entwicklung</p>
|
||||
<ol class="sdg_icons" aria-labelledby="sdg-title">
|
||||
|
||||
<li class="content-page">
|
||||
|
||||
<img alt="SDG 9 – Industrie, Innovation und Infrastruktur" title="SDG 9 – Industrie, Innovation und Infrastruktur" class="industry_innovation_and_infrastructure"
|
||||
src="/assets/sdg_icons/industry_innovation_and_infrastructure-38d336019fd4b8ef110b4e64f4c8d344.svg"
|
||||
role="presentation"/>
|
||||
<div class="sdg-name">
|
||||
<span>SDG 9 – Industrie, Innovation und Infrastruktur</span>
|
||||
<span></span>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<div class="content-sidebar publication-sidebar">
|
||||
|
||||
<h2 class="subheader">Dokumente</h2>
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_publicationaccessrenderer rendering_contributiontobookanthology rendering_publicationaccessrenderer rendering_contributiontobookanthology_publicationaccessrenderer"><ul class="dois"><li><div class="doi"><a onclick="window.open(this.href, '_blank','noopener,noreferrer'); return false;" href="https://doi.org/10.1109/HSCMA.2008.4538727" class="link"><span>10.1109/HSCMA.2008.4538727</span></a></div></li></ul></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<h2 class="subheader">Weitere Links</h2>
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_publicationotherfilesandlinksrenderer rendering_contributiontobookanthology rendering_publicationotherfilesandlinksrenderer rendering_contributiontobookanthology_publicationotherfilesandlinksrenderer"><ul class="links"><li><div class="link"><a onclick="window.open(this.href, '_blank','noopener,noreferrer'); return false;" href="https://www.scopus.com/pages/publications/50449102952" class="link"><span>https://www.scopus.com/pages/publications/50449102952</span></a></div></li></ul></div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page-section content-relation-section publication-fingerprint">
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h2 class="section-title">
|
||||
<i class="icon icon-fingerprint" aria-hidden="true"></i>
|
||||
<span class="title">Fingerprint</span>
|
||||
</h2>
|
||||
<span class="sub-title">
|
||||
Untersuchen Sie die Forschungsthemen von „System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller“. Zusammen bilden sie einen einzigartigen Fingerprint.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<ul class="publication-top-concepts" role="menubar" aria-label="Fingerprints">
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="4eafe263-ae6b-42d5-b0ce-d6da7277e755"
|
||||
data-concept-uuid="4eafe263-ae6b-42d5-b0ce-d6da7277e755"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="1.0"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="100%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Multichannel</span>
|
||||
<span class="thesauri">Engineering</span>
|
||||
<span class="value sr-only">100%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="86470407-3128-4455-8684-e3e947f97f7f"
|
||||
data-concept-uuid="86470407-3128-4455-8684-e3e947f97f7f"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="1.0"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="100%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Impulse Response</span>
|
||||
<span class="thesauri">Engineering</span>
|
||||
<span class="value sr-only">100%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="4741b98b-483a-4788-88a9-4952bd6bb3cd"
|
||||
data-concept-uuid="4741b98b-483a-4788-88a9-4952bd6bb3cd"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="1.0"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="100%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Listening Room</span>
|
||||
<span class="thesauri">Engineering</span>
|
||||
<span class="value sr-only">100%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="ae39eb57-add6-4a50-9674-b1de7b887840"
|
||||
data-concept-uuid="ae39eb57-add6-4a50-9674-b1de7b887840"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="1.0"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="100%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Noise Reduction</span>
|
||||
<span class="thesauri">Earth and Planetary Sciences</span>
|
||||
<span class="value sr-only">100%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="31592306-d0d0-4620-8ba6-638c18aeb985"
|
||||
data-concept-uuid="31592306-d0d0-4620-8ba6-638c18aeb985"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="0.3333333"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="33%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Equalizer</span>
|
||||
<span class="thesauri">Engineering</span>
|
||||
<span class="value sr-only">33%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="a773d085-8c98-44f2-b25a-bb2a9ed59a30"
|
||||
data-concept-uuid="a773d085-8c98-44f2-b25a-bb2a9ed59a30"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="0.1666667"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="16%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Filtration</span>
|
||||
<span class="thesauri">Engineering</span>
|
||||
<span class="value sr-only">16%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="concept-badge-large-container dropdown-overflow" role="none">
|
||||
|
||||
<button tabindex="0"
|
||||
class="concept-badge-large dropdown-toggle"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-controls="d14b1a5b-d90e-4f0a-bc73-bb45c75b9f3b"
|
||||
data-concept-uuid="d14b1a5b-d90e-4f0a-bc73-bb45c75b9f3b"
|
||||
data-rank-size="32"
|
||||
data-rank-thickness="8"
|
||||
data-rank-value="0.1666667"
|
||||
data-summary="true"
|
||||
data-summary-url="/de/concepts/summary/">
|
||||
<span class="concept-wrapper" title="16%">
|
||||
<span class="rank"></span>
|
||||
<span class="concept">Adaptive Method</span>
|
||||
<span class="thesauri">Engineering</span>
|
||||
<span class="value sr-only">16%</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div class="dropdown-container"></div>
|
||||
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
<div class="footer">
|
||||
<div class="view-all align-center">
|
||||
<a class="portal_link btn-primary btn-large btn-content-link" href="/de/publications/system-identification-for-multi-channel-listening-room-compensati/fingerprints/"><span>
|
||||
Vollständigen Fingerprint anzeigen
|
||||
<i class="icon icon-right-open-mini" aria-hidden="true"></i>
|
||||
</span></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<section class="page-section cite">
|
||||
<div class="container">
|
||||
<section class="publication-cite" aria-labelledby="publications-cite-title">
|
||||
<h2 class="subheader" id="publications-cite-title">Zitieren</h2>
|
||||
<ul class="tabs" role="tablist" aria-label="Zitieren">
|
||||
|
||||
<li class="selected" role="tab" id="tab-0" aria-controls="cite-apa" tabindex="-1" aria-selected="false" >
|
||||
APA
|
||||
</li>
|
||||
|
||||
<li class="" role="tab" id="tab-1" aria-controls="cite-author" tabindex="-1" aria-selected="false" >
|
||||
Author
|
||||
</li>
|
||||
|
||||
<li class="" role="tab" id="tab-2" aria-controls="cite-BIBTEX" tabindex="-1" aria-selected="false" >
|
||||
BIBTEX
|
||||
</li>
|
||||
|
||||
<li class="" role="tab" id="tab-3" aria-controls="cite-harvard" tabindex="-1" aria-selected="false" >
|
||||
Harvard
|
||||
</li>
|
||||
|
||||
<li class="" role="tab" id="tab-4" aria-controls="cite-standard" tabindex="-1" aria-selected="false" >
|
||||
Standard
|
||||
</li>
|
||||
|
||||
<li class="" role="tab" id="tab-5" aria-controls="cite-RIS" tabindex="-1" aria-selected="false" >
|
||||
RIS
|
||||
</li>
|
||||
|
||||
<li class="" role="tab" id="tab-6" aria-controls="cite-vancouver" tabindex="-1" aria-selected="false" >
|
||||
Vancouver
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
<div class="tab-container">
|
||||
|
||||
<div id="cite-apa" class="tab selected" role="tabpanel" aria-labelledby="tab-0" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_apa rendering_contributiontobookanthology rendering_apa rendering_contributiontobookanthology_apa">Goetze, S., Kallinger, M.<a rel="Person" href="https://research.uni-luebeck.de/de/persons/alfred-mertins/" class="link"><span>, Mertins, A.</span></a>, & Kammeyer, K. (2008). <a rel="ContributionToBookAnthology" href="https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/" class="link"><span>System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller</span></a>. in <em>2008 Hands-Free Speech Communication and Microphone Arrays </em>(S. 224-227). Artikel 4538727 (Hands-free Speech Communication and Microphone Arrays, Proceedings). IEEE. <a onclick="window.open(this.href, '_blank','noopener,noreferrer'); return false;" href="https://doi.org/10.1109/HSCMA.2008.4538727" class="link"><span>https://doi.org/10.1109/HSCMA.2008.4538727</span></a></div>
|
||||
</div>
|
||||
|
||||
<div id="cite-author" class="tab " role="tabpanel" aria-labelledby="tab-1" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_author rendering_contributiontobookanthology rendering_author rendering_contributiontobookanthology_author">Goetze, S. ; Kallinger, M. <a rel="Person" href="https://research.uni-luebeck.de/de/persons/alfred-mertins/" class="link"><span> ; Mertins, A.</span></a> et al. / <a rel="ContributionToBookAnthology" href="https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/" class="link"><span><strong>System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller</strong></span></a>. 2008 Hands-Free Speech Communication and Microphone Arrays. IEEE, 2008. S. 224-227 (Hands-free Speech Communication and Microphone Arrays, Proceedings).</div>
|
||||
</div>
|
||||
|
||||
<div id="cite-BIBTEX" class="tab " role="tabpanel" aria-labelledby="tab-2" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_bibtex rendering_contributiontobookanthology rendering_bibtex rendering_contributiontobookanthology_bibtex"><div>@inproceedings{0c5486f2317d4415922969e27b2a9485,</div><div> title = "System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller",</div><div> abstract = "Modern hands-free telecommunication devices jointly apply several subsystems, e.g. for noise reduction (NR), acoustic echo cancellation (AEC) and listening-room compensation (LRC). In this contribution the combination of an equalizer for listening room compensation and an acoustic echo canceller is analyzed. Inverse filtering of room impulse responses (RIRs) is a challenging task since they are, in general, mixed phase systems having hundreds of zeros inside and outside near the unit circle in the z-domain. Furthermore, a reliable estimate of the RIR which shall be inverted is important. Since RIRs are time-variant due to possible changes of the acoustic environment, they have to be identified adaptively. If an AEC (or any other adaptive method) is used to identify the time variant room impulse responses the estimate's distance to the real RIRs may be too high for a satisfying equalization, especially in periods of initial convergence of the AEC or after RIR changes. Therefore, we propose to estimate the convergence state of the AEC and to incorporate this knowledge into the equalizer design.",</div><div> author = "S. Goetze and M. Kallinger and A. Mertins and K. Kammeyer",</div><div> year = "2008",</div><div> month = may,</div><div> day = "1",</div><div> doi = "10.1109/HSCMA.2008.4538727",</div><div> language = "English",</div><div> isbn = "978-1-4244-2337-8",</div><div> series = "Hands-free Speech Communication and Microphone Arrays, Proceedings",</div><div> publisher = "IEEE",</div><div> pages = "224--227",</div><div> booktitle = "2008 Hands-Free Speech Communication and Microphone Arrays",</div><div> note = "2008 Hands-free Speech Communication and Microphone Arrays, HSCMA 2008 ; Conference date: 06-05-2008 Through 08-05-2008",</div><p>}</p></div>
|
||||
</div>
|
||||
|
||||
<div id="cite-harvard" class="tab " role="tabpanel" aria-labelledby="tab-3" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_harvard rendering_contributiontobookanthology rendering_harvard rendering_contributiontobookanthology_harvard">Goetze, S, Kallinger, M<a rel="Person" href="https://research.uni-luebeck.de/de/persons/alfred-mertins/" class="link"><span>, Mertins, A</span></a> & Kammeyer, K 2008, <a rel="ContributionToBookAnthology" href="https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/" class="link harvard_title"><span>System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller</span></a>. in <em>2008 Hands-Free Speech Communication and Microphone Arrays.</em>, 4538727, Hands-free Speech Communication and Microphone Arrays, Proceedings, IEEE, S. 224-227, 2008 Hands-free Speech Communication and Microphone Arrays, Trento, Italien, <span class="date">06.05.08</span>. <a onclick="window.open(this.href, '_blank','noopener,noreferrer'); return false;" href="https://doi.org/10.1109/HSCMA.2008.4538727" class="link"><span>https://doi.org/10.1109/HSCMA.2008.4538727</span></a></div>
|
||||
</div>
|
||||
|
||||
<div id="cite-standard" class="tab " role="tabpanel" aria-labelledby="tab-4" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_standard rendering_contributiontobookanthology rendering_standard rendering_contributiontobookanthology_standard"><a rel="ContributionToBookAnthology" href="https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/" class="link"><span><strong>System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller.</strong></span></a> / Goetze, S.; Kallinger, M.<a rel="Person" href="https://research.uni-luebeck.de/de/persons/alfred-mertins/" class="link"><span>; Mertins, A.</span></a> et al. <br />2008 Hands-Free Speech Communication and Microphone Arrays. IEEE, 2008. S. 224-227 4538727 (Hands-free Speech Communication and Microphone Arrays, Proceedings).<p class="type"><span class="type_family">Publikation<span class="type_family_sep">: </span></span><span class="type_classification_parent">Kapitel in Büchern/Berichten/Konferenzbänden<span class="type_parent_sep"> › </span></span><span class="type_classification">Konferenzbeitrag</span><span class="type_classification"><span class="type_parent_sep"> › </span>Begutachtung</span></p></div>
|
||||
</div>
|
||||
|
||||
<div id="cite-RIS" class="tab " role="tabpanel" aria-labelledby="tab-5" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_ris rendering_contributiontobookanthology rendering_ris rendering_contributiontobookanthology_ris"><p>TY - GEN</p><p>T1 - System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller</p><p>AU - Goetze, S.</p><p>AU - Kallinger, M.</p><p>AU - Mertins, A.</p><p>AU - Kammeyer, K.</p><p>N1 - Conference code: 73345</p><p>PY - 2008/5/1</p><p>Y1 - 2008/5/1</p><p>N2 - Modern hands-free telecommunication devices jointly apply several subsystems, e.g. for noise reduction (NR), acoustic echo cancellation (AEC) and listening-room compensation (LRC). In this contribution the combination of an equalizer for listening room compensation and an acoustic echo canceller is analyzed. Inverse filtering of room impulse responses (RIRs) is a challenging task since they are, in general, mixed phase systems having hundreds of zeros inside and outside near the unit circle in the z-domain. Furthermore, a reliable estimate of the RIR which shall be inverted is important. Since RIRs are time-variant due to possible changes of the acoustic environment, they have to be identified adaptively. If an AEC (or any other adaptive method) is used to identify the time variant room impulse responses the estimate's distance to the real RIRs may be too high for a satisfying equalization, especially in periods of initial convergence of the AEC or after RIR changes. Therefore, we propose to estimate the convergence state of the AEC and to incorporate this knowledge into the equalizer design.</p><p>AB - Modern hands-free telecommunication devices jointly apply several subsystems, e.g. for noise reduction (NR), acoustic echo cancellation (AEC) and listening-room compensation (LRC). In this contribution the combination of an equalizer for listening room compensation and an acoustic echo canceller is analyzed. Inverse filtering of room impulse responses (RIRs) is a challenging task since they are, in general, mixed phase systems having hundreds of zeros inside and outside near the unit circle in the z-domain. Furthermore, a reliable estimate of the RIR which shall be inverted is important. Since RIRs are time-variant due to possible changes of the acoustic environment, they have to be identified adaptively. If an AEC (or any other adaptive method) is used to identify the time variant room impulse responses the estimate's distance to the real RIRs may be too high for a satisfying equalization, especially in periods of initial convergence of the AEC or after RIR changes. Therefore, we propose to estimate the convergence state of the AEC and to incorporate this knowledge into the equalizer design.</p><p>UR - https://www.scopus.com/pages/publications/50449102952</p><p>U2 - 10.1109/HSCMA.2008.4538727</p><p>DO - 10.1109/HSCMA.2008.4538727</p><p>M3 - Conference contribution</p><p>SN - 978-1-4244-2337-8</p><p>T3 - Hands-free Speech Communication and Microphone Arrays, Proceedings</p><p>SP - 224</p><p>EP - 227</p><p>BT - 2008 Hands-Free Speech Communication and Microphone Arrays</p><p>PB - IEEE</p><p>T2 - 2008 Hands-free Speech Communication and Microphone Arrays</p><p>Y2 - 6 May 2008 through 8 May 2008</p><p>ER - </p></div>
|
||||
</div>
|
||||
|
||||
<div id="cite-vancouver" class="tab " role="tabpanel" aria-labelledby="tab-6" tabindex="-1" aria-hidden="true">
|
||||
<div class="rendering rendering_researchoutput rendering_researchoutput_vancouver rendering_contributiontobookanthology rendering_vancouver rendering_contributiontobookanthology_vancouver">Goetze S, Kallinger M<a rel="Person" href="https://research.uni-luebeck.de/de/persons/alfred-mertins/" class="link"><span>, Mertins A</span></a>, Kammeyer K. <span class="title"><a rel="ContributionToBookAnthology" href="https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/" class="link"><span>System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller</span></a></span>. in 2008 Hands-Free Speech Communication and Microphone Arrays. IEEE. 2008. S. 224-227. 4538727. (Hands-free Speech Communication and Microphone Arrays, Proceedings). doi: 10.1109/HSCMA.2008.4538727</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script>
|
||||
$(function() {
|
||||
$(".tab-container .rendering a:not([href^='http://dx.doi.org'])").contents().unwrap();
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
<script>
|
||||
$(function () {
|
||||
if($('.publication-sidebar').length > 0){
|
||||
if($('a.document-link').length === 0){
|
||||
$(".metrics-top").addClass("one");
|
||||
$('div.metrics-downloads').remove();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function plumXError(e) {
|
||||
$(e).closest('.metric-plum-x').closest('.metrics-bottom').addClass('one');
|
||||
$(e).closest('.metric-plum-x').remove();
|
||||
}
|
||||
$('div.altmetric-embed').on('altmetric:hide', function () {
|
||||
$(this).closest('.metric-altmetric').closest('.metrics-bottom').addClass('one');
|
||||
$(this).closest('.metric-altmetric').remove();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="share-box">
|
||||
<ul>
|
||||
<li class="icon-share"></li>
|
||||
<li><a aria-label="Auf Facebook teilen"
|
||||
href="https://www.facebook.com/sharer.php?u=https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/%3Futm_source%3Dfacebook%26utm_medium%3Dsocial%26utm_campaign%3Dsharelink%26doi%3D10.1109%2FHSCMA.2008.4538727&p[summary]=Schauen+Sie+sich+diese+Publikationen+an+unter+Universit%C3%A4t+zu+L%C3%BCbeck%3A+System+Identification+for+Multi-Channel+Listening-Room+Compensation+Using+an+Acoustic+Echo+Canceller"
|
||||
class="icon-facebook"
|
||||
onclick="window.location.origin('https://www.facebook.com/sharer.php?u=https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/%3Futm_source%3Dfacebook%26utm_medium%3Dsocial%26utm_campaign%3Dsharelink%26doi%3D10.1109%2FHSCMA.2008.4538727&p[summary]=Schauen+Sie+sich+diese+Publikationen+an+unter+Universit%C3%A4t+zu+L%C3%BCbeck%3A+System+Identification+for+Multi-Channel+Listening-Room+Compensation+Using+an+Acoustic+Echo+Canceller', 'Facebook', 'width=600,height=600,scrollbars=no,resizable=no');
|
||||
return false;" target="popup"></a></li>
|
||||
<li><a aria-label="Auf Twitter teilen"
|
||||
href="https://twitter.com/intent/tweet?url=https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/%3Futm_source%3Dtwitter%26utm_medium%3Dsocial%26utm_campaign%3Dsharelink%26doi%3D10.1109%2FHSCMA.2008.4538727&text=Schauen+Sie+sich+diese+Publikationen+an+unter+Universit%C3%A4t+zu+L%C3%BCbeck%3A+System+Identification+for+Multi-Channel+Listening-Room+Compensation+Using+an+Acoustic+Echo+Canceller"
|
||||
onclick="window.location.origin('https://twitter.com/intent/tweet?url=https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/%3Futm_source%3Dtwitter%26utm_medium%3Dsocial%26utm_campaign%3Dsharelink%26doi%3D10.1109%2FHSCMA.2008.4538727&text=Schauen+Sie+sich+diese+Publikationen+an+unter+Universit%C3%A4t+zu+L%C3%BCbeck%3A+System+Identification+for+Multi-Channel+Listening-Room+Compensation+Using+an+Acoustic+Echo+Canceller doi%3A10.1109%2FHSCMA.2008.4538727', 'Twitter', 'width=600,height=600,scrollbars=no,resizable=no');
|
||||
return false;" class="twitter" target="popup"><svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 300 271">
|
||||
|
||||
<path d="m236 0h46l-101 115 118 156h-92.6l-72.5-94.8-83 94.8h-46l107-123-113-148h94.9l65.5 86.6zm-16.1 244h25.5l-165-218h-27.4z"></path>
|
||||
</svg></a></li>
|
||||
<li><a aria-label="Auf LinkedIn teilen"
|
||||
href="https://www.linkedin.com/shareArticle?mini=true&url=https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/%3Futm_source%3Dlinkedin%26utm_medium%3Dsocial%26utm_campaign%3Dsharelink%26doi%3D10.1109%2FHSCMA.2008.4538727&summary=Schauen+Sie+sich+diese+Publikationen+an+unter+Universit%C3%A4t+zu+L%C3%BCbeck%3A+System+Identification+for+Multi-Channel+Listening-Room+Compensation+Using+an+Acoustic+Echo+Canceller"
|
||||
onclick="window.location.origin('https://www.linkedin.com/shareArticle?mini=true&url=https://research.uni-luebeck.de/de/publications/system-identification-for-multi-channel-listening-room-compensati/%3Futm_source%3Dlinkedin%26utm_medium%3Dsocial%26utm_campaign%3Dsharelink%26doi%3D10.1109%2FHSCMA.2008.4538727&summary=Schauen+Sie+sich+diese+Publikationen+an+unter+Universit%C3%A4t+zu+L%C3%BCbeck%3A+System+Identification+for+Multi-Channel+Listening-Room+Compensation+Using+an+Acoustic+Echo+Canceller doi%3A10.1109%2FHSCMA.2008.4538727', 'LinkedIn', 'width=600,height=600,scrollbars=no,resizable=no');
|
||||
return false;" class="icon-linkedin" target="popup"></a></li>
|
||||
<li><a aria-label="Per E-Mail teilen" href="/cdn-cgi/l/email-protection#bb84c8ced9d1ded8cf86e8c2c8cfded69e898bf2dfded5cfd2ddd2d8dacfd2d4d59e898bddd4c99e898bf6ced7cfd296f8d3dad5d5ded79e898bf7d2c8cfded5d2d5dc96e9d4d4d69e898bf8d4d6cbded5c8dacfd2d4d59e898beec8d2d5dc9e898bdad59e898bfad8d4cec8cfd2d89e898bfed8d3d49e898bf8dad5d8ded7d7dec99dd9d4dfc286e8d8d3daceded59e898be8d2de9e898bc8d2d8d39e898bdfd2dec8de9e898bebced9d7d2d0dacfd2d4d5ded59e898bdad59e898bced5cfdec99e898beed5d2cddec9c8d2cf9ef8889efa8fcf9e898bc1ce9e898bf79ef8889ef9f8d9ded8d09e88fa9e898be8c2c8cfded69e898bf2dfded5cfd2ddd2d8dacfd2d4d59e898bddd4c99e898bf6ced7cfd296f8d3dad5d5ded79e898bf7d2c8cfded5d2d5dc96e9d4d4d69e898bf8d4d6cbded5c8dacfd2d4d59e898beec8d2d5dc9e898bdad59e898bfad8d4cec8cfd2d89e898bfed8d3d49e898bf8dad5d8ded7d7dec99bc79bd3cfcfcbc8819494c9dec8dedac9d8d395ced5d296d7ceded9ded8d095dfde94dfde94cbced9d7d2d8dacfd2d4d5c894c8c2c8cfded696d2dfded5cfd2ddd2d8dacfd2d4d596ddd4c996d6ced7cfd296d8d3dad5d5ded796d7d2c8cfded5d2d5dc96c9d4d4d696d8d4d6cbded5c8dacfd29484cecfd6e4c8d4cec9d8de86ded6dad2d79ddad6cb80cecfd6e4d6dedfd2ced686ded6dad2d79ddad6cb80cecfd6e4d8dad6cbdad2dcd586c8d3dac9ded7d2d5d0" class="icon-email"></a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="new-modal-overlay"></div>
|
||||
|
||||
</main>
|
||||
|
||||
<footer id="page-footer" class="main-footer">
|
||||
<div class="container">
|
||||
<div class="footer-wrapper">
|
||||
<div class="content-navigation three-third">
|
||||
<div dir="ltr" class="footer-columns">
|
||||
|
||||
<div class="footer-column">
|
||||
<p>
|
||||
Angetrieben von <a href="http://www.elsevier.com/online-tools/research-intelligence/products-and-services/pure">Pure</a>, <a href="http://www.scopus.com/">Scopus</a> & <a href="https://www.elsevier.com/products/elsevier-fingerprint-engine">Elsevier Fingerprint Engine™</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Alle Inhalte auf dieser Website: Copyright © 2026 Universität zu Lübeck, zugehörige Lizenzgebende und Mitwirkende. Alle Rechte vorbehalten, einschließlich der Rechte für Text- und Data-Mining, KI-Training und ähnliche Technologien. Für alle Open Access-Inhalte gelten die entsprechenden Lizenzbedingungen.
|
||||
</p>
|
||||
|
||||
<p>Wir verwenden Cookies, um unseren Service bereitzustellen und zu verbessern und um Inhalte anzupassen. Wenn Sie fortfahren, stimmen Sie der <a href="/de/about/cookies/">Verwendung von Cookies</a> zu.</p>
|
||||
<p><button id="ot-sdk-btn" class="ot-sdk-show-settings"></button></p>
|
||||
|
||||
<p></p>
|
||||
</div>
|
||||
|
||||
<div class="footer-column">
|
||||
|
||||
|
||||
|
||||
<p><a href="/de/web-accessibility/" rel="nofollow" target="_blank">Über die Web-Zugänglichkeit <span class="sr-only"> Link öffnet neuen Tab</span></a></p>
|
||||
|
||||
|
||||
<p>
|
||||
|
||||
</p>
|
||||
|
||||
<p>
|
||||
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a href="https://elsevier.responsibledisclosure.com/hc/en-us/requests/new" target="_blank" rel="nofollow">Sicherheitslücke melden <span class="sr-only"> Link öffnet neuen Tab</span></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="back-to-top">
|
||||
<a href="#" class="back-to-top" aria-label="Zum Anfang"><i class="icon icon-up-open"></i></a>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
|
||||
<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script src="//d1bxh8uas1mnw7.cloudfront.net/assets/embed.js"></script>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Binary file not shown.
|
|
@ -1,88 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; img-src 'self' data:; media-src 'self' data:; object-src 'none'; style-src 'self' 'sha256-o4vzfmmUENEg4chMjjRP9EuW9ucGnGIGVdbl8d0SHQQ='; script-src 'self' 'sha256-a9bHdQGvRzDwDVzx8m+Rzw+0FHZad8L0zjtBwkxOIz4=';"
|
||||
/>
|
||||
<link
|
||||
href="/_fs-ch-1T1wmsGaOgGaSxcX/assets/inter-var.woff2"
|
||||
rel="preload"
|
||||
as="font"
|
||||
type="font/woff2"
|
||||
crossorigin
|
||||
/>
|
||||
<link href="/_fs-ch-1T1wmsGaOgGaSxcX/assets/styles.css" rel="stylesheet" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Client Challenge</title>
|
||||
<style>
|
||||
#loading-error {
|
||||
font-size: 16px;
|
||||
font-family: 'Inter', sans-serif;
|
||||
margin-top: 10px;
|
||||
margin-left: 10px;
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
<div class="noscript-container">
|
||||
<div class="noscript-content">
|
||||
<img
|
||||
src="/_fs-ch-1T1wmsGaOgGaSxcX/assets/errorIcon.svg"
|
||||
alt=""
|
||||
role="presentation"
|
||||
class="error-icon"
|
||||
/>
|
||||
<span class="noscript-span"
|
||||
>JavaScript is disabled in your browser.</span
|
||||
>
|
||||
<p>Please enable JavaScript to proceed.</p>
|
||||
</div>
|
||||
</div>
|
||||
</noscript>
|
||||
<div id="loading-error" role="alert" aria-live="polite">
|
||||
A required part of this site couldn’t load. This may be due to a browser
|
||||
extension, network issues, or browser settings. Please check your
|
||||
connection, disable any ad blockers, or try using a different browser.
|
||||
</div>
|
||||
<script>
|
||||
function loadScript(src) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.onload = resolve;
|
||||
script.onerror = (event) => {
|
||||
console.error('Script load error event:', event);
|
||||
document.getElementById('loading-error').style.display = 'block';
|
||||
reject(
|
||||
new Error(
|
||||
`Failed to load script: ${src}, Please contact the service administrator.`
|
||||
)
|
||||
);
|
||||
};
|
||||
script.src = src;
|
||||
document.body.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
loadScript('/_fs-ch-1T1wmsGaOgGaSxcX/errors.js')
|
||||
.then(() => {
|
||||
const script = document.createElement('script');
|
||||
script.src = '/_fs-ch-1T1wmsGaOgGaSxcX/script.js?reload=true';
|
||||
script.onerror = (event) => {
|
||||
console.error('Script load error event:', event);
|
||||
const errorMsg = new Error(
|
||||
`Failed to load script: ${script.src}. Please contact the service administrator.`
|
||||
);
|
||||
console.error(errorMsg);
|
||||
handleScriptError();
|
||||
};
|
||||
document.body.appendChild(script);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,96 +0,0 @@
|
|||
# Feedback As Continuous Calibration
|
||||
|
||||
## Objective
|
||||
|
||||
Treat speaker-to-microphone feedback as a useful measurement stream, not merely noise to suppress, so the system can continuously learn the playback-room-microphone transfer paths while running.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
The playback calibration note treats speaker measurements as an explicit calibration pass. The live adaptive sync note warns that speaker bleed can corrupt mic sync/localization. Both are true, but incomplete: because the emitted speaker signal is known, the bleed is also an online system-identification signal.
|
||||
|
||||
## Main Finding
|
||||
|
||||
This is the territory of acoustic echo cancellation, adaptive feedback cancellation, and online acoustic system identification. The useful model is:
|
||||
|
||||
```text
|
||||
mic_signal = live_sources + speaker_output convolved with room/speaker/mic paths + noise
|
||||
```
|
||||
|
||||
If the system knows `speaker_output`, an adaptive filter can estimate the transfer path from each speaker output channel to each microphone. Goetze et al. explicitly connect acoustic echo cancellation to listening-room compensation and note that room impulse responses are time-varying and must be identified adaptively, while also warning that equalizer design should account for the echo canceller's convergence state [Goetze 2008]. That warning matters: a half-converged estimator is not truth; it is a drunk ruler.
|
||||
|
||||
Nikunen and Virtanen describe online estimation of time-varying room impulse responses when isolated source signals are available, including playback material output through loudspeakers in a live performance recorded for 3D spatial audio [Nikunen/Virtanen 2018]. That is nearly our shape: known synth/playback streams, observed far-field mic mixtures, and spatial reconstruction.
|
||||
|
||||
Haubner et al. frame online acoustic impulse response estimation as a Kalman/system-identification problem and target faster convergence under correlated excitation and interfering noise [Haubner 2021]. Multichannel AEC work, including Apple ML's MIMO least-squares framing, addresses the harder version where multiple speakers and multiple microphones are coupled and "double-talk" or near-end sound is present [Apple 2020].
|
||||
|
||||
## Required Ownership
|
||||
|
||||
Feedback mining should be its own subsystem:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Known speaker/render output"] --> B["Echo path estimator"]
|
||||
C["Microphone returns"] --> B
|
||||
B --> D["Speaker->mic transfer matrix H_sm"]
|
||||
D --> E["Echo prediction"]
|
||||
C --> F["Live source estimator"]
|
||||
E --> F
|
||||
D --> G["Playback calibration updates"]
|
||||
D --> H["Sync/localization confidence gates"]
|
||||
F --> I["Aligned capture/spatial scene"]
|
||||
```
|
||||
|
||||
It should not be hidden inside the drift loop or the ambisonic encoder. The transfer matrix `H_sm` owns "what our speakers currently sound like at our microphones." The clock loop owns sampling-rate mismatch. The localization loop owns external source position. The decoder owns speaker rendering. Four authorities. No soup.
|
||||
|
||||
## Design Implications
|
||||
|
||||
- Continuous feedback is a calibration signal when the outgoing audio is known and time-aligned.
|
||||
- It is also an interference signal for voice capture, so the system should predict and optionally subtract or downweight it.
|
||||
- Adaptation must be gated during strong unknown near-field speech, heavy clipping, nonlinear speaker behavior, or low coherence.
|
||||
- Each speaker-to-mic path is a filter, not just one delay. Early taps are useful for direct-path timing and geometry; later taps describe room reflections.
|
||||
- In multichannel playback, the estimator is MIMO: every speaker can leak into every mic.
|
||||
- The estimator should publish confidence, convergence, residual error, and last-change time. Do not let downstream systems treat a stale or diverging filter as a fact.
|
||||
|
||||
## Candidate V1
|
||||
|
||||
1. Start offline/controlled:
|
||||
- play one speaker at a time with chirp/noise
|
||||
- estimate fixed speaker-to-reference-mic impulse responses
|
||||
- store speaker delay, gain, polarity, and early reflection sketch
|
||||
|
||||
2. Add online passive tracking:
|
||||
- feed known speaker output and mic input into an adaptive filter
|
||||
- start with two paths: left speaker -> reference mic, right speaker -> reference mic
|
||||
- estimate residual echo and convergence
|
||||
|
||||
3. Add live gating:
|
||||
- freeze or slow adaptation during strong unknown speech
|
||||
- adapt faster during known probe/noise windows or synth-only output
|
||||
- reject updates when residual/error spikes indicate nonlinearity or movement
|
||||
|
||||
4. Scale to MIMO:
|
||||
- speaker channels x microphone channels
|
||||
- use the resulting transfer matrix to improve playback correction, echo prediction, and confidence in mic localization
|
||||
|
||||
## How It Helps AquaSynth
|
||||
|
||||
- The system can tell whether a synth voice rendered to "front left" actually arrives front-left-ish at the mic array.
|
||||
- Speaker leakage can be subtracted or modeled before estimating external voice position.
|
||||
- The room response can update slowly as people move, doors open, or speaker volume changes.
|
||||
- Calibration pings become optional accelerators rather than the only source of truth.
|
||||
|
||||
## Risks
|
||||
|
||||
- Adaptive echo filters can diverge under double-talk unless gated or made robust.
|
||||
- Loudspeakers are nonlinear at high levels; a linear impulse response will not explain distortion.
|
||||
- Correlated stereo/ambisonic speaker feeds make MIMO echo identification harder because the system has trouble deciding which speaker caused which mic energy.
|
||||
- If we use the estimator to aggressively cancel feedback, we may remove useful spatial ambience. The goal is not sterile cancellation; it is intelligible ownership of the signal.
|
||||
|
||||
## Citations
|
||||
|
||||
- [Goetze 2008] S. Goetze, M. Kallinger, A. Mertins, and K. Kammeyer, "System Identification for Multi-Channel Listening-Room Compensation Using an Acoustic Echo Canceller." Mirror: `mirrors/goetze-2008-aec-listening-room-compensation.html`.
|
||||
- [Lindstrom 2007] F. Lindstrom, C. Schueldt, and I. Claesson, "Efficient Multichannel NLMS Implementation for Acoustic Echo Cancellation." Mirror: `mirrors/lindstrom-2007-efficient-multichannel-nlms.html`.
|
||||
- [Valin 2016] J.-M. Valin, "A New Robust Frequency Domain Echo Canceller With Closed-Loop Learning Rate Adaptation." Mirror: `mirrors/valin-2016-frequency-domain-echo-canceller-learning-rate.pdf`.
|
||||
- [EUSIPCO 2021] "Double-Talk Robust Acoustic Echo Cancellation." Mirror: `mirrors/eusipco-2021-double-talk-robust-aec.pdf`.
|
||||
- [Apple 2020] Apple Machine Learning Research, "Double-talk Robust Multichannel Acoustic Echo Cancellation Using Least Squares MIMO Adaptive Filtering." Mirror: `mirrors/apple-mimo-adaptive-echo-cancellation.html`.
|
||||
- [Nikunen/Virtanen 2018] J. Nikunen and T. Virtanen, "Estimation of Time-Varying Room Impulse Responses of Multiple Sound Sources from Observed Mixture and Isolated Source Signals." Mirror: `mirrors/nikunen-virtanen-2018-time-varying-rir.pdf`.
|
||||
- [Haubner 2021] T. Haubner, A. Brendel, and W. Kellermann, "Online Acoustic System Identification Exploiting Kalman Filtering and an Adaptive Impulse Response Subspace Model." Mirror: `mirrors/haubner-2021-online-acoustic-system-identification.pdf`.
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
# Bibliography: GPU Fusion And Live Splat Rendering
|
||||
|
||||
Mirrored copies live under `research/gpu-fusion-splatting/mirrors/`.
|
||||
|
||||
## CUDA / GPU Runtime
|
||||
|
||||
- [NVIDIA CUDA C++ Programming Guide](https://docs.nvidia.com/cuda/cuda-programming-guide/pdf/cuda-programming-guide.pdf)
|
||||
Mirror: `mirrors/nvidia-cuda-programming-guide.pdf`
|
||||
|
||||
- [NVIDIA CUDA C++ Programming Guide, asynchronous/concurrent execution](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#asynchronous-concurrent-execution)
|
||||
Mirror: `mirrors/nvidia-cuda-async-concurrent-execution.html`
|
||||
|
||||
- [NVIDIA Vision Programming Interface](https://docs.nvidia.com/vpi/)
|
||||
Mirror: `mirrors/nvidia-vpi-main.html`
|
||||
|
||||
- [NVIDIA Optical Flow SDK Programming Guide](https://docs.nvidia.com/video-technologies/optical-flow-sdk/pdf/NVOFA_Programming_Guide.pdf)
|
||||
Mirror: `mirrors/nvidia-optical-flow-programming-guide.pdf`
|
||||
|
||||
- [OpenCV CUDA-accelerated Computer Vision module](https://docs.opencv.org/3.4/d1/d1e/group__cuda.html)
|
||||
Mirror: `mirrors/opencv-cuda-module.html`
|
||||
|
||||
## Gaussian Splatting Implementations
|
||||
|
||||
- [GraphDeco/Inria, `gaussian-splatting`](https://github.com/graphdeco-inria/gaussian-splatting)
|
||||
Mirrors: `mirrors/graphdeco-gaussian-splatting-github.html`, `mirrors/graphdeco-gaussian-splatting-readme.md`
|
||||
|
||||
- [NVIDIA Developer Blog, "Real-Time GPU-Accelerated Gaussian Splatting with NVIDIA DesignWorks Sample vk_gaussian_splatting"](https://developer.nvidia.com/blog/real-time-gpu-accelerated-gaussian-splatting-with-nvidia-designworks-sample-vk_gaussian_splatting/)
|
||||
Mirror: `mirrors/nvidia-vk-gaussian-splatting-blog.html`
|
||||
|
||||
- [gsplat documentation](https://docs.gsplat.studio/main/)
|
||||
Mirror: `mirrors/gsplat-docs.html`
|
||||
|
||||
- [Nerfstudio Project, `gsplat`](https://github.com/nerfstudio-project/gsplat)
|
||||
Mirror: `mirrors/gsplat-github.html`
|
||||
|
||||
- M. Ye et al., ["gsplat: An Open-Source Library for Gaussian Splatting"](https://jmlr.org/papers/volume26/24-1476/24-1476.pdf), JMLR, 2025.
|
||||
Mirror: `mirrors/ye-2025-gsplat.pdf`
|
||||
|
||||
- [Nerfstudio, "Splatfacto"](https://docs.nerf.studio/nerfology/methods/splat.html)
|
||||
Mirror: `mirrors/nerfstudio-splatfacto.html`
|
||||
|
||||
## Gaussian Splatting Papers
|
||||
|
||||
- Bernhard Kerbl, Georgios Kopanas, Thomas Leimkuehler, and George Drettakis, ["3D Gaussian Splatting for Real-Time Radiance Field Rendering"](https://arxiv.org/abs/2308.04079), SIGGRAPH 2023.
|
||||
Mirror: `mirrors/kerbl-2023-3d-gaussian-splatting.pdf`
|
||||
|
||||
- Guanjun Wu et al., ["4D Gaussian Splatting for Real-Time Dynamic Scene Rendering"](https://openaccess.thecvf.com/content/CVPR2024/papers/Wu_4D_Gaussian_Splatting_for_Real-Time_Dynamic_Scene_Rendering_CVPR_2024_paper.pdf), CVPR 2024.
|
||||
Mirror: `mirrors/wu-2024-4d-gaussian-splatting.pdf`
|
||||
|
||||
- Zhexi Peng et al., ["RTG-SLAM: Real-time 3D Reconstruction at Scale using Gaussian Splatting"](https://arxiv.org/abs/2404.19706), SIGGRAPH 2024.
|
||||
Mirror: `mirrors/peng-2024-rtg-slam.pdf`
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1,615 +0,0 @@
|
|||
# 3D Gaussian Splatting for Real-Time Radiance Field Rendering
|
||||
Bernhard Kerbl*, Georgios Kopanas*, Thomas Leimkühler, George Drettakis (* indicates equal contribution)<br>
|
||||
| [Webpage](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/) | [Full Paper](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/3d_gaussian_splatting_high.pdf) | [Video](https://youtu.be/T_kXY43VZnk) | [Other GRAPHDECO Publications](http://www-sop.inria.fr/reves/publis/gdindex.php) | [FUNGRAPH project page](https://fungraph.inria.fr) |<br>
|
||||
| [T&T+DB COLMAP (650MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip) | [Pre-trained Models (14 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip) | [Viewers for Windows (60MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip) | [Evaluation Images (7 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip) |<br>
|
||||

|
||||
|
||||
This repository contains the official authors implementation associated with the paper "3D Gaussian Splatting for Real-Time Radiance Field Rendering", which can be found [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/). We further provide the reference images used to create the error metrics reported in the paper, as well as recently created, pre-trained models.
|
||||
|
||||
<a href="https://www.inria.fr/"><img height="100" src="assets/logo_inria.png"> </a>
|
||||
<a href="https://univ-cotedazur.eu/"><img height="100" src="assets/logo_uca.png"> </a>
|
||||
<a href="https://www.mpi-inf.mpg.de"><img height="100" src="assets/logo_mpi.png"> </a>
|
||||
<a href="https://team.inria.fr/graphdeco/"> <img style="width:100%;" src="assets/logo_graphdeco.png"></a>
|
||||
|
||||
Abstract: *Radiance Field methods have recently revolutionized novel-view synthesis of scenes captured with multiple photos or videos. However, achieving high visual quality still requires neural networks that are costly to train and render, while recent faster methods inevitably trade off speed for quality. For unbounded and complete scenes (rather than isolated objects) and 1080p resolution rendering, no current method can achieve real-time display rates. We introduce three key elements that allow us to achieve state-of-the-art visual quality while maintaining competitive training times and importantly allow high-quality real-time (≥ 30 fps) novel-view synthesis at 1080p resolution. First, starting from sparse points produced during camera calibration, we represent the scene with 3D Gaussians that preserve desirable properties of continuous volumetric radiance fields for scene optimization while avoiding unnecessary computation in empty space; Second, we perform interleaved optimization/density control of the 3D Gaussians, notably optimizing anisotropic covariance to achieve an accurate representation of the scene; Third, we develop a fast visibility-aware rendering algorithm that supports anisotropic splatting and both accelerates training and allows realtime rendering. We demonstrate state-of-the-art visual quality and real-time rendering on several established datasets.*
|
||||
|
||||
<section class="section" id="BibTeX">
|
||||
<div class="container is-max-desktop content">
|
||||
<h2 class="title">BibTeX</h2>
|
||||
<pre><code>@Article{kerbl3Dgaussians,
|
||||
author = {Kerbl, Bernhard and Kopanas, Georgios and Leimk{\"u}hler, Thomas and Drettakis, George},
|
||||
title = {3D Gaussian Splatting for Real-Time Radiance Field Rendering},
|
||||
journal = {ACM Transactions on Graphics},
|
||||
number = {4},
|
||||
volume = {42},
|
||||
month = {July},
|
||||
year = {2023},
|
||||
url = {https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/}
|
||||
}</code></pre>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
|
||||
## Funding and Acknowledgments
|
||||
|
||||
This research was funded by the ERC Advanced grant FUNGRAPH No 788065. The authors are grateful to Adobe for generous donations, the OPAL infrastructure from Université Côte d’Azur and for the HPC resources from GENCI–IDRIS (Grant 2022-AD011013409). The authors thank the anonymous reviewers for their valuable feedback, P. Hedman and A. Tewari for proofreading earlier drafts also T. Müller, A. Yu and S. Fridovich-Keil for helping with the comparisons.
|
||||
|
||||
## NEW FEATURES !
|
||||
|
||||
We have limited resources for maintaining and updating the code. However, we have added a few new features since the original release that are inspired by some of the excellent work many other researchers have been doing on 3DGS. We will be adding other features within the ability of our resources.
|
||||
|
||||
**Update of October 2024**: We integrated [training speed acceleration](#training-speed-acceleration) and made it compatible with [depth regularization](#depth-regularization), [anti-aliasing](#anti-aliasing) and [exposure compensation](#exposure-compensation). We have enhanced the SIBR real time viewer by correcting bugs and adding features in the [Top View](#sibr-top-view) that allows visualization of input and user cameras.
|
||||
|
||||
**Update of Spring 2024**:
|
||||
Orange Labs has kindly added [OpenXR support](#openxr-support) for VR viewing.
|
||||
|
||||
## Step-by-step Tutorial
|
||||
|
||||
Jonathan Stephens made a fantastic step-by-step tutorial for setting up Gaussian Splatting on your machine, along with instructions for creating usable datasets from videos. If the instructions below are too dry for you, go ahead and check it out [here](https://www.youtube.com/watch?v=UXtuigy_wYc).
|
||||
|
||||
## Colab
|
||||
|
||||
User [camenduru](https://github.com/camenduru) was kind enough to provide a Colab template that uses this repo's source (status: August 2023!) for quick and easy access to the method. Please check it out [here](https://github.com/camenduru/gaussian-splatting-colab).
|
||||
|
||||
## Cloning the Repository
|
||||
|
||||
The repository contains submodules, thus please check it out with
|
||||
```shell
|
||||
# SSH
|
||||
git clone git@github.com:graphdeco-inria/gaussian-splatting.git --recursive
|
||||
```
|
||||
or
|
||||
```shell
|
||||
# HTTPS
|
||||
git clone https://github.com/graphdeco-inria/gaussian-splatting --recursive
|
||||
```
|
||||
|
||||
## Overview
|
||||
|
||||
The codebase has 4 main components:
|
||||
- A PyTorch-based optimizer to produce a 3D Gaussian model from SfM inputs
|
||||
- A network viewer that allows to connect to and visualize the optimization process
|
||||
- An OpenGL-based real-time viewer to render trained models in real-time.
|
||||
- A script to help you turn your own images into optimization-ready SfM data sets
|
||||
|
||||
The components have different requirements w.r.t. both hardware and software. They have been tested on Windows 10 and Ubuntu Linux 22.04. Instructions for setting up and running each of them are found in the sections below.
|
||||
|
||||
|
||||
|
||||
|
||||
## Optimizer
|
||||
|
||||
The optimizer uses PyTorch and CUDA extensions in a Python environment to produce trained models.
|
||||
|
||||
### Hardware Requirements
|
||||
|
||||
- CUDA-ready GPU with Compute Capability 7.0+
|
||||
- 24 GB VRAM (to train to paper evaluation quality)
|
||||
- Please see FAQ for smaller VRAM configurations
|
||||
|
||||
### Software Requirements
|
||||
- Conda (recommended for easy setup)
|
||||
- C++ Compiler for PyTorch extensions (we used Visual Studio 2019 for Windows)
|
||||
- CUDA SDK 11 for PyTorch extensions, install *after* Visual Studio (we used 11.8, **known issues with 11.6**)
|
||||
- C++ Compiler and CUDA SDK must be compatible
|
||||
|
||||
### Setup
|
||||
|
||||
#### Local Setup
|
||||
|
||||
Our default, provided install method is based on Conda package and environment management:
|
||||
```shell
|
||||
SET DISTUTILS_USE_SDK=1 # Windows only
|
||||
conda env create --file environment.yml
|
||||
conda activate gaussian_splatting
|
||||
```
|
||||
Please note that this process assumes that you have CUDA SDK **11** installed, not **12**. For modifications, see below.
|
||||
|
||||
Tip: Downloading packages and creating a new environment with Conda can require a significant amount of disk space. By default, Conda will use the main system hard drive. You can avoid this by specifying a different package download location and an environment on a different drive:
|
||||
|
||||
```shell
|
||||
conda config --add pkgs_dirs <Drive>/<pkg_path>
|
||||
conda env create --file environment.yml --prefix <Drive>/<env_path>/gaussian_splatting
|
||||
conda activate <Drive>/<env_path>/gaussian_splatting
|
||||
```
|
||||
|
||||
#### Modifications
|
||||
|
||||
If you can afford the disk space, we recommend using our environment files for setting up a training environment identical to ours. If you want to make modifications, please note that major version changes might affect the results of our method. However, our (limited) experiments suggest that the codebase works just fine inside a more up-to-date environment (Python 3.8, PyTorch 2.0.0, CUDA 12). Make sure to create an environment where PyTorch and its CUDA runtime version match and the installed CUDA SDK has no major version difference with PyTorch's CUDA version.
|
||||
|
||||
#### Known Issues
|
||||
|
||||
Some users experience problems building the submodules on Windows (```cl.exe: File not found``` or similar). Please consider the workaround for this problem from the FAQ.
|
||||
|
||||
### Running
|
||||
|
||||
To run the optimizer, simply use
|
||||
|
||||
```shell
|
||||
python train.py -s <path to COLMAP or NeRF Synthetic dataset>
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Command Line Arguments for train.py</span></summary>
|
||||
|
||||
#### --source_path / -s
|
||||
Path to the source directory containing a COLMAP or Synthetic NeRF data set.
|
||||
#### --model_path / -m
|
||||
Path where the trained model should be stored (```output/<random>``` by default).
|
||||
#### --images / -i
|
||||
Alternative subdirectory for COLMAP images (```images``` by default).
|
||||
#### --eval
|
||||
Add this flag to use a MipNeRF360-style training/test split for evaluation.
|
||||
#### --resolution / -r
|
||||
Specifies resolution of the loaded images before training. If provided ```1, 2, 4``` or ```8```, uses original, 1/2, 1/4 or 1/8 resolution, respectively. For all other values, rescales the width to the given number while maintaining image aspect. **If not set and input image width exceeds 1.6K pixels, inputs are automatically rescaled to this target.**
|
||||
#### --data_device
|
||||
Specifies where to put the source image data, ```cuda``` by default, recommended to use ```cpu``` if training on large/high-resolution dataset, will reduce VRAM consumption, but slightly slow down training. Thanks to [HrsPythonix](https://github.com/HrsPythonix).
|
||||
#### --white_background / -w
|
||||
Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset.
|
||||
#### --sh_degree
|
||||
Order of spherical harmonics to be used (no larger than 3). ```3``` by default.
|
||||
#### --convert_SHs_python
|
||||
Flag to make pipeline compute forward and backward of SHs with PyTorch instead of ours.
|
||||
#### --convert_cov3D_python
|
||||
Flag to make pipeline compute forward and backward of the 3D covariance with PyTorch instead of ours.
|
||||
#### --debug
|
||||
Enables debug mode if you experience erros. If the rasterizer fails, a ```dump``` file is created that you may forward to us in an issue so we can take a look.
|
||||
#### --debug_from
|
||||
Debugging is **slow**. You may specify an iteration (starting from 0) after which the above debugging becomes active.
|
||||
#### --iterations
|
||||
Number of total iterations to train for, ```30_000``` by default.
|
||||
#### --ip
|
||||
IP to start GUI server on, ```127.0.0.1``` by default.
|
||||
#### --port
|
||||
Port to use for GUI server, ```6009``` by default.
|
||||
#### --test_iterations
|
||||
Space-separated iterations at which the training script computes L1 and PSNR over test set, ```7000 30000``` by default.
|
||||
#### --save_iterations
|
||||
Space-separated iterations at which the training script saves the Gaussian model, ```7000 30000 <iterations>``` by default.
|
||||
#### --checkpoint_iterations
|
||||
Space-separated iterations at which to store a checkpoint for continuing later, saved in the model directory.
|
||||
#### --start_checkpoint
|
||||
Path to a saved checkpoint to continue training from.
|
||||
#### --quiet
|
||||
Flag to omit any text written to standard out pipe.
|
||||
#### --feature_lr
|
||||
Spherical harmonics features learning rate, ```0.0025``` by default.
|
||||
#### --opacity_lr
|
||||
Opacity learning rate, ```0.05``` by default.
|
||||
#### --scaling_lr
|
||||
Scaling learning rate, ```0.005``` by default.
|
||||
#### --rotation_lr
|
||||
Rotation learning rate, ```0.001``` by default.
|
||||
#### --position_lr_max_steps
|
||||
Number of steps (from 0) where position learning rate goes from ```initial``` to ```final```. ```30_000``` by default.
|
||||
#### --position_lr_init
|
||||
Initial 3D position learning rate, ```0.00016``` by default.
|
||||
#### --position_lr_final
|
||||
Final 3D position learning rate, ```0.0000016``` by default.
|
||||
#### --position_lr_delay_mult
|
||||
Position learning rate multiplier (cf. Plenoxels), ```0.01``` by default.
|
||||
#### --densify_from_iter
|
||||
Iteration where densification starts, ```500``` by default.
|
||||
#### --densify_until_iter
|
||||
Iteration where densification stops, ```15_000``` by default.
|
||||
#### --densify_grad_threshold
|
||||
Limit that decides if points should be densified based on 2D position gradient, ```0.0002``` by default.
|
||||
#### --densification_interval
|
||||
How frequently to densify, ```100``` (every 100 iterations) by default.
|
||||
#### --opacity_reset_interval
|
||||
How frequently to reset opacity, ```3_000``` by default.
|
||||
#### --lambda_dssim
|
||||
Influence of SSIM on total loss from 0 to 1, ```0.2``` by default.
|
||||
#### --percent_dense
|
||||
Percentage of scene extent (0--1) a point must exceed to be forcibly densified, ```0.01``` by default.
|
||||
|
||||
</details>
|
||||
<br>
|
||||
|
||||
Note that similar to MipNeRF360, we target images at resolutions in the 1-1.6K pixel range. For convenience, arbitrary-size inputs can be passed and will be automatically resized if their width exceeds 1600 pixels. We recommend to keep this behavior, but you may force training to use your higher-resolution images by setting ```-r 1```.
|
||||
|
||||
The MipNeRF360 scenes are hosted by the paper authors [here](https://jonbarron.info/mipnerf360/). You can find our SfM data sets for Tanks&Temples and Deep Blending [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip). If you do not provide an output model directory (```-m```), trained models are written to folders with randomized unique names inside the ```output``` directory. At this point, the trained models may be viewed with the real-time viewer (see further below).
|
||||
|
||||
### Evaluation
|
||||
By default, the trained models use all available images in the dataset. To train them while withholding a test set for evaluation, use the ```--eval``` flag. This way, you can render training/test sets and produce error metrics as follows:
|
||||
```shell
|
||||
python train.py -s <path to COLMAP or NeRF Synthetic dataset> --eval # Train with train/test split
|
||||
python render.py -m <path to trained model> # Generate renderings
|
||||
python metrics.py -m <path to trained model> # Compute error metrics on renderings
|
||||
```
|
||||
|
||||
If you want to evaluate our [pre-trained models](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip), you will have to download the corresponding source data sets and indicate their location to ```render.py``` with an additional ```--source_path/-s``` flag. Note: The pre-trained models were created with the release codebase. This code base has been cleaned up and includes bugfixes, hence the metrics you get from evaluating them will differ from those in the paper.
|
||||
```shell
|
||||
python render.py -m <path to pre-trained model> -s <path to COLMAP dataset>
|
||||
python metrics.py -m <path to pre-trained model>
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Command Line Arguments for render.py</span></summary>
|
||||
|
||||
#### --model_path / -m
|
||||
Path to the trained model directory you want to create renderings for.
|
||||
#### --skip_train
|
||||
Flag to skip rendering the training set.
|
||||
#### --skip_test
|
||||
Flag to skip rendering the test set.
|
||||
#### --quiet
|
||||
Flag to omit any text written to standard out pipe.
|
||||
|
||||
**The below parameters will be read automatically from the model path, based on what was used for training. However, you may override them by providing them explicitly on the command line.**
|
||||
|
||||
#### --source_path / -s
|
||||
Path to the source directory containing a COLMAP or Synthetic NeRF data set.
|
||||
#### --images / -i
|
||||
Alternative subdirectory for COLMAP images (```images``` by default).
|
||||
#### --eval
|
||||
Add this flag to use a MipNeRF360-style training/test split for evaluation.
|
||||
#### --resolution / -r
|
||||
Changes the resolution of the loaded images before training. If provided ```1, 2, 4``` or ```8```, uses original, 1/2, 1/4 or 1/8 resolution, respectively. For all other values, rescales the width to the given number while maintaining image aspect. ```1``` by default.
|
||||
#### --white_background / -w
|
||||
Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset.
|
||||
#### --convert_SHs_python
|
||||
Flag to make pipeline render with computed SHs from PyTorch instead of ours.
|
||||
#### --convert_cov3D_python
|
||||
Flag to make pipeline render with computed 3D covariance from PyTorch instead of ours.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Command Line Arguments for metrics.py</span></summary>
|
||||
|
||||
#### --model_paths / -m
|
||||
Space-separated list of model paths for which metrics should be computed.
|
||||
</details>
|
||||
<br>
|
||||
|
||||
We further provide the ```full_eval.py``` script. This script specifies the routine used in our evaluation and demonstrates the use of some additional parameters, e.g., ```--images (-i)``` to define alternative image directories within COLMAP data sets. If you have downloaded and extracted all the training data, you can run it like this:
|
||||
```shell
|
||||
python full_eval.py -m360 <mipnerf360 folder> -tat <tanks and temples folder> -db <deep blending folder>
|
||||
```
|
||||
In the current version, this process takes about 7h on our reference machine containing an A6000. If you want to do the full evaluation on our pre-trained models, you can specify their download location and skip training.
|
||||
```shell
|
||||
python full_eval.py -o <directory with pretrained models> --skip_training -m360 <mipnerf360 folder> -tat <tanks and temples folder> -db <deep blending folder>
|
||||
```
|
||||
|
||||
If you want to compute the metrics on our paper's [evaluation images](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip), you can also skip rendering. In this case it is not necessary to provide the source datasets. You can compute metrics for multiple image sets at a time.
|
||||
```shell
|
||||
python full_eval.py -m <directory with evaluation images>/garden ... --skip_training --skip_rendering
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Command Line Arguments for full_eval.py</span></summary>
|
||||
|
||||
#### --skip_training
|
||||
Flag to skip training stage.
|
||||
#### --skip_rendering
|
||||
Flag to skip rendering stage.
|
||||
#### --skip_metrics
|
||||
Flag to skip metrics calculation stage.
|
||||
#### --output_path
|
||||
Directory to put renderings and results in, ```./eval``` by default, set to pre-trained model location if evaluating them.
|
||||
#### --mipnerf360 / -m360
|
||||
Path to MipNeRF360 source datasets, required if training or rendering.
|
||||
#### --tanksandtemples / -tat
|
||||
Path to Tanks&Temples source datasets, required if training or rendering.
|
||||
#### --deepblending / -db
|
||||
Path to Deep Blending source datasets, required if training or rendering.
|
||||
</details>
|
||||
<br>
|
||||
|
||||
## Interactive Viewers
|
||||
We provide two interactive viewers for our method: remote and real-time. Our viewing solutions are based on the [SIBR](https://sibr.gitlabpages.inria.fr/) framework, developed by the GRAPHDECO group for several novel-view synthesis projects.
|
||||
|
||||
### Hardware Requirements
|
||||
- OpenGL 4.5-ready GPU and drivers (or latest MESA software)
|
||||
- 4 GB VRAM recommended
|
||||
- CUDA-ready GPU with Compute Capability 7.0+ (only for Real-Time Viewer)
|
||||
|
||||
### Software Requirements
|
||||
- Visual Studio or g++, **not Clang** (we used Visual Studio 2019 for Windows)
|
||||
- CUDA SDK 11, install *after* Visual Studio (we used 11.8)
|
||||
- CMake (recent version, we used 3.24)
|
||||
- 7zip (only on Windows)
|
||||
|
||||
### Pre-built Windows Binaries
|
||||
We provide pre-built binaries for Windows [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip). We recommend using them on Windows for an efficient setup, since the building of SIBR involves several external dependencies that must be downloaded and compiled on-the-fly.
|
||||
|
||||
### Installation from Source
|
||||
If you cloned with submodules (e.g., using ```--recursive```), the source code for the viewers is found in ```SIBR_viewers```. The network viewer runs within the SIBR framework for Image-based Rendering applications.
|
||||
|
||||
#### Windows
|
||||
CMake should take care of your dependencies.
|
||||
```shell
|
||||
cd SIBR_viewers
|
||||
cmake -Bbuild .
|
||||
cmake --build build --target install --config RelWithDebInfo
|
||||
```
|
||||
You may specify a different configuration, e.g. ```Debug``` if you need more control during development.
|
||||
|
||||
#### Ubuntu 22.04
|
||||
You will need to install a few dependencies before running the project setup.
|
||||
```shell
|
||||
# Dependencies
|
||||
sudo apt install -y libglew-dev libassimp-dev libboost-all-dev libgtk-3-dev libopencv-dev libglfw3-dev libavdevice-dev libavcodec-dev libeigen3-dev libxxf86vm-dev libembree-dev
|
||||
# Project setup
|
||||
cd SIBR_viewers
|
||||
cmake -Bbuild . -DCMAKE_BUILD_TYPE=Release # add -G Ninja to build faster
|
||||
cmake --build build -j24 --target install
|
||||
```
|
||||
|
||||
#### Ubuntu 20.04
|
||||
Backwards compatibility with Focal Fossa is not fully tested, but building SIBR with CMake should still work after invoking
|
||||
```shell
|
||||
git checkout fossa_compatibility
|
||||
```
|
||||
|
||||
### Navigation in SIBR Viewers
|
||||
The SIBR interface provides several methods of navigating the scene. By default, you will be started with an FPS navigator, which you can control with ```W, A, S, D, Q, E``` for camera translation and ```I, K, J, L, U, O``` for rotation. Alternatively, you may want to use a Trackball-style navigator (select from the floating menu). You can also snap to a camera from the data set with the ```Snap to``` button or find the closest camera with ```Snap to closest```. The floating menues also allow you to change the navigation speed. You can use the ```Scaling Modifier``` to control the size of the displayed Gaussians, or show the initial point cloud.
|
||||
|
||||
### Running the Network Viewer
|
||||
|
||||
|
||||
|
||||
https://github.com/graphdeco-inria/gaussian-splatting/assets/40643808/90a2e4d3-cf2e-4633-b35f-bfe284e28ff7
|
||||
|
||||
|
||||
|
||||
After extracting or installing the viewers, you may run the compiled ```SIBR_remoteGaussian_app[_config]``` app in ```<SIBR install dir>/bin```, e.g.:
|
||||
```shell
|
||||
./<SIBR install dir>/bin/SIBR_remoteGaussian_app
|
||||
```
|
||||
The network viewer allows you to connect to a running training process on the same or a different machine. If you are training on the same machine and OS, no command line parameters should be required: the optimizer communicates the location of the training data to the network viewer. By default, optimizer and network viewer will try to establish a connection on **localhost** on port **6009**. You can change this behavior by providing matching ```--ip``` and ```--port``` parameters to both the optimizer and the network viewer. If for some reason the path used by the optimizer to find the training data is not reachable by the network viewer (e.g., due to them running on different (virtual) machines), you may specify an override location to the viewer by using ```-s <source path>```.
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Primary Command Line Arguments for Network Viewer</span></summary>
|
||||
|
||||
#### --path / -s
|
||||
Argument to override model's path to source dataset.
|
||||
#### --ip
|
||||
IP to use for connection to a running training script.
|
||||
#### --port
|
||||
Port to use for connection to a running training script.
|
||||
#### --rendering-size
|
||||
Takes two space separated numbers to define the resolution at which network rendering occurs, ```1200``` width by default.
|
||||
Note that to enforce an aspect that differs from the input images, you need ```--force-aspect-ratio``` too.
|
||||
#### --load_images
|
||||
Flag to load source dataset images to be displayed in the top view for each camera.
|
||||
</details>
|
||||
<br>
|
||||
|
||||
### Running the Real-Time Viewer
|
||||
|
||||
|
||||
|
||||
|
||||
https://github.com/graphdeco-inria/gaussian-splatting/assets/40643808/0940547f-1d82-4c2f-a616-44eabbf0f816
|
||||
|
||||
|
||||
|
||||
|
||||
After extracting or installing the viewers, you may run the compiled ```SIBR_gaussianViewer_app[_config]``` app in ```<SIBR install dir>/bin```, e.g.:
|
||||
```shell
|
||||
./<SIBR install dir>/bin/SIBR_gaussianViewer_app -m <path to trained model>
|
||||
```
|
||||
|
||||
It should suffice to provide the ```-m``` parameter pointing to a trained model directory. Alternatively, you can specify an override location for training input data using ```-s```. To use a specific resolution other than the auto-chosen one, specify ```--rendering-size <width> <height>```. Combine it with ```--force-aspect-ratio``` if you want the exact resolution and don't mind image distortion.
|
||||
|
||||
**To unlock the full frame rate, please disable V-Sync on your machine and also in the application (Menu → Display). In a multi-GPU system (e.g., laptop) your OpenGL/Display GPU should be the same as your CUDA GPU (e.g., by setting the application's GPU preference on Windows, see below) for maximum performance.**
|
||||
|
||||

|
||||
|
||||
In addition to the initial point cloud and the splats, you also have the option to visualize the Gaussians by rendering them as ellipsoids from the floating menu.
|
||||
SIBR has many other functionalities, please see the [documentation](https://sibr.gitlabpages.inria.fr/) for more details on the viewer, navigation options etc. There is also a Top View (available from the menu) that shows the placement of the input cameras and the original SfM point cloud; please note that Top View slows rendering when enabled. The real-time viewer also uses slightly more aggressive, fast culling, which can be toggled in the floating menu. If you ever encounter an issue that can be solved by turning fast culling off, please let us know.
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Primary Command Line Arguments for Real-Time Viewer</span></summary>
|
||||
|
||||
#### --model-path / -m
|
||||
Path to trained model.
|
||||
#### --iteration
|
||||
Specifies which of state to load if multiple are available. Defaults to latest available iteration.
|
||||
#### --path / -s
|
||||
Argument to override model's path to source dataset.
|
||||
#### --rendering-size
|
||||
Takes two space separated numbers to define the resolution at which real-time rendering occurs, ```1200``` width by default. Note that to enforce an aspect that differs from the input images, you need ```--force-aspect-ratio``` too.
|
||||
#### --load_images
|
||||
Flag to load source dataset images to be displayed in the top view for each camera.
|
||||
#### --device
|
||||
Index of CUDA device to use for rasterization if multiple are available, ```0``` by default.
|
||||
#### --no_interop
|
||||
Disables CUDA/GL interop forcibly. Use on systems that may not behave according to spec (e.g., WSL2 with MESA GL 4.5 software rendering).
|
||||
</details>
|
||||
<br>
|
||||
|
||||
## Processing your own Scenes
|
||||
|
||||
Our COLMAP loaders expect the following dataset structure in the source path location:
|
||||
|
||||
```
|
||||
<location>
|
||||
|---images
|
||||
| |---<image 0>
|
||||
| |---<image 1>
|
||||
| |---...
|
||||
|---sparse
|
||||
|---0
|
||||
|---cameras.bin
|
||||
|---images.bin
|
||||
|---points3D.bin
|
||||
```
|
||||
|
||||
For rasterization, the camera models must be either a SIMPLE_PINHOLE or PINHOLE camera. We provide a converter script ```convert.py```, to extract undistorted images and SfM information from input images. Optionally, you can use ImageMagick to resize the undistorted images. This rescaling is similar to MipNeRF360, i.e., it creates images with 1/2, 1/4 and 1/8 the original resolution in corresponding folders. To use them, please first install a recent version of COLMAP (ideally CUDA-powered) and ImageMagick. Put the images you want to use in a directory ```<location>/input```.
|
||||
```
|
||||
<location>
|
||||
|---input
|
||||
|---<image 0>
|
||||
|---<image 1>
|
||||
|---...
|
||||
```
|
||||
If you have COLMAP and ImageMagick on your system path, you can simply run
|
||||
```shell
|
||||
python convert.py -s <location> [--resize] #If not resizing, ImageMagick is not needed
|
||||
```
|
||||
Alternatively, you can use the optional parameters ```--colmap_executable``` and ```--magick_executable``` to point to the respective paths. Please note that on Windows, the executable should point to the COLMAP ```.bat``` file that takes care of setting the execution environment. Once done, ```<location>``` will contain the expected COLMAP data set structure with undistorted, resized input images, in addition to your original images and some temporary (distorted) data in the directory ```distorted```.
|
||||
|
||||
If you have your own COLMAP dataset without undistortion (e.g., using ```OPENCV``` camera), you can try to just run the last part of the script: Put the images in ```input``` and the COLMAP info in a subdirectory ```distorted```:
|
||||
```
|
||||
<location>
|
||||
|---input
|
||||
| |---<image 0>
|
||||
| |---<image 1>
|
||||
| |---...
|
||||
|---distorted
|
||||
|---database.db
|
||||
|---sparse
|
||||
|---0
|
||||
|---...
|
||||
```
|
||||
Then run
|
||||
```shell
|
||||
python convert.py -s <location> --skip_matching [--resize] #If not resizing, ImageMagick is not needed
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><span style="font-weight: bold;">Command Line Arguments for convert.py</span></summary>
|
||||
|
||||
#### --no_gpu
|
||||
Flag to avoid using GPU in COLMAP.
|
||||
#### --skip_matching
|
||||
Flag to indicate that COLMAP info is available for images.
|
||||
#### --source_path / -s
|
||||
Location of the inputs.
|
||||
#### --camera
|
||||
Which camera model to use for the early matching steps, ```OPENCV``` by default.
|
||||
#### --resize
|
||||
Flag for creating resized versions of input images.
|
||||
#### --colmap_executable
|
||||
Path to the COLMAP executable (```.bat``` on Windows).
|
||||
#### --magick_executable
|
||||
Path to the ImageMagick executable.
|
||||
</details>
|
||||
<br>
|
||||
|
||||
### Training speed acceleration
|
||||
|
||||
We integrated the drop-in replacements from [Taming-3dgs](https://humansensinglab.github.io/taming-3dgs/)<sup>1</sup> with [fused ssim](https://github.com/rahul-goel/fused-ssim/tree/main) into the original codebase to speed up training times. Once installed, the accelerated rasterizer delivers a **$\times$ 1.6 training time speedup** using `--optimizer_type default` and a **$\times$ 2.7 training time speedup** using `--optimizer_type sparse_adam`.
|
||||
|
||||
To get faster training times you must first install the accelerated rasterizer to your environment:
|
||||
|
||||
```bash
|
||||
pip uninstall diff-gaussian-rasterization -y
|
||||
cd submodules/diff-gaussian-rasterization
|
||||
rm -r build
|
||||
git checkout 3dgs_accel
|
||||
pip install .
|
||||
```
|
||||
|
||||
Then you can add the following parameter to use the sparse adam optimizer when running `train.py`:
|
||||
|
||||
```bash
|
||||
--optimizer_type sparse_adam
|
||||
```
|
||||
|
||||
*Note that this custom rasterizer has a different behaviour than the original version, for more details on training times please see [stats for training times](results.md/#training-times-comparisons)*.
|
||||
|
||||
*1. Mallick and Goel, et al. ‘Taming 3DGS: High-Quality Radiance Fields with Limited Resources’. SIGGRAPH Asia 2024 Conference Papers, 2024, https://doi.org/10.1145/3680528.3687694, [github](https://github.com/humansensinglab/taming-3dgs)*
|
||||
|
||||
|
||||
### Depth regularization
|
||||
|
||||
To have better reconstructed scenes we use depth maps as priors during optimization with each input images. It works best on untextured parts ex: roads and can remove floaters. Several papers have used similar ideas to improve various aspects of 3DGS; (e.g. [DepthRegularizedGS](https://robot0321.github.io/DepthRegGS/index.html), [SparseGS](https://formycat.github.io/SparseGS-Real-Time-360-Sparse-View-Synthesis-using-Gaussian-Splatting/), [DNGaussian](https://fictionarry.github.io/DNGaussian/)). The depth regularization we integrated is that used in our [Hierarchical 3DGS](https://repo-sam.inria.fr/fungraph/hierarchical-3d-gaussians/) paper, but applied to the original 3DGS; for some scenes (e.g., the DeepBlending scenes) it improves quality significantly; for others it either makes a small difference or can even be worse. For example results showing the potential benefit and statistics on quality please see here: [Stats for depth regularization](results.md).
|
||||
|
||||
When training on a synthetic dataset, depth maps can be produced and they do not require further processing to be used in our method.
|
||||
|
||||
For real world datasets depth maps should be generated for each input images, to generate them please do the following:
|
||||
1. Clone [Depth Anything v2](https://github.com/DepthAnything/Depth-Anything-V2?tab=readme-ov-file#usage):
|
||||
```
|
||||
git clone https://github.com/DepthAnything/Depth-Anything-V2.git
|
||||
```
|
||||
2. Download weights from [Depth-Anything-V2-Large](https://huggingface.co/depth-anything/Depth-Anything-V2-Large/resolve/main/depth_anything_v2_vitl.pth?download=true) and place it under `Depth-Anything-V2/checkpoints/`
|
||||
3. Generate depth maps:
|
||||
```
|
||||
python Depth-Anything-V2/run.py --encoder vitl --pred-only --grayscale --img-path <path to input images> --outdir <output path>
|
||||
```
|
||||
5. Generate a `depth_params.json` file using:
|
||||
```
|
||||
python utils/make_depth_scale.py --base_dir <path to colmap> --depths_dir <path to generated depths>
|
||||
```
|
||||
|
||||
A new parameter should be set when training if you want to use depth regularization `-d <path to depth maps>`.
|
||||
|
||||
### Exposure compensation
|
||||
To compensate for exposure changes in the different input images we optimize an affine transformation for each image just as in [Hierarchical 3dgs](https://repo-sam.inria.fr/fungraph/hierarchical-3d-gaussians/).
|
||||
|
||||
This can greatly improve reconstruction results for "in the wild" captures, e.g., with a smartphone when the exposure setting of the camera is not fixed. For example results showing the potential benefit and statistics on quality please see here: [Stats for exposure compensation](results.md).
|
||||
|
||||
Add the following parameters to enable it:
|
||||
```
|
||||
--exposure_lr_init 0.001 --exposure_lr_final 0.0001 --exposure_lr_delay_steps 5000 --exposure_lr_delay_mult 0.001 --train_test_exp
|
||||
```
|
||||
Again, other excellent papers have used similar ideas e.g. [NeRF-W](https://nerf-w.github.io/), [URF](https://urban-radiance-fields.github.io/).
|
||||
|
||||
### Anti-aliasing
|
||||
We added the EWA Filter from [Mip Splatting](https://niujinshuchong.github.io/mip-splatting/) in our codebase to remove aliasing. It is disabled by default but you can enable it by adding `--antialiasing` when training on a scene using `train.py` or rendering using `render.py`. Antialiasing can be toggled in the SIBR viewer, it is disabled by default but you should enable it when viewing a scene trained using `--antialiasing`.
|
||||

|
||||
*this scene was trained using `--antialiasing`*.
|
||||
|
||||
### SIBR: Top view
|
||||
> `Views > Top view`
|
||||
|
||||
The `Top view` renders the SfM point cloud in another view with the corresponding input cameras and the `Point view` user camera. This allows visualization of how far the viewer is from the input cameras for example.
|
||||
|
||||
It is a 3D view so the user can navigate through it just as in the `Point view` (modes available: FPS, trackball, orbit).
|
||||
<!-- _gif showing the top view, showing it is realtime_ -->
|
||||
<!--  -->
|
||||

|
||||
|
||||
Options are available to customize this view, meshes can be disabled/enabled and their scales can be modified.
|
||||
<!-- _gif showing different options_ -->
|
||||
<!--  -->
|
||||

|
||||
A useful additional functionality is to move to the position of an input image, and progressively fade out to the SfM point view in that position (e.g., to verify camera alignment). Views from input cameras can be displayed in the `Top view` (*note that `--images-path` must be set in the command line*). One can snap the `Top view` camera to the closest input camera from the user camera in the `Point view` by clicking `Top view settings > Cameras > Snap to closest`.
|
||||
<!-- _gif showing for a snapped camera the ground truth image with alpha_ -->
|
||||
<!--  -->
|
||||

|
||||
|
||||
### OpenXR support
|
||||
|
||||
OpenXR is supported in the branch `gaussian_code_release_openxr`
|
||||
Within that branch, you can find documentation for VR support [here](https://gitlab.inria.fr/sibr/sibr_core/-/tree/gaussian_code_release_openxr?ref_type=heads).
|
||||
|
||||
|
||||
## FAQ
|
||||
- *Where do I get data sets, e.g., those referenced in ```full_eval.py```?* The MipNeRF360 data set is provided by the authors of the original paper on the project site. Note that two of the data sets cannot be openly shared and require you to consult the authors directly. For Tanks&Temples and Deep Blending, please use the download links provided at the top of the page. Alternatively, you may access the cloned data (status: August 2023!) from [HuggingFace](https://huggingface.co/camenduru/gaussian-splatting)
|
||||
|
||||
|
||||
- *How can I use this for a much larger dataset, like a city district?* The current method was not designed for these, but given enough memory, it should work out. However, the approach can struggle in multi-scale detail scenes (extreme close-ups, mixed with far-away shots). This is usually the case in, e.g., driving data sets (cars close up, buildings far away). For such scenes, you can lower the ```--position_lr_init```, ```--position_lr_final``` and ```--scaling_lr``` (x0.3, x0.1, ...). The more extensive the scene, the lower these values should be. Below, we use default learning rates (left) and ```--position_lr_init 0.000016 --scaling_lr 0.001"``` (right).
|
||||
|
||||
|  <!-- --> | <!-- -->  |
|
||||
| --- | --- |
|
||||
|
||||
- *I'm on Windows and I can't manage to build the submodules, what do I do?* Consider following the steps in the excellent video tutorial [here](https://www.youtube.com/watch?v=UXtuigy_wYc), hopefully they should help. The order in which the steps are done is important! Alternatively, consider using the linked Colab template.
|
||||
|
||||
- *It still doesn't work. It says something about ```cl.exe```. What do I do?* User Henry Pearce found a workaround. You can you try adding the visual studio path to your environment variables (your version number might differ);
|
||||
```C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64```
|
||||
Then make sure you start a new conda prompt and cd to your repo location and try this;
|
||||
```
|
||||
conda activate gaussian_splatting
|
||||
cd <dir_to_repo>/gaussian-splatting
|
||||
pip install submodules\diff-gaussian-rasterization
|
||||
pip install submodules\simple-knn
|
||||
```
|
||||
|
||||
- *I'm on macOS/Puppy Linux/Greenhat and I can't manage to build, what do I do?* Sorry, we can't provide support for platforms outside of the ones we list in this README. Consider using the linked Colab template.
|
||||
|
||||
- *I don't have 24 GB of VRAM for training, what do I do?* The VRAM consumption is determined by the number of points that are being optimized, which increases over time. If you only want to train to 7k iterations, you will need significantly less. To do the full training routine and avoid running out of memory, you can increase the ```--densify_grad_threshold```, ```--densification_interval``` or reduce the value of ```--densify_until_iter```. Note however that this will affect the quality of the result. Also try setting ```--test_iterations``` to ```-1``` to avoid memory spikes during testing. If ```--densify_grad_threshold``` is very high, no densification should occur and training should complete if the scene itself loads successfully.
|
||||
|
||||
- *24 GB of VRAM for reference quality training is still a lot! Can't we do it with less?* Yes, most likely. By our calculations it should be possible with **way** less memory (~8GB). If we can find the time we will try to achieve this. If some PyTorch veteran out there wants to tackle this, we look forward to your pull request!
|
||||
|
||||
|
||||
- *How can I use the differentiable Gaussian rasterizer for my own project?* Easy, it is included in this repo as a submodule ```diff-gaussian-rasterization```. Feel free to check out and install the package. It's not really documented, but using it from the Python side is very straightforward (cf. ```gaussian_renderer/__init__.py```).
|
||||
|
||||
- *Wait, but ```<insert feature>``` isn't optimized and could be much better?* There are several parts we didn't even have time to think about improving (yet). The performance you get with this prototype is probably a rather slow baseline for what is physically possible.
|
||||
|
||||
- *Something is broken, how did this happen?* We tried hard to provide a solid and comprehensible basis to make use of the paper's method. We have refactored the code quite a bit, but we have limited capacity to test all possible usage scenarios. Thus, if part of the website, the code or the performance is lacking, please create an issue. If we find the time, we will do our best to address it.
|
||||
|
|
@ -1,493 +0,0 @@
|
|||
<!doctype html>
|
||||
<html class="no-js" lang="en" data-content_root="./">
|
||||
<head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark"><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="index" title="Index" href="genindex.html"><link rel="search" title="Search" href="search.html"><link rel="next" title="Fit a COLMAP Capture" href="examples/colmap.html">
|
||||
|
||||
<!-- Generated with Sphinx 8.1.3 and Furo 2025.12.19 -->
|
||||
<title>gsplat documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=7bdb33bb" />
|
||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo-extensions.css?v=8dab3a3b" />
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
body {
|
||||
--color-code-background: #f2f2f2;
|
||||
--color-code-foreground: #1e1e1e;
|
||||
|
||||
}
|
||||
@media not print {
|
||||
body[data-theme="dark"] {
|
||||
--color-code-background: #202020;
|
||||
--color-code-foreground: #d0d0d0;
|
||||
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body:not([data-theme="light"]) {
|
||||
--color-code-background: #202020;
|
||||
--color-code-foreground: #d0d0d0;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
</style></head>
|
||||
<body>
|
||||
|
||||
<script>
|
||||
document.body.dataset.theme = localStorage.getItem("theme") || "auto";
|
||||
</script>
|
||||
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
|
||||
<symbol id="svg-toc" viewBox="0 0 24 24">
|
||||
<title>Contents</title>
|
||||
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024">
|
||||
<path d="M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM115.4 518.9L271.7 642c5.8 4.6 14.4.5 14.4-6.9V388.9c0-7.4-8.5-11.5-14.4-6.9L115.4 505.1a8.74 8.74 0 0 0 0 13.8z"/>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-menu" viewBox="0 0 24 24">
|
||||
<title>Menu</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather-menu">
|
||||
<line x1="3" y1="12" x2="21" y2="12"></line>
|
||||
<line x1="3" y1="6" x2="21" y2="6"></line>
|
||||
<line x1="3" y1="18" x2="21" y2="18"></line>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-arrow-right" viewBox="0 0 24 24">
|
||||
<title>Expand</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather-chevron-right">
|
||||
<polyline points="9 18 15 12 9 6"></polyline>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-sun" viewBox="0 0 24 24">
|
||||
<title>Light mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather-sun">
|
||||
<circle cx="12" cy="12" r="5"></circle>
|
||||
<line x1="12" y1="1" x2="12" y2="3"></line>
|
||||
<line x1="12" y1="21" x2="12" y2="23"></line>
|
||||
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
|
||||
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
|
||||
<line x1="1" y1="12" x2="3" y2="12"></line>
|
||||
<line x1="21" y1="12" x2="23" y2="12"></line>
|
||||
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
|
||||
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-moon" viewBox="0 0 24 24">
|
||||
<title>Dark mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="icon-tabler-moon">
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z" />
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-sun-with-moon" viewBox="0 0 24 24">
|
||||
<title>Auto light/dark, in light mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="icon-custom-derived-from-feather-sun-and-tabler-moon">
|
||||
<path style="opacity: 50%" d="M 5.411 14.504 C 5.471 14.504 5.532 14.504 5.591 14.504 C 3.639 16.319 4.383 19.569 6.931 20.352 C 7.693 20.586 8.512 20.551 9.25 20.252 C 8.023 23.207 4.056 23.725 2.11 21.184 C 0.166 18.642 1.702 14.949 4.874 14.536 C 5.051 14.512 5.231 14.5 5.411 14.5 L 5.411 14.504 Z"/>
|
||||
<line x1="14.5" y1="3.25" x2="14.5" y2="1.25"/>
|
||||
<line x1="14.5" y1="15.85" x2="14.5" y2="17.85"/>
|
||||
<line x1="10.044" y1="5.094" x2="8.63" y2="3.68"/>
|
||||
<line x1="19" y1="14.05" x2="20.414" y2="15.464"/>
|
||||
<line x1="8.2" y1="9.55" x2="6.2" y2="9.55"/>
|
||||
<line x1="20.8" y1="9.55" x2="22.8" y2="9.55"/>
|
||||
<line x1="10.044" y1="14.006" x2="8.63" y2="15.42"/>
|
||||
<line x1="19" y1="5.05" x2="20.414" y2="3.636"/>
|
||||
<circle cx="14.5" cy="9.55" r="3.6"/>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-moon-with-sun" viewBox="0 0 24 24">
|
||||
<title>Auto light/dark, in dark mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="icon-custom-derived-from-feather-sun-and-tabler-moon">
|
||||
<path d="M 8.282 7.007 C 8.385 7.007 8.494 7.007 8.595 7.007 C 5.18 10.184 6.481 15.869 10.942 17.24 C 12.275 17.648 13.706 17.589 15 17.066 C 12.851 22.236 5.91 23.143 2.505 18.696 C -0.897 14.249 1.791 7.786 7.342 7.063 C 7.652 7.021 7.965 7 8.282 7 L 8.282 7.007 Z"/>
|
||||
<line style="opacity: 50%" x1="18" y1="3.705" x2="18" y2="2.5"/>
|
||||
<line style="opacity: 50%" x1="18" y1="11.295" x2="18" y2="12.5"/>
|
||||
<line style="opacity: 50%" x1="15.316" y1="4.816" x2="14.464" y2="3.964"/>
|
||||
<line style="opacity: 50%" x1="20.711" y1="10.212" x2="21.563" y2="11.063"/>
|
||||
<line style="opacity: 50%" x1="14.205" y1="7.5" x2="13.001" y2="7.5"/>
|
||||
<line style="opacity: 50%" x1="21.795" y1="7.5" x2="23" y2="7.5"/>
|
||||
<line style="opacity: 50%" x1="15.316" y1="10.184" x2="14.464" y2="11.036"/>
|
||||
<line style="opacity: 50%" x1="20.711" y1="4.789" x2="21.563" y2="3.937"/>
|
||||
<circle style="opacity: 50%" cx="18" cy="7.5" r="2.169"/>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-pencil" viewBox="0 0 24 24">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="icon-tabler-pencil-code">
|
||||
<path d="M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4" />
|
||||
<path d="M13.5 6.5l4 4" />
|
||||
<path d="M20 21l2 -2l-2 -2" />
|
||||
<path d="M17 17l-2 2l2 2" />
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-eye" viewBox="0 0 24 24">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="icon-tabler-eye-code">
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0" />
|
||||
<path
|
||||
d="M11.11 17.958c-3.209 -.307 -5.91 -2.293 -8.11 -5.958c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6c-.21 .352 -.427 .688 -.647 1.008" />
|
||||
<path d="M20 21l2 -2l-2 -2" />
|
||||
<path d="M17 17l-2 2l2 2" />
|
||||
</svg>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
||||
<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation" aria-label="Toggle site navigation sidebar">
|
||||
<input type="checkbox" class="sidebar-toggle" name="__toc" id="__toc" aria-label="Toggle table of contents sidebar">
|
||||
<label class="overlay sidebar-overlay" for="__navigation"></label>
|
||||
<label class="overlay toc-overlay" for="__toc"></label>
|
||||
|
||||
<a class="skip-to-content muted-link" href="#furo-main-content">Skip to content</a>
|
||||
|
||||
|
||||
|
||||
<div class="page">
|
||||
<header class="mobile-header">
|
||||
<div class="header-left">
|
||||
<label class="nav-overlay-icon" for="__navigation">
|
||||
<span class="icon"><svg><use href="#svg-menu"></use></svg></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="header-center">
|
||||
<a href="#"><div class="brand">gsplat documentation</div></a>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="theme-toggle-container theme-toggle-header">
|
||||
<button class="theme-toggle" aria-label="Toggle Light / Dark / Auto color theme">
|
||||
<svg class="theme-icon-when-auto-light"><use href="#svg-sun-with-moon"></use></svg>
|
||||
<svg class="theme-icon-when-auto-dark"><use href="#svg-moon-with-sun"></use></svg>
|
||||
<svg class="theme-icon-when-dark"><use href="#svg-moon"></use></svg>
|
||||
<svg class="theme-icon-when-light"><use href="#svg-sun"></use></svg>
|
||||
</button>
|
||||
</div>
|
||||
<label class="toc-overlay-icon toc-header-icon" for="__toc">
|
||||
<span class="icon"><svg><use href="#svg-toc"></use></svg></span>
|
||||
</label>
|
||||
</div>
|
||||
</header>
|
||||
<aside class="sidebar-drawer">
|
||||
<div class="sidebar-container">
|
||||
|
||||
<div class="sidebar-sticky"><a class="sidebar-brand" href="#">
|
||||
|
||||
<span class="sidebar-brand-text">gsplat documentation</span>
|
||||
</a>
|
||||
|
||||
<!-- Dropdown for different versions of the docs. Slightly hacky. -->
|
||||
<div style="padding: 0 1em;">
|
||||
<script>
|
||||
var DocsVersionsPopulated = false;
|
||||
|
||||
async function getVersionList() {
|
||||
// This index.txt file is written by the docs.yml GitHub action.
|
||||
// https://github.com/nerfstudio-project/gsplat/blob/main/.github/workflows/doc.yml
|
||||
const response = await fetch(
|
||||
"https://docs.gsplat.studio/versions/index.txt",
|
||||
{ cache: "no-cache" }
|
||||
);
|
||||
return await response.text();
|
||||
}
|
||||
async function DocsPopulateVersionDropDown () {
|
||||
// Load the version list lazily...
|
||||
if (DocsVersionsPopulated) {
|
||||
return;
|
||||
}
|
||||
DocsVersionsPopulated = true;
|
||||
|
||||
console.log("Populating docs version list!")
|
||||
const versions = (await getVersionList()).trim().split("\n").reverse();
|
||||
console.log(versions);
|
||||
let htmlString = "<ul style='margin: 0.5rem 0 0 0'>";
|
||||
htmlString += `<li><a href="https://docs.gsplat.studio/main">main</a></li>`;
|
||||
for (let version of versions) {
|
||||
htmlString += `<li><a href="https://docs.gsplat.studio/versions/${version}">${version}</a></li>`;
|
||||
}
|
||||
|
||||
htmlString += "</ul>";
|
||||
document.getElementById("version-dropdown").innerHTML = htmlString;
|
||||
}
|
||||
</script>
|
||||
<details
|
||||
style="padding: 0.5rem; background: var(--color-background-primary); border-radius: 0.5rem; border: 1px solid var(--color-sidebar-background-border);"
|
||||
ontoggle="DocsPopulateVersionDropDown()"
|
||||
>
|
||||
<summary style="cursor: pointer;"><strong>Version:</strong> <em>main</em></summary>
|
||||
<div id="version-dropdown"></div>
|
||||
</details>
|
||||
<!-- End dropdown -->
|
||||
</div>
|
||||
|
||||
<div style="text-align: left; padding: 1em">
|
||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||
<a class="github-button" href="https://github.com/nerfstudio-project/gsplat"
|
||||
data-color-scheme="no-preference: light; light: light; dark: light;" data-size="large" data-show-count="true"
|
||||
aria-label="Download buttons/github-buttons on GitHub">
|
||||
Github
|
||||
</a>
|
||||
</div><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||
<input type="hidden" name="check_keywords" value="yes">
|
||||
<input type="hidden" name="area" value="default">
|
||||
</form>
|
||||
<div id="searchbox"></div><div class="sidebar-scroll"><div class="sidebar-tree">
|
||||
<p class="caption" role="heading"><span class="caption-text">Examples</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/colmap.html">Fit a COLMAP Capture</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/image.html">Fit a Single Image</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/large_scale.html">Render a Large Scene</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/ncore.html">Train on an NCore v4 Capture</a></li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Conventions</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="conventions/data_conventions.html">Data Conventions</a></li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Python API</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/compression.html">Compression</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/rasterization.html">Rasterization</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/strategy.html">Densification</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/utils.html">Utils</a></li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Tests</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="tests/eval.html">Evaluation</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="tests/profile.html">Profiling</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="tests/tests.html">Tests</a></li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Migration</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="migration/migration_inria.html">Migrate from diff-gaussian-rasterization</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="migration/migration_legacy.html">Migrate from gsplat v0.1.11</a></li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<div class="content">
|
||||
<div class="article-container">
|
||||
<a href="#" class="back-to-top muted-link">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8v12z"></path>
|
||||
</svg>
|
||||
<span>Back to top</span>
|
||||
</a>
|
||||
<div class="content-icon-container">
|
||||
<div class="view-this-page">
|
||||
<a class="muted-link" href="_sources/index.rst.txt" title="View this page">
|
||||
<svg><use href="#svg-eye"></use></svg>
|
||||
<span class="visually-hidden">View this page</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="theme-toggle-container theme-toggle-content">
|
||||
<button class="theme-toggle" aria-label="Toggle Light / Dark / Auto color theme">
|
||||
<svg class="theme-icon-when-auto-light"><use href="#svg-sun-with-moon"></use></svg>
|
||||
<svg class="theme-icon-when-auto-dark"><use href="#svg-moon-with-sun"></use></svg>
|
||||
<svg class="theme-icon-when-dark"><use href="#svg-moon"></use></svg>
|
||||
<svg class="theme-icon-when-light"><use href="#svg-sun"></use></svg>
|
||||
</button>
|
||||
</div>
|
||||
<label class="toc-overlay-icon toc-content-icon" for="__toc">
|
||||
<span class="icon"><svg><use href="#svg-toc"></use></svg></span>
|
||||
</label>
|
||||
</div>
|
||||
<article role="main" id="furo-main-content">
|
||||
<section id="gsplat">
|
||||
<h1>gsplat<a class="headerlink" href="#gsplat" title="Link to this heading">¶</a></h1>
|
||||
<a class="reference internal image-reference" href="_images/training.gif"><img alt="Example training image" src="_images/training.gif" style="width: 800px;" />
|
||||
</a>
|
||||
<section id="overview">
|
||||
<h2>Overview<a class="headerlink" href="#overview" title="Link to this heading">¶</a></h2>
|
||||
<p><em>gsplat</em> is an open-source library for CUDA-accelerated differentiable rasterization of
|
||||
3D gaussians with Python bindings. It is inspired by the SIGGRAPH paper “3D Gaussian Splatting for
|
||||
Real-Time Rendering of Radiance Fields” <span class="bibtex-citation" id="id1">[<a class="reference internal" href="#id3" title="Bernhard Kerbl, Georgios Kopanas, Thomas Leimkühler, and George Drettakis. 3d gaussian splatting for real-time radiance field rendering. ACM Transactions on Graphics, July 2023. URL: https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/.">1</a>]</span>, but we’ve made <em>gsplat</em> even
|
||||
faster, more memory efficient, and with a growing list of new features!</p>
|
||||
<ul class="simple">
|
||||
<li><p><em>gsplat</em> is developed with efficiency in mind. Comparing to the <a class="reference external" href="https://github.com/graphdeco-inria/gaussian-splatting">official implementation</a>,
|
||||
<em>gsplat</em> enables up to <strong>4x less training memory footprint</strong>, and up to <strong>15% less training time</strong> on Mip-NeRF 360 captures, and potential more on larger scenes. See <a class="reference internal" href="tests/eval.html"><span class="doc">Evaluation</span></a> for details.</p></li>
|
||||
<li><p><em>gsplat</em> is designed to <strong>support extremely large scene rendering</strong>, which is magnitudes
|
||||
faster than the official CUDA backend <a class="reference external" href="https://github.com/graphdeco-inria/diff-gaussian-rasterization">diff-gaussian-rasterization</a>. See <a class="reference internal" href="examples/large_scale.html"><span class="doc">Render a Large Scene</span></a> for an example.</p></li>
|
||||
<li><p><em>gsplat</em> offers many extra features, including <strong>batch rasterization</strong>,
|
||||
<strong>N-D feature rendering</strong>, <strong>depth rendering</strong>, <strong>sparse gradient</strong>,
|
||||
<strong>multi-GPU distributed rasterization</strong>
|
||||
etc. See <a class="reference internal" href="apis/rasterization.html"><span class="doc">Rasterization</span></a> for details.</p></li>
|
||||
<li><p><em>gsplat</em> is equipped with the <strong>latest and greatest</strong> 3D Gaussian Splatting techniques,
|
||||
including <a class="reference external" href="https://ty424.github.io/AbsGS.github.io/">absgrad</a>,
|
||||
<a class="reference external" href="https://niujinshuchong.github.io/mip-splatting/">anti-aliasing</a>,
|
||||
<a class="reference external" href="https://ubc-vision.github.io/3dgs-mcmc/">3DGS-MCMC</a> etc. And more to come!</p></li>
|
||||
</ul>
|
||||
<div style="position:relative; padding-bottom:56.25%; height:0; width:100%">
|
||||
<iframe style="position:absolute; top:0; left:0; width:100%; height:100%" src="https://www.youtube.com/embed/d5vOUYm5k34?si=fQBdwPgoi0FZOSyD" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
|
||||
</div></section>
|
||||
<section id="installation">
|
||||
<h2>Installation<a class="headerlink" href="#installation" title="Link to this heading">¶</a></h2>
|
||||
<p><em>gsplat</em> is available on PyPI and can be installed with pip:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>pip<span class="w"> </span>install<span class="w"> </span>gsplat
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>To get the latest features, it can also be installed from source:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>pip<span class="w"> </span>install<span class="w"> </span>git+https://github.com/nerfstudio-project/gsplat
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="contributing">
|
||||
<h2>Contributing<a class="headerlink" href="#contributing" title="Link to this heading">¶</a></h2>
|
||||
<p>This repository was born from the curiosity of people on the Nerfstudio team trying to
|
||||
understand a new rendering technique. We welcome contributions of any kind and are open
|
||||
to feedback, bug-reports, and improvements to help expand the capabilities of this software.</p>
|
||||
<p>This project is developed by the contributors coming from following institutes (unordered):</p>
|
||||
<ul class="simple">
|
||||
<li><p>UC Berkeley</p></li>
|
||||
<li><p>NVIDIA</p></li>
|
||||
<li><p>ShanghaiTech University</p></li>
|
||||
<li><p>Amazon</p></li>
|
||||
<li><p>Meta</p></li>
|
||||
<li><p>IIIT</p></li>
|
||||
<li><p>LumaAI</p></li>
|
||||
<li><p>SpectacularAI</p></li>
|
||||
<li><p>Aalto University</p></li>
|
||||
<li><p>CMU</p></li>
|
||||
</ul>
|
||||
</section>
|
||||
<section id="links">
|
||||
<h2>Links<a class="headerlink" href="#links" title="Link to this heading">¶</a></h2>
|
||||
<div class="toctree-wrapper compound">
|
||||
<p class="caption" role="heading"><span class="caption-text">Examples</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/colmap.html">Fit a COLMAP Capture</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/image.html">Fit a Single Image</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/large_scale.html">Render a Large Scene</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="examples/ncore.html">Train on an NCore v4 Capture</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="toctree-wrapper compound">
|
||||
<p class="caption" role="heading"><span class="caption-text">Conventions</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="conventions/data_conventions.html">Data Conventions</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="toctree-wrapper compound">
|
||||
<p class="caption" role="heading"><span class="caption-text">Python API</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/compression.html">Compression</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/rasterization.html">Rasterization</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/strategy.html">Densification</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="apis/utils.html">Utils</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="toctree-wrapper compound">
|
||||
<p class="caption" role="heading"><span class="caption-text">Tests</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="tests/eval.html">Evaluation</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="tests/profile.html">Profiling</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="tests/tests.html">Tests</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="toctree-wrapper compound">
|
||||
<p class="caption" role="heading"><span class="caption-text">Migration</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="migration/migration_inria.html">Migrate from diff-gaussian-rasterization</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="migration/migration_legacy.html">Migrate from gsplat v0.1.11</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
<section id="citations">
|
||||
<h2>Citations<a class="headerlink" href="#citations" title="Link to this heading">¶</a></h2>
|
||||
<div class="docutils container" id="id2">
|
||||
<div role="list" class="citation-list">
|
||||
<div class="citation" id="id3" role="doc-biblioentry">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p>Bernhard Kerbl, Georgios Kopanas, Thomas Leimkühler, and George Drettakis. 3d gaussian splatting for real-time radiance field rendering. <em>ACM Transactions on Graphics</em>, July 2023. URL: <a class="reference external" href="https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/">https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
</article>
|
||||
</div>
|
||||
<footer>
|
||||
|
||||
<div class="related-pages">
|
||||
<a class="next-page" href="examples/colmap.html">
|
||||
<div class="page-info">
|
||||
<div class="context">
|
||||
<span>Next</span>
|
||||
</div>
|
||||
<div class="title">Fit a COLMAP Capture</div>
|
||||
</div>
|
||||
<svg class="furo-related-icon"><use href="#svg-arrow-right"></use></svg>
|
||||
</a>
|
||||
|
||||
</div>
|
||||
<div class="bottom-of-page">
|
||||
<div class="left-details">
|
||||
<div class="copyright">
|
||||
Copyright © 2023, nerfstudio team
|
||||
</div>
|
||||
Made with <a href="https://www.sphinx-doc.org/">Sphinx</a> and <a class="muted-link" href="https://pradyunsg.me">@pradyunsg</a>'s
|
||||
|
||||
<a href="https://github.com/pradyunsg/furo">Furo</a>
|
||||
|
||||
</div>
|
||||
<div class="right-details">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</footer>
|
||||
</div>
|
||||
<aside class="toc-drawer">
|
||||
|
||||
|
||||
<div class="toc-sticky toc-scroll">
|
||||
<div class="toc-title-container">
|
||||
<span class="toc-title">
|
||||
On this page
|
||||
</span>
|
||||
</div>
|
||||
<div class="toc-tree-container">
|
||||
<div class="toc-tree">
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">gsplat</a><ul>
|
||||
<li><a class="reference internal" href="#overview">Overview</a></li>
|
||||
<li><a class="reference internal" href="#installation">Installation</a></li>
|
||||
<li><a class="reference internal" href="#contributing">Contributing</a></li>
|
||||
<li><a class="reference internal" href="#links">Links</a><ul>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#citations">Citations</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div><script src="_static/documentation_options.js?v=5929fcd5"></script>
|
||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||
<script async="async" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
|
@ -1,610 +0,0 @@
|
|||
<!doctype html>
|
||||
<html class="no-js" lang="en" >
|
||||
|
||||
<head><meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<meta name="color-scheme" content="light dark"><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />
|
||||
|
||||
<meta property="og:title" content="Splatfacto" />
|
||||
|
||||
<meta property="og:type" content="website" />
|
||||
|
||||
<meta property="og:url" content="http://docs.nerf.studio/nerfology/methods/splat.html" />
|
||||
|
||||
<meta property="og:description" content="Paper Website 3D Gaussian Splatting was proposed in SIGGRAPH 2023 from INRIA, and is a completely different method of representing radiance fields by explicitly storing a collection of 3D volumetri..." />
|
||||
|
||||
<meta property="og:image" content="https://assets.nerf.studio/opg.png" />
|
||||
|
||||
<meta property="og:image:alt" content="Splatfacto" />
|
||||
<link rel="index" title="Index" href="../../genindex.html" /><link rel="search" title="Search" href="../../search.html" /><link rel="next" title="Splatfacto in the Wild" href="splatw.html" /><link rel="prev" title="Instant-NGP" href="instant_ngp.html" />
|
||||
|
||||
<meta name="generator" content="sphinx-5.2.1, furo 2022.09.29" />
|
||||
<title>Splatfacto - nerfstudio</title>
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/styles/furo.css?digest=d81277517bee4d6b0349d71bb2661d4890b5617c" />
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/mystnb.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/togglebutton.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/copybutton.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/design-style.b7bb847fb20b106c3d81b95245e65545.min.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../../_static/styles/furo-extensions.css?digest=30d1aed668e5c3a91c3e3bf6a60b675221979f0e" />
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
body {
|
||||
--color-code-background: #f8f9fb;
|
||||
--color-code-foreground: black;
|
||||
--color-brand-primary: #d34600;
|
||||
--color-brand-content: #ff6f00;
|
||||
|
||||
}
|
||||
@media not print {
|
||||
body[data-theme="dark"] {
|
||||
--color-code-background: #282C34;
|
||||
--color-code-foreground: #ABB2BF;
|
||||
--color-brand-primary: #fdd06c;
|
||||
--color-brand-content: ##fea96a;
|
||||
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body:not([data-theme="light"]) {
|
||||
--color-code-background: #282C34;
|
||||
--color-code-foreground: #ABB2BF;
|
||||
--color-brand-primary: #fdd06c;
|
||||
--color-brand-content: ##fea96a;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
</style><script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
|
||||
<script src="../../_static/jquery.js"></script>
|
||||
<script src="../../_static/underscore.js"></script>
|
||||
<script src="../../_static/_sphinx_javascript_frameworks_compat.js"></script>
|
||||
<script src="../../_static/doctools.js"></script>
|
||||
<script src="../../_static/sphinx_highlight.js"></script>
|
||||
<script src="../../_static/scripts/furo.js"></script>
|
||||
<script src="../../_static/clipboard.min.js"></script>
|
||||
<script src="../../_static/copybutton.js"></script>
|
||||
<script>let toggleHintShow = 'Click to show';</script>
|
||||
<script>let toggleHintHide = 'Click to hide';</script>
|
||||
<script>let toggleOpenOnPrint = 'true';</script>
|
||||
<script src="../../_static/togglebutton.js"></script>
|
||||
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
|
||||
<script src="../../_static/design-tabs.js"></script>
|
||||
<script src="../../_static/require.min.js"></script>
|
||||
<script src="../../_static/custom.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<script>
|
||||
document.body.dataset.theme = localStorage.getItem("theme") || "auto";
|
||||
</script>
|
||||
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
|
||||
<symbol id="svg-toc" viewBox="0 0 24 24">
|
||||
<title>Contents</title>
|
||||
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024">
|
||||
<path d="M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM115.4 518.9L271.7 642c5.8 4.6 14.4.5 14.4-6.9V388.9c0-7.4-8.5-11.5-14.4-6.9L115.4 505.1a8.74 8.74 0 0 0 0 13.8z"/>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-menu" viewBox="0 0 24 24">
|
||||
<title>Menu</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather-menu">
|
||||
<line x1="3" y1="12" x2="21" y2="12"></line>
|
||||
<line x1="3" y1="6" x2="21" y2="6"></line>
|
||||
<line x1="3" y1="18" x2="21" y2="18"></line>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-arrow-right" viewBox="0 0 24 24">
|
||||
<title>Expand</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather-chevron-right">
|
||||
<polyline points="9 18 15 12 9 6"></polyline>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-sun" viewBox="0 0 24 24">
|
||||
<title>Light mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather-sun">
|
||||
<circle cx="12" cy="12" r="5"></circle>
|
||||
<line x1="12" y1="1" x2="12" y2="3"></line>
|
||||
<line x1="12" y1="21" x2="12" y2="23"></line>
|
||||
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
|
||||
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
|
||||
<line x1="1" y1="12" x2="3" y2="12"></line>
|
||||
<line x1="21" y1="12" x2="23" y2="12"></line>
|
||||
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
|
||||
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-moon" viewBox="0 0 24 24">
|
||||
<title>Dark mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon-tabler-moon">
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z" />
|
||||
</svg>
|
||||
</symbol>
|
||||
<symbol id="svg-sun-half" viewBox="0 0 24 24">
|
||||
<title>Auto light/dark mode</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon-tabler-shadow">
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M13 12h5" />
|
||||
<path d="M13 15h4" />
|
||||
<path d="M13 18h1" />
|
||||
<path d="M13 9h4" />
|
||||
<path d="M13 6h1" />
|
||||
</svg>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
||||
<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation">
|
||||
<input type="checkbox" class="sidebar-toggle" name="__toc" id="__toc">
|
||||
<label class="overlay sidebar-overlay" for="__navigation">
|
||||
<div class="visually-hidden">Hide navigation sidebar</div>
|
||||
</label>
|
||||
<label class="overlay toc-overlay" for="__toc">
|
||||
<div class="visually-hidden">Hide table of contents sidebar</div>
|
||||
</label>
|
||||
|
||||
|
||||
|
||||
<div class="page">
|
||||
<header class="mobile-header">
|
||||
<div class="header-left">
|
||||
<label class="nav-overlay-icon" for="__navigation">
|
||||
<div class="visually-hidden">Toggle site navigation sidebar</div>
|
||||
<i class="icon"><svg><use href="#svg-menu"></use></svg></i>
|
||||
</label>
|
||||
</div>
|
||||
<div class="header-center">
|
||||
<a href="../../index.html"><div class="brand">nerfstudio</div></a>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="theme-toggle-container theme-toggle-header">
|
||||
<button class="theme-toggle">
|
||||
<div class="visually-hidden">Toggle Light / Dark / Auto color theme</div>
|
||||
<svg class="theme-icon-when-auto"><use href="#svg-sun-half"></use></svg>
|
||||
<svg class="theme-icon-when-dark"><use href="#svg-moon"></use></svg>
|
||||
<svg class="theme-icon-when-light"><use href="#svg-sun"></use></svg>
|
||||
</button>
|
||||
</div>
|
||||
<label class="toc-overlay-icon toc-header-icon" for="__toc">
|
||||
<div class="visually-hidden">Toggle table of contents sidebar</div>
|
||||
<i class="icon"><svg><use href="#svg-toc"></use></svg></i>
|
||||
</label>
|
||||
</div>
|
||||
</header>
|
||||
<aside class="sidebar-drawer">
|
||||
<div class="sidebar-container">
|
||||
|
||||
<div class="sidebar-sticky"><a
|
||||
class="sidebar-brand"
|
||||
href="../../index.html"
|
||||
>
|
||||
|
||||
<div class="sidebar-logo-container">
|
||||
<img
|
||||
class="sidebar-logo only-light"
|
||||
src="../../_static/imgs/logo.png"
|
||||
alt="Light Logo"
|
||||
/>
|
||||
<img
|
||||
class="sidebar-logo only-dark"
|
||||
src="../../_static/imgs/logo-dark.png"
|
||||
alt="Dark Logo"
|
||||
/>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<div style="text-align: center">
|
||||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||||
<!-- Place this tag where you want the button to render. -->
|
||||
<a
|
||||
class="github-button"
|
||||
href="https://github.com/nerfstudio-project/nerfstudio/"
|
||||
data-color-scheme="no-preference: light; light: light; dark: light;"
|
||||
data-size="large"
|
||||
data-show-count="true"
|
||||
aria-label="Download buttons/github-buttons on GitHub"
|
||||
>
|
||||
Github
|
||||
</a>
|
||||
<br />
|
||||
<a
|
||||
href="https://colab.research.google.com/github/nerfstudio-project/nerfstudio/blob/main/colab/demo.ipynb"
|
||||
style="
|
||||
background-color: #ebf0f4;
|
||||
background-image: linear-gradient(180deg, #f6f8fa, #ebf0f4 90%);
|
||||
border-radius: 3px;
|
||||
border: 1px solid #1b1f2426;
|
||||
display: inline-flex;
|
||||
cursor: pointer;
|
||||
color: #0d0d0d;
|
||||
font-family: Arial;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
padding: 5px 41px;
|
||||
line-height: 16px;
|
||||
text-decoration: none;
|
||||
"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width="16"
|
||||
height="16"
|
||||
class="octicon octicon-mark-github"
|
||||
>
|
||||
<g>
|
||||
<path
|
||||
d="M4.54,9.46,2.19,7.1a6.93,6.93,0,0,0,0,9.79l2.36-2.36A3.59,3.59,0,0,1,4.54,9.46Z"
|
||||
style=""
|
||||
fill="#E8710A"
|
||||
></path>
|
||||
<path
|
||||
d="M2.19,7.1,4.54,9.46a3.59,3.59,0,0,1,5.08,0l1.71-2.93h0l-.1-.08h0A6.93,6.93,0,0,0,2.19,7.1Z"
|
||||
style=""
|
||||
fill="#F9AB00"
|
||||
></path>
|
||||
<path
|
||||
d="M11.34,17.46h0L9.62,14.54a3.59,3.59,0,0,1-5.08,0L2.19,16.9a6.93,6.93,0,0,0,9,.65l.11-.09"
|
||||
style=""
|
||||
fill="#F9AB00"
|
||||
></path>
|
||||
<path
|
||||
d="M12,7.1a6.93,6.93,0,0,0,0,9.79l2.36-2.36a3.59,3.59,0,1,1,5.08-5.08L21.81,7.1A6.93,6.93,0,0,0,12,7.1Z"
|
||||
style=""
|
||||
fill="#F9AB00"
|
||||
></path>
|
||||
<path
|
||||
d="M21.81,7.1,19.46,9.46a3.59,3.59,0,0,1-5.08,5.08L12,16.9A6.93,6.93,0,0,0,21.81,7.1Z"
|
||||
style=""
|
||||
fill="#E8710A"
|
||||
></path>
|
||||
</g>
|
||||
</svg>
|
||||
<span> colab</span></a
|
||||
>
|
||||
</div><form class="sidebar-search-container" method="get" action="../../search.html" role="search">
|
||||
<input class="sidebar-search" placeholder=Search name="q" aria-label="Search">
|
||||
<input type="hidden" name="check_keywords" value="yes">
|
||||
<input type="hidden" name="area" value="default">
|
||||
</form>
|
||||
<div id="searchbox"></div><div class="sidebar-scroll"><div class="sidebar-tree">
|
||||
<p class="caption" role="heading"><span class="caption-text">Getting Started</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/installation.html">Installation</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/first_nerf.html">Training your first model</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/existing_dataset.html">Using existing data</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/custom_dataset.html">Using custom data</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/viewer_quickstart.html">Using the viewer</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/export_geometry.html">Export geometry</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../quickstart/data_conventions.html">Data conventions</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../reference/contributing.html">Contributing</a></li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Extensions</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../extensions/blender_addon.html">Blender VFX add-on</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../extensions/maya_plugin.html">Autodesk Maya Plug-in</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../extensions/unreal_engine.html">Exporting to Unreal Engine</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../extensions/sdfstudio.html">SDFStudio</a></li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">NeRFology</span></p>
|
||||
<ul class="current">
|
||||
<li class="toctree-l1 current has-children"><a class="reference internal" href="index.html">Methods</a><input checked="" class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" role="switch" type="checkbox"/><label for="toctree-checkbox-1"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul class="current">
|
||||
<li class="toctree-l2"><a class="reference internal" href="instant_ngp.html"> Instant-NGP</a></li>
|
||||
<li class="toctree-l2 current current-page"><a class="current reference internal" href="#"> Splatfacto</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="splatw.html"> Splatfacto-W</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="in2n.html"> Instruct-NeRF2NeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="igs2gs.html"> Instruct-GS2GS</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="signerf.html"> SIGNeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="kplanes.html"> K-Planes</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="lerf.html"> LERF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="livescene.html"> LiveScene</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="feature_splatting.html"> Feature-Splatting</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="mipnerf.html"> Mip-NeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="nerf.html"> NeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="nerfacto.html"> Nerfacto</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="nerfbusters.html"> Nerfbusters</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="nerfplayer.html"> NeRFPlayer</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="tetranerf.html"> Tetra-NeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="tensorf.html"> TensoRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="generfacto.html"> Generfacto</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="pynerf.html"> PyNeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="seathru_nerf.html"> SeaThru-NeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="zipnerf.html"> Zip-NeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="bionerf.html"> BioNeRF</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="nerf2gs2nerf.html"> NeRFtoGSandBack</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="opennerf.html"> OpenNeRF</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1 has-children"><a class="reference internal" href="../model_components/index.html">Model components</a><input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" role="switch" type="checkbox"/><label for="toctree-checkbox-2"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../model_components/visualize_cameras.html"> Cameras models</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../model_components/visualize_samples.html"> Sample representation</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../model_components/visualize_samplers.html"> Ray samplers</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../model_components/visualize_spatial_distortions.html"> Spatial distortions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../model_components/visualize_encoders.html"> Encoders</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Developer Guides</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../developer_guides/new_methods.html">Adding a New Method</a></li>
|
||||
<li class="toctree-l1 has-children"><a class="reference internal" href="../../developer_guides/pipelines/index.html">Pipelines overview</a><input class="toctree-checkbox" id="toctree-checkbox-3" name="toctree-checkbox-3" role="switch" type="checkbox"/><label for="toctree-checkbox-3"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l2 has-children"><a class="reference internal" href="../../developer_guides/pipelines/dataparsers.html">DataParsers</a><input class="toctree-checkbox" id="toctree-checkbox-4" name="toctree-checkbox-4" role="switch" type="checkbox"/><label for="toctree-checkbox-4"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/data/dataparsers.html">Data Parsers</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/pipelines/datamanagers.html">DataManagers</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/pipelines/models.html">Models</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/pipelines/fields.html">Fields</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/pipelines/pipelines.html">Pipelines</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1 has-children"><a class="reference internal" href="../../developer_guides/viewer/index.html">Viewer</a><input class="toctree-checkbox" id="toctree-checkbox-5" name="toctree-checkbox-5" role="switch" type="checkbox"/><label for="toctree-checkbox-5"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/viewer/custom_gui.html">Custom GUI</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/viewer/viewer_control.html">Python Viewer Control</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/viewer/local_viewer.html">(Legacy Viewer) Local Server</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="../../developer_guides/config.html">Customizable configs</a></li>
|
||||
<li class="toctree-l1 has-children"><a class="reference internal" href="../../developer_guides/debugging_tools/index.html">Debugging tools</a><input class="toctree-checkbox" id="toctree-checkbox-6" name="toctree-checkbox-6" role="switch" type="checkbox"/><label for="toctree-checkbox-6"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/debugging_tools/local_logger.html">Local writer</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/debugging_tools/profiling.html">Code profiling support</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../developer_guides/debugging_tools/benchmarking.html">Benchmarking workflow</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="caption" role="heading"><span class="caption-text">Reference</span></p>
|
||||
<ul>
|
||||
<li class="toctree-l1 has-children"><a class="reference internal" href="../../reference/cli/index.html">CLI</a><input class="toctree-checkbox" id="toctree-checkbox-7" name="toctree-checkbox-7" role="switch" type="checkbox"/><label for="toctree-checkbox-7"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_install_cli.html">ns-install-cli</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_process_data.html">ns-process-data</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_download_data.html">ns-download-data</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_train.html">ns-train</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_render.html">ns-render</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_viewer.html">ns-viewer</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_export.html">ns-export</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/cli/ns_eval.html">ns-eval</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1 has-children"><a class="reference internal" href="../../reference/api/index.html">API</a><input class="toctree-checkbox" id="toctree-checkbox-8" name="toctree-checkbox-8" role="switch" type="checkbox"/><label for="toctree-checkbox-8"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/cameras.html">Cameras</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/config.html">Configs</a></li>
|
||||
<li class="toctree-l2 has-children"><a class="reference internal" href="../../reference/api/data/index.html">Data</a><input class="toctree-checkbox" id="toctree-checkbox-9" name="toctree-checkbox-9" role="switch" type="checkbox"/><label for="toctree-checkbox-9"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/data/dataparsers.html">Data Parsers</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/data/datamanagers.html">Datamanagers</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/data/datasets.html">Datasets</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/data/utils.html">Utils</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/fields.html">Fields</a></li>
|
||||
<li class="toctree-l2 has-children"><a class="reference internal" href="../../reference/api/field_components/index.html">Field Modules</a><input class="toctree-checkbox" id="toctree-checkbox-10" name="toctree-checkbox-10" role="switch" type="checkbox"/><label for="toctree-checkbox-10"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/field_components/encodings.html">Encodings</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/field_components/embeddings.html">Embeddings</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/field_components/field_heads.html">Field Heads</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/field_components/mlp.html">MLP</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/field_components/spatial_distortions.html">Spatial Distortions</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/models.html">Models</a></li>
|
||||
<li class="toctree-l2 has-children"><a class="reference internal" href="../../reference/api/model_components/index.html">Model components</a><input class="toctree-checkbox" id="toctree-checkbox-11" name="toctree-checkbox-11" role="switch" type="checkbox"/><label for="toctree-checkbox-11"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/model_components/ray_sampler.html">Ray Sampler</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/model_components/losses.html">Losses</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/model_components/renderers.html">Renderers</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/optimizers.html">Engine</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/plugins.html">Plugins</a></li>
|
||||
<li class="toctree-l2 has-children"><a class="reference internal" href="../../reference/api/utils/index.html">Utils</a><input class="toctree-checkbox" id="toctree-checkbox-12" name="toctree-checkbox-12" role="switch" type="checkbox"/><label for="toctree-checkbox-12"><div class="visually-hidden">Toggle child pages in navigation</div><i class="icon"><svg><use href="#svg-arrow-right"></use></svg></i></label><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/utils/colors.html">Colors</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/utils/math.html">Math</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/utils/colormaps.html">Colormaps</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="../../reference/api/utils/tensor_dataclass.html">TensorDataclass</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="../../reference/api/viewer.html">Viewer</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<div class="content">
|
||||
<div class="article-container">
|
||||
<a href="#" class="back-to-top muted-link">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8v12z"></path>
|
||||
</svg>
|
||||
<span>Back to top</span>
|
||||
</a>
|
||||
<div class="content-icon-container">
|
||||
|
||||
<div class="theme-toggle-container theme-toggle-content">
|
||||
<button class="theme-toggle">
|
||||
<div class="visually-hidden">Toggle Light / Dark / Auto color theme</div>
|
||||
<svg class="theme-icon-when-auto"><use href="#svg-sun-half"></use></svg>
|
||||
<svg class="theme-icon-when-dark"><use href="#svg-moon"></use></svg>
|
||||
<svg class="theme-icon-when-light"><use href="#svg-sun"></use></svg>
|
||||
</button>
|
||||
</div>
|
||||
<label class="toc-overlay-icon toc-content-icon" for="__toc">
|
||||
<div class="visually-hidden">Toggle table of contents sidebar</div>
|
||||
<i class="icon"><svg><use href="#svg-toc"></use></svg></i>
|
||||
</label>
|
||||
</div>
|
||||
<article role="main">
|
||||
<section class="tex2jax_ignore mathjax_ignore" id="splatfacto">
|
||||
<h1>Splatfacto<a class="headerlink" href="#splatfacto" title="Permalink to this heading">#</a></h1>
|
||||
<h4>Nerfstudio's Gaussian Splatting Implementation</h4>
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/0yueTFx-MdQ?si=GxiYnFAeYVVl-soJ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
|
||||
<p><a class="sd-sphinx-override sd-btn sd-text-wrap sd-btn-outline-primary reference external" href="https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/"><span>Paper Website</span></a></p>
|
||||
<p><a class="reference external" href="https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/">3D Gaussian Splatting</a> was proposed in SIGGRAPH 2023 from INRIA, and is a completely different method of representing radiance fields by explicitly storing a collection of 3D volumetric gaussians. These can be “splatted”, or projected, onto a 2D image provided a camera pose, and rasterized to obtain per-pixel colors. Because rasterization is very fast on GPUs, this method can render much faster than neural representations of radiance fields.</p>
|
||||
<p>To avoid confusion with the original paper, we refer to nerfstudio’s implementation as “Splatfacto”, which will drift away from the original as more features are added. Just as Nerfacto is a blend of various different methods, Splatfacto will be a blend of different gaussian splatting methodologies.</p>
|
||||
<section id="installation">
|
||||
<h2>Installation<a class="headerlink" href="#installation" title="Permalink to this heading">#</a></h2>
|
||||
<p><a class="sd-sphinx-override sd-btn sd-text-wrap sd-btn-outline-primary reference external" href="https://docs.gsplat.studio/"><span>GSplat </span></a></p>
|
||||
<p>Nerfstudio uses <a class="reference external" href="https://github.com/nerfstudio-project/gsplat">gsplat</a> as its gaussian rasterization backend, an in-house re-implementation which is designed to be more developer friendly. This can be installed with <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">gsplat</span></code>. The associated CUDA code will be compiled the first time gsplat is executed. Some users with PyTorch 2.0 have experienced issues with this, which can be resolved by either installing gsplat from source, or upgrading torch to 2.1.</p>
|
||||
</section>
|
||||
<section id="data">
|
||||
<h2>Data<a class="headerlink" href="#data" title="Permalink to this heading">#</a></h2>
|
||||
<p>Gaussian splatting works much better if you initialize it from pre-existing geometry, such as SfM points from COLMAP. COLMAP datasets or datasets from <code class="docutils literal notranslate"><span class="pre">ns-process-data</span></code> will automatically save these points and initialize gaussians on them. Other datasets currently do not support initialization, and will initialize gaussians randomly. Initializing from other data inputs (i.e. depth from phone app scanners) may be supported in the future.</p>
|
||||
<p>Because the method trains on <em>full images</em> instead of bundles of rays, there is a new datamanager in <code class="docutils literal notranslate"><span class="pre">full_images_datamanager.py</span></code> which undistorts input images, caches them, and provides single images at each train step.</p>
|
||||
</section>
|
||||
<section id="running-the-method">
|
||||
<h2>Running the Method<a class="headerlink" href="#running-the-method" title="Permalink to this heading">#</a></h2>
|
||||
<p>To run splatfacto, run <code class="docutils literal notranslate"><span class="pre">ns-train</span> <span class="pre">splatfacto</span> <span class="pre">--data</span> <span class="pre"><data></span></code>. Just like NeRF methods, the splat can be interactively viewed in the web-viewer, loaded from a checkpoint, rendered, and exported.</p>
|
||||
<p>We provide a few additional variants:</p>
|
||||
<div class="table-wrapper colwidths-auto docutils container">
|
||||
<table class="docutils align-default">
|
||||
<thead>
|
||||
<tr class="row-odd"><th class="head"><p>Method</p></th>
|
||||
<th class="head"><p>Description</p></th>
|
||||
<th class="head"><p>Memory</p></th>
|
||||
<th class="head"><p>Speed</p></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">splatfacto</span></code></p></td>
|
||||
<td><p>Default Model</p></td>
|
||||
<td><p>~6GB</p></td>
|
||||
<td><p>Fast</p></td>
|
||||
</tr>
|
||||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">splatfacto-big</span></code></p></td>
|
||||
<td><p>More Gaussians, Higher Quality</p></td>
|
||||
<td><p>~12GB</p></td>
|
||||
<td><p>Slower</p></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p>A full evalaution of Nerfstudio’s implementation of Gaussian Splatting against the original Inria method can be found <a class="reference external" href="https://docs.gsplat.studio/main/tests/eval.html">here</a>.</p>
|
||||
<section id="quality-and-regularization">
|
||||
<h3>Quality and Regularization<a class="headerlink" href="#quality-and-regularization" title="Permalink to this heading">#</a></h3>
|
||||
<p>The default settings provided maintain a balance between speed, quality, and splat file size, but if you care more about quality than training speed or size, you can decrease the alpha cull threshold
|
||||
(threshold to delete translucent gaussians) and disable culling after 15k steps like so: <code class="docutils literal notranslate"><span class="pre">ns-train</span> <span class="pre">splatfacto</span> <span class="pre">--pipeline.model.cull_alpha_thresh=0.005</span> <span class="pre">--pipeline.model.continue_cull_post_densification=False</span> <span class="pre">--data</span> <span class="pre"><data></span></code></p>
|
||||
<p>A common artifact in splatting is long, spikey gaussians. <a class="reference external" href="https://xpandora.github.io/PhysGaussian/">PhysGaussian</a> proposes a scale regularizer that encourages gaussians to be more evenly shaped. To enable this, set the <code class="docutils literal notranslate"><span class="pre">pipeline.model.use_scale_regularization</span></code> flag to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
|
||||
</section>
|
||||
</section>
|
||||
<section id="details">
|
||||
<h2>Details<a class="headerlink" href="#details" title="Permalink to this heading">#</a></h2>
|
||||
<p>For more details on the method, see the <a class="reference external" href="https://arxiv.org/abs/2308.04079">original paper</a>. Additionally, for a detailed derivation of the gradients used in the gsplat library, see <a class="reference external" href="https://arxiv.org/abs/2312.02121">here</a>.</p>
|
||||
</section>
|
||||
<section id="exporting-splats">
|
||||
<h2>Exporting splats<a class="headerlink" href="#exporting-splats" title="Permalink to this heading">#</a></h2>
|
||||
<p>Gaussian splats can be exported as a <code class="docutils literal notranslate"><span class="pre">.ply</span></code> file which are ingestable by a variety of online web viewers. You can do this via the viewer, or <code class="docutils literal notranslate"><span class="pre">ns-export</span> <span class="pre">gaussian-splat</span> <span class="pre">--load-config</span> <span class="pre"><config></span> <span class="pre">--output-dir</span> <span class="pre">exports/splat</span></code>. Currently splats can only be exported from trained splats, not from nerfacto.</p>
|
||||
<p>Nerfstudio’s splat export currently supports multiple third-party splat viewers:</p>
|
||||
<ul class="simple">
|
||||
<li><p><a class="reference external" href="https://poly.cam/tools/gaussian-splatting">Polycam Viewer</a></p></li>
|
||||
<li><p><a class="reference external" href="https://playcanvas.com/super-splat">Playcanvas SuperSplat</a></p></li>
|
||||
<li><p><a class="reference external" href="https://antimatter15.com/splat/">WebGL Viewer by antimatter15</a></p></li>
|
||||
<li><p><a class="reference external" href="https://spline.design/">Spline</a></p></li>
|
||||
<li><p><a class="reference external" href="https://github.com/mkkellogg/GaussianSplats3D">Three.js Viewer by mkkellogg</a></p></li>
|
||||
</ul>
|
||||
</section>
|
||||
<section id="faq">
|
||||
<h2>FAQ<a class="headerlink" href="#faq" title="Permalink to this heading">#</a></h2>
|
||||
<ul class="simple">
|
||||
<li><p>Can I export a mesh or pointcloud?</p></li>
|
||||
</ul>
|
||||
<p>Currently these export options are not supported, but may be in the future. Contributions are always welcome!</p>
|
||||
<ul class="simple">
|
||||
<li><p>Can I render fisheye, equirectangular, orthographic images?</p></li>
|
||||
</ul>
|
||||
<p>Currently, no. Gaussian rasterization assumes a perspective camera for its rasterization pipeline. Implementing other camera models is of interest but not currently planned.</p>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
</article>
|
||||
</div>
|
||||
<footer>
|
||||
|
||||
<div class="related-pages">
|
||||
<a class="next-page" href="splatw.html">
|
||||
<div class="page-info">
|
||||
<div class="context">
|
||||
<span>Next</span>
|
||||
</div>
|
||||
<div class="title">Splatfacto in the Wild</div>
|
||||
</div>
|
||||
<svg class="furo-related-icon"><use href="#svg-arrow-right"></use></svg>
|
||||
</a>
|
||||
<a class="prev-page" href="instant_ngp.html">
|
||||
<svg class="furo-related-icon"><use href="#svg-arrow-right"></use></svg>
|
||||
<div class="page-info">
|
||||
<div class="context">
|
||||
<span>Previous</span>
|
||||
</div>
|
||||
|
||||
<div class="title">Instant-NGP</div>
|
||||
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
<div class="bottom-of-page">
|
||||
<div class="left-details">
|
||||
<div class="copyright">
|
||||
Copyright © 2022, nerfstudio Team
|
||||
</div>
|
||||
Made with <a href="https://www.sphinx-doc.org/">Sphinx</a> and <a class="muted-link" href="https://pradyunsg.me">@pradyunsg</a>'s
|
||||
|
||||
<a href="https://github.com/pradyunsg/furo">Furo</a>
|
||||
|
||||
</div>
|
||||
<div class="right-details">
|
||||
<div class="icons">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</footer>
|
||||
</div>
|
||||
<aside class="toc-drawer">
|
||||
|
||||
|
||||
<div class="toc-sticky toc-scroll">
|
||||
<div class="toc-title-container">
|
||||
<span class="toc-title">
|
||||
On this page
|
||||
</span>
|
||||
</div>
|
||||
<div class="toc-tree-container">
|
||||
<div class="toc-tree">
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">Splatfacto</a><ul>
|
||||
<li><a class="reference internal" href="#installation">Installation</a></li>
|
||||
<li><a class="reference internal" href="#data">Data</a></li>
|
||||
<li><a class="reference internal" href="#running-the-method">Running the Method</a><ul>
|
||||
<li><a class="reference internal" href="#quality-and-regularization">Quality and Regularization</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#details">Details</a></li>
|
||||
<li><a class="reference internal" href="#exporting-splats">Exporting splats</a></li>
|
||||
<li><a class="reference internal" href="#faq">FAQ</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div></body>
|
||||
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load diff
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue