Remove Electron and make Rust Slint the sole native client
This commit is contained in:
1 parent
eb24965076
commit
220852f8cb
720 files changed
+2535
-130856
No files matched your search
+6
-6
@@ -1,22 +1,22 @@
|
||||
# Microphone noise reduction for the renderer's AudioWorklet, compiled to a zero-import
|
||||
# WebAssembly module (app/renderer/assets/audio/denoise.wasm) by scripts/build-denoise.mjs.
|
||||
# Workspace package; the root denoise profile preserves the shipped WASM build settings.
|
||||
# Native microphone capture processing for the dedicated audio worker.
|
||||
[package]
|
||||
name = "teamspeach-denoise"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
publish = false
|
||||
description = "TeamsPeach native capture DSP and reference WASM noise reduction"
|
||||
description = "TeamsPeach native capture DSP"
|
||||
|
||||
[lib]
|
||||
crate-type = ["rlib", "cdylib"]
|
||||
crate-type = ["rlib"]
|
||||
path = "src/lib.rs"
|
||||
|
||||
# Exact pins: the shipped DSP must not change behind a lockfile refresh.
|
||||
# Native capture uses sonora AEC3, noise suppression and adaptive AGC2 together.
|
||||
# The reference WASM exports retain the standalone sonora-ns filter-bank path.
|
||||
# The standalone noise-only behavioral reference is compiled only for Rust tests.
|
||||
[dependencies]
|
||||
sonora = "=0.2.0"
|
||||
|
||||
[dev-dependencies]
|
||||
sonora-ns = "=0.2.0"
|
||||
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
//! Direct, normalized 10 ms capture processing for the native audio worker.
|
||||
//!
|
||||
//! Sonora owns the split/filter/synthesis path. Never put `Denoiser`, another noise
|
||||
//! suppressor, or OS/WebRTC AEC in front of this processor. The caller supplies the
|
||||
//! actual post-gain playout mix, aligned to the capture clock, before capture processing.
|
||||
//! Sonora owns the split/filter/synthesis path. Never put another noise suppressor
|
||||
//! or OS/WebRTC AEC in front of this processor. The caller supplies the actual
|
||||
//! post-gain playout mix, aligned to the capture clock, before capture processing.
|
||||
//!
|
||||
//! Sonora's integrated NS also enables its split-band high-pass filter. The legacy
|
||||
//! noise-only `Denoiser` does not; waveform equivalence to that wrapper is not promised.
|
||||
//! Sonora's integrated NS also enables its split-band high-pass filter. The test-only
|
||||
//! noise-only reference does not; waveform equivalence to that wrapper is not promised.
|
||||
|
||||
use std::{error::Error, fmt};
|
||||
|
||||
|
||||
+7
-515
@@ -1,527 +1,19 @@
|
||||
//! TeamsPeach 48 kHz mono capture processing.
|
||||
//!
|
||||
//! Native workers use [`CaptureProcessor`]: one Sonora APM for AEC3, noise suppression and
|
||||
//! adaptive AGC2, with a separate render-reference input. No pointer ABI is used by native code.
|
||||
//! adaptive AGC2, with a separate render-reference input. No pointer ABI is exposed.
|
||||
//! Device callbacks must not run DSP; the processor belongs to the dedicated audio worker.
|
||||
//! Frames use normalized samples. Sonora owns internal buffers, so processing makes no
|
||||
//! end-to-end allocation-free or lock-free guarantee.
|
||||
//!
|
||||
//! The legacy [`Denoiser`] below remains the reference renderer's noise-only implementation.
|
||||
//! Its WebAssembly exports exist only on `wasm32`; it is not chained into native processing.
|
||||
//!
|
||||
//! # Processing
|
||||
//!
|
||||
//! WebRTC noise suppression as ported by sonora (pure Rust, BSD-3-Clause), wired the way the
|
||||
//! WebRTC audio processing module runs it at 48 kHz:
|
||||
//!
|
||||
//! 1. the 480-sample fullband frame is split by the WebRTC three-band QMF filter bank into
|
||||
//! 0–8, 8–16 and 16–24 kHz bands of 160 samples each;
|
||||
//! 2. the noise suppressor analyses and filters the 0–8 kHz band, and derives one gain for the
|
||||
//! upper bands from its speech probability and filter gains;
|
||||
//! 3. the upper bands are delayed to stay aligned with the lower band and scaled by that gain;
|
||||
//! 4. the three bands are merged back into 480 samples.
|
||||
//!
|
||||
//! Internally sonora works on the WebRTC "FloatS16" scale (±32768); the ABI uses normalized
|
||||
//! samples and converts at the boundary exactly like WebRTC's `FloatToFloatS16`/`FloatS16ToFloat`.
|
||||
//!
|
||||
//! Levels map 1:1 onto WebRTC's suppression levels, which are also the TeamSpeak labels:
|
||||
//! `0` Low (6 dB), `1` Moderate (12 dB, default), `2` High (18 dB), `3` Very High (21 dB).
|
||||
//!
|
||||
//! Fixed algorithmic delay: the suppressor's 96-sample overlap at 16 kHz (6 ms) plus the
|
||||
//! filter bank's short FIR delay — roughly 6.5 ms in total. Every input frame yields exactly one
|
||||
//! output frame, in order. After creation or reset the noise estimate converges over the first
|
||||
//! ~0.5–2 s (WebRTC's 50/200-block startup phases).
|
||||
//!
|
||||
//! # WebAssembly ABI
|
||||
//!
|
||||
//! The module imports nothing and exports `memory` plus:
|
||||
//!
|
||||
//! | export | signature | meaning |
|
||||
//! |---|---|---|
|
||||
//! | `dsp_new` | `(level: u32) -> u32` | new instance; handle, or `0` for an invalid level or a full instance table ([`MAX_INSTANCES`]) |
|
||||
//! | `dsp_input` | `(handle: u32) -> u32` | byte offset in `memory` of the instance's frame: 480 `f32`, 4-byte aligned, stable for the handle's lifetime (resets included); `0` for an invalid handle |
|
||||
//! | `dsp_process` | `(handle: u32) -> u32` | process the frame in place; status below |
|
||||
//! | `dsp_reset` | `(handle: u32, level: u32) -> u32` | discard all signal state, zero the frame and switch level; status below |
|
||||
//! | `dsp_free` | `(handle: u32)` | release the instance; invalid or stale handles are ignored |
|
||||
//!
|
||||
//! Frame samples are normalized: input is clamped to `[-1, 1]`, output lies in `[-1, 1]`.
|
||||
//!
|
||||
//! Status codes: [`STATUS_OK`] `0`, [`STATUS_INVALID_HANDLE`] `1`, [`STATUS_NON_FINITE_INPUT`] `2`
|
||||
//! (frame zeroed, signal state untouched), [`STATUS_INVALID_LEVEL`] `3` (state unchanged).
|
||||
//!
|
||||
//! Handles carry a generation counter, so a handle stays invalid after `dsp_free` even when its
|
||||
//! slot is reused. `dsp_new` and `dsp_reset` allocate (and may grow `memory`, detaching typed-array
|
||||
//! views). Native processing has no end-to-end allocation guarantee; Sonora owns internal buffers.
|
||||
//! The former renderer's noise-only processing is retained solely as a test reference,
|
||||
//! including its attenuation, reset, isolation, clamping and rejected-input behavior tests.
|
||||
|
||||
mod capture;
|
||||
pub use capture::{CaptureError, CaptureProcessor, CaptureSettings};
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use sonora::three_band_filter_bank::{
|
||||
FULL_BAND_SIZE, NUM_BANDS, SPLIT_BAND_SIZE, ThreeBandFilterBank,
|
||||
};
|
||||
use sonora_ns::config::{NS_FRAME_SIZE, NsConfig, SuppressionLevel};
|
||||
use sonora_ns::noise_suppressor::NoiseSuppressor;
|
||||
|
||||
/// Samples per frame: 10 ms of 48 kHz mono audio.
|
||||
pub const FRAME_SAMPLES: usize = FULL_BAND_SIZE;
|
||||
/// Highest accepted level (Very High).
|
||||
pub const MAX_LEVEL: u32 = 3;
|
||||
/// Instances that may exist at once in one module instance.
|
||||
pub const MAX_INSTANCES: usize = 16;
|
||||
|
||||
pub const STATUS_OK: u32 = 0;
|
||||
pub const STATUS_INVALID_HANDLE: u32 = 1;
|
||||
pub const STATUS_NON_FINITE_INPUT: u32 = 2;
|
||||
pub const STATUS_INVALID_LEVEL: u32 = 3;
|
||||
|
||||
const _: () = assert!(FRAME_SAMPLES == 480 && NUM_BANDS == 3 && SPLIT_BAND_SIZE == NS_FRAME_SIZE);
|
||||
|
||||
/// WebRTC FloatS16 full scale.
|
||||
const S16_SCALE: f32 = 32768.0;
|
||||
|
||||
fn suppression_level(level: u32) -> Option<SuppressionLevel> {
|
||||
match level {
|
||||
0 => Some(SuppressionLevel::K6dB),
|
||||
1 => Some(SuppressionLevel::K12dB),
|
||||
2 => Some(SuppressionLevel::K18dB),
|
||||
3 => Some(SuppressionLevel::K21dB),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_suppressor(target_level: SuppressionLevel) -> NoiseSuppressor {
|
||||
NoiseSuppressor::new_with_bands(NsConfig { target_level }, NUM_BANDS)
|
||||
}
|
||||
|
||||
/// Rejected frame.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProcessError {
|
||||
/// The frame held NaN or an infinity; it was zeroed and no state was updated.
|
||||
NonFiniteInput,
|
||||
}
|
||||
|
||||
/// One 48 kHz mono noise-reduction stream with all state and buffers preallocated.
|
||||
#[derive(Debug)]
|
||||
pub struct Denoiser {
|
||||
frame: [f32; FRAME_SAMPLES],
|
||||
bands: [[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
filter_bank: ThreeBandFilterBank,
|
||||
suppressor: NoiseSuppressor,
|
||||
}
|
||||
|
||||
impl Denoiser {
|
||||
/// A fresh stream at `level` (`0..=MAX_LEVEL`), or `None` for any other level.
|
||||
pub fn new(level: u32) -> Option<Self> {
|
||||
let target = suppression_level(level)?;
|
||||
Some(Self {
|
||||
frame: [0.0; FRAME_SAMPLES],
|
||||
bands: [[0.0; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
filter_bank: ThreeBandFilterBank::new(),
|
||||
suppressor: new_suppressor(target),
|
||||
})
|
||||
}
|
||||
|
||||
/// Start a new segment at `level`: afterwards the stream behaves exactly like
|
||||
/// `Denoiser::new(level)`. Returns `false`, changing nothing, for an invalid level.
|
||||
pub fn reset(&mut self, level: u32) -> bool {
|
||||
let Some(target) = suppression_level(level) else {
|
||||
return false;
|
||||
};
|
||||
self.frame.fill(0.0);
|
||||
self.bands = [[0.0; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
self.filter_bank = ThreeBandFilterBank::new();
|
||||
self.suppressor = new_suppressor(target);
|
||||
true
|
||||
}
|
||||
|
||||
/// The in/out frame: write 480 normalized input samples, call [`process`](Self::process),
|
||||
/// read 480 normalized output samples.
|
||||
pub fn frame_mut(&mut self) -> &mut [f32; FRAME_SAMPLES] {
|
||||
&mut self.frame
|
||||
}
|
||||
|
||||
/// Denoise the frame in place.
|
||||
pub fn process(&mut self) -> Result<(), ProcessError> {
|
||||
if self.frame.iter().any(|sample| !sample.is_finite()) {
|
||||
self.frame.fill(0.0);
|
||||
return Err(ProcessError::NonFiniteInput);
|
||||
}
|
||||
for sample in &mut self.frame {
|
||||
*sample = sample.clamp(-1.0, 1.0) * S16_SCALE;
|
||||
}
|
||||
|
||||
self.filter_bank.analysis(&self.frame, &mut self.bands);
|
||||
let [low, mid, high] = &mut self.bands;
|
||||
self.suppressor.analyze(low);
|
||||
self.suppressor.process(low);
|
||||
let upper_gain = self.suppressor.upper_band_gain();
|
||||
self.suppressor.process_upper_band(mid, 0, upper_gain);
|
||||
self.suppressor.process_upper_band(high, 1, upper_gain);
|
||||
NoiseSuppressor::clamp_frame(mid);
|
||||
NoiseSuppressor::clamp_frame(high);
|
||||
self.filter_bank.synthesis(&self.bands, &mut self.frame);
|
||||
|
||||
for sample in &mut self.frame {
|
||||
*sample = sample.clamp(-S16_SCALE, S16_SCALE) / S16_SCALE;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ── WebAssembly exports ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use wasm_abi::{dsp_free, dsp_input, dsp_new, dsp_process, dsp_reset};
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod wasm_abi {
|
||||
use super::*;
|
||||
|
||||
const SLOT_BITS: u32 = 8;
|
||||
const SLOT_MASK: u32 = (1 << SLOT_BITS) - 1;
|
||||
const GENERATION_MASK: u32 = u32::MAX >> SLOT_BITS;
|
||||
const _: () = assert!(MAX_INSTANCES < SLOT_MASK as usize);
|
||||
|
||||
struct Slot {
|
||||
generation: u32,
|
||||
dsp: Option<Box<Denoiser>>,
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
const EMPTY: Self = Self {
|
||||
generation: 0,
|
||||
dsp: None,
|
||||
};
|
||||
}
|
||||
|
||||
// The module is single-threaded; the mutex only makes the shared table sound Rust.
|
||||
static SLOTS: Mutex<[Slot; MAX_INSTANCES]> = Mutex::new([Slot::EMPTY; MAX_INSTANCES]);
|
||||
|
||||
fn slots() -> MutexGuard<'static, [Slot; MAX_INSTANCES]> {
|
||||
SLOTS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Handle layout: generation in the upper 24 bits, slot index + 1 in the low 8 bits (never 0).
|
||||
fn live_slot(slots: &mut [Slot; MAX_INSTANCES], handle: u32) -> Option<&mut Slot> {
|
||||
let index = (handle & SLOT_MASK) as usize;
|
||||
if index == 0 || index > MAX_INSTANCES {
|
||||
return None;
|
||||
}
|
||||
let slot = &mut slots[index - 1];
|
||||
(slot.dsp.is_some() && slot.generation == handle >> SLOT_BITS).then_some(slot)
|
||||
}
|
||||
|
||||
fn live_dsp(slots: &mut [Slot; MAX_INSTANCES], handle: u32) -> Option<&mut Denoiser> {
|
||||
live_slot(slots, handle)?.dsp.as_deref_mut()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn dsp_new(level: u32) -> u32 {
|
||||
let Some(dsp) = Denoiser::new(level) else {
|
||||
return 0;
|
||||
};
|
||||
let mut slots = slots();
|
||||
let Some((index, slot)) = slots
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.find(|(_, slot)| slot.dsp.is_none())
|
||||
else {
|
||||
return 0;
|
||||
};
|
||||
slot.generation = slot.generation.wrapping_add(1) & GENERATION_MASK;
|
||||
slot.dsp = Some(Box::new(dsp));
|
||||
(slot.generation << SLOT_BITS) | (index as u32 + 1)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn dsp_input(handle: u32) -> u32 {
|
||||
let mut slots = slots();
|
||||
live_dsp(&mut slots, handle).map_or(0, |dsp| dsp.frame.as_mut_ptr() as usize as u32)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn dsp_process(handle: u32) -> u32 {
|
||||
let mut slots = slots();
|
||||
match live_dsp(&mut slots, handle).map(Denoiser::process) {
|
||||
None => STATUS_INVALID_HANDLE,
|
||||
Some(Err(ProcessError::NonFiniteInput)) => STATUS_NON_FINITE_INPUT,
|
||||
Some(Ok(())) => STATUS_OK,
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn dsp_reset(handle: u32, level: u32) -> u32 {
|
||||
let mut slots = slots();
|
||||
let Some(dsp) = live_dsp(&mut slots, handle) else {
|
||||
return STATUS_INVALID_HANDLE;
|
||||
};
|
||||
if dsp.reset(level) {
|
||||
STATUS_OK
|
||||
} else {
|
||||
STATUS_INVALID_LEVEL
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn dsp_free(handle: u32) {
|
||||
let mut slots = slots();
|
||||
if let Some(slot) = live_slot(&mut slots, handle) {
|
||||
slot.dsp = None;
|
||||
}
|
||||
}
|
||||
pub const FRAME_SAMPLES: usize = sonora::three_band_filter_bank::FULL_BAND_SIZE;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// All export-table checks in one test: the table is process-global state.
|
||||
#[test]
|
||||
fn exported_handle_lifecycle() {
|
||||
assert_eq!(dsp_new(MAX_LEVEL + 1), 0);
|
||||
for bogus in [0, 0x0000_00FF, u32::MAX, MAX_INSTANCES as u32 + 1] {
|
||||
assert_eq!(dsp_input(bogus), 0);
|
||||
assert_eq!(dsp_process(bogus), STATUS_INVALID_HANDLE);
|
||||
assert_eq!(dsp_reset(bogus, 1), STATUS_INVALID_HANDLE);
|
||||
dsp_free(bogus);
|
||||
}
|
||||
|
||||
let handle = dsp_new(1);
|
||||
assert_ne!(handle, 0);
|
||||
assert_eq!(dsp_process(handle), STATUS_OK);
|
||||
assert_eq!(dsp_reset(handle, MAX_LEVEL + 1), STATUS_INVALID_LEVEL);
|
||||
assert_eq!(dsp_reset(handle, 3), STATUS_OK);
|
||||
{
|
||||
let mut table = slots();
|
||||
let dsp = live_dsp(&mut table, handle).unwrap();
|
||||
dsp.frame_mut()[0] = f32::NAN;
|
||||
}
|
||||
assert_eq!(dsp_process(handle), STATUS_NON_FINITE_INPUT);
|
||||
assert_eq!(dsp_process(handle), STATUS_OK);
|
||||
|
||||
dsp_free(handle);
|
||||
assert_eq!(dsp_process(handle), STATUS_INVALID_HANDLE);
|
||||
dsp_free(handle);
|
||||
|
||||
// Fill the table; the freed slot is reused under a new generation.
|
||||
let handles: Vec<u32> = (0..MAX_INSTANCES).map(|_| dsp_new(0)).collect();
|
||||
assert!(handles.iter().all(|&h| h != 0 && h != handle));
|
||||
assert_eq!(dsp_new(0), 0, "table should be full");
|
||||
assert_eq!(dsp_process(handle), STATUS_INVALID_HANDLE, "stale handle revived");
|
||||
for &h in &handles {
|
||||
assert_eq!(dsp_process(h), STATUS_OK);
|
||||
dsp_free(h);
|
||||
assert_eq!(dsp_process(h), STATUS_INVALID_HANDLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SAMPLE_RATE: f32 = 48_000.0;
|
||||
|
||||
/// Deterministic uniform white noise in `[-amplitude, amplitude)` (xorshift32).
|
||||
fn white_noise(frames: usize, amplitude: f32, mut seed: u32) -> Vec<f32> {
|
||||
(0..frames * FRAME_SAMPLES)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
(seed as f32 / u32::MAX as f32 * 2.0 - 1.0) * amplitude
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn run(dsp: &mut Denoiser, input: &[f32]) -> Vec<f32> {
|
||||
let mut output = Vec::with_capacity(input.len());
|
||||
for chunk in input.chunks_exact(FRAME_SAMPLES) {
|
||||
dsp.frame_mut().copy_from_slice(chunk);
|
||||
dsp.process().expect("finite input");
|
||||
output.extend_from_slice(dsp.frame_mut());
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn energy(samples: &[f32]) -> f64 {
|
||||
samples.iter().map(|&s| f64::from(s) * f64::from(s)).sum()
|
||||
}
|
||||
|
||||
fn frames(samples: &[f32], range: std::ops::Range<usize>) -> &[f32] {
|
||||
&samples[range.start * FRAME_SAMPLES..range.end * FRAME_SAMPLES]
|
||||
}
|
||||
|
||||
/// Input-to-output energy loss in dB over the given frames (positive = attenuated).
|
||||
fn attenuation_db(input: &[f32], output: &[f32], range: std::ops::Range<usize>) -> f64 {
|
||||
10.0 * (energy(frames(input, range.clone())) / energy(frames(output, range))).log10()
|
||||
}
|
||||
|
||||
/// The split/merge path alone, without suppression, as the bypass reference.
|
||||
fn split_merge_only(input: &[f32]) -> Vec<f32> {
|
||||
let mut bank = ThreeBandFilterBank::new();
|
||||
let mut bands = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
let mut output = Vec::with_capacity(input.len());
|
||||
for chunk in input.chunks_exact(FRAME_SAMPLES) {
|
||||
let frame: &[f32; FRAME_SAMPLES] = chunk.try_into().unwrap();
|
||||
let mut merged = [0.0f32; FRAME_SAMPLES];
|
||||
bank.analysis(frame, &mut bands);
|
||||
bank.synthesis(&bands, &mut merged);
|
||||
output.extend_from_slice(&merged);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_merge_bypass_preserves_noise_energy() {
|
||||
let input = white_noise(200, 0.1, 0x1234_5678);
|
||||
let output = split_merge_only(&input);
|
||||
let loss = attenuation_db(&input, &output, 100..200);
|
||||
assert!(loss.abs() < 1.5, "split/merge alone changed noise energy by {loss:.2} dB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stationary_noise_attenuation_grows_with_level() {
|
||||
// 8 s of fullband white noise; measure the last 3 s, after the noise estimate converged.
|
||||
// Two thirds of white-noise energy lies above 8 kHz, so suppressing only the low band
|
||||
// could never exceed 1.8 dB: the thresholds also prove the upper bands are attenuated.
|
||||
let input = white_noise(800, 0.1, 0x9E37_79B9);
|
||||
let bypass = attenuation_db(&input, &split_merge_only(&input), 500..800);
|
||||
let minimum_db = [3.0, 6.0, 10.0, 12.0];
|
||||
let mut previous = f64::NEG_INFINITY;
|
||||
for level in 0..=MAX_LEVEL {
|
||||
let output = run(&mut Denoiser::new(level).unwrap(), &input);
|
||||
let attenuation = attenuation_db(&input, &output, 500..800) - bypass;
|
||||
assert!(
|
||||
attenuation >= minimum_db[level as usize],
|
||||
"level {level}: {attenuation:.2} dB < {} dB",
|
||||
minimum_db[level as usize]
|
||||
);
|
||||
assert!(
|
||||
attenuation > previous + 0.5,
|
||||
"level {level}: {attenuation:.2} dB not above previous level's {previous:.2} dB"
|
||||
);
|
||||
previous = attenuation;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voiced_bursts_survive_while_noise_floor_drops() {
|
||||
// 400 ms harmonic bursts (220 Hz, 10 harmonics) every second over steady white noise.
|
||||
let total_frames = 1000;
|
||||
let mut input = white_noise(total_frames, 0.03, 0xDEAD_BEEF);
|
||||
for (n, sample) in input.iter_mut().enumerate() {
|
||||
if (n / FRAME_SAMPLES) % 100 < 40 {
|
||||
let t = n as f32 / SAMPLE_RATE;
|
||||
for k in 1..=10u8 {
|
||||
let k = f32::from(k);
|
||||
*sample += 0.08 / k * (std::f32::consts::TAU * 220.0 * k * t).sin();
|
||||
}
|
||||
}
|
||||
}
|
||||
let output = run(&mut Denoiser::new(1).unwrap(), &input);
|
||||
|
||||
let mut voiced = (0.0, 0.0);
|
||||
let mut noise_only = (0.0, 0.0);
|
||||
for frame in 300..total_frames {
|
||||
let phase = frame % 100;
|
||||
let target = match phase {
|
||||
5..=37 => &mut voiced,
|
||||
50..=97 => &mut noise_only,
|
||||
_ => continue,
|
||||
};
|
||||
target.0 += energy(frames(&input, frame..frame + 1));
|
||||
target.1 += energy(frames(&output, frame..frame + 1));
|
||||
}
|
||||
let voiced_loss = 10.0 * (voiced.0 / voiced.1).log10();
|
||||
let noise_loss = 10.0 * (noise_only.0 / noise_only.1).log10();
|
||||
assert!(voiced_loss < 4.0, "voiced bursts lost {voiced_loss:.2} dB");
|
||||
assert!(
|
||||
noise_loss > voiced_loss + 6.0,
|
||||
"noise-only frames lost {noise_loss:.2} dB vs voiced {voiced_loss:.2} dB"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_starts_a_segment_identical_to_a_fresh_instance() {
|
||||
let mut reused = Denoiser::new(0).unwrap();
|
||||
run(&mut reused, &white_noise(300, 0.2, 7));
|
||||
assert!(reused.reset(2));
|
||||
assert!(reused.frame_mut().iter().all(|&s| s == 0.0), "reset left stale frame data");
|
||||
|
||||
// Silence right after reset must stay exactly silent: no tail of the old segment.
|
||||
let silence = vec![0.0f32; 20 * FRAME_SAMPLES];
|
||||
assert!(run(&mut reused, &silence).iter().all(|&s| s == 0.0));
|
||||
|
||||
let segment = white_noise(300, 0.05, 99);
|
||||
let mut fresh = Denoiser::new(2).unwrap();
|
||||
run(&mut fresh, &silence);
|
||||
let expected = run(&mut fresh, &segment);
|
||||
let actual = run(&mut reused, &segment);
|
||||
assert!(
|
||||
expected.iter().zip(&actual).all(|(a, b)| a.to_bits() == b.to_bits()),
|
||||
"reset instance diverged from a fresh one"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_are_independent_and_deterministic() {
|
||||
let input = white_noise(200, 0.1, 42);
|
||||
let mut a = Denoiser::new(3).unwrap();
|
||||
let mut b = Denoiser::new(3).unwrap();
|
||||
let mut other = Denoiser::new(3).unwrap();
|
||||
let mut out_a = Vec::new();
|
||||
let mut out_b = Vec::new();
|
||||
for chunk in input.chunks_exact(FRAME_SAMPLES) {
|
||||
out_a.extend(run(&mut a, chunk));
|
||||
// Interleave an unrelated stream to catch shared hidden state.
|
||||
run(&mut other, &white_noise(1, 0.5, out_a.len() as u32 + 1));
|
||||
out_b.extend(run(&mut b, chunk));
|
||||
}
|
||||
assert!(out_a.iter().zip(&out_b).all(|(x, y)| x.to_bits() == y.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_level_changes_nothing() {
|
||||
assert!(Denoiser::new(MAX_LEVEL + 1).is_none());
|
||||
let warmup = white_noise(100, 0.1, 5);
|
||||
let after = white_noise(100, 0.1, 6);
|
||||
let mut probed = Denoiser::new(1).unwrap();
|
||||
let mut twin = Denoiser::new(1).unwrap();
|
||||
run(&mut probed, &warmup);
|
||||
run(&mut twin, &warmup);
|
||||
assert!(!probed.reset(MAX_LEVEL + 1));
|
||||
let a = run(&mut probed, &after);
|
||||
let b = run(&mut twin, &after);
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_input_is_rejected_without_touching_state() {
|
||||
let warmup = white_noise(100, 0.1, 11);
|
||||
let after = white_noise(100, 0.1, 12);
|
||||
let mut probed = Denoiser::new(2).unwrap();
|
||||
let mut twin = Denoiser::new(2).unwrap();
|
||||
run(&mut probed, &warmup);
|
||||
run(&mut twin, &warmup);
|
||||
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
probed.frame_mut().fill(0.1);
|
||||
probed.frame_mut()[123] = bad;
|
||||
assert_eq!(probed.process(), Err(ProcessError::NonFiniteInput));
|
||||
assert!(probed.frame_mut().iter().all(|&s| s == 0.0));
|
||||
}
|
||||
let a = run(&mut probed, &after);
|
||||
let b = run(&mut twin, &after);
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_stays_normalized_for_overdriven_input() {
|
||||
let input: Vec<f32> = white_noise(100, 4.0, 3);
|
||||
for level in 0..=MAX_LEVEL {
|
||||
let output = run(&mut Denoiser::new(level).unwrap(), &input);
|
||||
assert!(output.iter().all(|s| s.is_finite() && (-1.0..=1.0).contains(s)));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
mod noise_reference;
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Noise-only signal regression reference, compiled only by Rust tests.
|
||||
//!
|
||||
//! Preserves filter-bank, suppression-level, normalization and state-isolation checks
|
||||
//! independently of the integrated capture chain. This is not a production DSP API.
|
||||
use crate::FRAME_SAMPLES;
|
||||
use sonora::three_band_filter_bank::{
|
||||
FULL_BAND_SIZE, NUM_BANDS, SPLIT_BAND_SIZE, ThreeBandFilterBank,
|
||||
};
|
||||
use sonora_ns::config::{NS_FRAME_SIZE, NsConfig, SuppressionLevel};
|
||||
use sonora_ns::noise_suppressor::NoiseSuppressor;
|
||||
|
||||
/// Highest accepted level (Very High).
|
||||
pub const MAX_LEVEL: u32 = 3;
|
||||
const _: () = assert!(FRAME_SAMPLES == 480 && NUM_BANDS == 3 && SPLIT_BAND_SIZE == NS_FRAME_SIZE);
|
||||
|
||||
/// WebRTC FloatS16 full scale.
|
||||
const S16_SCALE: f32 = 32768.0;
|
||||
|
||||
fn suppression_level(level: u32) -> Option<SuppressionLevel> {
|
||||
match level {
|
||||
0 => Some(SuppressionLevel::K6dB),
|
||||
1 => Some(SuppressionLevel::K12dB),
|
||||
2 => Some(SuppressionLevel::K18dB),
|
||||
3 => Some(SuppressionLevel::K21dB),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_suppressor(target_level: SuppressionLevel) -> NoiseSuppressor {
|
||||
NoiseSuppressor::new_with_bands(NsConfig { target_level }, NUM_BANDS)
|
||||
}
|
||||
|
||||
/// Rejected frame.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProcessError {
|
||||
/// The frame held NaN or an infinity; it was zeroed and no state was updated.
|
||||
NonFiniteInput,
|
||||
}
|
||||
|
||||
/// One 48 kHz mono noise-reduction stream with all state and buffers preallocated.
|
||||
#[derive(Debug)]
|
||||
pub struct Denoiser {
|
||||
frame: [f32; FRAME_SAMPLES],
|
||||
bands: [[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
filter_bank: ThreeBandFilterBank,
|
||||
suppressor: NoiseSuppressor,
|
||||
}
|
||||
|
||||
impl Denoiser {
|
||||
/// A fresh stream at `level` (`0..=MAX_LEVEL`), or `None` for any other level.
|
||||
pub fn new(level: u32) -> Option<Self> {
|
||||
let target = suppression_level(level)?;
|
||||
Some(Self {
|
||||
frame: [0.0; FRAME_SAMPLES],
|
||||
bands: [[0.0; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
filter_bank: ThreeBandFilterBank::new(),
|
||||
suppressor: new_suppressor(target),
|
||||
})
|
||||
}
|
||||
|
||||
/// Start a new segment at `level`: afterwards the stream behaves exactly like
|
||||
/// `Denoiser::new(level)`. Returns `false`, changing nothing, for an invalid level.
|
||||
pub fn reset(&mut self, level: u32) -> bool {
|
||||
let Some(target) = suppression_level(level) else {
|
||||
return false;
|
||||
};
|
||||
self.frame.fill(0.0);
|
||||
self.bands = [[0.0; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
self.filter_bank = ThreeBandFilterBank::new();
|
||||
self.suppressor = new_suppressor(target);
|
||||
true
|
||||
}
|
||||
|
||||
/// The in/out frame: write 480 normalized input samples, call [`process`](Self::process),
|
||||
/// read 480 normalized output samples.
|
||||
pub fn frame_mut(&mut self) -> &mut [f32; FRAME_SAMPLES] {
|
||||
&mut self.frame
|
||||
}
|
||||
|
||||
/// Denoise the frame in place.
|
||||
pub fn process(&mut self) -> Result<(), ProcessError> {
|
||||
if self.frame.iter().any(|sample| !sample.is_finite()) {
|
||||
self.frame.fill(0.0);
|
||||
return Err(ProcessError::NonFiniteInput);
|
||||
}
|
||||
for sample in &mut self.frame {
|
||||
*sample = sample.clamp(-1.0, 1.0) * S16_SCALE;
|
||||
}
|
||||
|
||||
self.filter_bank.analysis(&self.frame, &mut self.bands);
|
||||
let [low, mid, high] = &mut self.bands;
|
||||
self.suppressor.analyze(low);
|
||||
self.suppressor.process(low);
|
||||
let upper_gain = self.suppressor.upper_band_gain();
|
||||
self.suppressor.process_upper_band(mid, 0, upper_gain);
|
||||
self.suppressor.process_upper_band(high, 1, upper_gain);
|
||||
NoiseSuppressor::clamp_frame(mid);
|
||||
NoiseSuppressor::clamp_frame(high);
|
||||
self.filter_bank.synthesis(&self.bands, &mut self.frame);
|
||||
|
||||
for sample in &mut self.frame {
|
||||
*sample = sample.clamp(-S16_SCALE, S16_SCALE) / S16_SCALE;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SAMPLE_RATE: f32 = 48_000.0;
|
||||
|
||||
/// Deterministic uniform white noise in `[-amplitude, amplitude)` (xorshift32).
|
||||
fn white_noise(frames: usize, amplitude: f32, mut seed: u32) -> Vec<f32> {
|
||||
(0..frames * FRAME_SAMPLES)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
(seed as f32 / u32::MAX as f32 * 2.0 - 1.0) * amplitude
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn run(dsp: &mut Denoiser, input: &[f32]) -> Vec<f32> {
|
||||
let mut output = Vec::with_capacity(input.len());
|
||||
for chunk in input.chunks_exact(FRAME_SAMPLES) {
|
||||
dsp.frame_mut().copy_from_slice(chunk);
|
||||
dsp.process().expect("finite input");
|
||||
output.extend_from_slice(dsp.frame_mut());
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn energy(samples: &[f32]) -> f64 {
|
||||
samples.iter().map(|&s| f64::from(s) * f64::from(s)).sum()
|
||||
}
|
||||
|
||||
fn frames(samples: &[f32], range: std::ops::Range<usize>) -> &[f32] {
|
||||
&samples[range.start * FRAME_SAMPLES..range.end * FRAME_SAMPLES]
|
||||
}
|
||||
|
||||
/// Input-to-output energy loss in dB over the given frames (positive = attenuated).
|
||||
fn attenuation_db(input: &[f32], output: &[f32], range: std::ops::Range<usize>) -> f64 {
|
||||
10.0 * (energy(frames(input, range.clone())) / energy(frames(output, range))).log10()
|
||||
}
|
||||
|
||||
/// The split/merge path alone, without suppression, as the bypass reference.
|
||||
fn split_merge_only(input: &[f32]) -> Vec<f32> {
|
||||
let mut bank = ThreeBandFilterBank::new();
|
||||
let mut bands = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
let mut output = Vec::with_capacity(input.len());
|
||||
for chunk in input.chunks_exact(FRAME_SAMPLES) {
|
||||
let frame: &[f32; FRAME_SAMPLES] = chunk.try_into().unwrap();
|
||||
let mut merged = [0.0f32; FRAME_SAMPLES];
|
||||
bank.analysis(frame, &mut bands);
|
||||
bank.synthesis(&bands, &mut merged);
|
||||
output.extend_from_slice(&merged);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_merge_bypass_preserves_noise_energy() {
|
||||
let input = white_noise(200, 0.1, 0x1234_5678);
|
||||
let output = split_merge_only(&input);
|
||||
let loss = attenuation_db(&input, &output, 100..200);
|
||||
assert!(loss.abs() < 1.5, "split/merge alone changed noise energy by {loss:.2} dB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stationary_noise_attenuation_grows_with_level() {
|
||||
// 8 s of fullband white noise; measure the last 3 s, after the noise estimate converged.
|
||||
// Two thirds of white-noise energy lies above 8 kHz, so suppressing only the low band
|
||||
// could never exceed 1.8 dB: the thresholds also prove the upper bands are attenuated.
|
||||
let input = white_noise(800, 0.1, 0x9E37_79B9);
|
||||
let bypass = attenuation_db(&input, &split_merge_only(&input), 500..800);
|
||||
let minimum_db = [3.0, 6.0, 10.0, 12.0];
|
||||
let mut previous = f64::NEG_INFINITY;
|
||||
for level in 0..=MAX_LEVEL {
|
||||
let output = run(&mut Denoiser::new(level).unwrap(), &input);
|
||||
let attenuation = attenuation_db(&input, &output, 500..800) - bypass;
|
||||
assert!(
|
||||
attenuation >= minimum_db[level as usize],
|
||||
"level {level}: {attenuation:.2} dB < {} dB",
|
||||
minimum_db[level as usize]
|
||||
);
|
||||
assert!(
|
||||
attenuation > previous + 0.5,
|
||||
"level {level}: {attenuation:.2} dB not above previous level's {previous:.2} dB"
|
||||
);
|
||||
previous = attenuation;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voiced_bursts_survive_while_noise_floor_drops() {
|
||||
// 400 ms harmonic bursts (220 Hz, 10 harmonics) every second over steady white noise.
|
||||
let total_frames = 1000;
|
||||
let mut input = white_noise(total_frames, 0.03, 0xDEAD_BEEF);
|
||||
for (n, sample) in input.iter_mut().enumerate() {
|
||||
if (n / FRAME_SAMPLES) % 100 < 40 {
|
||||
let t = n as f32 / SAMPLE_RATE;
|
||||
for k in 1..=10u8 {
|
||||
let k = f32::from(k);
|
||||
*sample += 0.08 / k * (std::f32::consts::TAU * 220.0 * k * t).sin();
|
||||
}
|
||||
}
|
||||
}
|
||||
let output = run(&mut Denoiser::new(1).unwrap(), &input);
|
||||
|
||||
let mut voiced = (0.0, 0.0);
|
||||
let mut noise_only = (0.0, 0.0);
|
||||
for frame in 300..total_frames {
|
||||
let phase = frame % 100;
|
||||
let target = match phase {
|
||||
5..=37 => &mut voiced,
|
||||
50..=97 => &mut noise_only,
|
||||
_ => continue,
|
||||
};
|
||||
target.0 += energy(frames(&input, frame..frame + 1));
|
||||
target.1 += energy(frames(&output, frame..frame + 1));
|
||||
}
|
||||
let voiced_loss = 10.0 * (voiced.0 / voiced.1).log10();
|
||||
let noise_loss = 10.0 * (noise_only.0 / noise_only.1).log10();
|
||||
assert!(voiced_loss < 4.0, "voiced bursts lost {voiced_loss:.2} dB");
|
||||
assert!(
|
||||
noise_loss > voiced_loss + 6.0,
|
||||
"noise-only frames lost {noise_loss:.2} dB vs voiced {voiced_loss:.2} dB"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_starts_a_segment_identical_to_a_fresh_instance() {
|
||||
let mut reused = Denoiser::new(0).unwrap();
|
||||
run(&mut reused, &white_noise(300, 0.2, 7));
|
||||
assert!(reused.reset(2));
|
||||
assert!(reused.frame_mut().iter().all(|&s| s == 0.0), "reset left stale frame data");
|
||||
|
||||
// Silence right after reset must stay exactly silent: no tail of the old segment.
|
||||
let silence = vec![0.0f32; 20 * FRAME_SAMPLES];
|
||||
assert!(run(&mut reused, &silence).iter().all(|&s| s == 0.0));
|
||||
|
||||
let segment = white_noise(300, 0.05, 99);
|
||||
let mut fresh = Denoiser::new(2).unwrap();
|
||||
run(&mut fresh, &silence);
|
||||
let expected = run(&mut fresh, &segment);
|
||||
let actual = run(&mut reused, &segment);
|
||||
assert!(
|
||||
expected.iter().zip(&actual).all(|(a, b)| a.to_bits() == b.to_bits()),
|
||||
"reset instance diverged from a fresh one"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_are_independent_and_deterministic() {
|
||||
let input = white_noise(200, 0.1, 42);
|
||||
let mut a = Denoiser::new(3).unwrap();
|
||||
let mut b = Denoiser::new(3).unwrap();
|
||||
let mut other = Denoiser::new(3).unwrap();
|
||||
let mut out_a = Vec::new();
|
||||
let mut out_b = Vec::new();
|
||||
for chunk in input.chunks_exact(FRAME_SAMPLES) {
|
||||
out_a.extend(run(&mut a, chunk));
|
||||
// Interleave an unrelated stream to catch shared hidden state.
|
||||
run(&mut other, &white_noise(1, 0.5, out_a.len() as u32 + 1));
|
||||
out_b.extend(run(&mut b, chunk));
|
||||
}
|
||||
assert!(out_a.iter().zip(&out_b).all(|(x, y)| x.to_bits() == y.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_level_changes_nothing() {
|
||||
assert!(Denoiser::new(MAX_LEVEL + 1).is_none());
|
||||
let warmup = white_noise(100, 0.1, 5);
|
||||
let after = white_noise(100, 0.1, 6);
|
||||
let mut probed = Denoiser::new(1).unwrap();
|
||||
let mut twin = Denoiser::new(1).unwrap();
|
||||
run(&mut probed, &warmup);
|
||||
run(&mut twin, &warmup);
|
||||
assert!(!probed.reset(MAX_LEVEL + 1));
|
||||
let a = run(&mut probed, &after);
|
||||
let b = run(&mut twin, &after);
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_input_is_rejected_without_touching_state() {
|
||||
let warmup = white_noise(100, 0.1, 11);
|
||||
let after = white_noise(100, 0.1, 12);
|
||||
let mut probed = Denoiser::new(2).unwrap();
|
||||
let mut twin = Denoiser::new(2).unwrap();
|
||||
run(&mut probed, &warmup);
|
||||
run(&mut twin, &warmup);
|
||||
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
probed.frame_mut().fill(0.1);
|
||||
probed.frame_mut()[123] = bad;
|
||||
assert_eq!(probed.process(), Err(ProcessError::NonFiniteInput));
|
||||
assert!(probed.frame_mut().iter().all(|&s| s == 0.0));
|
||||
}
|
||||
let a = run(&mut probed, &after);
|
||||
let b = run(&mut twin, &after);
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_stays_normalized_for_overdriven_input() {
|
||||
let input: Vec<f32> = white_noise(100, 4.0, 3);
|
||||
for level in 0..=MAX_LEVEL {
|
||||
let output = run(&mut Denoiser::new(level).unwrap(), &input);
|
||||
assert!(output.iter().all(|s| s.is_finite() && (-1.0..=1.0).contains(s)));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user