From 7f811d5e5ee9717169674b22fdc5742e3f621512 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 17:41:36 +0100 Subject: [PATCH] Add room suppression stage --- audio_field/room_suppression.py | 113 ++++++++++++++++++++++++++++++++ docs/audio-field.md | 10 +++ scripts/audio_field.py | 82 +++++++++++++++++++++++ tests/test_room_suppression.py | 37 +++++++++++ 4 files changed, 242 insertions(+) create mode 100644 audio_field/room_suppression.py create mode 100644 tests/test_room_suppression.py diff --git a/audio_field/room_suppression.py b/audio_field/room_suppression.py new file mode 100644 index 0000000..faa0535 --- /dev/null +++ b/audio_field/room_suppression.py @@ -0,0 +1,113 @@ +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) diff --git a/docs/audio-field.md b/docs/audio-field.md index ddf0aea..b99bb63 100644 --- a/docs/audio-field.md +++ b/docs/audio-field.md @@ -165,6 +165,15 @@ Encode an offline aligned six-channel WAV to FOA AmbiX: .\.venv\Scripts\python.exe .\scripts\audio_field.py encode-foa --profile .\config\audio-field.json --input .\calibration\runs\\field-aligned.wav --output .\calibration\runs\\field-foa-ambix.wav ``` +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\\field-aligned.wav --output .\calibration\runs\\field-cleaned.wav +.\.venv\Scripts\python.exe .\scripts\audio_field.py encode-foa --profile .\config\audio-field.json --input .\calibration\runs\\field-cleaned.wav --output .\calibration\runs\\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. + 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 @@ -193,6 +202,7 @@ The audio code is split so the hard parts can be tested without the room, driver - `audio_field.pipeline` wires those ports together without knowing whether the source is a real Focusrite, an SRT receiver, a WAV fixture, or a test double. - The next runtime estimator module should own chirplet observations, delay/SRO/phase state, confidence gates, and phase-field updates. It should feed the aligner; it should not be hidden inside the FOA encoder. - The active probe optimizer owns whether to emit extra chirplets. It reads sync confidence and probe budget, then decides when and where an intentional chirplet is worth the cost. +- 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. - `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. diff --git a/scripts/audio_field.py b/scripts/audio_field.py index d60480f..ceecfea 100644 --- a/scripts/audio_field.py +++ b/scripts/audio_field.py @@ -33,6 +33,20 @@ SmoothPhaseField = _phase_fit.SmoothPhaseField estimate_phase_delay = _phase_fit.estimate_phase_delay +def load_room_suppression_module(): + spec = importlib.util.spec_from_file_location("localcast_room_suppression", ROOT / "audio_field" / "room_suppression.py") + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +_room_suppression = load_room_suppression_module() +RoomSuppressionConfig = _room_suppression.RoomSuppressionConfig +suppress_room_field = _room_suppression.suppress_room_field + + def utc_stamp() -> str: return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ") @@ -1708,6 +1722,57 @@ def cmd_encode_foa(args): print(json.dumps({"output": str(args.output), "sampleRate": int(sample_rate), "channels": ["W", "Y", "Z", "X"], "peakBeforeLimit": peak}, indent=2)) +def cmd_suppress_room(args): + profile = load_profile(args.profile) + sample_rate, data = wavfile.read(args.input) + field = as_float_matrix(data) + anchors = infer_anchor_channels(profile) if not args.anchor_channel else [int(value) for value in args.anchor_channel] + witnesses = infer_witness_channels(profile, anchors) if not args.witness_channel else [int(value) for value in args.witness_channel] + config = RoomSuppressionConfig( + block_size=int(args.block_size), + hop_size=int(args.hop_size), + transient_ratio=float(args.transient_ratio), + max_witness_attenuation_db=float(args.max_witness_attenuation_db), + anchor_transient_attenuation_db=float(args.anchor_transient_attenuation_db), + room_subtraction=float(args.room_subtraction), + envelope_floor=float(args.envelope_floor), + ) + cleaned, report = suppress_room_field(field, anchors, witnesses, config) + output = args.output or args.input.with_name(args.input.stem + "-room-suppressed.wav") + peak = float(np.max(np.abs(cleaned))) if cleaned.size else 0.0 + if args.limit_peak and peak > float(args.limit_peak): + cleaned = cleaned * (float(args.limit_peak) / peak) + wavfile.write(output, int(sample_rate), cleaned.astype(np.float32)) + result = { + "output": str(output), + "sampleRate": int(sample_rate), + "shape": list(cleaned.shape), + "anchors": anchors, + "witnesses": witnesses, + "transientBlocks": report.transient_blocks, + "meanWitnessGain": report.mean_witness_gain, + "meanAnchorGain": report.mean_anchor_gain, + "peakBeforeLimit": peak, + } + report_path = args.report or output.with_suffix(".room-suppression.json") + write_json(report_path, result) + print(json.dumps(result, indent=2)) + + +def infer_anchor_channels(profile): + anchors = [] + for mic in profile["microphones"]: + role = str(mic.get("role", "")) + if "dialogue-anchor" in role or int(mic.get("qualityPriority", 0)) >= 100: + anchors.append(mic_channel(mic)) + return sorted(set(anchors)) + + +def infer_witness_channels(profile, anchors): + anchor_set = set(int(channel) for channel in anchors) + return [mic_channel(mic) for mic in sorted(profile["microphones"], key=mic_channel) if mic_channel(mic) not in anchor_set] + + def cmd_sync_plan(args): profile = load_profile(args.profile) groups = {} @@ -1956,6 +2021,23 @@ def main(): p.add_argument("--output", type=Path, required=True) p.set_defaults(func=cmd_encode_foa) + p = sub.add_parser("suppress-room", help="Suppress room/transient witness energy before FOA encoding.") + p.add_argument("--profile", type=Path, default=ROOT / "config" / "audio-field.example.json") + p.add_argument("--input", type=Path, required=True) + p.add_argument("--output", type=Path) + p.add_argument("--report", type=Path) + p.add_argument("--anchor-channel", type=int, action="append") + p.add_argument("--witness-channel", type=int, action="append") + p.add_argument("--block-size", type=int, default=1024) + p.add_argument("--hop-size", type=int, default=512) + p.add_argument("--transient-ratio", type=float, default=2.5) + p.add_argument("--max-witness-attenuation-db", type=float, default=-18.0) + p.add_argument("--anchor-transient-attenuation-db", type=float, default=-6.0) + p.add_argument("--room-subtraction", type=float, default=0.15) + p.add_argument("--envelope-floor", type=float, default=1e-5) + p.add_argument("--limit-peak", type=float, default=0.98) + p.set_defaults(func=cmd_suppress_room) + args = parser.parse_args() args.func(args) diff --git a/tests/test_room_suppression.py b/tests/test_room_suppression.py new file mode 100644 index 0000000..d5fcf57 --- /dev/null +++ b/tests/test_room_suppression.py @@ -0,0 +1,37 @@ +import unittest + +import numpy as np + +from audio_field.room_suppression import RoomSuppressionConfig, suppress_room_field + + +class RoomSuppressionTests(unittest.TestCase): + def test_witness_only_click_is_suppressed_without_killing_anchor(self): + field = np.zeros((4096, 3), dtype=np.float32) + t = np.arange(4096, dtype=np.float32) / 48000.0 + field[:, 0] = 0.05 * np.sin(2 * np.pi * 220 * t) + field[1600:1604, 1] = 1.0 + field[1600:1604, 2] = -0.8 + + cleaned, report = suppress_room_field( + field, + anchor_channels=[0], + witness_channels=[1, 2], + config=RoomSuppressionConfig(block_size=512, hop_size=256, transient_ratio=2.0, max_witness_attenuation_db=-24.0), + ) + + self.assertGreater(report.transient_blocks, 0) + self.assertLess(float(np.max(np.abs(cleaned[1600:1604, 1]))), 0.2) + self.assertGreater(float(np.max(np.abs(cleaned[:, 0]))), 0.03) + + def test_no_witnesses_returns_copy(self): + field = np.ones((16, 2), dtype=np.float32) + + cleaned, report = suppress_room_field(field, anchor_channels=[0], witness_channels=[]) + + np.testing.assert_allclose(cleaned, field) + self.assertEqual(0, report.transient_blocks) + + +if __name__ == "__main__": + unittest.main()