Implement Rust and Slint native client migration and fix desktop startup
This commit is contained in:
1 parent
0d11f8f99d
commit
eb24965076
1303 files changed
+732670
-2375
No files matched your search
Generated
-251
@@ -1,251 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
dependencies = [
|
||||
"bytemuck_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
|
||||
dependencies = [
|
||||
"derive_more-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more-impl"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn 2.0.119",
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "sonora"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250"
|
||||
dependencies = [
|
||||
"sonora-aec3",
|
||||
"sonora-agc2",
|
||||
"sonora-common-audio",
|
||||
"sonora-ns",
|
||||
"sonora-simd",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-aec3"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50280e31256d09f7838aff6715ed4b7640e514dc1092a1e14013c01e552380db"
|
||||
dependencies = [
|
||||
"sonora-common-audio",
|
||||
"sonora-fft",
|
||||
"sonora-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
"sonora-common-audio",
|
||||
"sonora-fft",
|
||||
"sonora-simd",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-common-audio"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"sonora-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-fft"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
|
||||
|
||||
[[package]]
|
||||
name = "sonora-ns"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f"
|
||||
dependencies = [
|
||||
"sonora-fft",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-simd"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "teamspeach-denoise"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"sonora",
|
||||
"sonora-ns",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
+5
-17
@@ -1,34 +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.
|
||||
# Standalone package: not part of the core/ workspace and never linked into the native core.
|
||||
# Workspace package; the root denoise profile preserves the shipped WASM build settings.
|
||||
[package]
|
||||
name = "teamspeach-denoise"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
publish = false
|
||||
description = "TeamsPeach 48 kHz mono noise reduction (sonora WebRTC NS) as a WebAssembly module"
|
||||
description = "TeamsPeach native capture DSP and reference WASM noise reduction"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
crate-type = ["rlib", "cdylib"]
|
||||
path = "src/lib.rs"
|
||||
|
||||
# Exact pins: the shipped DSP must not change behind a lockfile refresh.
|
||||
# sonora provides the public 48 kHz ThreeBandFilterBank (split/merge); sonora-ns the
|
||||
# noise suppressor. Neither crate has cargo features; AEC3/AGC2 are compiled as sonora's
|
||||
# dependencies but never constructed or called, so they are dead-stripped from the module.
|
||||
# Native capture uses sonora AEC3, noise suppression and adaptive AGC2 together.
|
||||
# The reference WASM exports retain the standalone sonora-ns filter-bank path.
|
||||
[dependencies]
|
||||
sonora = "=0.2.0"
|
||||
sonora-ns = "=0.2.0"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
debug = false
|
||||
strip = true
|
||||
incremental = false
|
||||
|
||||
# Own workspace root so this crate is never absorbed into another workspace.
|
||||
[workspace]
|
||||
@@ -0,0 +1,221 @@
|
||||
//! 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'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.
|
||||
|
||||
use std::{error::Error, fmt};
|
||||
|
||||
use sonora::{AudioProcessing, StreamConfig};
|
||||
use sonora::config::{
|
||||
AdaptiveDigital, Config, EchoCanceller, GainController2, NoiseSuppression,
|
||||
MaxProcessingRate, NoiseSuppressionLevel, Pipeline,
|
||||
};
|
||||
|
||||
use crate::FRAME_SAMPLES;
|
||||
|
||||
/// Independent processing switches; noise levels match the existing settings schema.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CaptureSettings {
|
||||
pub echo_cancellation: bool,
|
||||
/// `None` disables NS; `Some(0..=3)` means Low / Moderate / High / Very High.
|
||||
pub noise_suppression: Option<u8>,
|
||||
/// Enables adaptive digital AGC2, not hardware microphone-volume control.
|
||||
pub automatic_gain_control: bool,
|
||||
}
|
||||
|
||||
impl Default for CaptureSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
echo_cancellation: true,
|
||||
noise_suppression: Some(1),
|
||||
automatic_gain_control: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A rejected frame or configuration. No audio samples appear in error messages.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CaptureError {
|
||||
InvalidNoiseSuppressionLevel(u8),
|
||||
/// Delay is outside Sonora's supported inclusive 0..=500 ms range.
|
||||
InvalidDelay(i32),
|
||||
NonFiniteInput,
|
||||
NonFiniteOutput,
|
||||
/// AEC capture is disallowed until the first reverse frame after creation/reset.
|
||||
MissingRenderReference,
|
||||
Sonora(sonora::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for CaptureError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidNoiseSuppressionLevel(level) => {
|
||||
write!(f, "invalid capture noise suppression level {level} (expected 0..=3)")
|
||||
}
|
||||
Self::InvalidDelay(delay) => {
|
||||
write!(f, "invalid capture/render delay {delay} ms (expected 0..=500)")
|
||||
}
|
||||
Self::NonFiniteInput => f.write_str("capture processor rejected non-finite input"),
|
||||
Self::NonFiniteOutput => f.write_str("capture processor produced non-finite output; reset required"),
|
||||
Self::MissingRenderReference => f.write_str("capture processor requires a render reference"),
|
||||
Self::Sonora(error) => fmt::Display::fmt(error, f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CaptureError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Sonora(error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sonora::Error> for CaptureError {
|
||||
fn from(error: sonora::Error) -> Self {
|
||||
Self::Sonora(error)
|
||||
}
|
||||
}
|
||||
|
||||
fn configuration(settings: CaptureSettings) -> Result<Config, CaptureError> {
|
||||
let noise_suppression = match settings.noise_suppression {
|
||||
None => None,
|
||||
Some(level) => Some(NoiseSuppression {
|
||||
level: match level {
|
||||
0 => NoiseSuppressionLevel::Low,
|
||||
1 => NoiseSuppressionLevel::Moderate,
|
||||
2 => NoiseSuppressionLevel::High,
|
||||
3 => NoiseSuppressionLevel::VeryHigh,
|
||||
other => return Err(CaptureError::InvalidNoiseSuppressionLevel(other)),
|
||||
},
|
||||
..NoiseSuppression::default()
|
||||
}),
|
||||
};
|
||||
Ok(Config {
|
||||
// Sonora defaults to 32 kHz internally; keep the fullband 48 kHz capture path.
|
||||
pipeline: Pipeline {
|
||||
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
|
||||
..Pipeline::default()
|
||||
},
|
||||
echo_canceller: settings.echo_cancellation.then(EchoCanceller::default),
|
||||
noise_suppression,
|
||||
gain_controller2: settings.automatic_gain_control.then(|| GainController2 {
|
||||
// GainController2::default() alone does NOT enable adaptive gain.
|
||||
adaptive_digital: Some(AdaptiveDigital::default()),
|
||||
input_volume_controller: false,
|
||||
..GainController2::default()
|
||||
}),
|
||||
..Config::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// One stateful AEC3 -> NS -> adaptive AGC2 chain, with 48 kHz mono on both sides.
|
||||
///
|
||||
/// Construct/reset and process on the dedicated DSP worker, never in device callbacks.
|
||||
/// The wrapper reuses its scratch buffers, but no allocation-free or lock-free claim
|
||||
/// is made for Sonora's internal processing. Processing is not bit-identical to Chromium.
|
||||
#[derive(Debug)]
|
||||
pub struct CaptureProcessor {
|
||||
processing: AudioProcessing,
|
||||
settings: CaptureSettings,
|
||||
input: [f32; FRAME_SAMPLES],
|
||||
render_output: [f32; FRAME_SAMPLES],
|
||||
render_ready: bool,
|
||||
}
|
||||
|
||||
impl CaptureProcessor {
|
||||
pub fn new(settings: CaptureSettings) -> Result<Self, CaptureError> {
|
||||
let config = configuration(settings)?;
|
||||
let stream = StreamConfig::new(48_000, 1);
|
||||
Ok(Self {
|
||||
processing: AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(stream)
|
||||
.render_config(stream)
|
||||
.build(),
|
||||
settings,
|
||||
input: [0.0; FRAME_SAMPLES],
|
||||
render_output: [0.0; FRAME_SAMPLES],
|
||||
render_ready: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Analyze the actual post-gain playout mix; this never modifies the supplied PCM.
|
||||
///
|
||||
/// `delay_ms` includes hardware delay, queued samples and resampler latency. Reject
|
||||
/// out-of-range delay rather than silently continuing with Sonora's clamped estimate.
|
||||
/// A silent physical sink must still supply silent reference blocks while AEC runs.
|
||||
/// This API does not infer timestamps or reference freshness; the engine owns those.
|
||||
pub fn process_render(
|
||||
&mut self,
|
||||
samples: &[f32; FRAME_SAMPLES],
|
||||
delay_ms: i32,
|
||||
) -> Result<(), CaptureError> {
|
||||
if !(0..=500).contains(&delay_ms) {
|
||||
return Err(CaptureError::InvalidDelay(delay_ms));
|
||||
}
|
||||
self.copy_input(samples)?;
|
||||
self.processing.set_stream_delay_ms(delay_ms)?;
|
||||
self.processing.process_render_f32(
|
||||
&[&self.input],
|
||||
&mut [&mut self.render_output],
|
||||
)?;
|
||||
self.render_ready = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Process one normalized frame in place. Invalid input is zeroed before returning
|
||||
/// an error, without entering Sonora; finite input/output is clamped to [-1, 1].
|
||||
/// On any processing error the caller must discard the frame, not transmit bypass PCM.
|
||||
pub fn process_capture(
|
||||
&mut self,
|
||||
samples: &mut [f32; FRAME_SAMPLES],
|
||||
) -> Result<(), CaptureError> {
|
||||
if let Err(error) = self.copy_input(samples) {
|
||||
samples.fill(0.0);
|
||||
return Err(error);
|
||||
}
|
||||
if self.settings.echo_cancellation && !self.render_ready {
|
||||
samples.fill(0.0);
|
||||
return Err(CaptureError::MissingRenderReference);
|
||||
}
|
||||
if let Err(error) = self.processing.process_capture_f32(&[&self.input], &mut [&mut samples[..]]) {
|
||||
samples.fill(0.0);
|
||||
return Err(error.into());
|
||||
}
|
||||
if samples.iter().any(|sample| !sample.is_finite()) {
|
||||
samples.fill(0.0);
|
||||
return Err(CaptureError::NonFiniteOutput);
|
||||
}
|
||||
for sample in samples {
|
||||
*sample = sample.clamp(-1.0, 1.0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Discard ALL signal history and pending reverse frames, e.g. on device/route change.
|
||||
/// Rebuild AEC instead of using Sonora's no-op playout-device-change runtime setting.
|
||||
/// An invalid setting leaves the existing processor intact.
|
||||
pub fn reset(&mut self, settings: CaptureSettings) -> Result<(), CaptureError> {
|
||||
*self = Self::new(settings)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_input(&mut self, samples: &[f32; FRAME_SAMPLES]) -> Result<(), CaptureError> {
|
||||
if samples.iter().any(|sample| !sample.is_finite()) {
|
||||
return Err(CaptureError::NonFiniteInput);
|
||||
}
|
||||
for (destination, sample) in self.input.iter_mut().zip(samples) {
|
||||
*destination = sample.clamp(-1.0, 1.0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,276 @@
|
||||
use super::*;
|
||||
|
||||
const BYPASS: CaptureSettings = CaptureSettings {
|
||||
echo_cancellation: false,
|
||||
noise_suppression: None,
|
||||
automatic_gain_control: false,
|
||||
};
|
||||
|
||||
fn noise(seed: &mut u32, amplitude: f32) -> [f32; FRAME_SAMPLES] {
|
||||
std::array::from_fn(|_| {
|
||||
*seed ^= *seed << 13;
|
||||
*seed ^= *seed >> 17;
|
||||
*seed ^= *seed << 5;
|
||||
(*seed as f32 / u32::MAX as f32 * 2.0 - 1.0) * amplitude
|
||||
})
|
||||
}
|
||||
|
||||
fn harmonic(frame: usize, amplitude: f32) -> [f32; FRAME_SAMPLES] {
|
||||
std::array::from_fn(|sample| {
|
||||
let time = (frame * FRAME_SAMPLES + sample) as f32 / 48_000.0;
|
||||
(1..=8).map(|harmonic| {
|
||||
let harmonic = harmonic as f32;
|
||||
amplitude / harmonic * (std::f32::consts::TAU * 220.0 * harmonic * time).sin()
|
||||
}).sum()
|
||||
})
|
||||
}
|
||||
|
||||
fn energy(samples: &[f32]) -> f64 {
|
||||
samples.iter().map(|&sample| f64::from(sample).powi(2)).sum()
|
||||
}
|
||||
|
||||
fn assert_normalized(samples: &[f32]) {
|
||||
assert!(samples.iter().all(|sample| sample.is_finite() && (-1.0..=1.0).contains(sample)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_stages_preserve_signal_without_filterbank_delay() {
|
||||
let mut processor = CaptureProcessor::new(BYPASS).unwrap();
|
||||
let mut seed = 0x1234_5678;
|
||||
for _ in 0..100 {
|
||||
let input = noise(&mut seed, 0.8);
|
||||
let mut output = input;
|
||||
processor.process_capture(&mut output).unwrap();
|
||||
for (actual, expected) in output.iter().zip(input) {
|
||||
assert!((actual - expected).abs() < 1.0 / 32768.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_noise_levels_attenuate_stationary_noise_in_order() {
|
||||
let mut previous = 0.0;
|
||||
for (level, minimum_db) in [3.0, 6.0, 10.0, 12.0].into_iter().enumerate() {
|
||||
let mut processor = CaptureProcessor::new(CaptureSettings {
|
||||
noise_suppression: Some(level as u8),
|
||||
..BYPASS
|
||||
}).unwrap();
|
||||
let mut seed = 0x9e37_79b9;
|
||||
let mut input_energy = 0.0;
|
||||
let mut output_energy = 0.0;
|
||||
for frame in 0..800 {
|
||||
let mut samples = noise(&mut seed, 0.1);
|
||||
if frame >= 500 {
|
||||
input_energy += energy(&samples);
|
||||
}
|
||||
processor.process_capture(&mut samples).unwrap();
|
||||
assert_normalized(&samples);
|
||||
if frame >= 500 {
|
||||
output_energy += energy(&samples);
|
||||
}
|
||||
}
|
||||
let attenuation = 10.0 * (input_energy / output_energy).log10();
|
||||
assert!(attenuation > minimum_db, "level {level}: only {attenuation:.2} dB attenuation");
|
||||
assert!(attenuation > previous + 0.5, "level {level}: {attenuation:.2} vs {previous:.2} dB");
|
||||
previous = attenuation;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn adaptive_agc_boosts_quiet_voiced_input_without_hardware_gain() {
|
||||
let mut processor = CaptureProcessor::new(CaptureSettings {
|
||||
automatic_gain_control: true,
|
||||
..BYPASS
|
||||
}).unwrap();
|
||||
let mut input_energy = 0.0;
|
||||
let mut output_energy = 0.0;
|
||||
// Exercise initial adaptive gain (15 dB) and its bounded adaptation, not a fixed gain.
|
||||
for frame in 0..30 {
|
||||
let mut samples = harmonic(frame, 0.002);
|
||||
input_energy += energy(&samples);
|
||||
processor.process_capture(&mut samples).unwrap();
|
||||
assert_normalized(&samples);
|
||||
output_energy += energy(&samples);
|
||||
}
|
||||
let gain_db = 10.0 * (output_energy / input_energy).log10();
|
||||
assert!(gain_db > 6.0, "adaptive digital gain was not applied: {gain_db:.2} dB");
|
||||
let config = processor.processing.config().gain_controller2.as_ref().unwrap();
|
||||
assert!(config.adaptive_digital.is_some());
|
||||
assert!(!config.input_volume_controller);
|
||||
assert_eq!(config.fixed_digital.gain_db, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_reference_is_required_after_each_device_reset() {
|
||||
let settings = CaptureSettings { echo_cancellation: true, ..BYPASS };
|
||||
let mut processor = CaptureProcessor::new(settings).unwrap();
|
||||
let mut samples = [0.25; FRAME_SAMPLES];
|
||||
assert_eq!(processor.process_capture(&mut samples), Err(CaptureError::MissingRenderReference));
|
||||
assert_eq!(samples, [0.0; FRAME_SAMPLES]);
|
||||
processor.process_render(&[0.0; FRAME_SAMPLES], 30).unwrap();
|
||||
processor.process_capture(&mut samples).unwrap();
|
||||
processor.reset(settings).unwrap();
|
||||
assert_eq!(processor.process_capture(&mut samples), Err(CaptureError::MissingRenderReference));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_echo_is_attenuated_by_the_actual_reverse_signal() {
|
||||
let settings = CaptureSettings { echo_cancellation: true, ..BYPASS };
|
||||
let mut matching = CaptureProcessor::new(settings).unwrap();
|
||||
let mut silent_reference = CaptureProcessor::new(settings).unwrap();
|
||||
let mut history = [[0.0; FRAME_SAMPLES]; 4];
|
||||
let mut seed = 0x72ad_b643;
|
||||
let mut matched_energy = 0.0;
|
||||
let mut unmatched_energy = 0.0;
|
||||
// A synthetic 40 ms linear echo path; not a speakerphone/double-talk acoustic gate.
|
||||
for frame in 0..1200 {
|
||||
let render = noise(&mut seed, 0.2);
|
||||
let slot = frame % history.len();
|
||||
let mut actual = history[slot].map(|sample| sample * 0.6);
|
||||
let mut unmatched = actual;
|
||||
history[slot] = render;
|
||||
matching.process_render(&render, 40).unwrap();
|
||||
silent_reference.process_render(&[0.0; FRAME_SAMPLES], 40).unwrap();
|
||||
matching.process_capture(&mut actual).unwrap();
|
||||
silent_reference.process_capture(&mut unmatched).unwrap();
|
||||
assert_normalized(&actual);
|
||||
if frame >= 800 {
|
||||
matched_energy += energy(&actual);
|
||||
unmatched_energy += energy(&unmatched);
|
||||
}
|
||||
}
|
||||
assert!(unmatched_energy > 0.0);
|
||||
let benefit_db = 10.0 * (unmatched_energy / matched_energy).log10();
|
||||
assert!(benefit_db > 3.0, "render reference did not reduce synthetic echo: {benefit_db:.2} dB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_pipeline_matches_one_direct_sonora_instance() {
|
||||
let mut processor = CaptureProcessor::new(CaptureSettings::default()).unwrap();
|
||||
// Construct independently, so accidentally disabling adaptive AGC/NS/AEC in the wrapper
|
||||
// or inserting another denoiser cannot silently redefine this expected signal.
|
||||
let mut reference = AudioProcessing::builder()
|
||||
.config(Config {
|
||||
pipeline: Pipeline {
|
||||
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
|
||||
..Pipeline::default()
|
||||
},
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
noise_suppression: Some(NoiseSuppression::default()),
|
||||
gain_controller2: Some(GainController2 {
|
||||
adaptive_digital: Some(AdaptiveDigital::default()),
|
||||
..GainController2::default()
|
||||
}),
|
||||
..Config::default()
|
||||
})
|
||||
.capture_config(StreamConfig::new(48_000, 1))
|
||||
.render_config(StreamConfig::new(48_000, 1))
|
||||
.build();
|
||||
let mut seed = 71;
|
||||
let mut render_output = [0.0; FRAME_SAMPLES];
|
||||
for frame in 0..100 {
|
||||
let render = noise(&mut seed, 0.1);
|
||||
let original = render;
|
||||
let input = harmonic(frame, 0.04);
|
||||
let mut actual = input;
|
||||
let mut expected = [0.0; FRAME_SAMPLES];
|
||||
processor.process_render(&render, 25).unwrap();
|
||||
reference.set_stream_delay_ms(25).unwrap();
|
||||
reference.process_render_f32(&[&render], &mut [&mut render_output]).unwrap();
|
||||
processor.process_capture(&mut actual).unwrap();
|
||||
reference.process_capture_f32(&[&input], &mut [&mut expected]).unwrap();
|
||||
assert_eq!(render, original, "reference analysis modified physical playout samples");
|
||||
for (actual, expected) in actual.into_iter().zip(expected) {
|
||||
assert_eq!(actual.to_bits(), expected.clamp(-1.0, 1.0).to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_extremes_are_clamped_before_any_stage() {
|
||||
let settings = CaptureSettings::default();
|
||||
let mut probed = CaptureProcessor::new(settings).unwrap();
|
||||
let mut twin = CaptureProcessor::new(settings).unwrap();
|
||||
for frame in 0..50 {
|
||||
let input = std::array::from_fn(|index| if (index + frame) % 2 == 0 { f32::MAX } else { -f32::MAX });
|
||||
let clamped = input.map(|sample| sample.clamp(-1.0, 1.0));
|
||||
probed.process_render(&input, 0).unwrap();
|
||||
twin.process_render(&clamped, 0).unwrap();
|
||||
let mut actual = input;
|
||||
let mut expected = clamped;
|
||||
probed.process_capture(&mut actual).unwrap();
|
||||
twin.process_capture(&mut expected).unwrap();
|
||||
assert_normalized(&actual);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_inputs_and_delays_do_not_change_processing_state() {
|
||||
let settings = CaptureSettings::default();
|
||||
let mut probed = CaptureProcessor::new(settings).unwrap();
|
||||
let mut twin = CaptureProcessor::new(settings).unwrap();
|
||||
let mut seed = 98;
|
||||
for frame in 0..120 {
|
||||
let render = noise(&mut seed, 0.1);
|
||||
probed.process_render(&render, 20).unwrap();
|
||||
twin.process_render(&render, 20).unwrap();
|
||||
if frame == 60 {
|
||||
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut samples = render;
|
||||
samples[123] = bad;
|
||||
assert_eq!(probed.process_render(&samples, 20), Err(CaptureError::NonFiniteInput));
|
||||
assert_eq!(probed.process_capture(&mut samples), Err(CaptureError::NonFiniteInput));
|
||||
assert_eq!(samples, [0.0; FRAME_SAMPLES]);
|
||||
}
|
||||
for delay in [i32::MIN, -1, 501, i32::MAX] {
|
||||
assert_eq!(probed.process_render(&render, delay), Err(CaptureError::InvalidDelay(delay)));
|
||||
}
|
||||
assert_eq!(probed.processing.stream_delay_ms(), 20);
|
||||
assert_eq!(probed.reset(CaptureSettings { noise_suppression: Some(4), ..settings }), Err(CaptureError::InvalidNoiseSuppressionLevel(4)));
|
||||
}
|
||||
let mut actual = harmonic(frame, 0.03);
|
||||
let mut expected = actual;
|
||||
probed.process_capture(&mut actual).unwrap();
|
||||
twin.process_capture(&mut expected).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_discards_echo_noise_gain_history_and_matches_a_fresh_device() {
|
||||
let mut reused = CaptureProcessor::new(CaptureSettings::default()).unwrap();
|
||||
let mut seed = 0x1111_1234;
|
||||
for _ in 0..100 {
|
||||
let render = noise(&mut seed, 0.2);
|
||||
let mut capture = noise(&mut seed, 0.1);
|
||||
reused.process_render(&render, 80).unwrap();
|
||||
reused.process_capture(&mut capture).unwrap();
|
||||
}
|
||||
let settings = CaptureSettings { noise_suppression: Some(3), ..CaptureSettings::default() };
|
||||
reused.reset(settings).unwrap();
|
||||
let mut fresh = CaptureProcessor::new(settings).unwrap();
|
||||
for frame in 0..100 {
|
||||
let render = if frame < 10 { [0.0; FRAME_SAMPLES] } else { noise(&mut seed, 0.05) };
|
||||
let input = if frame < 10 { [0.0; FRAME_SAMPLES] } else { harmonic(frame, 0.02) };
|
||||
let mut actual = input;
|
||||
let mut expected = input;
|
||||
reused.process_render(&render, 10).unwrap();
|
||||
fresh.process_render(&render, 10).unwrap();
|
||||
reused.process_capture(&mut actual).unwrap();
|
||||
fresh.process_capture(&mut expected).unwrap();
|
||||
assert_eq!(actual, expected, "reset leaked signal history at frame {frame}");
|
||||
assert_normalized(&actual);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_settings_never_construct_a_processor() {
|
||||
for level in [4, 255] {
|
||||
assert!(matches!(CaptureProcessor::new(CaptureSettings {
|
||||
noise_suppression: Some(level),
|
||||
..BYPASS
|
||||
}), Err(CaptureError::InvalidNoiseSuppressionLevel(actual)) if actual == level));
|
||||
}
|
||||
}
|
||||
+65
-45
@@ -1,8 +1,11 @@
|
||||
//! TeamsPeach microphone noise reduction, compiled to a zero-import WebAssembly module.
|
||||
//! TeamsPeach 48 kHz mono capture processing.
|
||||
//!
|
||||
//! The renderer's capture AudioWorklet runs every 10 ms frame of 48 kHz mono microphone audio
|
||||
//! through this module, both for live voice and for the settings record test, so both paths hear
|
||||
//! exactly the same processing. Every architecture executes the same scalar WebAssembly code.
|
||||
//! 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.
|
||||
//! Device callbacks must not run DSP; the processor belongs to the dedicated audio worker.
|
||||
//!
|
||||
//! 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
|
||||
//!
|
||||
@@ -46,8 +49,12 @@
|
||||
//!
|
||||
//! 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); `dsp_process` never allocates.
|
||||
//! views). Native processing has no end-to-end allocation guarantee; Sonora owns internal buffers.
|
||||
|
||||
mod capture;
|
||||
pub use capture::{CaptureError, CaptureProcessor, CaptureSettings};
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use sonora::three_band_filter_bank::{
|
||||
@@ -134,7 +141,7 @@ impl Denoiser {
|
||||
&mut self.frame
|
||||
}
|
||||
|
||||
/// Denoise the frame in place. Allocation-free.
|
||||
/// 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);
|
||||
@@ -164,6 +171,13 @@ impl Denoiser {
|
||||
|
||||
// ── 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;
|
||||
@@ -257,6 +271,51 @@ pub extern "C" fn dsp_free(handle: u32) {
|
||||
}
|
||||
}
|
||||
|
||||
#[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::*;
|
||||
@@ -465,43 +524,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"upstream_revision": "a024d6ef8351add55be5e8b1d6cc35f555787660",
|
||||
"packages": [
|
||||
{
|
||||
"name": "sonora",
|
||||
"version": "0.2.0",
|
||||
"registry": "https://crates.io",
|
||||
"archive": "https://static.crates.io/crates/sonora/sonora-0.2.0.crate",
|
||||
"sha256": "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250",
|
||||
"path_in_vcs": "crates/sonora",
|
||||
"modified_sources": ["src/gain_controller2.rs"],
|
||||
"patch": "Mono AGC2 noise analysis uses a stack channel descriptor. Adaptive gain, fixed gain and limiter borrow AudioBuffer::channel_mut(0), eliminating caller-side per-frame channel/sample Vec allocation and copy-back. Multichannel processing remains the upstream path. Includes mono-vs-identical-stereo signal equivalence test."
|
||||
},
|
||||
{
|
||||
"name": "sonora-agc2",
|
||||
"version": "0.2.0",
|
||||
"registry": "https://crates.io",
|
||||
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.2.0.crate",
|
||||
"sha256": "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f",
|
||||
"path_in_vcs": "crates/sonora-agc2",
|
||||
"modified_sources": ["src/limiter.rs"],
|
||||
"patch": "Mono limiter level estimation uses a stack immutable channel descriptor rather than collecting Vec<&[f32]>. Multichannel processing and numerical operations remain unchanged."
|
||||
}
|
||||
],
|
||||
"scope": "This removes the inspected AGC2 mono channel-adapter allocations/copies; it is not an allocation-free guarantee for the complete Sonora APM or its other dependencies.",
|
||||
"source": "Copied installed pinned registry sources, retaining upstream Cargo manifests, lockfiles, license, README and VCS metadata; registry .cargo-ok extraction markers omitted.",
|
||||
"verification": "Tests added, not executed by delegated worker. Parent runs verification after integration."
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
|
||||
},
|
||||
"path_in_vcs": "crates/sonora-agc2"
|
||||
}
|
||||
+532
@@ -0,0 +1,532 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
dependencies = [
|
||||
"bytemuck_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive-ex"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bba95f299f6b9cd47f68a847eca2ae9060a2713af532dc35c342065544845407"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
|
||||
dependencies = [
|
||||
"derive_more-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more-impl"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn",
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-vec",
|
||||
"bitflags",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
"tempfile",
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xorshift"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusty-fork"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"quick-error",
|
||||
"tempfile",
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
"proptest",
|
||||
"sonora-common-audio",
|
||||
"sonora-fft",
|
||||
"sonora-simd",
|
||||
"test-strategy",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-common-audio"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"sonora-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-fft"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
|
||||
|
||||
[[package]]
|
||||
name = "sonora-simd"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "structmeta"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e1575d8d40908d70f6fd05537266b90ae71b15dbbe7a8b7dffa2b759306d329"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta-derive",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "structmeta-derive"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "test-strategy"
|
||||
version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f7fd1eb9efb36942b85a290c4201d317980fe09bc88d34dd48aaaae03075c6a"
|
||||
dependencies = [
|
||||
"derive-ex",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unarray"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.4+wasi-0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
Vendored
+86
@@ -0,0 +1,86 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Automatic Gain Control 2 (AGC2) with RNN VAD for WebRTC Audio Processing"
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"webrtc",
|
||||
"audio",
|
||||
"agc",
|
||||
"gain-control",
|
||||
"vad",
|
||||
]
|
||||
categories = ["multimedia::audio"]
|
||||
license = "BSD-3-Clause"
|
||||
repository = "https://github.com/dignifiedquire/sonora"
|
||||
|
||||
[lib]
|
||||
name = "sonora_agc2"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.bytemuck]
|
||||
version = "1"
|
||||
features = ["derive"]
|
||||
|
||||
[dependencies.derive_more]
|
||||
version = "2"
|
||||
features = ["debug"]
|
||||
|
||||
[dependencies.sonora-common-audio]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-fft]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-simd]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
|
||||
[dev-dependencies.proptest]
|
||||
version = "1.11"
|
||||
|
||||
[dev-dependencies.test-strategy]
|
||||
version = "0.4"
|
||||
|
||||
[lints.clippy]
|
||||
absolute_paths = "warn"
|
||||
allow_attributes_without_reason = "warn"
|
||||
approx_constant = "allow"
|
||||
excessive_precision = "allow"
|
||||
manual_let_else = "warn"
|
||||
mod_module_files = "deny"
|
||||
or_fun_call = "warn"
|
||||
unused_async = "warn"
|
||||
use_self = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
missing_debug_implementations = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
|
||||
[lints.rust.unexpected_cfgs]
|
||||
level = "deny"
|
||||
priority = 0
|
||||
check-cfg = ["cfg(docsrs)"]
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
description = "Automatic Gain Control 2 (AGC2) with RNN VAD for WebRTC Audio Processing"
|
||||
keywords = ["webrtc", "audio", "agc", "gain-control", "vad"]
|
||||
categories = ["multimedia::audio"]
|
||||
readme = "README.md"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
sonora-common-audio = { workspace = true }
|
||||
sonora-fft = { workspace = true }
|
||||
sonora-simd = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
derive_more = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
test-strategy = { workspace = true }
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
Copyright (c) 2011, The WebRTC Project Authors. All rights reserved.
|
||||
Copyright (c) 2016, Arun Raghavan and contributors. All rights reserved.
|
||||
Copyright (c) 2026, dignifiedquire. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# sonora-agc2
|
||||
|
||||
[![crate][crate-image]][crate-link]
|
||||
[![docs][docs-image]][docs-link]
|
||||
![BSD-3-Clause licensed][license-image]
|
||||
![Rust Version][rustc-image]
|
||||
|
||||
Pure Rust implementation of [Automatic Gain Control 2 (AGC2)][AGC2] from WebRTC.
|
||||
|
||||
RNN-based voice activity detection (VAD) drives an adaptive digital gain
|
||||
controller with limiter and clipping predictor. Includes fixed digital gain,
|
||||
speech level estimation, and input volume control.
|
||||
|
||||
Part of the [Sonora] audio processing library.
|
||||
|
||||
## License
|
||||
|
||||
BSD-3-Clause. See [LICENSE] for details.
|
||||
|
||||
[//]: # (badges)
|
||||
|
||||
[crate-image]: https://img.shields.io/crates/v/sonora-agc2.svg
|
||||
[crate-link]: https://crates.io/crates/sonora-agc2
|
||||
[docs-image]: https://docs.rs/sonora-agc2/badge.svg
|
||||
[docs-link]: https://docs.rs/sonora-agc2/
|
||||
[license-image]: https://img.shields.io/badge/license-BSD--3--Clause-blue.svg
|
||||
[rustc-image]: https://img.shields.io/badge/rustc-1.91+-blue.svg
|
||||
|
||||
[//]: # (general links)
|
||||
|
||||
[AGC2]: https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_processing/agc2/
|
||||
[Sonora]: https://github.com/dignifiedquire/sonora#readme
|
||||
[LICENSE]: https://github.com/dignifiedquire/sonora/blob/main/LICENSE
|
||||
@@ -0,0 +1,538 @@
|
||||
//! Adaptive digital gain controller.
|
||||
//!
|
||||
//! Selects the target digital gain, decides when and how quickly to adapt to
|
||||
//! the target and applies the current gain to 10 ms frames.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/adaptive_digital_gain_controller.h/.cc`.
|
||||
|
||||
use crate::common::{
|
||||
FRAME_DURATION_MS, LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS, VAD_CONFIDENCE_THRESHOLD, db_to_ratio,
|
||||
};
|
||||
use crate::gain_applier::GainApplier;
|
||||
use crate::speech_level_estimator::AdaptiveDigitalConfig;
|
||||
|
||||
/// Information about a frame to process.
|
||||
#[derive(Debug)]
|
||||
pub struct FrameInfo {
|
||||
/// Probability of speech in the [0, 1] range.
|
||||
pub speech_probability: f32,
|
||||
/// Estimated speech level (dBFS).
|
||||
pub speech_level_dbfs: f32,
|
||||
/// True with reliable speech level estimation.
|
||||
pub speech_level_reliable: bool,
|
||||
/// Estimated noise RMS level (dBFS).
|
||||
pub noise_rms_dbfs: f32,
|
||||
/// Headroom (dB).
|
||||
pub headroom_db: f32,
|
||||
/// Envelope level from the limiter (dBFS).
|
||||
pub limiter_envelope_dbfs: f32,
|
||||
}
|
||||
|
||||
/// Computes the gain for `input_level_dbfs` to reach `-config.headroom_db`.
|
||||
/// Clamps the gain in [0, `config.max_gain_db`].
|
||||
fn compute_gain_db(input_level_dbfs: f32, config: &AdaptiveDigitalConfig) -> f32 {
|
||||
// If the level is very low, apply the maximum gain.
|
||||
if input_level_dbfs < -(config.headroom_db + config.max_gain_db) {
|
||||
return config.max_gain_db;
|
||||
}
|
||||
// We expect to end up here most of the time: the level is below
|
||||
// -headroom, but we can boost it to -headroom.
|
||||
if input_level_dbfs < -config.headroom_db {
|
||||
return -config.headroom_db - input_level_dbfs;
|
||||
}
|
||||
// The level is too high and we can't boost.
|
||||
0.0
|
||||
}
|
||||
|
||||
/// Returns `target_gain_db` if applying such a gain to `input_noise_level_dbfs`
|
||||
/// does not exceed `max_output_noise_level_dbfs`. Otherwise lowers the gain.
|
||||
fn limit_gain_by_noise(
|
||||
target_gain_db: f32,
|
||||
input_noise_level_dbfs: f32,
|
||||
max_output_noise_level_dbfs: f32,
|
||||
) -> f32 {
|
||||
let max_allowed_gain_db = max_output_noise_level_dbfs - input_noise_level_dbfs;
|
||||
target_gain_db.min(max_allowed_gain_db.max(0.0))
|
||||
}
|
||||
|
||||
fn limit_gain_by_low_confidence(
|
||||
target_gain_db: f32,
|
||||
last_gain_db: f32,
|
||||
limiter_audio_level_dbfs: f32,
|
||||
estimate_is_confident: bool,
|
||||
) -> f32 {
|
||||
if estimate_is_confident || limiter_audio_level_dbfs <= LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS {
|
||||
return target_gain_db;
|
||||
}
|
||||
let limiter_level_dbfs_before_gain = limiter_audio_level_dbfs - last_gain_db;
|
||||
|
||||
// Compute a new gain so that `limiter_level_dbfs_before_gain` +
|
||||
// `new_target_gain_db` is not greater than the threshold.
|
||||
let new_target_gain_db =
|
||||
(LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS - limiter_level_dbfs_before_gain).max(0.0);
|
||||
new_target_gain_db.min(target_gain_db)
|
||||
}
|
||||
|
||||
/// Computes how the gain should change during this frame.
|
||||
fn compute_gain_change_this_frame_db(
|
||||
target_gain_db: f32,
|
||||
last_gain_db: f32,
|
||||
gain_increase_allowed: bool,
|
||||
max_gain_decrease_db: f32,
|
||||
max_gain_increase_db: f32,
|
||||
) -> f32 {
|
||||
debug_assert!(max_gain_decrease_db > 0.0);
|
||||
debug_assert!(max_gain_increase_db > 0.0);
|
||||
let mut target_gain_difference_db = target_gain_db - last_gain_db;
|
||||
if !gain_increase_allowed {
|
||||
target_gain_difference_db = target_gain_difference_db.min(0.0);
|
||||
}
|
||||
target_gain_difference_db.clamp(-max_gain_decrease_db, max_gain_increase_db)
|
||||
}
|
||||
|
||||
/// Adaptive digital gain controller.
|
||||
#[derive(Debug)]
|
||||
pub struct AdaptiveDigitalGainController {
|
||||
gain_applier: GainApplier,
|
||||
config: AdaptiveDigitalConfig,
|
||||
adjacent_speech_frames_threshold: i32,
|
||||
max_gain_change_db_per_10ms: f32,
|
||||
frames_to_gain_increase_allowed: i32,
|
||||
last_gain_db: f32,
|
||||
}
|
||||
|
||||
impl AdaptiveDigitalGainController {
|
||||
/// Creates a new adaptive digital gain controller.
|
||||
pub fn new(config: AdaptiveDigitalConfig, adjacent_speech_frames_threshold: i32) -> Self {
|
||||
let max_gain_change_db_per_10ms =
|
||||
config.max_gain_change_db_per_second * FRAME_DURATION_MS as f32 / 1000.0;
|
||||
debug_assert!(max_gain_change_db_per_10ms > 0.0);
|
||||
debug_assert!(adjacent_speech_frames_threshold >= 1);
|
||||
debug_assert!(config.max_output_noise_level_dbfs >= -90.0);
|
||||
debug_assert!(config.max_output_noise_level_dbfs <= 0.0);
|
||||
Self {
|
||||
gain_applier: GainApplier::new(false, db_to_ratio(config.initial_gain_db)),
|
||||
config,
|
||||
adjacent_speech_frames_threshold,
|
||||
max_gain_change_db_per_10ms,
|
||||
frames_to_gain_increase_allowed: adjacent_speech_frames_threshold,
|
||||
last_gain_db: config.initial_gain_db,
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyzes `info`, updates the digital gain and applies it to a 10 ms frame.
|
||||
pub fn process(&mut self, info: &FrameInfo, frame: &mut [&mut [f32]]) {
|
||||
debug_assert!(info.speech_level_dbfs >= -150.0);
|
||||
debug_assert!(!frame.is_empty());
|
||||
|
||||
// Compute the input level used to select the desired gain.
|
||||
debug_assert!(info.headroom_db > 0.0);
|
||||
let input_level_dbfs = info.speech_level_dbfs + info.headroom_db;
|
||||
|
||||
let target_gain_db = limit_gain_by_low_confidence(
|
||||
limit_gain_by_noise(
|
||||
compute_gain_db(input_level_dbfs, &self.config),
|
||||
info.noise_rms_dbfs,
|
||||
self.config.max_output_noise_level_dbfs,
|
||||
),
|
||||
self.last_gain_db,
|
||||
info.limiter_envelope_dbfs,
|
||||
info.speech_level_reliable,
|
||||
);
|
||||
|
||||
// Forbid increasing the gain until enough adjacent speech frames are
|
||||
// observed.
|
||||
let mut first_confident_speech_frame = false;
|
||||
if info.speech_probability < VAD_CONFIDENCE_THRESHOLD {
|
||||
self.frames_to_gain_increase_allowed = self.adjacent_speech_frames_threshold;
|
||||
} else if self.frames_to_gain_increase_allowed > 0 {
|
||||
self.frames_to_gain_increase_allowed -= 1;
|
||||
first_confident_speech_frame = self.frames_to_gain_increase_allowed == 0;
|
||||
}
|
||||
|
||||
let gain_increase_allowed = self.frames_to_gain_increase_allowed == 0;
|
||||
|
||||
let mut max_gain_increase_db = self.max_gain_change_db_per_10ms;
|
||||
if first_confident_speech_frame {
|
||||
// No gain increase happened while waiting for a long enough speech
|
||||
// sequence. Therefore, temporarily allow a faster gain increase.
|
||||
debug_assert!(gain_increase_allowed);
|
||||
max_gain_increase_db *= self.adjacent_speech_frames_threshold as f32;
|
||||
}
|
||||
|
||||
let gain_change_this_frame_db = compute_gain_change_this_frame_db(
|
||||
target_gain_db,
|
||||
self.last_gain_db,
|
||||
gain_increase_allowed,
|
||||
self.max_gain_change_db_per_10ms,
|
||||
max_gain_increase_db,
|
||||
);
|
||||
|
||||
// Optimization: avoid calling math functions if gain does not change.
|
||||
if gain_change_this_frame_db != 0.0 {
|
||||
self.gain_applier
|
||||
.set_gain_factor(db_to_ratio(self.last_gain_db + gain_change_this_frame_db));
|
||||
}
|
||||
|
||||
self.gain_applier.apply_gain(frame);
|
||||
|
||||
// Remember that the gain has changed for the next iteration.
|
||||
self.last_gain_db += gain_change_this_frame_db;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::common::{
|
||||
ADJACENT_SPEECH_FRAMES_THRESHOLD, FRAME_DURATION_MS, MIN_LEVEL_DBFS, db_to_ratio,
|
||||
};
|
||||
|
||||
const MONO: usize = 1;
|
||||
const STEREO: usize = 2;
|
||||
const FRAME_LEN_10MS_8KHZ: usize = 80;
|
||||
const FRAME_LEN_10MS_48KHZ: usize = 480;
|
||||
|
||||
const MAX_SPEECH_PROBABILITY: f32 = 1.0;
|
||||
|
||||
// Constants used in place of estimated noise levels.
|
||||
const NO_NOISE_DBFS: f32 = MIN_LEVEL_DBFS;
|
||||
const WITH_NOISE_DBFS: f32 = -20.0;
|
||||
|
||||
// Number of additional frames to process to ensure convergence.
|
||||
const NUM_EXTRA_FRAMES: i32 = 10;
|
||||
|
||||
const fn get_max_gain_change_per_frame_db(max_gain_change_db_per_second: f32) -> f32 {
|
||||
max_gain_change_db_per_second * FRAME_DURATION_MS as f32 / 1000.0
|
||||
}
|
||||
|
||||
fn default_config() -> AdaptiveDigitalConfig {
|
||||
AdaptiveDigitalConfig {
|
||||
headroom_db: 5.0,
|
||||
max_gain_db: 50.0,
|
||||
initial_gain_db: 15.0,
|
||||
max_gain_change_db_per_second: 6.0,
|
||||
max_output_noise_level_dbfs: -50.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `FrameInfo` that should cause no gain adaptation.
|
||||
fn get_frame_info_to_not_adapt(config: &AdaptiveDigitalConfig) -> FrameInfo {
|
||||
FrameInfo {
|
||||
speech_probability: MAX_SPEECH_PROBABILITY,
|
||||
speech_level_dbfs: -config.initial_gain_db - config.headroom_db,
|
||||
speech_level_reliable: true,
|
||||
noise_rms_dbfs: NO_NOISE_DBFS,
|
||||
headroom_db: config.headroom_db,
|
||||
limiter_envelope_dbfs: -2.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_frame(num_channels: usize, samples_per_channel: usize, value: f32) -> Vec<Vec<f32>> {
|
||||
vec![vec![value; samples_per_channel]; num_channels]
|
||||
}
|
||||
|
||||
fn as_mut_slices(frame: &mut [Vec<f32>]) -> Vec<&mut [f32]> {
|
||||
frame.iter_mut().map(|ch| ch.as_mut_slice()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_applier_should_not_crash() {
|
||||
let config = default_config();
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
let mut audio = make_frame(STEREO, FRAME_LEN_10MS_48KHZ, 10000.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
controller.process(&get_frame_info_to_not_adapt(&config), &mut slices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_gain_applied() {
|
||||
let config = default_config();
|
||||
let num_frames_to_adapt = (config.max_gain_db
|
||||
/ get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second))
|
||||
as i32
|
||||
+ NUM_EXTRA_FRAMES;
|
||||
let high_noise_config = AdaptiveDigitalConfig {
|
||||
max_output_noise_level_dbfs: -40.0,
|
||||
..config
|
||||
};
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(high_noise_config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
let mut info = get_frame_info_to_not_adapt(&high_noise_config);
|
||||
info.speech_level_dbfs = -60.0;
|
||||
let mut applied_gain = 0.0_f32;
|
||||
for _ in 0..num_frames_to_adapt {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_8KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
controller.process(&info, &mut slices);
|
||||
applied_gain = audio[0][0];
|
||||
}
|
||||
let applied_gain_db = 20.0 * applied_gain.log10();
|
||||
assert!(
|
||||
(applied_gain_db - config.max_gain_db).abs() < 0.1,
|
||||
"applied_gain_db={applied_gain_db}, expected ~{}",
|
||||
config.max_gain_db
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_does_not_change_fast() {
|
||||
let config = default_config();
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
|
||||
let initial_level_dbfs = -25.0_f32;
|
||||
let max_gain_change_db_per_frame =
|
||||
get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second);
|
||||
let num_frames_to_adapt =
|
||||
(initial_level_dbfs / max_gain_change_db_per_frame) as i32 + NUM_EXTRA_FRAMES;
|
||||
|
||||
let max_change_per_frame_linear = db_to_ratio(max_gain_change_db_per_frame);
|
||||
|
||||
let mut last_gain_linear = 1.0_f32;
|
||||
for _ in 0..num_frames_to_adapt {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_8KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs = initial_level_dbfs;
|
||||
controller.process(&info, &mut slices);
|
||||
let current_gain_linear = audio[0][0];
|
||||
assert!(
|
||||
(current_gain_linear - last_gain_linear).abs() <= max_change_per_frame_linear,
|
||||
"gain change {} exceeds max {}",
|
||||
(current_gain_linear - last_gain_linear).abs(),
|
||||
max_change_per_frame_linear
|
||||
);
|
||||
last_gain_linear = current_gain_linear;
|
||||
}
|
||||
|
||||
// Check that the same is true when gain decreases as well.
|
||||
for _ in 0..num_frames_to_adapt {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_8KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs = 0.0;
|
||||
controller.process(&info, &mut slices);
|
||||
let current_gain_linear = audio[0][0];
|
||||
assert!(
|
||||
(current_gain_linear - last_gain_linear).abs() <= max_change_per_frame_linear,
|
||||
"gain change {} exceeds max {}",
|
||||
(current_gain_linear - last_gain_linear).abs(),
|
||||
max_change_per_frame_linear
|
||||
);
|
||||
last_gain_linear = current_gain_linear;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_is_ramped_in_a_frame() {
|
||||
let config = default_config();
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
|
||||
let initial_level_dbfs = -25.0_f32;
|
||||
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs = initial_level_dbfs;
|
||||
controller.process(&info, &mut slices);
|
||||
let mut maximal_difference = 0.0_f32;
|
||||
let mut current_value = 1.0 * db_to_ratio(config.initial_gain_db);
|
||||
for &x in &audio[0] {
|
||||
let difference = (x - current_value).abs();
|
||||
maximal_difference = maximal_difference.max(difference);
|
||||
current_value = x;
|
||||
}
|
||||
|
||||
let max_change_per_frame_linear = db_to_ratio(get_max_gain_change_per_frame_db(
|
||||
config.max_gain_change_db_per_second,
|
||||
));
|
||||
let max_change_per_sample = max_change_per_frame_linear / FRAME_LEN_10MS_48KHZ as f32;
|
||||
|
||||
assert!(
|
||||
maximal_difference <= max_change_per_sample,
|
||||
"maximal_difference {maximal_difference} > max_change_per_sample {max_change_per_sample}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_limits_gain() {
|
||||
let config = default_config();
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
|
||||
let initial_level_dbfs = -25.0_f32;
|
||||
let num_initial_frames = (config.initial_gain_db
|
||||
/ get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second))
|
||||
as i32;
|
||||
let num_frames = 50;
|
||||
|
||||
assert!(
|
||||
WITH_NOISE_DBFS > config.max_output_noise_level_dbfs,
|
||||
"WITH_NOISE_DBFS is too low"
|
||||
);
|
||||
|
||||
for i in 0..num_initial_frames + num_frames {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs = initial_level_dbfs;
|
||||
info.noise_rms_dbfs = WITH_NOISE_DBFS;
|
||||
controller.process(&info, &mut slices);
|
||||
|
||||
// Wait so that the adaptive gain applier has time to lower the gain.
|
||||
if i > num_initial_frames {
|
||||
let maximal_ratio = audio[0].iter().copied().reduce(f32::max).unwrap();
|
||||
assert!(
|
||||
(maximal_ratio - 1.0).abs() < 0.001,
|
||||
"frame {i}: maximal_ratio={maximal_ratio}, expected ~1.0"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_handle_positive_speech_levels() {
|
||||
let config = default_config();
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
|
||||
let mut audio = make_frame(STEREO, FRAME_LEN_10MS_48KHZ, 10000.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs = 5.0;
|
||||
controller.process(&info, &mut slices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_level_limits_gain() {
|
||||
let config = default_config();
|
||||
let mut controller =
|
||||
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
|
||||
let initial_level_dbfs = -25.0_f32;
|
||||
let num_initial_frames = (config.initial_gain_db
|
||||
/ get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second))
|
||||
as i32;
|
||||
let num_frames = 50;
|
||||
|
||||
assert!(
|
||||
WITH_NOISE_DBFS > config.max_output_noise_level_dbfs,
|
||||
"WITH_NOISE_DBFS is too low"
|
||||
);
|
||||
|
||||
for i in 0..num_initial_frames + num_frames {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs = initial_level_dbfs;
|
||||
info.limiter_envelope_dbfs = 1.0;
|
||||
info.speech_level_reliable = false;
|
||||
controller.process(&info, &mut slices);
|
||||
|
||||
// Wait so that the adaptive gain applier has time to lower the gain.
|
||||
if i > num_initial_frames {
|
||||
let maximal_ratio = audio[0].iter().copied().reduce(f32::max).unwrap();
|
||||
assert!(
|
||||
(maximal_ratio - 1.0).abs() < 0.001,
|
||||
"frame {i}: maximal_ratio={maximal_ratio}, expected ~1.0"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parametrized tests for adjacent_speech_frames_threshold = 1, 7, 31, 12.
|
||||
|
||||
#[test]
|
||||
fn do_not_increase_gain_with_too_few_speech_frames_1() {
|
||||
do_not_increase_gain_with_too_few_speech_frames(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_increase_gain_with_too_few_speech_frames_7() {
|
||||
do_not_increase_gain_with_too_few_speech_frames(7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_increase_gain_with_too_few_speech_frames_31() {
|
||||
do_not_increase_gain_with_too_few_speech_frames(31);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_increase_gain_with_too_few_speech_frames_default() {
|
||||
do_not_increase_gain_with_too_few_speech_frames(ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
}
|
||||
|
||||
fn do_not_increase_gain_with_too_few_speech_frames(threshold: i32) {
|
||||
let config = default_config();
|
||||
let mut controller = AdaptiveDigitalGainController::new(config, threshold);
|
||||
|
||||
// Lower the speech level so that the target gain will be increased.
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs -= 12.0;
|
||||
|
||||
let mut prev_gain = 0.0_f32;
|
||||
for i in 0..threshold {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
controller.process(&info, &mut slices);
|
||||
let gain = audio[0][0];
|
||||
if i > 0 {
|
||||
assert_eq!(prev_gain, gain, "no gain increase expected at frame {i}");
|
||||
}
|
||||
prev_gain = gain;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn increase_gain_with_enough_speech_frames_1() {
|
||||
increase_gain_with_enough_speech_frames(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn increase_gain_with_enough_speech_frames_7() {
|
||||
increase_gain_with_enough_speech_frames(7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn increase_gain_with_enough_speech_frames_31() {
|
||||
increase_gain_with_enough_speech_frames(31);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn increase_gain_with_enough_speech_frames_default() {
|
||||
increase_gain_with_enough_speech_frames(ADJACENT_SPEECH_FRAMES_THRESHOLD);
|
||||
}
|
||||
|
||||
fn increase_gain_with_enough_speech_frames(threshold: i32) {
|
||||
let config = default_config();
|
||||
let mut controller = AdaptiveDigitalGainController::new(config, threshold);
|
||||
|
||||
// Lower the speech level so that the target gain will be increased.
|
||||
let mut info = get_frame_info_to_not_adapt(&config);
|
||||
info.speech_level_dbfs -= 12.0;
|
||||
|
||||
let mut prev_gain = 0.0_f32;
|
||||
for _ in 0..threshold {
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
controller.process(&info, &mut slices);
|
||||
prev_gain = audio[0][0];
|
||||
}
|
||||
|
||||
// Process one more speech frame.
|
||||
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
|
||||
let mut slices = as_mut_slices(&mut audio);
|
||||
controller.process(&info, &mut slices);
|
||||
|
||||
// An increased gain has been applied.
|
||||
assert!(
|
||||
audio[0][0] > prev_gain,
|
||||
"gain {} should be > prev_gain {}",
|
||||
audio[0][0],
|
||||
prev_gain
|
||||
);
|
||||
}
|
||||
}
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
//! IIR biquad filter.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/biquad_filter.h`.
|
||||
|
||||
/// Biquad filter coefficients.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct BiquadFilterConfig {
|
||||
/// Feedforward coefficients `[b0, b1, b2]`.
|
||||
pub b: [f32; 3],
|
||||
/// Feedback coefficients `[a1, a2]`.
|
||||
pub a: [f32; 2],
|
||||
}
|
||||
|
||||
/// Second-order IIR (biquad) filter.
|
||||
///
|
||||
/// Transfer function: `H(z) = (b0 + b1*z^-1 + b2*z^-2) / (1 + a1*z^-1 + a2*z^-2)`
|
||||
#[derive(Debug)]
|
||||
pub struct BiquadFilter {
|
||||
config: BiquadFilterConfig,
|
||||
/// State: `[x[n-1], x[n-2], y[n-1], y[n-2]]`.
|
||||
state: [f32; 4],
|
||||
}
|
||||
|
||||
impl BiquadFilter {
|
||||
/// Creates a new biquad filter with the given configuration.
|
||||
pub fn new(config: BiquadFilterConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
state: [0.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the filter state to zero.
|
||||
pub fn reset(&mut self) {
|
||||
self.state = [0.0; 4];
|
||||
}
|
||||
|
||||
/// Reconfigures the filter and resets state.
|
||||
pub fn set_config(&mut self, config: BiquadFilterConfig) {
|
||||
self.config = config;
|
||||
self.reset();
|
||||
}
|
||||
|
||||
/// Processes input samples `x` and writes filtered output to `y`.
|
||||
///
|
||||
/// `x` and `y` may be the same slice for in-place processing.
|
||||
pub fn process(&mut self, x: &[f32], y: &mut [f32]) {
|
||||
debug_assert_eq!(x.len(), y.len());
|
||||
for k in 0..x.len() {
|
||||
let tmp = x[k];
|
||||
y[k] = self.config.b[0] * tmp
|
||||
+ self.config.b[1] * self.state[0]
|
||||
+ self.config.b[2] * self.state[1]
|
||||
- self.config.a[0] * self.state[2]
|
||||
- self.config.a[1] * self.state[3];
|
||||
self.state[1] = self.state[0];
|
||||
self.state[0] = tmp;
|
||||
self.state[3] = self.state[2];
|
||||
self.state[2] = y[k];
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes samples in-place.
|
||||
pub fn process_in_place(&mut self, samples: &mut [f32]) {
|
||||
for sample in samples.iter_mut() {
|
||||
let tmp = *sample;
|
||||
*sample = self.config.b[0] * tmp
|
||||
+ self.config.b[1] * self.state[0]
|
||||
+ self.config.b[2] * self.state[1]
|
||||
- self.config.a[0] * self.state[2]
|
||||
- self.config.a[1] * self.state[3];
|
||||
self.state[1] = self.state[0];
|
||||
self.state[0] = tmp;
|
||||
self.state[3] = self.state[2];
|
||||
self.state[2] = *sample;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FRAME_SIZE: usize = 8;
|
||||
const NUM_FRAMES: usize = 4;
|
||||
|
||||
const BIQUAD_INPUT_SEQ: [[f32; FRAME_SIZE]; NUM_FRAMES] = [
|
||||
[
|
||||
-87.166_29, -8.029_022, 101.619_58, -0.294_296, -5.825_764, -8.890_625, 10.310_432,
|
||||
54.845_333,
|
||||
],
|
||||
[
|
||||
-64.647_644,
|
||||
-6.883_945,
|
||||
11.059_189,
|
||||
-95.242_54,
|
||||
-108.870_834,
|
||||
11.024_944,
|
||||
63.044_1,
|
||||
-52.709_583,
|
||||
],
|
||||
[
|
||||
-32.350_53,
|
||||
-18.108_028,
|
||||
-74.022_34,
|
||||
-8.986_874,
|
||||
-1.525_581,
|
||||
103.705_51,
|
||||
6.346_226,
|
||||
-14.319_557,
|
||||
],
|
||||
[
|
||||
22.645_832,
|
||||
-64.597_15,
|
||||
55.462_52,
|
||||
-109.393_19,
|
||||
10.117_825,
|
||||
-40.019_64,
|
||||
-98.612_23,
|
||||
-8.330_326,
|
||||
],
|
||||
];
|
||||
|
||||
// Computed as `scipy.signal.butter(N=2, Wn=60/24000, btype='highpass')`.
|
||||
const BIQUAD_CONFIG: BiquadFilterConfig = BiquadFilterConfig {
|
||||
b: [0.994_461_8, -1.988_923_5, 0.994_461_8],
|
||||
a: [-1.988_892_9, 0.988_954_25],
|
||||
};
|
||||
|
||||
// Comparing to scipy. The expected output is generated as follows:
|
||||
// zi = np.float32([0, 0])
|
||||
// for i in range(4):
|
||||
// yn, zi = scipy.signal.lfilter(B, A, x[i], zi=zi)
|
||||
// print(yn)
|
||||
const BIQUAD_OUTPUT_SEQ: [[f32; FRAME_SIZE]; NUM_FRAMES] = [
|
||||
[
|
||||
-86.683_55,
|
||||
-7.021_753_5,
|
||||
102.102_9,
|
||||
-0.374_873_33,
|
||||
-5.872_058_5,
|
||||
-8.855_216,
|
||||
10.337_726,
|
||||
54.511_57,
|
||||
],
|
||||
[
|
||||
-64.925_316,
|
||||
-6.763_96,
|
||||
11.155_345,
|
||||
-94.680_73,
|
||||
-107.181_78,
|
||||
13.246_425,
|
||||
64.842_89,
|
||||
-50.978_226,
|
||||
],
|
||||
[
|
||||
-30.157_965,
|
||||
-15.648_509,
|
||||
-71.066_63,
|
||||
-5.588_323,
|
||||
1.911_753_5,
|
||||
106.557_2,
|
||||
8.571_83,
|
||||
-12.062_985,
|
||||
],
|
||||
[
|
||||
24.842_866,
|
||||
-62.180_94,
|
||||
57.914_88,
|
||||
-106.656_86,
|
||||
13.387_601,
|
||||
-36.603_67,
|
||||
-94.448_8,
|
||||
-3.599_203_5,
|
||||
],
|
||||
];
|
||||
|
||||
/// Checks that the relative error between expected and computed values
|
||||
/// is within tolerance.
|
||||
fn expect_near_relative(expected: &[f32], computed: &[f32], tolerance: f32) {
|
||||
assert_eq!(expected.len(), computed.len());
|
||||
for (i, (&exp, &comp)) in expected.iter().zip(computed.iter()).enumerate() {
|
||||
let abs_diff = (exp - comp).abs();
|
||||
if abs_diff == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let den = if exp == 0.0 { 1.0 } else { exp.abs() };
|
||||
assert!(
|
||||
abs_diff / den <= tolerance,
|
||||
"index {i}: expected {exp}, computed {comp}, relative error {}",
|
||||
abs_diff / den,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_not_in_place() {
|
||||
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
|
||||
let mut samples = [0.0_f32; FRAME_SIZE];
|
||||
for (input, expected) in BIQUAD_INPUT_SEQ.iter().zip(&BIQUAD_OUTPUT_SEQ) {
|
||||
filter.process(input, &mut samples);
|
||||
expect_near_relative(expected, &samples, 2e-4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_in_place() {
|
||||
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
|
||||
let mut samples = [0.0_f32; FRAME_SIZE];
|
||||
for (input, expected) in BIQUAD_INPUT_SEQ.iter().zip(&BIQUAD_OUTPUT_SEQ) {
|
||||
samples.copy_from_slice(input);
|
||||
filter.process_in_place(&mut samples);
|
||||
expect_near_relative(expected, &samples, 2e-4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_config_different_output() {
|
||||
let mut filter = BiquadFilter::new(BiquadFilterConfig {
|
||||
b: [0.978_030_5, -1.956_061, 0.978_030_5],
|
||||
a: [-1.955_578_2, 0.956_543_7],
|
||||
});
|
||||
let mut samples1 = [0.0_f32; FRAME_SIZE];
|
||||
for input in &BIQUAD_INPUT_SEQ {
|
||||
filter.process(input, &mut samples1);
|
||||
}
|
||||
|
||||
filter.set_config(BiquadFilterConfig {
|
||||
b: [0.097_631_07, 0.195_262_15, 0.097_631_07],
|
||||
a: [-0.942_809_04, 0.333_333_33],
|
||||
});
|
||||
let mut samples2 = [0.0_f32; FRAME_SIZE];
|
||||
for input in &BIQUAD_INPUT_SEQ {
|
||||
filter.process(input, &mut samples2);
|
||||
}
|
||||
|
||||
assert_ne!(samples1, samples2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_config_resets_state() {
|
||||
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
|
||||
let mut samples1 = [0.0_f32; FRAME_SIZE];
|
||||
for input in &BIQUAD_INPUT_SEQ {
|
||||
filter.process(input, &mut samples1);
|
||||
}
|
||||
|
||||
filter.set_config(BIQUAD_CONFIG);
|
||||
let mut samples2 = [0.0_f32; FRAME_SIZE];
|
||||
for input in &BIQUAD_INPUT_SEQ {
|
||||
filter.process(input, &mut samples2);
|
||||
}
|
||||
|
||||
assert_eq!(samples1, samples2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset() {
|
||||
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
|
||||
let mut samples1 = [0.0_f32; FRAME_SIZE];
|
||||
for input in &BIQUAD_INPUT_SEQ {
|
||||
filter.process(input, &mut samples1);
|
||||
}
|
||||
|
||||
filter.reset();
|
||||
let mut samples2 = [0.0_f32; FRAME_SIZE];
|
||||
for input in &BIQUAD_INPUT_SEQ {
|
||||
filter.process(input, &mut samples2);
|
||||
}
|
||||
|
||||
assert_eq!(samples1, samples2);
|
||||
}
|
||||
}
|
||||
+1147
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,350 @@
|
||||
//! Circular buffer for frame-wise level metrics used by the clipping predictor.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/clipping_predictor_level_buffer.h/cc`.
|
||||
|
||||
/// Recommended maximum capacity. It is possible to create a buffer with a
|
||||
/// larger capacity, but the implementation is not optimized for large values.
|
||||
pub const MAX_CAPACITY: usize = 100;
|
||||
|
||||
/// Frame-wise level metrics: average (mean squared) and max (peak).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Level {
|
||||
pub average: f32,
|
||||
pub max: f32,
|
||||
}
|
||||
|
||||
impl PartialEq for Level {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
const EPSILON: f32 = 1e-6;
|
||||
(self.average - other.average).abs() < EPSILON && (self.max - other.max).abs() < EPSILON
|
||||
}
|
||||
}
|
||||
|
||||
/// A circular buffer to store frame-wise [`Level`] items for clipping prediction.
|
||||
/// The current implementation is not optimized for large buffer lengths.
|
||||
#[derive(Debug)]
|
||||
pub struct ClippingPredictorLevelBuffer {
|
||||
tail: isize,
|
||||
size: usize,
|
||||
data: Vec<Level>,
|
||||
}
|
||||
|
||||
impl ClippingPredictorLevelBuffer {
|
||||
/// Creates a new buffer with the given capacity (minimum 1).
|
||||
/// Logs a warning if capacity exceeds [`MAX_CAPACITY`].
|
||||
pub fn new(capacity: i32) -> Self {
|
||||
let capacity = capacity.max(1) as usize;
|
||||
if capacity > MAX_CAPACITY {
|
||||
tracing::warn!(
|
||||
"[agc]: ClippingPredictorLevelBuffer exceeds the maximum allowed capacity. Capacity: {}",
|
||||
capacity
|
||||
);
|
||||
}
|
||||
Self {
|
||||
tail: -1,
|
||||
size: 0,
|
||||
data: vec![
|
||||
Level {
|
||||
average: 0.0,
|
||||
max: 0.0
|
||||
};
|
||||
capacity
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the buffer, discarding all stored items.
|
||||
pub fn reset(&mut self) {
|
||||
self.tail = -1;
|
||||
self.size = 0;
|
||||
}
|
||||
|
||||
/// Returns the number of items currently in the buffer.
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
|
||||
/// Returns the capacity of the buffer.
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.data.len()
|
||||
}
|
||||
|
||||
/// Pushes a [`Level`] item into the circular buffer. If the buffer is full,
|
||||
/// the oldest item is replaced.
|
||||
pub fn push(&mut self, level: Level) {
|
||||
self.tail += 1;
|
||||
if self.tail as usize == self.capacity() {
|
||||
self.tail = 0;
|
||||
}
|
||||
if self.size < self.capacity() {
|
||||
self.size += 1;
|
||||
}
|
||||
self.data[self.tail as usize] = level;
|
||||
}
|
||||
|
||||
/// If at least `num_items + delay` items have been pushed, returns the
|
||||
/// average and maximum value for the `num_items` most recently pushed items
|
||||
/// starting from `delay` positions back (delay=0 is the most recent item).
|
||||
pub fn compute_partial_metrics(&self, delay: usize, num_items: usize) -> Option<Level> {
|
||||
debug_assert!(delay < self.capacity());
|
||||
debug_assert!(num_items > 0);
|
||||
debug_assert!(num_items <= self.capacity());
|
||||
debug_assert!(delay + num_items <= self.capacity());
|
||||
|
||||
if delay + num_items > self.size {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut sum = 0.0_f32;
|
||||
let mut max = 0.0_f32;
|
||||
for i in 0..num_items.min(self.size) {
|
||||
let mut idx = self.tail - delay as isize - i as isize;
|
||||
if idx < 0 {
|
||||
idx += self.capacity() as isize;
|
||||
}
|
||||
sum += self.data[idx as usize].average;
|
||||
max = max.max(self.data[idx as usize].max);
|
||||
}
|
||||
Some(Level {
|
||||
average: sum / num_items as f32,
|
||||
max,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Parametrized test helper: checks empty buffer size for various capacities.
|
||||
#[test]
|
||||
fn check_empty_buffer_size() {
|
||||
for &capacity in &[-1, 0, 1, 123] {
|
||||
let buffer = ClippingPredictorLevelBuffer::new(capacity);
|
||||
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
|
||||
assert_eq!(buffer.size(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_half_empty_buffer_size() {
|
||||
for &capacity in &[-1, 0, 1, 123] {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
|
||||
for _ in 0..buffer.capacity() / 2 {
|
||||
buffer.push(Level {
|
||||
average: 2.0,
|
||||
max: 4.0,
|
||||
});
|
||||
}
|
||||
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
|
||||
assert_eq!(buffer.size(), capacity.max(1) as usize / 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_full_buffer_size() {
|
||||
for &capacity in &[-1, 0, 1, 123] {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
|
||||
for _ in 0..buffer.capacity() {
|
||||
buffer.push(Level {
|
||||
average: 2.0,
|
||||
max: 4.0,
|
||||
});
|
||||
}
|
||||
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
|
||||
assert_eq!(buffer.size(), capacity.max(1) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_large_buffer_size() {
|
||||
for &capacity in &[-1, 0, 1, 123] {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
|
||||
for _ in 0..2 * buffer.capacity() {
|
||||
buffer.push(Level {
|
||||
average: 2.0,
|
||||
max: 4.0,
|
||||
});
|
||||
}
|
||||
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
|
||||
assert_eq!(buffer.size(), capacity.max(1) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_size_after_reset() {
|
||||
for &capacity in &[-1, 0, 1, 123] {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 1.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 1.0,
|
||||
});
|
||||
buffer.reset();
|
||||
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
|
||||
assert_eq!(buffer.size(), 0);
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 1.0,
|
||||
});
|
||||
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
|
||||
assert_eq!(buffer.size(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_metrics_after_full_buffer() {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(2);
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 2.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 3.0,
|
||||
max: 6.0,
|
||||
});
|
||||
|
||||
let m = buffer.compute_partial_metrics(0, 1).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 3.0,
|
||||
max: 6.0
|
||||
}
|
||||
);
|
||||
|
||||
let m = buffer.compute_partial_metrics(1, 1).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 1.0,
|
||||
max: 2.0
|
||||
}
|
||||
);
|
||||
|
||||
let m = buffer.compute_partial_metrics(0, 2).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 2.0,
|
||||
max: 6.0
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_metrics_after_push_beyond_capacity() {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(2);
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 1.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 3.0,
|
||||
max: 6.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 5.0,
|
||||
max: 10.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 7.0,
|
||||
max: 14.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 6.0,
|
||||
max: 12.0,
|
||||
});
|
||||
|
||||
let m = buffer.compute_partial_metrics(0, 1).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 6.0,
|
||||
max: 12.0
|
||||
}
|
||||
);
|
||||
|
||||
let m = buffer.compute_partial_metrics(1, 1).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 7.0,
|
||||
max: 14.0
|
||||
}
|
||||
);
|
||||
|
||||
let m = buffer.compute_partial_metrics(0, 2).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 6.5,
|
||||
max: 14.0
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_metrics_after_too_few_items() {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(4);
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 2.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 3.0,
|
||||
max: 6.0,
|
||||
});
|
||||
|
||||
assert!(buffer.compute_partial_metrics(0, 3).is_none());
|
||||
assert!(buffer.compute_partial_metrics(2, 1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_metrics_after_reset() {
|
||||
let mut buffer = ClippingPredictorLevelBuffer::new(2);
|
||||
buffer.push(Level {
|
||||
average: 1.0,
|
||||
max: 2.0,
|
||||
});
|
||||
buffer.reset();
|
||||
buffer.push(Level {
|
||||
average: 5.0,
|
||||
max: 10.0,
|
||||
});
|
||||
buffer.push(Level {
|
||||
average: 7.0,
|
||||
max: 14.0,
|
||||
});
|
||||
|
||||
let m = buffer.compute_partial_metrics(0, 1).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 7.0,
|
||||
max: 14.0
|
||||
}
|
||||
);
|
||||
|
||||
let m = buffer.compute_partial_metrics(0, 2).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 6.0,
|
||||
max: 14.0
|
||||
}
|
||||
);
|
||||
|
||||
let m = buffer.compute_partial_metrics(1, 1).unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Level {
|
||||
average: 5.0,
|
||||
max: 10.0
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+104
@@ -0,0 +1,104 @@
|
||||
//! AGC2 common constants and audio utility functions.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/agc2_common.h`
|
||||
//! and `webrtc/common_audio/include/audio_util.h`.
|
||||
|
||||
/// Minimum value of a float-encoded S16 sample (`-32768.0`).
|
||||
pub const MIN_FLOAT_S16_VALUE: f32 = -32768.0;
|
||||
/// Maximum value of a float-encoded S16 sample (`32767.0`).
|
||||
pub const MAX_FLOAT_S16_VALUE: f32 = 32767.0;
|
||||
/// Absolute maximum magnitude of a float-encoded S16 sample (`32768.0`).
|
||||
pub const MAX_ABS_FLOAT_S16_VALUE: f32 = 32768.0;
|
||||
|
||||
/// Minimum audio level in dBFS scale for S16 samples (`20 * log10(1/32768)`).
|
||||
pub const MIN_LEVEL_DBFS: f32 = -90.309;
|
||||
|
||||
/// Duration of one audio frame in milliseconds.
|
||||
pub const FRAME_DURATION_MS: i32 = 10;
|
||||
/// Number of sub-frames per frame (used for gain interpolation).
|
||||
pub const SUB_FRAMES_IN_FRAME: i32 = 20;
|
||||
/// Maximum number of samples per channel in a single frame (48 kHz * 10 ms).
|
||||
pub const MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL: usize = 480;
|
||||
|
||||
// Adaptive digital gain applier settings.
|
||||
|
||||
/// At what limiter levels should we start decreasing the adaptive digital gain.
|
||||
pub const LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS: f32 = -1.0;
|
||||
|
||||
/// Number of milliseconds to wait to periodically reset the VAD.
|
||||
pub const VAD_RESET_PERIOD_MS: i32 = 1500;
|
||||
|
||||
/// Speech probability threshold to detect speech activity.
|
||||
pub const VAD_CONFIDENCE_THRESHOLD: f32 = 0.95;
|
||||
|
||||
/// Minimum number of adjacent speech frames having a sufficiently high speech
|
||||
/// probability to reliably detect speech activity.
|
||||
pub const ADJACENT_SPEECH_FRAMES_THRESHOLD: i32 = 12;
|
||||
|
||||
/// Number of milliseconds of speech frames to observe to make the estimator
|
||||
/// confident.
|
||||
pub const LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS: f32 = 400.0;
|
||||
/// Exponential decay factor for the speech level estimator.
|
||||
pub const LEVEL_ESTIMATOR_LEAK_FACTOR: f32 = 1.0 - 1.0 / LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS;
|
||||
|
||||
/// Initial headroom in dB for the saturation protector.
|
||||
pub const SATURATION_PROTECTOR_INITIAL_HEADROOM_DB: f32 = 20.0;
|
||||
/// Ring buffer size (in 10 ms frames) for the saturation protector.
|
||||
pub const SATURATION_PROTECTOR_BUFFER_SIZE: usize = 4;
|
||||
|
||||
/// Number of interpolation points in the knee region of the limiter gain curve.
|
||||
///
|
||||
/// These values have been tuned to limit the interpolated gain curve error given
|
||||
/// the limiter parameters and allowing a maximum error of +/- 32768^-1.
|
||||
pub const INTERPOLATED_GAIN_CURVE_KNEE_POINTS: usize = 22;
|
||||
/// Number of interpolation points beyond the knee region.
|
||||
pub const INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS: usize = 10;
|
||||
/// Total number of interpolation points in the limiter gain curve.
|
||||
pub const INTERPOLATED_GAIN_CURVE_TOTAL_POINTS: usize =
|
||||
INTERPOLATED_GAIN_CURVE_KNEE_POINTS + INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS;
|
||||
|
||||
/// Maximum input level in dBFS for the limiter.
|
||||
pub const LIMITER_MAX_INPUT_LEVEL_DB_FS: f64 = 1.0;
|
||||
/// Smoothness of the limiter knee transition in dB.
|
||||
pub const LIMITER_KNEE_SMOOTHNESS_DB: f64 = 1.0;
|
||||
/// Compression ratio applied above the limiter knee.
|
||||
pub const LIMITER_COMPRESSION_RATIO: f64 = 5.0;
|
||||
|
||||
// Audio utility functions ported from common_audio/include/audio_util.h.
|
||||
|
||||
/// Converts a dB value to a linear ratio: `10^(v/20)`.
|
||||
pub fn db_to_ratio(v: f32) -> f32 {
|
||||
10.0_f32.powf(v / 20.0)
|
||||
}
|
||||
|
||||
/// Converts a dBFS value to a float S16 linear value.
|
||||
pub fn dbfs_to_float_s16(v: f32) -> f32 {
|
||||
db_to_ratio(v) * MAX_ABS_FLOAT_S16_VALUE
|
||||
}
|
||||
|
||||
/// Converts a float S16 linear value to dBFS.
|
||||
pub fn float_s16_to_dbfs(v: f32) -> f32 {
|
||||
debug_assert!(v >= 0.0);
|
||||
// kMinDbfs is equal to -20.0 * log10(-limits_int16::min())
|
||||
const MIN_DBFS: f32 = -90.309;
|
||||
if v <= 1.0 {
|
||||
return MIN_DBFS;
|
||||
}
|
||||
// Equal to 20 * log10(v / (-limits_int16::min()))
|
||||
20.0 * v.log10() + MIN_DBFS
|
||||
}
|
||||
|
||||
/// Converts a dBFS value to a float S16 linear value (f64 version).
|
||||
pub fn dbfs_to_float_s16_f64(v: f64) -> f64 {
|
||||
10.0_f64.powf(v / 20.0) * MAX_ABS_FLOAT_S16_VALUE as f64
|
||||
}
|
||||
|
||||
/// Converts a float S16 linear value to dBFS (f64 version).
|
||||
pub fn float_s16_to_dbfs_f64(v: f64) -> f64 {
|
||||
debug_assert!(v >= 0.0);
|
||||
const MIN_DBFS: f64 = -90.308_998_699_194_36;
|
||||
if v <= 1.0 {
|
||||
return MIN_DBFS;
|
||||
}
|
||||
20.0 * v.log10() + MIN_DBFS
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
//! Peak envelope level estimator with exponential smoothing.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/fixed_digital_level_estimator.h/.cc`.
|
||||
|
||||
use crate::common::SUB_FRAMES_IN_FRAME;
|
||||
|
||||
/// Initial filter state level.
|
||||
const INITIAL_FILTER_STATE_LEVEL: f32 = 0.0;
|
||||
|
||||
/// Instant attack.
|
||||
const ATTACK_FILTER_CONSTANT: f32 = 0.0;
|
||||
|
||||
/// Limiter decay constant.
|
||||
/// Computed as `10 ** (-1/20 * subframe_duration / decay_ms)` where:
|
||||
/// - `subframe_duration` is `FRAME_DURATION_MS / SUB_FRAMES_IN_FRAME`;
|
||||
/// - `decay_ms` is 20.0 (from `agc2_testing_common.h`).
|
||||
const DECAY_FILTER_CONSTANT: f32 = 0.9971259;
|
||||
|
||||
/// Produces a smooth signal level estimate from an input audio stream.
|
||||
/// The estimate smoothing is done through exponential filtering.
|
||||
#[derive(Debug)]
|
||||
pub struct FixedDigitalLevelEstimator {
|
||||
filter_state_level: f32,
|
||||
samples_in_frame: i32,
|
||||
samples_in_sub_frame: i32,
|
||||
}
|
||||
|
||||
impl FixedDigitalLevelEstimator {
|
||||
/// Creates a new estimator.
|
||||
///
|
||||
/// `samples_per_channel` must be divisible by `SUB_FRAMES_IN_FRAME`.
|
||||
pub fn new(samples_per_channel: usize) -> Self {
|
||||
let mut est = Self {
|
||||
filter_state_level: INITIAL_FILTER_STATE_LEVEL,
|
||||
samples_in_frame: 0,
|
||||
samples_in_sub_frame: 0,
|
||||
};
|
||||
est.set_samples_per_channel(samples_per_channel);
|
||||
est.check_parameter_combination();
|
||||
est
|
||||
}
|
||||
|
||||
/// Computes the level envelope for a multi-channel frame.
|
||||
///
|
||||
/// The input is assumed to be in FloatS16 format. Returns `SUB_FRAMES_IN_FRAME`
|
||||
/// level estimates, one per sub-frame.
|
||||
pub fn compute_level(&mut self, frame: &[&[f32]]) -> [f32; SUB_FRAMES_IN_FRAME as usize] {
|
||||
let num_channels = frame.len();
|
||||
debug_assert!(num_channels > 0);
|
||||
debug_assert_eq!(frame[0].len(), self.samples_in_frame as usize);
|
||||
|
||||
// Compute max envelope without smoothing.
|
||||
let mut envelope = [0.0_f32; SUB_FRAMES_IN_FRAME as usize];
|
||||
let sub_frame_len = self.samples_in_sub_frame as usize;
|
||||
for channel in frame {
|
||||
for (sub_frame, env) in envelope.iter_mut().enumerate() {
|
||||
let sub_frame_samples =
|
||||
&channel[sub_frame * sub_frame_len..(sub_frame + 1) * sub_frame_len];
|
||||
for &sample in sub_frame_samples {
|
||||
*env = env.max(sample.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure envelope increases happen one step earlier so that the
|
||||
// corresponding *gain decrease* doesn't miss a sudden signal
|
||||
// increase due to interpolation.
|
||||
for sub_frame in 0..SUB_FRAMES_IN_FRAME as usize - 1 {
|
||||
if envelope[sub_frame] < envelope[sub_frame + 1] {
|
||||
envelope[sub_frame] = envelope[sub_frame + 1];
|
||||
}
|
||||
}
|
||||
|
||||
// Add attack / decay smoothing.
|
||||
for env in &mut envelope {
|
||||
let envelope_value = *env;
|
||||
if envelope_value > self.filter_state_level {
|
||||
*env = envelope_value * (1.0 - ATTACK_FILTER_CONSTANT)
|
||||
+ self.filter_state_level * ATTACK_FILTER_CONSTANT;
|
||||
} else {
|
||||
*env = envelope_value * (1.0 - DECAY_FILTER_CONSTANT)
|
||||
+ self.filter_state_level * DECAY_FILTER_CONSTANT;
|
||||
}
|
||||
self.filter_state_level = *env;
|
||||
}
|
||||
|
||||
envelope
|
||||
}
|
||||
|
||||
/// Changes the sample rate (samples per channel for a 10ms frame).
|
||||
pub fn set_samples_per_channel(&mut self, samples_per_channel: usize) {
|
||||
self.samples_in_frame = samples_per_channel as i32;
|
||||
self.samples_in_sub_frame = self.samples_in_frame / SUB_FRAMES_IN_FRAME;
|
||||
self.check_parameter_combination();
|
||||
}
|
||||
|
||||
/// Resets the level estimator internal state.
|
||||
pub fn reset(&mut self) {
|
||||
self.filter_state_level = INITIAL_FILTER_STATE_LEVEL;
|
||||
}
|
||||
|
||||
/// Returns the last computed audio level.
|
||||
pub fn last_audio_level(&self) -> f32 {
|
||||
self.filter_state_level
|
||||
}
|
||||
|
||||
fn check_parameter_combination(&self) {
|
||||
debug_assert!(self.samples_in_frame > 0);
|
||||
debug_assert!(SUB_FRAMES_IN_FRAME <= self.samples_in_frame);
|
||||
debug_assert_eq!(self.samples_in_frame % SUB_FRAMES_IN_FRAME, 0);
|
||||
debug_assert!(self.samples_in_sub_frame > 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::common::{FRAME_DURATION_MS, SUB_FRAMES_IN_FRAME, dbfs_to_float_s16};
|
||||
|
||||
const INPUT_LEVEL: f32 = 10000.0;
|
||||
|
||||
/// Decay time constant in ms (from agc2_testing_common.h).
|
||||
const DECAY_MS: f32 = 20.0;
|
||||
|
||||
/// Returns `sample_rate / 100` (samples per channel for 10ms).
|
||||
fn sample_rate_to_default_channel_size(sample_rate: usize) -> usize {
|
||||
sample_rate / 100
|
||||
}
|
||||
|
||||
/// Run audio at specified settings through the level estimator, and
|
||||
/// verify that the output level falls within the bounds.
|
||||
fn test_level_estimator(
|
||||
samples_per_channel: usize,
|
||||
num_channels: usize,
|
||||
input_level_linear_scale: f32,
|
||||
expected_min: f32,
|
||||
expected_max: f32,
|
||||
) {
|
||||
let mut level_estimator = FixedDigitalLevelEstimator::new(samples_per_channel);
|
||||
|
||||
// Create constant-level frame.
|
||||
let channel_data = vec![input_level_linear_scale; samples_per_channel];
|
||||
let channels: Vec<&[f32]> = vec![channel_data.as_slice(); num_channels];
|
||||
|
||||
for i in 0..500 {
|
||||
let level = level_estimator.compute_level(&channels);
|
||||
|
||||
// Give the estimator some time to ramp up.
|
||||
if i < 50 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for x in &level {
|
||||
assert!(
|
||||
expected_min <= *x,
|
||||
"level {x} < expected_min {expected_min} at frame {i}"
|
||||
);
|
||||
assert!(
|
||||
*x <= expected_max,
|
||||
"level {x} > expected_max {expected_max} at frame {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns time it takes for the level estimator to decrease its level
|
||||
/// estimate by `level_reduction_db`.
|
||||
fn time_ms_to_decrease_level(
|
||||
samples_per_channel: usize,
|
||||
num_channels: usize,
|
||||
input_level_db: f32,
|
||||
level_reduction_db: f32,
|
||||
) -> f32 {
|
||||
let input_level = dbfs_to_float_s16(input_level_db);
|
||||
debug_assert!(level_reduction_db > 0.0);
|
||||
|
||||
let channel_data = vec![input_level; samples_per_channel];
|
||||
let channels: Vec<&[f32]> = vec![channel_data.as_slice(); num_channels];
|
||||
|
||||
let mut level_estimator = FixedDigitalLevelEstimator::new(samples_per_channel);
|
||||
|
||||
// Give the LevelEstimator plenty of time to ramp up and stabilize.
|
||||
let mut last_level = 0.0_f32;
|
||||
for _ in 0..500 {
|
||||
let level_envelope = level_estimator.compute_level(&channels);
|
||||
last_level = *level_envelope.last().unwrap();
|
||||
}
|
||||
|
||||
// Set input to 0.
|
||||
let zero_channel_data = vec![0.0_f32; samples_per_channel];
|
||||
let zero_channels: Vec<&[f32]> = vec![zero_channel_data.as_slice(); num_channels];
|
||||
|
||||
let reduced_level_linear = dbfs_to_float_s16(input_level_db - level_reduction_db);
|
||||
let mut sub_frames_until_level_reduction = 0;
|
||||
while last_level > reduced_level_linear {
|
||||
let level_envelope = level_estimator.compute_level(&zero_channels);
|
||||
for v in &level_envelope {
|
||||
assert!(*v < last_level, "level should decrease monotonically");
|
||||
sub_frames_until_level_reduction += 1;
|
||||
last_level = *v;
|
||||
if last_level <= reduced_level_linear {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sub_frames_until_level_reduction as f32 * FRAME_DURATION_MS as f32
|
||||
/ SUB_FRAMES_IN_FRAME as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimator_should_not_crash() {
|
||||
test_level_estimator(
|
||||
sample_rate_to_default_channel_size(8000),
|
||||
1,
|
||||
0.0,
|
||||
f32::MIN,
|
||||
f32::MAX,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimator_should_estimate_constant_level() {
|
||||
test_level_estimator(
|
||||
sample_rate_to_default_channel_size(10000),
|
||||
1,
|
||||
INPUT_LEVEL,
|
||||
INPUT_LEVEL * 0.99,
|
||||
INPUT_LEVEL * 1.01,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimator_should_estimate_constant_level_for_many_channels() {
|
||||
let num_channels = 10;
|
||||
test_level_estimator(
|
||||
sample_rate_to_default_channel_size(20000),
|
||||
num_channels,
|
||||
INPUT_LEVEL,
|
||||
INPUT_LEVEL * 0.99,
|
||||
INPUT_LEVEL * 1.01,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_to_decrease_for_low_level() {
|
||||
let level_reduction_db = 25.0;
|
||||
let initial_low_level = -40.0;
|
||||
let expected_time = level_reduction_db * DECAY_MS;
|
||||
|
||||
let time_to_decrease = time_ms_to_decrease_level(
|
||||
sample_rate_to_default_channel_size(22000),
|
||||
1,
|
||||
initial_low_level,
|
||||
level_reduction_db,
|
||||
);
|
||||
|
||||
assert!(
|
||||
expected_time * 0.9 <= time_to_decrease,
|
||||
"time_to_decrease {time_to_decrease} < expected {}",
|
||||
expected_time * 0.9
|
||||
);
|
||||
assert!(
|
||||
time_to_decrease <= expected_time * 1.1,
|
||||
"time_to_decrease {time_to_decrease} > expected {}",
|
||||
expected_time * 1.1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_to_decrease_for_full_scale_level() {
|
||||
let level_reduction_db = 25.0;
|
||||
let expected_time = level_reduction_db * DECAY_MS;
|
||||
|
||||
let time_to_decrease = time_ms_to_decrease_level(
|
||||
sample_rate_to_default_channel_size(26000),
|
||||
1,
|
||||
0.0,
|
||||
level_reduction_db,
|
||||
);
|
||||
|
||||
assert!(
|
||||
expected_time * 0.9 <= time_to_decrease,
|
||||
"time_to_decrease {time_to_decrease} < expected {}",
|
||||
expected_time * 0.9
|
||||
);
|
||||
assert!(
|
||||
time_to_decrease <= expected_time * 1.1,
|
||||
"time_to_decrease {time_to_decrease} > expected {}",
|
||||
expected_time * 1.1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_to_decrease_for_multiple_channels() {
|
||||
let level_reduction_db = 25.0;
|
||||
let expected_time = level_reduction_db * DECAY_MS;
|
||||
let num_channels = 10;
|
||||
|
||||
let time_to_decrease = time_ms_to_decrease_level(
|
||||
sample_rate_to_default_channel_size(28000),
|
||||
num_channels,
|
||||
0.0,
|
||||
level_reduction_db,
|
||||
);
|
||||
|
||||
assert!(
|
||||
expected_time * 0.9 <= time_to_decrease,
|
||||
"time_to_decrease {time_to_decrease} < expected {}",
|
||||
expected_time * 0.9
|
||||
);
|
||||
assert!(
|
||||
time_to_decrease <= expected_time * 1.1,
|
||||
"time_to_decrease {time_to_decrease} > expected {}",
|
||||
expected_time * 1.1
|
||||
);
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
//! Per-sample gain application with linear ramping.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/gain_applier.h/.cc`.
|
||||
|
||||
use crate::common::{MAX_FLOAT_S16_VALUE, MIN_FLOAT_S16_VALUE};
|
||||
|
||||
/// Returns true when the gain factor is so close to 1 that it would
|
||||
/// not affect int16 samples.
|
||||
fn gain_close_to_one(gain_factor: f32) -> bool {
|
||||
let threshold = 1.0 / MAX_FLOAT_S16_VALUE;
|
||||
(1.0 - threshold..=1.0 + threshold).contains(&gain_factor)
|
||||
}
|
||||
|
||||
/// Clamps all samples in multi-channel signal to FloatS16 range.
|
||||
fn clip_signal(signal: &mut [&mut [f32]]) {
|
||||
for channel in signal.iter_mut() {
|
||||
for sample in channel.iter_mut() {
|
||||
*sample = sample.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies gain with linear ramping across the frame.
|
||||
fn apply_gain_with_ramping(
|
||||
last_gain: f32,
|
||||
gain_at_end: f32,
|
||||
inverse_samples_per_channel: f32,
|
||||
signal: &mut [&mut [f32]],
|
||||
) {
|
||||
// Do not modify the signal.
|
||||
if last_gain == gain_at_end && gain_close_to_one(gain_at_end) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Gain is constant and different from 1.
|
||||
if last_gain == gain_at_end {
|
||||
for channel in signal.iter_mut() {
|
||||
for sample in channel.iter_mut() {
|
||||
*sample *= gain_at_end;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// The gain changes. Ramp linearly to avoid discontinuities.
|
||||
let increment = (gain_at_end - last_gain) * inverse_samples_per_channel;
|
||||
for channel in signal.iter_mut() {
|
||||
let mut gain = last_gain;
|
||||
for sample in channel.iter_mut() {
|
||||
*sample *= gain;
|
||||
gain += increment;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a gain factor to multi-channel audio with linear ramping between
|
||||
/// frames and optional hard clipping.
|
||||
#[derive(Debug)]
|
||||
pub struct GainApplier {
|
||||
hard_clip_samples: bool,
|
||||
last_gain_factor: f32,
|
||||
current_gain_factor: f32,
|
||||
samples_per_channel: i32,
|
||||
inverse_samples_per_channel: f32,
|
||||
}
|
||||
|
||||
impl GainApplier {
|
||||
/// Creates a new gain applier.
|
||||
///
|
||||
/// - `hard_clip_samples`: if true, output is clamped to `[-32768, 32767]`
|
||||
/// - `initial_gain_factor`: starting linear gain factor
|
||||
pub fn new(hard_clip_samples: bool, initial_gain_factor: f32) -> Self {
|
||||
Self {
|
||||
hard_clip_samples,
|
||||
last_gain_factor: initial_gain_factor,
|
||||
current_gain_factor: initial_gain_factor,
|
||||
samples_per_channel: -1,
|
||||
inverse_samples_per_channel: -1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies gain to the signal with linear ramping between frames.
|
||||
pub fn apply_gain(&mut self, signal: &mut [&mut [f32]]) {
|
||||
let spc = signal.first().map_or(0, |ch| ch.len()) as i32;
|
||||
if spc != self.samples_per_channel {
|
||||
self.initialize(spc);
|
||||
}
|
||||
|
||||
apply_gain_with_ramping(
|
||||
self.last_gain_factor,
|
||||
self.current_gain_factor,
|
||||
self.inverse_samples_per_channel,
|
||||
signal,
|
||||
);
|
||||
|
||||
self.last_gain_factor = self.current_gain_factor;
|
||||
|
||||
if self.hard_clip_samples {
|
||||
clip_signal(signal);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the target gain factor for the next frame.
|
||||
pub fn set_gain_factor(&mut self, gain_factor: f32) {
|
||||
debug_assert!(gain_factor > 0.0);
|
||||
self.current_gain_factor = gain_factor;
|
||||
}
|
||||
|
||||
/// Returns the current gain factor.
|
||||
pub fn get_gain_factor(&self) -> f32 {
|
||||
self.current_gain_factor
|
||||
}
|
||||
|
||||
fn initialize(&mut self, samples_per_channel: i32) {
|
||||
debug_assert!(samples_per_channel > 0);
|
||||
self.samples_per_channel = samples_per_channel;
|
||||
self.inverse_samples_per_channel = 1.0 / samples_per_channel as f32;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Creates a multi-channel audio frame filled with a constant value.
|
||||
fn make_frame(num_channels: usize, samples_per_channel: usize, value: f32) -> Vec<Vec<f32>> {
|
||||
vec![vec![value; samples_per_channel]; num_channels]
|
||||
}
|
||||
|
||||
/// Converts `Vec<Vec<f32>>` to `&mut [&mut [f32]]` for the API.
|
||||
fn as_mut_slices(frame: &mut [Vec<f32>]) -> Vec<&mut [f32]> {
|
||||
frame.iter_mut().map(|ch| ch.as_mut_slice()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_gain_is_respected() {
|
||||
let initial_signal_level = 123.0_f32;
|
||||
let gain_factor = 10.0_f32;
|
||||
let mut frame = make_frame(1, 1, initial_signal_level);
|
||||
let mut gain_applier = GainApplier::new(true, gain_factor);
|
||||
|
||||
let mut slices = as_mut_slices(&mut frame);
|
||||
gain_applier.apply_gain(&mut slices);
|
||||
assert!(
|
||||
(frame[0][0] - initial_signal_level * gain_factor).abs() < 0.1,
|
||||
"expected ~{}, got {}",
|
||||
initial_signal_level * gain_factor,
|
||||
frame[0][0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipping_is_done() {
|
||||
let initial_signal_level = 30000.0_f32;
|
||||
let gain_factor = 10.0_f32;
|
||||
let mut frame = make_frame(1, 1, initial_signal_level);
|
||||
let mut gain_applier = GainApplier::new(true, gain_factor);
|
||||
|
||||
let mut slices = as_mut_slices(&mut frame);
|
||||
gain_applier.apply_gain(&mut slices);
|
||||
assert!(
|
||||
(frame[0][0] - i16::MAX as f32).abs() < 0.1,
|
||||
"expected ~{}, got {}",
|
||||
i16::MAX,
|
||||
frame[0][0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipping_is_not_done() {
|
||||
let initial_signal_level = 30000.0_f32;
|
||||
let gain_factor = 10.0_f32;
|
||||
let mut frame = make_frame(1, 1, initial_signal_level);
|
||||
let mut gain_applier = GainApplier::new(false, gain_factor);
|
||||
|
||||
let mut slices = as_mut_slices(&mut frame);
|
||||
gain_applier.apply_gain(&mut slices);
|
||||
assert!(
|
||||
(frame[0][0] - initial_signal_level * gain_factor).abs() < 0.1,
|
||||
"expected ~{}, got {}",
|
||||
initial_signal_level * gain_factor,
|
||||
frame[0][0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ramping_is_done() {
|
||||
let initial_signal_level = 30000.0_f32;
|
||||
let initial_gain_factor = 1.0_f32;
|
||||
let target_gain_factor = 0.5_f32;
|
||||
let num_channels = 3;
|
||||
let samples_per_channel = 4;
|
||||
let mut frame = make_frame(num_channels, samples_per_channel, initial_signal_level);
|
||||
let mut gain_applier = GainApplier::new(false, initial_gain_factor);
|
||||
|
||||
gain_applier.set_gain_factor(target_gain_factor);
|
||||
let mut slices = as_mut_slices(&mut frame);
|
||||
gain_applier.apply_gain(&mut slices);
|
||||
|
||||
// The maximal gain change should be close to linear interpolation.
|
||||
for (channel, ch_data) in frame.iter().enumerate() {
|
||||
let mut max_signal_change = 0.0_f32;
|
||||
let mut last_signal_level = initial_signal_level;
|
||||
for &sample in ch_data {
|
||||
let current_change = (last_signal_level - sample).abs();
|
||||
max_signal_change = max_signal_change.max(current_change);
|
||||
last_signal_level = sample;
|
||||
}
|
||||
let total_gain_change =
|
||||
((initial_gain_factor - target_gain_factor) * initial_signal_level).abs();
|
||||
assert!(
|
||||
(max_signal_change - total_gain_change / samples_per_channel as f32).abs() < 0.1,
|
||||
"channel {channel}: max_change {max_signal_change}, expected ~{}",
|
||||
total_gain_change / samples_per_channel as f32,
|
||||
);
|
||||
}
|
||||
|
||||
// Next frame should have the desired level.
|
||||
let mut next_frame = make_frame(num_channels, samples_per_channel, initial_signal_level);
|
||||
let mut slices = as_mut_slices(&mut next_frame);
|
||||
gain_applier.apply_gain(&mut slices);
|
||||
|
||||
// The first sample should have the new gain (no ramping needed).
|
||||
assert!(
|
||||
(next_frame[0][0] - initial_signal_level * target_gain_factor).abs() < 0.1,
|
||||
"expected ~{}, got {}",
|
||||
initial_signal_level * target_gain_factor,
|
||||
next_frame[0][0]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
//! Interpolated gain curve using piecewise-linear under-approximation.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/interpolated_gain_curve.h/.cc`.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use crate::common::{INTERPOLATED_GAIN_CURVE_KNEE_POINTS, INTERPOLATED_GAIN_CURVE_TOTAL_POINTS};
|
||||
|
||||
/// Defined as `DbfsToLinear(kLimiterMaxInputLevelDbFs)`.
|
||||
const MAX_INPUT_LEVEL_LINEAR: f32 = 36_766.3;
|
||||
|
||||
/// Region of the gain curve.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GainCurveRegion {
|
||||
Identity = 0,
|
||||
Knee = 1,
|
||||
Limiter = 2,
|
||||
Saturation = 3,
|
||||
}
|
||||
|
||||
/// Statistics tracking for gain curve lookups.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Stats {
|
||||
pub look_ups_identity_region: usize,
|
||||
pub look_ups_knee_region: usize,
|
||||
pub look_ups_limiter_region: usize,
|
||||
pub look_ups_saturation_region: usize,
|
||||
pub available: bool,
|
||||
pub region: GainCurveRegion,
|
||||
pub region_duration_frames: i64,
|
||||
}
|
||||
|
||||
impl Default for Stats {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
look_ups_identity_region: 0,
|
||||
look_ups_knee_region: 0,
|
||||
look_ups_limiter_region: 0,
|
||||
look_ups_saturation_region: 0,
|
||||
available: false,
|
||||
region: GainCurveRegion::Identity,
|
||||
region_duration_frames: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolated gain curve using piecewise-linear under-approximation to avoid
|
||||
/// saturation.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct InterpolatedGainCurve {
|
||||
pub stats: Stats,
|
||||
}
|
||||
|
||||
// Pre-computed approximation parameters (x boundaries, slopes m, intercepts q).
|
||||
// These are static constexpr in the C++ header.
|
||||
const APPROXIMATION_PARAMS_X: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS] = [
|
||||
30057.297, 30148.986, 30240.676, 30424.053, 30607.43, 30790.807, 30974.184, 31157.56, 31340.94,
|
||||
31524.316, 31707.693, 31891.07, 32074.447, 32257.824, 32441.201, 32624.58, 32807.957,
|
||||
32991.332, 33174.71, 33358.09, 33541.465, 33724.844, 33819.535, 34009.54, 34200.06, 34389.816,
|
||||
34674.49, 35054.375, 35434.863, 35814.816, 36195.168, 36575.03,
|
||||
];
|
||||
|
||||
const APPROXIMATION_PARAMS_M: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS] = [
|
||||
-3.515_235_7e-07,
|
||||
-1.050_251_6e-06,
|
||||
-2.085_213_7e-06,
|
||||
-3.443_004_7e-06,
|
||||
-4.773_849_5e-06,
|
||||
-6.077_376e-06,
|
||||
-7.353_258e-6,
|
||||
-8.601_22e-06,
|
||||
-9.821_013e-06,
|
||||
-1.101_243_4e-05,
|
||||
-1.217_532_6e-05,
|
||||
-1.330_956_9e-05,
|
||||
-1.441_507_5e-05,
|
||||
-1.549_179_3e-05,
|
||||
-1.653_970_7e-05,
|
||||
-1.755_882_8e-05,
|
||||
-1.854_918_4e-05,
|
||||
-1.951_086_8e-05,
|
||||
-2.044_398e-05,
|
||||
-2.134_862_7e-05,
|
||||
-2.222_497e-5,
|
||||
-2.265_374_7e-05,
|
||||
-2.242_571e-5,
|
||||
-2.220_122e-05,
|
||||
-2.198_021e-05,
|
||||
-2.176_260_2e-05,
|
||||
-2.133_731_7e-05,
|
||||
-2.092_482e-5,
|
||||
-2.052_459_6e-05,
|
||||
-2.013_615_4e-05,
|
||||
-1.975_903e-5,
|
||||
-1.939_277_9e-05,
|
||||
];
|
||||
|
||||
const APPROXIMATION_PARAMS_Q: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS] = [
|
||||
1.010_565_9,
|
||||
1.031_631_8,
|
||||
1.062_929_7,
|
||||
1.104_239_2,
|
||||
1.144_973,
|
||||
1.185_109_6,
|
||||
1.224_629,
|
||||
1.263_512_5,
|
||||
1.301_742,
|
||||
1.339_300_6,
|
||||
1.376_173_3,
|
||||
1.412_345_5,
|
||||
1.447_804,
|
||||
1.482_536_6,
|
||||
1.516_532_2,
|
||||
1.549_780_6,
|
||||
1.582_272_2,
|
||||
1.613_999_4,
|
||||
1.644_955,
|
||||
1.675_132_4,
|
||||
1.704_526_2,
|
||||
1.718_986_6,
|
||||
1.711_274_5,
|
||||
1.703_639_7,
|
||||
1.696_081_2,
|
||||
1.688_597_7,
|
||||
1.673_851_1,
|
||||
1.659_391_3,
|
||||
1.645_209_4,
|
||||
1.631_297_5,
|
||||
1.617_647_4,
|
||||
1.604_251_7,
|
||||
];
|
||||
|
||||
impl InterpolatedGainCurve {
|
||||
/// Returns the statistics for gain curve region lookups.
|
||||
pub fn get_stats(&self) -> &Stats {
|
||||
&self.stats
|
||||
}
|
||||
|
||||
/// Given a non-negative input level (linear scale), returns a scalar gain
|
||||
/// factor to apply. Levels above `kLimiterMaxInputLevelDbFs` will be
|
||||
/// reduced to 0 dBFS after applying this gain.
|
||||
pub fn look_up_gain_to_apply(&mut self, input_level: f32) -> f32 {
|
||||
self.update_stats(input_level);
|
||||
|
||||
if input_level <= APPROXIMATION_PARAMS_X[0] {
|
||||
// Identity region.
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
if input_level >= MAX_INPUT_LEVEL_LINEAR {
|
||||
// Saturation region: clamp to clipping level.
|
||||
return 32768.0 / input_level;
|
||||
}
|
||||
|
||||
// Knee and limiter regions: find the linear piece index via binary search.
|
||||
let index = match APPROXIMATION_PARAMS_X
|
||||
.binary_search_by(|x| x.partial_cmp(&input_level).unwrap_or(Ordering::Equal))
|
||||
{
|
||||
Ok(i) => i.saturating_sub(1),
|
||||
Err(i) => i.saturating_sub(1),
|
||||
};
|
||||
|
||||
debug_assert!(index < APPROXIMATION_PARAMS_M.len());
|
||||
debug_assert!(APPROXIMATION_PARAMS_X[index] <= input_level);
|
||||
|
||||
// Piecewise linear interpolation.
|
||||
let gain = APPROXIMATION_PARAMS_M[index] * input_level + APPROXIMATION_PARAMS_Q[index];
|
||||
debug_assert!(gain >= 0.0);
|
||||
gain
|
||||
}
|
||||
|
||||
fn update_stats(&mut self, input_level: f32) {
|
||||
self.stats.available = true;
|
||||
|
||||
let region = if input_level < APPROXIMATION_PARAMS_X[0] {
|
||||
self.stats.look_ups_identity_region += 1;
|
||||
GainCurveRegion::Identity
|
||||
} else if input_level < APPROXIMATION_PARAMS_X[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] {
|
||||
self.stats.look_ups_knee_region += 1;
|
||||
GainCurveRegion::Knee
|
||||
} else if input_level < MAX_INPUT_LEVEL_LINEAR {
|
||||
self.stats.look_ups_limiter_region += 1;
|
||||
GainCurveRegion::Limiter
|
||||
} else {
|
||||
self.stats.look_ups_saturation_region += 1;
|
||||
GainCurveRegion::Saturation
|
||||
};
|
||||
|
||||
if region == self.stats.region {
|
||||
self.stats.region_duration_frames += 1;
|
||||
} else {
|
||||
self.stats.region_duration_frames = 0;
|
||||
self.stats.region = region;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::common::{MAX_ABS_FLOAT_S16_VALUE, dbfs_to_float_s16};
|
||||
use crate::limiter_db_gain_curve::LimiterDbGainCurve;
|
||||
|
||||
const LEVEL_EPSILON: f64 = 1e-2 * MAX_ABS_FLOAT_S16_VALUE as f64;
|
||||
const TOLERANCE: f32 = 1.0 / 32768.0;
|
||||
|
||||
/// Returns evenly spaced points over `[l, r]`.
|
||||
fn lin_space(l: f64, r: f64, num_points: usize) -> Vec<f64> {
|
||||
assert!(num_points >= 2);
|
||||
let step = (r - l) / (num_points - 1) as f64;
|
||||
let mut points = Vec::with_capacity(num_points);
|
||||
points.push(l);
|
||||
for i in 1..num_points - 1 {
|
||||
points.push(l + i as f64 * step);
|
||||
}
|
||||
points.push(r);
|
||||
points
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_use() {
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(
|
||||
LEVEL_EPSILON,
|
||||
dbfs_to_float_s16(limiter.max_input_level_db() as f32 + 1.0) as f64,
|
||||
500,
|
||||
);
|
||||
for level in levels {
|
||||
assert!(igc.look_up_gain_to_apply(level as f32) >= 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_valid_output() {
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(LEVEL_EPSILON, limiter.max_input_level_linear() * 2.0, 500);
|
||||
for level in levels {
|
||||
let gain = igc.look_up_gain_to_apply(level as f32);
|
||||
assert!(
|
||||
(0.0..=1.0).contains(&gain),
|
||||
"gain {gain} out of range at level {level}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_monotonicity() {
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(
|
||||
LEVEL_EPSILON,
|
||||
limiter.max_input_level_linear() + LEVEL_EPSILON + 0.5,
|
||||
500,
|
||||
);
|
||||
let mut prev_gain = igc.look_up_gain_to_apply(0.0);
|
||||
for level in levels {
|
||||
let gain = igc.look_up_gain_to_apply(level as f32);
|
||||
assert!(
|
||||
prev_gain >= gain,
|
||||
"not monotone at level {level}: {prev_gain} < {gain}"
|
||||
);
|
||||
prev_gain = gain;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_approximation() {
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(
|
||||
LEVEL_EPSILON,
|
||||
limiter.max_input_level_linear() - LEVEL_EPSILON,
|
||||
500,
|
||||
);
|
||||
for level in levels {
|
||||
let diff = (limiter.get_gain_linear(level) as f32
|
||||
- igc.look_up_gain_to_apply(level as f32))
|
||||
.abs();
|
||||
assert!(
|
||||
diff < TOLERANCE,
|
||||
"approximation error {diff} at level {level}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_region_boundaries() {
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
|
||||
igc.look_up_gain_to_apply(LEVEL_EPSILON as f32);
|
||||
igc.look_up_gain_to_apply((limiter.knee_start_linear() + LEVEL_EPSILON) as f32);
|
||||
igc.look_up_gain_to_apply((limiter.limiter_start_linear() + LEVEL_EPSILON) as f32);
|
||||
igc.look_up_gain_to_apply((limiter.max_input_level_linear() + LEVEL_EPSILON) as f32);
|
||||
|
||||
let stats = &igc.stats;
|
||||
assert_eq!(1, stats.look_ups_identity_region);
|
||||
assert_eq!(1, stats.look_ups_knee_region);
|
||||
assert_eq!(1, stats.look_ups_limiter_region);
|
||||
assert_eq!(1, stats.look_ups_saturation_region);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_identity_region() {
|
||||
const NUM_STEPS: usize = 10;
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(LEVEL_EPSILON, limiter.knee_start_linear(), NUM_STEPS);
|
||||
for level in &levels {
|
||||
assert_eq!(1.0, igc.look_up_gain_to_apply(*level as f32));
|
||||
}
|
||||
|
||||
let stats = &igc.stats;
|
||||
assert_eq!(NUM_STEPS - 1, stats.look_ups_identity_region);
|
||||
assert_eq!(1, stats.look_ups_knee_region);
|
||||
assert_eq!(0, stats.look_ups_limiter_region);
|
||||
assert_eq!(0, stats.look_ups_saturation_region);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_no_over_approximation_knee() {
|
||||
const NUM_STEPS: usize = 10;
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(
|
||||
limiter.knee_start_linear() + LEVEL_EPSILON,
|
||||
limiter.limiter_start_linear(),
|
||||
NUM_STEPS,
|
||||
);
|
||||
for level in &levels {
|
||||
assert!(
|
||||
igc.look_up_gain_to_apply(*level as f32)
|
||||
<= limiter.get_gain_linear(*level) as f32 + 1e-7,
|
||||
"over-approximation at level {level}"
|
||||
);
|
||||
}
|
||||
|
||||
let stats = &igc.stats;
|
||||
assert_eq!(0, stats.look_ups_identity_region);
|
||||
assert_eq!(NUM_STEPS - 1, stats.look_ups_knee_region);
|
||||
assert_eq!(1, stats.look_ups_limiter_region);
|
||||
assert_eq!(0, stats.look_ups_saturation_region);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_no_over_approximation_beyond_knee() {
|
||||
const NUM_STEPS: usize = 10;
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(
|
||||
limiter.limiter_start_linear() + LEVEL_EPSILON,
|
||||
limiter.max_input_level_linear() - LEVEL_EPSILON,
|
||||
NUM_STEPS,
|
||||
);
|
||||
for level in &levels {
|
||||
assert!(
|
||||
igc.look_up_gain_to_apply(*level as f32)
|
||||
<= limiter.get_gain_linear(*level) as f32 + 1e-7,
|
||||
"over-approximation at level {level}"
|
||||
);
|
||||
}
|
||||
|
||||
let stats = &igc.stats;
|
||||
assert_eq!(0, stats.look_ups_identity_region);
|
||||
assert_eq!(0, stats.look_ups_knee_region);
|
||||
assert_eq!(NUM_STEPS, stats.look_ups_limiter_region);
|
||||
assert_eq!(0, stats.look_ups_saturation_region);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_no_over_approximation_with_saturation() {
|
||||
const NUM_STEPS: usize = 3;
|
||||
let mut igc = InterpolatedGainCurve::default();
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
let levels = lin_space(
|
||||
limiter.max_input_level_linear() + LEVEL_EPSILON,
|
||||
limiter.max_input_level_linear() + LEVEL_EPSILON + 0.5,
|
||||
NUM_STEPS,
|
||||
);
|
||||
for level in &levels {
|
||||
assert!(
|
||||
igc.look_up_gain_to_apply(*level as f32) <= limiter.get_gain_linear(*level) as f32,
|
||||
"over-approximation at level {level}"
|
||||
);
|
||||
}
|
||||
|
||||
let stats = &igc.stats;
|
||||
assert_eq!(0, stats.look_ups_identity_region);
|
||||
assert_eq!(0, stats.look_ups_knee_region);
|
||||
assert_eq!(0, stats.look_ups_limiter_region);
|
||||
assert_eq!(NUM_STEPS, stats.look_ups_saturation_region);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_approximation_params() {
|
||||
let params = compute_interpolated_gain_curve_approximation_params();
|
||||
let igc = InterpolatedGainCurve::default();
|
||||
|
||||
for i in 0..INTERPOLATED_GAIN_CURVE_TOTAL_POINTS {
|
||||
assert!(
|
||||
(APPROXIMATION_PARAMS_X[i] - params.x[i]).abs() < 0.9,
|
||||
"x[{i}]: {} vs {}",
|
||||
APPROXIMATION_PARAMS_X[i],
|
||||
params.x[i]
|
||||
);
|
||||
assert!(
|
||||
(APPROXIMATION_PARAMS_M[i] - params.m[i]).abs() < 0.00001,
|
||||
"m[{i}]: {} vs {}",
|
||||
APPROXIMATION_PARAMS_M[i],
|
||||
params.m[i]
|
||||
);
|
||||
assert!(
|
||||
(APPROXIMATION_PARAMS_Q[i] - params.q[i]).abs() < 0.001,
|
||||
"q[{i}]: {} vs {}",
|
||||
APPROXIMATION_PARAMS_Q[i],
|
||||
params.q[i]
|
||||
);
|
||||
}
|
||||
// Silence unused variable warning.
|
||||
let _ = igc;
|
||||
}
|
||||
|
||||
/// Computed approximation parameters for verification.
|
||||
struct InterpolatedParameters {
|
||||
x: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
|
||||
m: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
|
||||
q: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
|
||||
}
|
||||
|
||||
/// Recomputes the interpolated gain curve parameters from the analytical
|
||||
/// `LimiterDbGainCurve`. Port of `compute_interpolated_gain_curve.cc`.
|
||||
fn compute_interpolated_gain_curve_approximation_params() -> InterpolatedParameters {
|
||||
use crate::common::{
|
||||
INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS, INTERPOLATED_GAIN_CURVE_KNEE_POINTS,
|
||||
};
|
||||
|
||||
let limiter = LimiterDbGainCurve::default();
|
||||
|
||||
let mut params = InterpolatedParameters {
|
||||
x: [0.0; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
|
||||
m: [0.0; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
|
||||
q: [0.0; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
|
||||
};
|
||||
|
||||
// Knee region: equally spaced points with an extra point at the start.
|
||||
let knee_points = lin_space(
|
||||
limiter.knee_start_linear(),
|
||||
limiter.limiter_start_linear(),
|
||||
INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1,
|
||||
);
|
||||
params.x[0] = knee_points[0] as f32;
|
||||
params.x[1] = ((knee_points[0] + knee_points[1]) / 2.0) as f32;
|
||||
for (i, &kp) in knee_points.iter().enumerate().skip(1) {
|
||||
params.x[i + 1] = kp as f32;
|
||||
}
|
||||
|
||||
// Compute (m, q) for knee region linear pieces.
|
||||
for i in 0..INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1 {
|
||||
let x0 = params.x[i] as f64;
|
||||
let x1 = params.x[i + 1] as f64;
|
||||
let y0 = limiter.get_gain_linear(x0);
|
||||
let y1 = limiter.get_gain_linear(x1);
|
||||
params.m[i] = ((y1 - y0) / (x1 - x0)) as f32;
|
||||
params.q[i] = (y0 - params.m[i] as f64 * x0) as f32;
|
||||
}
|
||||
|
||||
// Beyond-knee region: sample using greedy error minimization.
|
||||
let samples = sample_limiter_region(&limiter);
|
||||
|
||||
// First beyond-knee piece uses the last knee point as boundary.
|
||||
let (m, q) = compute_linear_approximation_params(
|
||||
&limiter,
|
||||
params.x[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] as f64,
|
||||
);
|
||||
params.m[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] = m as f32;
|
||||
params.q[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] = q as f32;
|
||||
|
||||
for (i, &sample) in samples.iter().enumerate() {
|
||||
let (m, q) = compute_linear_approximation_params(&limiter, sample);
|
||||
params.m[i + INTERPOLATED_GAIN_CURVE_KNEE_POINTS] = m as f32;
|
||||
params.q[i + INTERPOLATED_GAIN_CURVE_KNEE_POINTS] = q as f32;
|
||||
}
|
||||
|
||||
// Find intersection points between adjacent linear pieces.
|
||||
for i in INTERPOLATED_GAIN_CURVE_KNEE_POINTS
|
||||
..INTERPOLATED_GAIN_CURVE_KNEE_POINTS + INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS
|
||||
{
|
||||
params.x[i] = ((params.q[i - 1] as f64 - params.q[i] as f64)
|
||||
/ (params.m[i] as f64 - params.m[i - 1] as f64)) as f32;
|
||||
}
|
||||
|
||||
params
|
||||
}
|
||||
|
||||
fn compute_linear_approximation_params(limiter: &LimiterDbGainCurve, x: f64) -> (f64, f64) {
|
||||
let m = limiter.get_gain_first_derivative_linear(x);
|
||||
let q = limiter.get_gain_linear(x) - m * x;
|
||||
(m, q)
|
||||
}
|
||||
|
||||
fn limiter_under_approximation_negative_error(
|
||||
limiter: &LimiterDbGainCurve,
|
||||
x0: f64,
|
||||
x1: f64,
|
||||
) -> f64 {
|
||||
let area_limiter = limiter.get_gain_integral_linear(x0, x1);
|
||||
let area_interpolated = compute_area_under_piecewise_linear_approximation(limiter, x0, x1);
|
||||
area_limiter - area_interpolated
|
||||
}
|
||||
|
||||
fn compute_area_under_piecewise_linear_approximation(
|
||||
limiter: &LimiterDbGainCurve,
|
||||
x0: f64,
|
||||
x1: f64,
|
||||
) -> f64 {
|
||||
let (m0, q0) = compute_linear_approximation_params(limiter, x0);
|
||||
let (m1, q1) = compute_linear_approximation_params(limiter, x1);
|
||||
let x_split = (q0 - q1) / (m1 - m0);
|
||||
|
||||
let area =
|
||||
|xl: f64, xr: f64, m: f64, q: f64| xr * (m * xr / 2.0 + q) - xl * (m * xl / 2.0 + q);
|
||||
area(x0, x_split, m0, q0) + area(x_split, x1, m1, q1)
|
||||
}
|
||||
|
||||
fn sample_limiter_region(limiter: &LimiterDbGainCurve) -> Vec<f64> {
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BinaryHeap;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
struct Interval {
|
||||
x0: f64,
|
||||
x1: f64,
|
||||
error: f64,
|
||||
}
|
||||
|
||||
impl Eq for Interval {}
|
||||
|
||||
impl PartialOrd for Interval {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Interval {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.error.total_cmp(&other.error)
|
||||
}
|
||||
}
|
||||
|
||||
let mut heap = BinaryHeap::new();
|
||||
let start = limiter.limiter_start_linear();
|
||||
let end = limiter.max_input_level_linear();
|
||||
heap.push(Interval {
|
||||
x0: start,
|
||||
x1: end,
|
||||
error: limiter_under_approximation_negative_error(limiter, start, end),
|
||||
});
|
||||
|
||||
use crate::common::INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS;
|
||||
while heap.len() < INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS {
|
||||
let interval = heap.pop().unwrap();
|
||||
let x_split = (interval.x0 + interval.x1) / 2.0;
|
||||
heap.push(Interval {
|
||||
x0: interval.x0,
|
||||
x1: x_split,
|
||||
error: limiter_under_approximation_negative_error(limiter, interval.x0, x_split),
|
||||
});
|
||||
heap.push(Interval {
|
||||
x0: x_split,
|
||||
x1: interval.x1,
|
||||
error: limiter_under_approximation_negative_error(limiter, x_split, interval.x1),
|
||||
});
|
||||
}
|
||||
|
||||
let mut samples: Vec<f64> = heap.into_iter().map(|i| i.x1).collect();
|
||||
samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
samples
|
||||
}
|
||||
}
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
|
||||
pub mod adaptive_digital_gain_controller;
|
||||
pub mod biquad_filter;
|
||||
pub mod clipping_predictor;
|
||||
pub mod clipping_predictor_level_buffer;
|
||||
pub mod common;
|
||||
pub mod fixed_digital_level_estimator;
|
||||
pub mod gain_applier;
|
||||
pub mod interpolated_gain_curve;
|
||||
pub mod limiter;
|
||||
pub mod limiter_db_gain_curve;
|
||||
pub mod noise_level_estimator;
|
||||
pub(crate) mod rnn_vad;
|
||||
pub mod saturation_protector;
|
||||
pub mod saturation_protector_buffer;
|
||||
pub mod speech_level_estimator;
|
||||
pub mod vad_wrapper;
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
//! Output limiter with interpolated gain curve and per-sample scaling.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/limiter.h/.cc`.
|
||||
|
||||
use crate::common::{
|
||||
MAX_FLOAT_S16_VALUE, MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL, MIN_FLOAT_S16_VALUE,
|
||||
SUB_FRAMES_IN_FRAME,
|
||||
};
|
||||
use crate::fixed_digital_level_estimator::FixedDigitalLevelEstimator;
|
||||
use crate::interpolated_gain_curve::InterpolatedGainCurve;
|
||||
|
||||
/// Power used for interpolation of the first sub-frame during attack.
|
||||
/// Reduces the chances of over-shooting (and hence saturation).
|
||||
const ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER: f32 = 8.0;
|
||||
|
||||
fn interpolate_first_subframe(last_factor: f32, current_factor: f32, subframe: &mut [f32]) {
|
||||
let n = subframe.len() as f32;
|
||||
let p = ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER;
|
||||
for (i, sample) in subframe.iter_mut().enumerate() {
|
||||
let t = i as f32 / n;
|
||||
*sample = (1.0 - t).powf(p) * (last_factor - current_factor) + current_factor;
|
||||
}
|
||||
}
|
||||
|
||||
fn compute_per_sample_subframe_factors(
|
||||
scaling_factors: &[f32],
|
||||
per_sample_scaling_factors: &mut [f32],
|
||||
) {
|
||||
let num_subframes = scaling_factors.len() - 1;
|
||||
let subframe_size = per_sample_scaling_factors.len() / num_subframes;
|
||||
debug_assert_eq!(per_sample_scaling_factors.len() % num_subframes, 0);
|
||||
|
||||
// Handle first sub-frame differently in case of attack.
|
||||
let is_attack = scaling_factors[0] > scaling_factors[1];
|
||||
if is_attack {
|
||||
interpolate_first_subframe(
|
||||
scaling_factors[0],
|
||||
scaling_factors[1],
|
||||
&mut per_sample_scaling_factors[..subframe_size],
|
||||
);
|
||||
}
|
||||
|
||||
let start = if is_attack { 1 } else { 0 };
|
||||
for i in start..num_subframes {
|
||||
let subframe_start = i * subframe_size;
|
||||
let scaling_start = scaling_factors[i];
|
||||
let scaling_end = scaling_factors[i + 1];
|
||||
let scaling_diff = (scaling_end - scaling_start) / subframe_size as f32;
|
||||
for j in 0..subframe_size {
|
||||
per_sample_scaling_factors[subframe_start + j] =
|
||||
scaling_start + scaling_diff * j as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scale_samples(per_sample_scaling_factors: &[f32], signal: &mut [&mut [f32]]) {
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
|
||||
debug_assert_eq!(samples_per_channel, per_sample_scaling_factors.len());
|
||||
for channel in signal.iter_mut() {
|
||||
for (sample, &factor) in channel.iter_mut().zip(per_sample_scaling_factors) {
|
||||
*sample = (*sample * factor).clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output limiter that applies gain curve compression and hard clipping.
|
||||
#[derive(Debug)]
|
||||
pub struct Limiter {
|
||||
interp_gain_curve: InterpolatedGainCurve,
|
||||
level_estimator: FixedDigitalLevelEstimator,
|
||||
scaling_factors: [f32; SUB_FRAMES_IN_FRAME as usize + 1],
|
||||
per_sample_scaling_factors: [f32; MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL],
|
||||
last_scaling_factor: f32,
|
||||
}
|
||||
|
||||
impl Limiter {
|
||||
/// Creates a new limiter.
|
||||
///
|
||||
/// `samples_per_channel` must be <= `MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL`
|
||||
/// and divisible by `SUB_FRAMES_IN_FRAME`.
|
||||
pub fn new(samples_per_channel: usize) -> Self {
|
||||
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
|
||||
Self {
|
||||
interp_gain_curve: InterpolatedGainCurve::default(),
|
||||
level_estimator: FixedDigitalLevelEstimator::new(samples_per_channel),
|
||||
scaling_factors: [0.0; SUB_FRAMES_IN_FRAME as usize + 1],
|
||||
per_sample_scaling_factors: [0.0; MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL],
|
||||
last_scaling_factor: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies limiter and hard-clipping to the signal.
|
||||
pub fn process(&mut self, signal: &mut [&mut [f32]]) {
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
|
||||
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
|
||||
|
||||
// Mono capture needs only a stack descriptor; keep the generic multichannel path.
|
||||
let level_estimate = if signal.len() == 1 {
|
||||
self.level_estimator.compute_level(&[&*signal[0]])
|
||||
} else {
|
||||
let signal_refs: Vec<&[f32]> = signal.iter().map(|ch| &**ch).collect();
|
||||
self.level_estimator.compute_level(&signal_refs)
|
||||
};
|
||||
|
||||
debug_assert_eq!(level_estimate.len() + 1, self.scaling_factors.len());
|
||||
self.scaling_factors[0] = self.last_scaling_factor;
|
||||
for (i, &level) in level_estimate.iter().enumerate() {
|
||||
self.scaling_factors[i + 1] = self.interp_gain_curve.look_up_gain_to_apply(level);
|
||||
}
|
||||
|
||||
compute_per_sample_subframe_factors(
|
||||
&self.scaling_factors,
|
||||
&mut self.per_sample_scaling_factors[..samples_per_channel],
|
||||
);
|
||||
scale_samples(
|
||||
&self.per_sample_scaling_factors[..samples_per_channel],
|
||||
signal,
|
||||
);
|
||||
|
||||
self.last_scaling_factor = self.scaling_factors[SUB_FRAMES_IN_FRAME as usize];
|
||||
}
|
||||
|
||||
/// Changes the sample rate.
|
||||
pub fn set_samples_per_channel(&mut self, samples_per_channel: usize) {
|
||||
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
|
||||
self.level_estimator
|
||||
.set_samples_per_channel(samples_per_channel);
|
||||
}
|
||||
|
||||
/// Resets the internal state.
|
||||
pub fn reset(&mut self) {
|
||||
self.level_estimator.reset();
|
||||
}
|
||||
|
||||
/// Returns the last audio level from the level estimator.
|
||||
pub fn last_audio_level(&self) -> f32 {
|
||||
self.level_estimator.last_audio_level()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::common::{MAX_ABS_FLOAT_S16_VALUE, dbfs_to_float_s16};
|
||||
|
||||
#[test]
|
||||
fn limiter_should_construct_and_run() {
|
||||
let samples_per_channel = 480;
|
||||
let mut limiter = Limiter::new(samples_per_channel);
|
||||
|
||||
let mut buffer = vec![MAX_ABS_FLOAT_S16_VALUE; samples_per_channel];
|
||||
let mut channels: Vec<&mut [f32]> = vec![buffer.as_mut_slice()];
|
||||
limiter.process(&mut channels);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_volume_above_threshold() {
|
||||
let samples_per_channel = 480;
|
||||
let input_level = (MAX_ABS_FLOAT_S16_VALUE + dbfs_to_float_s16(1.0)) / 2.0;
|
||||
let mut limiter = Limiter::new(samples_per_channel);
|
||||
|
||||
// Give the level estimator time to adapt.
|
||||
for _ in 0..5 {
|
||||
let mut buffer = vec![input_level; samples_per_channel];
|
||||
let mut channels: Vec<&mut [f32]> = vec![buffer.as_mut_slice()];
|
||||
limiter.process(&mut channels);
|
||||
}
|
||||
|
||||
let mut buffer = vec![input_level; samples_per_channel];
|
||||
let mut channels: Vec<&mut [f32]> = vec![buffer.as_mut_slice()];
|
||||
limiter.process(&mut channels);
|
||||
for &sample in channels[0].iter() {
|
||||
assert!(
|
||||
0.9 * MAX_ABS_FLOAT_S16_VALUE < sample,
|
||||
"sample {sample} should be above threshold {}",
|
||||
0.9 * MAX_ABS_FLOAT_S16_VALUE
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
//! Limiter dB gain curve.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/limiter_db_gain_curve.h/.cc`.
|
||||
|
||||
use crate::common::{
|
||||
LIMITER_COMPRESSION_RATIO, LIMITER_KNEE_SMOOTHNESS_DB, LIMITER_MAX_INPUT_LEVEL_DB_FS,
|
||||
MAX_ABS_FLOAT_S16_VALUE, dbfs_to_float_s16_f64, float_s16_to_dbfs_f64,
|
||||
};
|
||||
|
||||
/// A limiter gain curve (in dB scale) with four regions:
|
||||
/// identity (linear), knee (quadratic polynomial), compression (linear),
|
||||
/// saturation (linear).
|
||||
#[derive(Debug)]
|
||||
pub struct LimiterDbGainCurve {
|
||||
max_input_level_linear: f64,
|
||||
knee_start_dbfs: f64,
|
||||
knee_start_linear: f64,
|
||||
limiter_start_dbfs: f64,
|
||||
limiter_start_linear: f64,
|
||||
/// Coefficients `[a, b, c]` of the knee region polynomial `ax^2 + bx + c`.
|
||||
knee_region_polynomial: [f64; 3],
|
||||
gain_curve_limiter_d1: f64,
|
||||
gain_curve_limiter_d2: f64,
|
||||
gain_curve_limiter_i1: f64,
|
||||
gain_curve_limiter_i2: f64,
|
||||
}
|
||||
|
||||
fn compute_knee_start(
|
||||
max_input_level_db: f64,
|
||||
knee_smoothness_db: f64,
|
||||
compression_ratio: f64,
|
||||
) -> f64 {
|
||||
debug_assert!(
|
||||
(compression_ratio - 1.0) * knee_smoothness_db / (2.0 * compression_ratio)
|
||||
< max_input_level_db
|
||||
);
|
||||
-knee_smoothness_db / 2.0 - max_input_level_db / (compression_ratio - 1.0)
|
||||
}
|
||||
|
||||
fn compute_knee_region_polynomial(
|
||||
knee_start_dbfs: f64,
|
||||
knee_smoothness_db: f64,
|
||||
compression_ratio: f64,
|
||||
) -> [f64; 3] {
|
||||
let a = (1.0 - compression_ratio) / (2.0 * knee_smoothness_db * compression_ratio);
|
||||
let b = 1.0 - 2.0 * a * knee_start_dbfs;
|
||||
let c = a * knee_start_dbfs * knee_start_dbfs;
|
||||
[a, b, c]
|
||||
}
|
||||
|
||||
fn compute_limiter_d1(max_input_level_db: f64, compression_ratio: f64) -> f64 {
|
||||
(10.0_f64.powf(-max_input_level_db / (20.0 * compression_ratio)) * (1.0 - compression_ratio)
|
||||
/ compression_ratio)
|
||||
/ MAX_ABS_FLOAT_S16_VALUE as f64
|
||||
}
|
||||
|
||||
const fn compute_limiter_d2(compression_ratio: f64) -> f64 {
|
||||
(1.0 - 2.0 * compression_ratio) / compression_ratio
|
||||
}
|
||||
|
||||
fn compute_limiter_i2(
|
||||
max_input_level_db: f64,
|
||||
compression_ratio: f64,
|
||||
gain_curve_limiter_i1: f64,
|
||||
) -> f64 {
|
||||
debug_assert!(gain_curve_limiter_i1 != 0.0);
|
||||
10.0_f64.powf(-max_input_level_db / (20.0 * compression_ratio))
|
||||
/ gain_curve_limiter_i1
|
||||
/ (MAX_ABS_FLOAT_S16_VALUE as f64).powf(gain_curve_limiter_i1 - 1.0)
|
||||
}
|
||||
|
||||
impl Default for LimiterDbGainCurve {
|
||||
fn default() -> Self {
|
||||
let max_input_level_db = LIMITER_MAX_INPUT_LEVEL_DB_FS;
|
||||
let knee_smoothness_db = LIMITER_KNEE_SMOOTHNESS_DB;
|
||||
let compression_ratio = LIMITER_COMPRESSION_RATIO;
|
||||
|
||||
let max_input_level_linear = dbfs_to_float_s16_f64(max_input_level_db);
|
||||
let knee_start_dbfs =
|
||||
compute_knee_start(max_input_level_db, knee_smoothness_db, compression_ratio);
|
||||
let knee_start_linear = dbfs_to_float_s16_f64(knee_start_dbfs);
|
||||
let limiter_start_dbfs = knee_start_dbfs + knee_smoothness_db;
|
||||
let limiter_start_linear = dbfs_to_float_s16_f64(limiter_start_dbfs);
|
||||
let knee_region_polynomial =
|
||||
compute_knee_region_polynomial(knee_start_dbfs, knee_smoothness_db, compression_ratio);
|
||||
let gain_curve_limiter_d1 = compute_limiter_d1(max_input_level_db, compression_ratio);
|
||||
let gain_curve_limiter_d2 = compute_limiter_d2(compression_ratio);
|
||||
let gain_curve_limiter_i1 = 1.0 / compression_ratio;
|
||||
let gain_curve_limiter_i2 =
|
||||
compute_limiter_i2(max_input_level_db, compression_ratio, gain_curve_limiter_i1);
|
||||
|
||||
debug_assert!(knee_smoothness_db > 0.0);
|
||||
debug_assert!(compression_ratio > 1.0);
|
||||
debug_assert!(max_input_level_db >= knee_start_dbfs + knee_smoothness_db);
|
||||
|
||||
Self {
|
||||
max_input_level_linear,
|
||||
knee_start_dbfs,
|
||||
knee_start_linear,
|
||||
limiter_start_dbfs,
|
||||
limiter_start_linear,
|
||||
knee_region_polynomial,
|
||||
gain_curve_limiter_d1,
|
||||
gain_curve_limiter_d2,
|
||||
gain_curve_limiter_i1,
|
||||
gain_curve_limiter_i2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LimiterDbGainCurve {
|
||||
pub fn max_input_level_db(&self) -> f64 {
|
||||
LIMITER_MAX_INPUT_LEVEL_DB_FS
|
||||
}
|
||||
|
||||
pub fn max_input_level_linear(&self) -> f64 {
|
||||
self.max_input_level_linear
|
||||
}
|
||||
|
||||
pub fn knee_start_linear(&self) -> f64 {
|
||||
self.knee_start_linear
|
||||
}
|
||||
|
||||
pub fn limiter_start_linear(&self) -> f64 {
|
||||
self.limiter_start_linear
|
||||
}
|
||||
|
||||
/// Returns the output level in dBFS given an input level in dBFS.
|
||||
pub fn get_output_level_dbfs(&self, input_level_dbfs: f64) -> f64 {
|
||||
if input_level_dbfs < self.knee_start_dbfs {
|
||||
input_level_dbfs
|
||||
} else if input_level_dbfs < self.limiter_start_dbfs {
|
||||
self.get_knee_region_output_level_dbfs(input_level_dbfs)
|
||||
} else {
|
||||
self.get_compressor_region_output_level_dbfs(input_level_dbfs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the gain (linear scale) for a given input level (linear scale).
|
||||
pub fn get_gain_linear(&self, input_level_linear: f64) -> f64 {
|
||||
if input_level_linear < self.knee_start_linear {
|
||||
return 1.0;
|
||||
}
|
||||
dbfs_to_float_s16_f64(self.get_output_level_dbfs(float_s16_to_dbfs_f64(input_level_linear)))
|
||||
/ input_level_linear
|
||||
}
|
||||
|
||||
/// Computes the first derivative of `get_gain_linear()` at `x`.
|
||||
/// Beyond-knee region only.
|
||||
pub fn get_gain_first_derivative_linear(&self, x: f64) -> f64 {
|
||||
debug_assert!(x >= self.limiter_start_linear - 1e-7 * MAX_ABS_FLOAT_S16_VALUE as f64);
|
||||
self.gain_curve_limiter_d1
|
||||
* (x / MAX_ABS_FLOAT_S16_VALUE as f64).powf(self.gain_curve_limiter_d2)
|
||||
}
|
||||
|
||||
/// Computes the integral of `get_gain_linear()` in the range `[x0, x1]`.
|
||||
/// Beyond-knee region only.
|
||||
pub fn get_gain_integral_linear(&self, x0: f64, x1: f64) -> f64 {
|
||||
debug_assert!(x0 <= x1);
|
||||
debug_assert!(x0 >= self.limiter_start_linear);
|
||||
let limiter_integral =
|
||||
|x: f64| self.gain_curve_limiter_i2 * x.powf(self.gain_curve_limiter_i1);
|
||||
limiter_integral(x1) - limiter_integral(x0)
|
||||
}
|
||||
|
||||
fn get_knee_region_output_level_dbfs(&self, input_level_dbfs: f64) -> f64 {
|
||||
self.knee_region_polynomial[0] * input_level_dbfs * input_level_dbfs
|
||||
+ self.knee_region_polynomial[1] * input_level_dbfs
|
||||
+ self.knee_region_polynomial[2]
|
||||
}
|
||||
|
||||
fn get_compressor_region_output_level_dbfs(&self, input_level_dbfs: f64) -> f64 {
|
||||
(input_level_dbfs - LIMITER_MAX_INPUT_LEVEL_DB_FS) / LIMITER_COMPRESSION_RATIO
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn construct() {
|
||||
let _l = LimiterDbGainCurve::default();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_curve_should_be_monotone() {
|
||||
let l = LimiterDbGainCurve::default();
|
||||
let mut last_output_level = None;
|
||||
let mut level = -90.0_f64;
|
||||
while level <= l.max_input_level_db() {
|
||||
let current_output_level = l.get_output_level_dbfs(level);
|
||||
if let Some(last) = last_output_level {
|
||||
assert!(
|
||||
last <= current_output_level,
|
||||
"not monotone at level {level}: {last} > {current_output_level}"
|
||||
);
|
||||
}
|
||||
last_output_level = Some(current_output_level);
|
||||
level += 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_curve_should_be_continuous() {
|
||||
let l = LimiterDbGainCurve::default();
|
||||
let mut last_output_level = None;
|
||||
const MAX_DELTA: f64 = 0.5;
|
||||
let mut level = -90.0_f64;
|
||||
while level <= l.max_input_level_db() {
|
||||
let current_output_level = l.get_output_level_dbfs(level);
|
||||
if let Some(last) = last_output_level {
|
||||
assert!(
|
||||
current_output_level <= last + MAX_DELTA,
|
||||
"not continuous at level {level}"
|
||||
);
|
||||
}
|
||||
last_output_level = Some(current_output_level);
|
||||
level += 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_gain_should_be_less_than_full_scale() {
|
||||
let l = LimiterDbGainCurve::default();
|
||||
let mut level = -90.0_f64;
|
||||
while level <= l.max_input_level_db() {
|
||||
let current_output_level = l.get_output_level_dbfs(level);
|
||||
assert!(
|
||||
current_output_level <= 0.0,
|
||||
"output {current_output_level} > 0 at level {level}"
|
||||
);
|
||||
level += 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
//! Noise floor estimator based on minimum statistics.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/noise_level_estimator.h/.cc`.
|
||||
|
||||
const FRAMES_PER_SECOND: i32 = 100;
|
||||
|
||||
/// Update the noise floor every 5 seconds.
|
||||
const UPDATE_PERIOD_NUM_FRAMES: i32 = 500;
|
||||
|
||||
fn frame_energy(audio: &[&[f32]]) -> f32 {
|
||||
let mut energy = 0.0_f32;
|
||||
for channel in audio {
|
||||
let channel_energy: f32 = channel.iter().map(|&s| s * s).sum();
|
||||
energy = energy.max(channel_energy);
|
||||
}
|
||||
energy
|
||||
}
|
||||
|
||||
fn energy_to_dbfs(signal_energy: f32, num_samples: i32) -> f32 {
|
||||
use crate::common::MIN_LEVEL_DBFS;
|
||||
debug_assert!(signal_energy >= 0.0);
|
||||
let rms_square = signal_energy / num_samples as f32;
|
||||
if rms_square <= 1.0 {
|
||||
return MIN_LEVEL_DBFS;
|
||||
}
|
||||
10.0 * rms_square.log10() + MIN_LEVEL_DBFS
|
||||
}
|
||||
|
||||
/// Updates the noise floor with instant decay and slow attack. This tuning is
|
||||
/// specific for AGC2, so that (i) it can promptly increase the gain if the noise
|
||||
/// floor drops (instant decay) and (ii) in case of music or fast speech, due to
|
||||
/// which the noise floor can be overestimated, the gain reduction is slowed
|
||||
/// down.
|
||||
fn smooth_noise_floor_estimate(current_estimate: f32, new_estimate: f32) -> f32 {
|
||||
const ATTACK: f32 = 0.5;
|
||||
if current_estimate < new_estimate {
|
||||
// Attack phase.
|
||||
ATTACK * new_estimate + (1.0 - ATTACK) * current_estimate
|
||||
} else {
|
||||
// Instant decay.
|
||||
new_estimate
|
||||
}
|
||||
}
|
||||
|
||||
/// Noise level estimator based on noise floor detection.
|
||||
#[derive(Debug)]
|
||||
pub struct NoiseLevelEstimator {
|
||||
sample_rate_hz: i32,
|
||||
min_noise_energy: f32,
|
||||
first_period: bool,
|
||||
preliminary_noise_energy_set: bool,
|
||||
preliminary_noise_energy: f32,
|
||||
noise_energy: f32,
|
||||
counter: i32,
|
||||
}
|
||||
|
||||
impl Default for NoiseLevelEstimator {
|
||||
fn default() -> Self {
|
||||
let mut est = Self {
|
||||
sample_rate_hz: 0,
|
||||
min_noise_energy: 0.0,
|
||||
first_period: true,
|
||||
preliminary_noise_energy_set: false,
|
||||
preliminary_noise_energy: 0.0,
|
||||
noise_energy: 0.0,
|
||||
counter: 0,
|
||||
};
|
||||
// Initially assume that 48 kHz will be used. `analyze()` will detect the
|
||||
// used sample rate and call `initialize()` again if needed.
|
||||
est.initialize(48000);
|
||||
est
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseLevelEstimator {
|
||||
/// Analyzes a 10 ms frame, updates the noise level estimation and returns
|
||||
/// the value for the latter in dBFS.
|
||||
pub fn analyze(&mut self, frame: &[&[f32]]) -> f32 {
|
||||
debug_assert!(!frame.is_empty());
|
||||
let samples_per_channel = frame[0].len();
|
||||
|
||||
// Detect sample rate changes.
|
||||
let sample_rate_hz = samples_per_channel as i32 * FRAMES_PER_SECOND;
|
||||
if sample_rate_hz != self.sample_rate_hz {
|
||||
self.initialize(sample_rate_hz);
|
||||
}
|
||||
|
||||
let frame_energy = frame_energy(frame);
|
||||
if frame_energy <= self.min_noise_energy {
|
||||
// Ignore frames when muted or below the minimum measurable energy.
|
||||
return energy_to_dbfs(self.noise_energy, samples_per_channel as i32);
|
||||
}
|
||||
|
||||
if self.preliminary_noise_energy_set {
|
||||
self.preliminary_noise_energy = self.preliminary_noise_energy.min(frame_energy);
|
||||
} else {
|
||||
self.preliminary_noise_energy = frame_energy;
|
||||
self.preliminary_noise_energy_set = true;
|
||||
}
|
||||
|
||||
if self.counter == 0 {
|
||||
// Full period observed.
|
||||
self.first_period = false;
|
||||
// Update the estimated noise floor energy with the preliminary
|
||||
// estimation.
|
||||
self.noise_energy =
|
||||
smooth_noise_floor_estimate(self.noise_energy, self.preliminary_noise_energy);
|
||||
// Reset for a new observation period.
|
||||
self.counter = UPDATE_PERIOD_NUM_FRAMES;
|
||||
self.preliminary_noise_energy_set = false;
|
||||
} else if self.first_period {
|
||||
// While analyzing the signal during the initial period, continuously
|
||||
// update the estimated noise energy, which is monotonic.
|
||||
self.noise_energy = self.preliminary_noise_energy;
|
||||
self.counter -= 1;
|
||||
} else {
|
||||
// During the observation period it's only allowed to lower the energy.
|
||||
self.noise_energy = self.noise_energy.min(self.preliminary_noise_energy);
|
||||
self.counter -= 1;
|
||||
}
|
||||
|
||||
energy_to_dbfs(self.noise_energy, samples_per_channel as i32)
|
||||
}
|
||||
|
||||
fn initialize(&mut self, sample_rate_hz: i32) {
|
||||
self.sample_rate_hz = sample_rate_hz;
|
||||
self.first_period = true;
|
||||
self.preliminary_noise_energy_set = false;
|
||||
// Initialize the minimum noise energy to -84 dBFS.
|
||||
self.min_noise_energy = sample_rate_hz as f32 * 2.0 * 2.0 / FRAMES_PER_SECOND as f32;
|
||||
self.preliminary_noise_energy = self.min_noise_energy;
|
||||
self.noise_energy = self.min_noise_energy;
|
||||
self.counter = UPDATE_PERIOD_NUM_FRAMES;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::f32::consts::PI;
|
||||
|
||||
const NUM_ITERATIONS: i32 = 200;
|
||||
|
||||
const MIN_S16: f32 = -32768.0;
|
||||
const MAX_S16: f32 = 32767.0;
|
||||
|
||||
/// PRNG matching WebRTC's `Random` class (xorshift128+).
|
||||
struct WebRtcRandom {
|
||||
x: u64,
|
||||
y: u64,
|
||||
}
|
||||
|
||||
impl WebRtcRandom {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self { x: seed, y: seed }
|
||||
}
|
||||
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
let mut s1 = self.x;
|
||||
let s0 = self.y;
|
||||
self.x = s0;
|
||||
s1 ^= s1 << 23;
|
||||
s1 ^= s1 >> 17;
|
||||
s1 ^= s0;
|
||||
s1 ^= s0 >> 26;
|
||||
self.y = s1;
|
||||
self.x.wrapping_add(self.y)
|
||||
}
|
||||
|
||||
fn rand_int(&mut self, low: i32, high: i32) -> i32 {
|
||||
let range = (high as i64 - low as i64 + 1) as u64;
|
||||
let val = self.next_u64() % range;
|
||||
low + val as i32
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates white noise.
|
||||
struct WhiteNoiseGenerator {
|
||||
rng: WebRtcRandom,
|
||||
min_amplitude: i32,
|
||||
max_amplitude: i32,
|
||||
}
|
||||
|
||||
impl WhiteNoiseGenerator {
|
||||
fn new(min_amplitude: i32, max_amplitude: i32) -> Self {
|
||||
Self {
|
||||
rng: WebRtcRandom::new(42),
|
||||
min_amplitude,
|
||||
max_amplitude,
|
||||
}
|
||||
}
|
||||
|
||||
fn generate(&mut self) -> f32 {
|
||||
self.rng.rand_int(self.min_amplitude, self.max_amplitude) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a sine function.
|
||||
struct SineGenerator {
|
||||
amplitude: f32,
|
||||
frequency_hz: f32,
|
||||
sample_rate_hz: i32,
|
||||
x_radians: f32,
|
||||
}
|
||||
|
||||
impl SineGenerator {
|
||||
fn new(amplitude: f32, frequency_hz: f32, sample_rate_hz: i32) -> Self {
|
||||
Self {
|
||||
amplitude,
|
||||
frequency_hz,
|
||||
sample_rate_hz,
|
||||
x_radians: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn generate(&mut self) -> f32 {
|
||||
self.x_radians += self.frequency_hz / self.sample_rate_hz as f32 * 2.0 * PI;
|
||||
if self.x_radians >= 2.0 * PI {
|
||||
self.x_radians -= 2.0 * PI;
|
||||
}
|
||||
self.amplitude * self.x_radians.sin()
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates periodic pulses.
|
||||
struct PulseGenerator {
|
||||
pulse_amplitude: f32,
|
||||
no_pulse_amplitude: f32,
|
||||
samples_period: i32,
|
||||
sample_counter: i32,
|
||||
}
|
||||
|
||||
impl PulseGenerator {
|
||||
fn new(
|
||||
pulse_amplitude: f32,
|
||||
no_pulse_amplitude: f32,
|
||||
frequency_hz: f32,
|
||||
sample_rate_hz: i32,
|
||||
) -> Self {
|
||||
Self {
|
||||
pulse_amplitude,
|
||||
no_pulse_amplitude,
|
||||
samples_period: (sample_rate_hz as f32 / frequency_hz) as i32,
|
||||
sample_counter: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn generate(&mut self) -> f32 {
|
||||
self.sample_counter += 1;
|
||||
if self.sample_counter >= self.samples_period {
|
||||
self.sample_counter -= self.samples_period;
|
||||
}
|
||||
if self.sample_counter == 0 {
|
||||
self.pulse_amplitude
|
||||
} else {
|
||||
self.no_pulse_amplitude
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the noise estimator on audio generated by `gen_fn`
|
||||
/// for NUM_ITERATIONS. Returns the last noise level estimate.
|
||||
fn run_estimator(
|
||||
gen_fn: &mut dyn FnMut() -> f32,
|
||||
estimator: &mut NoiseLevelEstimator,
|
||||
sample_rate_hz: i32,
|
||||
) -> f32 {
|
||||
let samples_per_channel = sample_rate_hz / FRAMES_PER_SECOND;
|
||||
let mut signal = vec![0.0_f32; samples_per_channel as usize];
|
||||
|
||||
for _ in 0..NUM_ITERATIONS {
|
||||
for s in &mut signal {
|
||||
*s = gen_fn();
|
||||
}
|
||||
let channels: [&[f32]; 1] = [&signal];
|
||||
estimator.analyze(&channels);
|
||||
}
|
||||
|
||||
// Final analysis.
|
||||
for s in &mut signal {
|
||||
*s = gen_fn();
|
||||
}
|
||||
let channels: [&[f32]; 1] = [&signal];
|
||||
estimator.analyze(&channels)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_random_noise_8000() {
|
||||
noise_floor_estimator_with_random_noise(8000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_random_noise_16000() {
|
||||
noise_floor_estimator_with_random_noise(16000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_random_noise_32000() {
|
||||
noise_floor_estimator_with_random_noise(32000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_random_noise_48000() {
|
||||
noise_floor_estimator_with_random_noise(48000);
|
||||
}
|
||||
|
||||
fn noise_floor_estimator_with_random_noise(sample_rate_hz: i32) {
|
||||
let mut estimator = NoiseLevelEstimator::default();
|
||||
let mut noise_gen = WhiteNoiseGenerator::new(MIN_S16 as i32, MAX_S16 as i32);
|
||||
let noise_level_dbfs =
|
||||
run_estimator(&mut || noise_gen.generate(), &mut estimator, sample_rate_hz);
|
||||
assert!(
|
||||
(noise_level_dbfs - (-5.5)).abs() < 0.5,
|
||||
"noise_level_dbfs={noise_level_dbfs} at {sample_rate_hz}Hz, expected ~-5.5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_sine_tone_8000() {
|
||||
noise_floor_estimator_with_sine_tone(8000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_sine_tone_16000() {
|
||||
noise_floor_estimator_with_sine_tone(16000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_sine_tone_32000() {
|
||||
noise_floor_estimator_with_sine_tone(32000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_sine_tone_48000() {
|
||||
noise_floor_estimator_with_sine_tone(48000);
|
||||
}
|
||||
|
||||
fn noise_floor_estimator_with_sine_tone(sample_rate_hz: i32) {
|
||||
let mut estimator = NoiseLevelEstimator::default();
|
||||
let mut sine_gen = SineGenerator::new(MAX_S16, 600.0, sample_rate_hz);
|
||||
let noise_level_dbfs =
|
||||
run_estimator(&mut || sine_gen.generate(), &mut estimator, sample_rate_hz);
|
||||
assert!(
|
||||
(noise_level_dbfs - (-3.0)).abs() < 0.1,
|
||||
"noise_level_dbfs={noise_level_dbfs} at {sample_rate_hz}Hz, expected ~-3.0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_pulse_tone_8000() {
|
||||
noise_floor_estimator_with_pulse_tone(8000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_pulse_tone_16000() {
|
||||
noise_floor_estimator_with_pulse_tone(16000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_pulse_tone_32000() {
|
||||
noise_floor_estimator_with_pulse_tone(32000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_floor_estimator_with_pulse_tone_48000() {
|
||||
noise_floor_estimator_with_pulse_tone(48000);
|
||||
}
|
||||
|
||||
fn noise_floor_estimator_with_pulse_tone(sample_rate_hz: i32) {
|
||||
let mut estimator = NoiseLevelEstimator::default();
|
||||
let no_pulse_amplitude = 10.0_f32;
|
||||
let mut pulse_gen = PulseGenerator::new(MAX_S16, no_pulse_amplitude, 20.0, sample_rate_hz);
|
||||
let noise_level_dbfs =
|
||||
run_estimator(&mut || pulse_gen.generate(), &mut estimator, sample_rate_hz);
|
||||
let expected_noise_floor_dbfs = 20.0 * (no_pulse_amplitude / MAX_S16).log10();
|
||||
assert!(
|
||||
(noise_level_dbfs - expected_noise_floor_dbfs).abs() < 0.5,
|
||||
"noise_level_dbfs={noise_level_dbfs} at {sample_rate_hz}Hz, expected ~{expected_noise_floor_dbfs}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
//! RNN-based Voice Activity Detector for AGC2.
|
||||
//!
|
||||
//! A neural network-based VAD that uses spectral features and pitch
|
||||
//! analysis to estimate speech probability. Operates at 24kHz internally.
|
||||
|
||||
pub(crate) mod activations;
|
||||
pub(crate) mod auto_correlation;
|
||||
pub(crate) mod common;
|
||||
pub(crate) mod fc_layer;
|
||||
pub(crate) mod features_extraction;
|
||||
pub(crate) mod gru_layer;
|
||||
pub(crate) mod lp_residual;
|
||||
pub(crate) mod pitch_search;
|
||||
pub(crate) mod pitch_search_internal;
|
||||
pub(crate) mod ring_buffer;
|
||||
pub(crate) mod rnn;
|
||||
pub(crate) mod sequence_buffer;
|
||||
pub(crate) mod spectral_features;
|
||||
pub(crate) mod spectral_features_internal;
|
||||
pub(crate) mod symmetric_matrix_buffer;
|
||||
pub(crate) mod vector_math;
|
||||
pub(crate) mod weights;
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
//! Neural network activation functions.
|
||||
//!
|
||||
//! Ported from `webrtc/third_party/rnnoise/src/rnn_activations.h`.
|
||||
|
||||
/// Lookup table for the tanh approximation.
|
||||
const TANSIG_TABLE: [f32; 201] = [
|
||||
0.000000, 0.039979, 0.079830, 0.119427, 0.158649, 0.197375, 0.235496, 0.272905, 0.309507,
|
||||
0.345214, 0.379949, 0.413644, 0.446244, 0.477700, 0.507977, 0.537050, 0.564900, 0.591519,
|
||||
0.616909, 0.641077, 0.664037, 0.685809, 0.706419, 0.725897, 0.744277, 0.761594, 0.777888,
|
||||
0.793199, 0.807569, 0.821040, 0.833655, 0.845456, 0.856485, 0.866784, 0.876393, 0.885352,
|
||||
0.893698, 0.901468, 0.908698, 0.915420, 0.921669, 0.927473, 0.932862, 0.937863, 0.942503,
|
||||
0.946806, 0.950795, 0.954492, 0.957917, 0.961090, 0.964028, 0.966747, 0.969265, 0.971594,
|
||||
0.973749, 0.975743, 0.977587, 0.979293, 0.980869, 0.982327, 0.983675, 0.984921, 0.986072,
|
||||
0.987136, 0.988119, 0.989027, 0.989867, 0.990642, 0.991359, 0.992020, 0.992631, 0.993196,
|
||||
0.993718, 0.994199, 0.994644, 0.995055, 0.995434, 0.995784, 0.996108, 0.996407, 0.996682,
|
||||
0.996937, 0.997172, 0.997389, 0.997590, 0.997775, 0.997946, 0.998104, 0.998249, 0.998384,
|
||||
0.998508, 0.998623, 0.998728, 0.998826, 0.998916, 0.999000, 0.999076, 0.999147, 0.999213,
|
||||
0.999273, 0.999329, 0.999381, 0.999428, 0.999472, 0.999513, 0.999550, 0.999585, 0.999617,
|
||||
0.999646, 0.999673, 0.999699, 0.999722, 0.999743, 0.999763, 0.999781, 0.999798, 0.999813,
|
||||
0.999828, 0.999841, 0.999853, 0.999865, 0.999875, 0.999885, 0.999893, 0.999902, 0.999909,
|
||||
0.999916, 0.999923, 0.999929, 0.999934, 0.999939, 0.999944, 0.999948, 0.999952, 0.999956,
|
||||
0.999959, 0.999962, 0.999965, 0.999968, 0.999970, 0.999973, 0.999975, 0.999977, 0.999978,
|
||||
0.999980, 0.999982, 0.999983, 0.999984, 0.999986, 0.999987, 0.999988, 0.999989, 0.999990,
|
||||
0.999990, 0.999991, 0.999992, 0.999992, 0.999993, 0.999994, 0.999994, 0.999994, 0.999995,
|
||||
0.999995, 0.999996, 0.999996, 0.999996, 0.999997, 0.999997, 0.999997, 0.999997, 0.999997,
|
||||
0.999998, 0.999998, 0.999998, 0.999998, 0.999998, 0.999998, 0.999999, 0.999999, 0.999999,
|
||||
0.999999, 0.999999, 0.999999, 0.999999, 0.999999, 0.999999, 0.999999, 0.999999, 0.999999,
|
||||
0.999999, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
|
||||
1.000000, 1.000000, 1.000000,
|
||||
];
|
||||
|
||||
/// Approximated tanh using a lookup table with linear interpolation.
|
||||
///
|
||||
/// Must match the C++ `rnnoise::TansigApproximated` exactly for bit-exact
|
||||
/// neural network inference.
|
||||
#[inline]
|
||||
pub(crate) fn tansig_approximated(x: f32) -> f32 {
|
||||
// Tests are reversed to catch NaNs — must match C++ exactly.
|
||||
#[allow(
|
||||
clippy::neg_cmp_op_on_partial_ord,
|
||||
reason = "intentional NaN handling matching C++"
|
||||
)]
|
||||
if !(x < 8.0) {
|
||||
return 1.0;
|
||||
}
|
||||
#[allow(
|
||||
clippy::neg_cmp_op_on_partial_ord,
|
||||
reason = "intentional NaN handling matching C++"
|
||||
)]
|
||||
if !(x > -8.0) {
|
||||
return -1.0;
|
||||
}
|
||||
let (x_abs, sign) = if x < 0.0 {
|
||||
(-x, -1.0_f32)
|
||||
} else {
|
||||
(x, 1.0_f32)
|
||||
};
|
||||
// Look-up.
|
||||
let i = (0.5 + 25.0 * x_abs) as usize;
|
||||
let y = TANSIG_TABLE[i];
|
||||
// Map i back to x's scale (undo 25 factor).
|
||||
let x_residual = x_abs - 0.04 * i as f32;
|
||||
let y = y + x_residual * (1.0 - y * y) * (1.0 - y * x_residual);
|
||||
sign * y
|
||||
}
|
||||
|
||||
/// Approximated sigmoid: `0.5 + 0.5 * tansig(0.5 * x)`.
|
||||
#[inline]
|
||||
pub(crate) fn sigmoid_approximated(x: f32) -> f32 {
|
||||
0.5 + 0.5 * tansig_approximated(0.5 * x)
|
||||
}
|
||||
|
||||
/// Rectified linear unit: `max(0, x)`.
|
||||
#[cfg(test)]
|
||||
#[inline]
|
||||
pub(crate) fn rectified_linear_unit(x: f32) -> f32 {
|
||||
if x < 0.0 { 0.0 } else { x }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tansig_symmetry() {
|
||||
// tansig(-x) == -tansig(x)
|
||||
for &x in &[0.0_f32, 0.5, 1.0, 2.0, 4.0, 7.9] {
|
||||
let pos = tansig_approximated(x);
|
||||
let neg = tansig_approximated(-x);
|
||||
assert!(
|
||||
(pos + neg).abs() < 1e-6,
|
||||
"Symmetry failed for x={x}: tansig({x})={pos}, tansig(-{x})={neg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tansig_boundary_values() {
|
||||
assert_eq!(tansig_approximated(0.0), 0.0);
|
||||
assert_eq!(tansig_approximated(8.0), 1.0);
|
||||
assert_eq!(tansig_approximated(100.0), 1.0);
|
||||
assert_eq!(tansig_approximated(-8.0), -1.0);
|
||||
assert_eq!(tansig_approximated(-100.0), -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tansig_nan_handling() {
|
||||
// NaN should return 1.0 (same as C++ which tests !(x < 8.f) first)
|
||||
assert_eq!(tansig_approximated(f32::NAN), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tansig_approximately_monotonic() {
|
||||
// The lookup table approximation can have tiny non-monotonicity at
|
||||
// f32 precision in the saturation region. Allow small regressions.
|
||||
let mut prev = tansig_approximated(-7.99);
|
||||
let mut x = -7.9;
|
||||
while x <= 7.99 {
|
||||
let current = tansig_approximated(x);
|
||||
assert!(
|
||||
current >= prev - 1e-6,
|
||||
"Not monotonic at x={x}: prev={prev}, current={current}"
|
||||
);
|
||||
prev = current;
|
||||
x += 0.01;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sigmoid_boundary_values() {
|
||||
// sigmoid(0) = 0.5
|
||||
let s0 = sigmoid_approximated(0.0);
|
||||
assert!((s0 - 0.5).abs() < 1e-6, "sigmoid(0) = {s0}, expected 0.5");
|
||||
// sigmoid(large) ≈ 1.0
|
||||
assert!((sigmoid_approximated(100.0) - 1.0).abs() < 1e-4);
|
||||
// sigmoid(-large) ≈ 0.0
|
||||
assert!(sigmoid_approximated(-100.0).abs() < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relu_values() {
|
||||
assert_eq!(rectified_linear_unit(0.0), 0.0);
|
||||
assert_eq!(rectified_linear_unit(1.5), 1.5);
|
||||
assert_eq!(rectified_linear_unit(-1.5), 0.0);
|
||||
assert_eq!(rectified_linear_unit(-0.001), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! FFT-based auto-correlation computation on the pitch buffer.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/auto_correlation.cc`.
|
||||
|
||||
use super::common::{BUF_SIZE_12K_HZ, MAX_PITCH_12K_HZ, NUM_LAGS_12K_HZ};
|
||||
use sonora_fft::pffft::{FftType, Pffft, PffftBuffer};
|
||||
|
||||
/// FFT order for auto-correlation (length-512 FFT).
|
||||
const AUTO_CORRELATION_FFT_ORDER: u32 = 9;
|
||||
|
||||
/// Class to compute the auto-correlation on the pitch buffer for a target
|
||||
/// pitch interval.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AutoCorrelationCalculator {
|
||||
fft: Pffft,
|
||||
tmp: PffftBuffer,
|
||||
tmp2: PffftBuffer,
|
||||
x_buf: PffftBuffer,
|
||||
h_buf: PffftBuffer,
|
||||
}
|
||||
|
||||
impl Default for AutoCorrelationCalculator {
|
||||
fn default() -> Self {
|
||||
let fft_size = 1 << AUTO_CORRELATION_FFT_ORDER;
|
||||
let fft = Pffft::new(fft_size, FftType::Real);
|
||||
let tmp = fft.create_buffer();
|
||||
let tmp2 = fft.create_buffer();
|
||||
let x_buf = fft.create_buffer();
|
||||
let h_buf = fft.create_buffer();
|
||||
Self {
|
||||
fft,
|
||||
tmp,
|
||||
tmp2,
|
||||
x_buf,
|
||||
h_buf,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AutoCorrelationCalculator {
|
||||
/// Computes the auto-correlation coefficients for a target pitch interval.
|
||||
///
|
||||
/// `pitch_buf` must have size `BUF_SIZE_12K_HZ`.
|
||||
/// `auto_corr` must have size `NUM_LAGS_12K_HZ`. Indexes are inverted lags.
|
||||
pub(crate) fn compute_on_pitch_buffer(&mut self, pitch_buf: &[f32], auto_corr: &mut [f32]) {
|
||||
debug_assert_eq!(pitch_buf.len(), BUF_SIZE_12K_HZ);
|
||||
debug_assert_eq!(auto_corr.len(), NUM_LAGS_12K_HZ);
|
||||
|
||||
let fft_frame_size = 1 << AUTO_CORRELATION_FFT_ORDER;
|
||||
let convolution_length = BUF_SIZE_12K_HZ - MAX_PITCH_12K_HZ;
|
||||
|
||||
// Compute the FFT for the reversed reference frame.
|
||||
// pitch_buf[-convolution_length:]
|
||||
let tmp = self.tmp.as_mut_slice();
|
||||
for i in 0..convolution_length {
|
||||
tmp[i] = pitch_buf[BUF_SIZE_12K_HZ - 1 - i];
|
||||
}
|
||||
tmp[convolution_length..fft_frame_size].fill(0.0);
|
||||
self.fft.forward(&self.tmp, &mut self.h_buf, false);
|
||||
|
||||
// Compute the FFT for the sliding frames chunk.
|
||||
// pitch_buf[:convolution_length + NUM_LAGS_12K_HZ]
|
||||
let tmp = self.tmp.as_mut_slice();
|
||||
let copy_len = convolution_length + NUM_LAGS_12K_HZ;
|
||||
tmp[..copy_len].copy_from_slice(&pitch_buf[..copy_len]);
|
||||
tmp[copy_len..fft_frame_size].fill(0.0);
|
||||
self.fft.forward(&self.tmp, &mut self.x_buf, false);
|
||||
|
||||
// Convolve in the frequency domain.
|
||||
let scaling = 1.0 / fft_frame_size as f32;
|
||||
self.tmp.as_mut_slice().fill(0.0);
|
||||
self.fft
|
||||
.convolve_accumulate(&self.x_buf, &self.h_buf, &mut self.tmp, scaling);
|
||||
self.fft.backward(&self.tmp, &mut self.tmp2, false);
|
||||
|
||||
// Extract the auto-correlation coefficients.
|
||||
let tmp = self.tmp2.as_slice();
|
||||
auto_corr.copy_from_slice(
|
||||
&tmp[convolution_length - 1..convolution_length - 1 + NUM_LAGS_12K_HZ],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auto_correlation_on_constant_pitch_buffer() {
|
||||
let pitch_buf = [1.0_f32; BUF_SIZE_12K_HZ];
|
||||
let mut auto_corr = [0.0_f32; NUM_LAGS_12K_HZ];
|
||||
let mut calc = AutoCorrelationCalculator::default();
|
||||
calc.compute_on_pitch_buffer(&pitch_buf, &mut auto_corr);
|
||||
|
||||
// For a constant signal, auto-correlation at all lags should be
|
||||
// approximately equal to the convolution_length.
|
||||
let convolution_length = (BUF_SIZE_12K_HZ - MAX_PITCH_12K_HZ) as f32;
|
||||
for (i, &ac) in auto_corr.iter().enumerate() {
|
||||
assert!(
|
||||
(ac - convolution_length).abs() < 1.0,
|
||||
"auto_corr[{i}] = {ac}, expected ~{convolution_length}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_correlation_on_zero_buffer() {
|
||||
let pitch_buf = [0.0_f32; BUF_SIZE_12K_HZ];
|
||||
let mut auto_corr = [0.0_f32; NUM_LAGS_12K_HZ];
|
||||
let mut calc = AutoCorrelationCalculator::default();
|
||||
calc.compute_on_pitch_buffer(&pitch_buf, &mut auto_corr);
|
||||
|
||||
for (i, &ac) in auto_corr.iter().enumerate() {
|
||||
assert!(ac.abs() < 1e-6, "auto_corr[{i}] = {ac}, expected ~0");
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
//! RNN VAD common constants.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/common.h`.
|
||||
|
||||
pub(crate) const SAMPLE_RATE_24K_HZ: i32 = 24000;
|
||||
pub(crate) const FRAME_SIZE_10MS_24K_HZ: usize = SAMPLE_RATE_24K_HZ as usize / 100;
|
||||
pub(crate) const FRAME_SIZE_20MS_24K_HZ: usize = FRAME_SIZE_10MS_24K_HZ * 2;
|
||||
|
||||
// Pitch buffer.
|
||||
pub(crate) const MIN_PITCH_24K_HZ: usize = SAMPLE_RATE_24K_HZ as usize / 800; // 0.00125 s.
|
||||
pub(crate) const MAX_PITCH_24K_HZ: usize = (SAMPLE_RATE_24K_HZ as f64 / 62.5) as usize; // 0.016 s.
|
||||
pub(crate) const BUF_SIZE_24K_HZ: usize = MAX_PITCH_24K_HZ + FRAME_SIZE_20MS_24K_HZ;
|
||||
const _: () = assert!(BUF_SIZE_24K_HZ & 1 == 0, "The buffer size must be even.");
|
||||
|
||||
// 24 kHz analysis.
|
||||
pub(crate) const INITIAL_MIN_PITCH_24K_HZ: usize = 3 * MIN_PITCH_24K_HZ;
|
||||
const _: () = assert!(MIN_PITCH_24K_HZ < INITIAL_MIN_PITCH_24K_HZ);
|
||||
const _: () = assert!(INITIAL_MIN_PITCH_24K_HZ < MAX_PITCH_24K_HZ);
|
||||
const _: () = assert!(MAX_PITCH_24K_HZ > INITIAL_MIN_PITCH_24K_HZ);
|
||||
/// Number of (inverted) lags during the initial pitch search phase at 24 kHz.
|
||||
pub(crate) const INITIAL_NUM_LAGS_24K_HZ: usize = MAX_PITCH_24K_HZ - INITIAL_MIN_PITCH_24K_HZ;
|
||||
/// Number of (inverted) lags during the pitch search refinement phase at 24 kHz.
|
||||
pub(crate) const REFINE_NUM_LAGS_24K_HZ: usize = MAX_PITCH_24K_HZ + 1;
|
||||
const _: () = assert!(
|
||||
REFINE_NUM_LAGS_24K_HZ > INITIAL_NUM_LAGS_24K_HZ,
|
||||
"The refinement step must search the pitch in an extended pitch range."
|
||||
);
|
||||
|
||||
// 12 kHz analysis.
|
||||
pub(crate) const SAMPLE_RATE_12K_HZ: i32 = 12000;
|
||||
pub(crate) const FRAME_SIZE_10MS_12K_HZ: usize = SAMPLE_RATE_12K_HZ as usize / 100;
|
||||
pub(crate) const FRAME_SIZE_20MS_12K_HZ: usize = FRAME_SIZE_10MS_12K_HZ * 2;
|
||||
pub(crate) const BUF_SIZE_12K_HZ: usize = BUF_SIZE_24K_HZ / 2;
|
||||
pub(crate) const INITIAL_MIN_PITCH_12K_HZ: usize = INITIAL_MIN_PITCH_24K_HZ / 2;
|
||||
pub(crate) const MAX_PITCH_12K_HZ: usize = MAX_PITCH_24K_HZ / 2;
|
||||
const _: () = assert!(MAX_PITCH_12K_HZ > INITIAL_MIN_PITCH_12K_HZ);
|
||||
/// The inverted lags for the pitch interval are in range [0, `NUM_LAGS_12K_HZ`].
|
||||
pub(crate) const NUM_LAGS_12K_HZ: usize = MAX_PITCH_12K_HZ - INITIAL_MIN_PITCH_12K_HZ;
|
||||
|
||||
// 48 kHz constants.
|
||||
pub(crate) const MIN_PITCH_48K_HZ: usize = MIN_PITCH_24K_HZ * 2;
|
||||
pub(crate) const MAX_PITCH_48K_HZ: usize = MAX_PITCH_24K_HZ * 2;
|
||||
|
||||
// Spectral features.
|
||||
pub(crate) const NUM_BANDS: usize = 22;
|
||||
pub(crate) const NUM_LOWER_BANDS: usize = 6;
|
||||
const _: () = assert!(0 < NUM_LOWER_BANDS && NUM_LOWER_BANDS < NUM_BANDS);
|
||||
pub(crate) const CEPSTRAL_COEFFS_HISTORY_SIZE: usize = 8;
|
||||
const _: () = assert!(
|
||||
CEPSTRAL_COEFFS_HISTORY_SIZE > 2,
|
||||
"The history size must at least be 3 to compute first and second derivatives."
|
||||
);
|
||||
|
||||
/// Number of higher-band cepstral coefficients in the feature vector.
|
||||
pub(crate) const NUM_HIGHER_BANDS: usize = NUM_BANDS - NUM_LOWER_BANDS;
|
||||
|
||||
/// 42-element feature vector fed to the VAD RNN.
|
||||
///
|
||||
/// Layout matches `[f32; 42]` via `#[repr(C)]`. Named fields replace the
|
||||
/// manual index arithmetic that the C++ code uses with `ArrayView<float, 42>`.
|
||||
///
|
||||
/// Use `bytemuck::cast_ref::<_, [f32; 42]>()` for zero-copy
|
||||
/// conversion to a flat slice when needed (e.g. feeding the RNN input layer).
|
||||
#[derive(Clone, Debug, bytemuck::Pod, bytemuck::Zeroable, Copy)]
|
||||
#[repr(C)]
|
||||
pub(crate) struct FeatureVector {
|
||||
/// Average lower-band cepstral coefficients.
|
||||
pub average: [f32; NUM_LOWER_BANDS],
|
||||
/// Higher-band cepstral coefficients.
|
||||
pub higher_bands_cepstrum: [f32; NUM_HIGHER_BANDS],
|
||||
/// First derivative of lower-band cepstral coefficients.
|
||||
pub first_derivative: [f32; NUM_LOWER_BANDS],
|
||||
/// Second derivative of lower-band cepstral coefficients.
|
||||
pub second_derivative: [f32; NUM_LOWER_BANDS],
|
||||
/// Cross-correlation between reference and lagged frames per band.
|
||||
pub bands_cross_correlation: [f32; NUM_LOWER_BANDS],
|
||||
/// Normalized pitch period.
|
||||
pub pitch_period: f32,
|
||||
/// Spectral variability.
|
||||
pub spectral_variability: f32,
|
||||
}
|
||||
|
||||
impl Default for FeatureVector {
|
||||
fn default() -> Self {
|
||||
bytemuck::Zeroable::zeroed()
|
||||
}
|
||||
}
|
||||
|
||||
impl FeatureVector {
|
||||
/// Views the feature vector as a flat slice of floats (zero-copy).
|
||||
pub(crate) fn as_slice(&self) -> &[f32] {
|
||||
bytemuck::cast_slice(bytemuck::bytes_of(self))
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
//! Fully-connected neural network layer.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/rnn_fc.cc`.
|
||||
|
||||
use super::activations::{sigmoid_approximated, tansig_approximated};
|
||||
use super::vector_math::VectorMath;
|
||||
use super::weights::WEIGHTS_SCALE;
|
||||
|
||||
/// Activation function for a neural network cell.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum ActivationFunction {
|
||||
TansigApproximated,
|
||||
SigmoidApproximated,
|
||||
}
|
||||
|
||||
/// Maximum number of units for an FC layer.
|
||||
pub(crate) const FC_LAYER_MAX_UNITS: usize = 24;
|
||||
|
||||
/// Fully-connected layer with a custom activation function.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FullyConnectedLayer {
|
||||
input_size: usize,
|
||||
output_size: usize,
|
||||
bias: Vec<f32>,
|
||||
weights: Vec<f32>,
|
||||
vector_math: VectorMath,
|
||||
activation: ActivationFunction,
|
||||
output: [f32; FC_LAYER_MAX_UNITS],
|
||||
}
|
||||
|
||||
impl FullyConnectedLayer {
|
||||
/// Creates a new fully-connected layer.
|
||||
///
|
||||
/// `bias` and `weights` are i8 quantized values that get scaled by
|
||||
/// `WEIGHTS_SCALE` and transposed during construction.
|
||||
pub(crate) fn new(
|
||||
input_size: usize,
|
||||
output_size: usize,
|
||||
bias: &[i8],
|
||||
weights: &[i8],
|
||||
activation: ActivationFunction,
|
||||
vector_math: VectorMath,
|
||||
) -> Self {
|
||||
debug_assert!(output_size <= FC_LAYER_MAX_UNITS);
|
||||
debug_assert_eq!(bias.len(), output_size);
|
||||
debug_assert_eq!(weights.len(), input_size * output_size);
|
||||
|
||||
let scaled_bias = scale_params(bias);
|
||||
let preprocessed_weights = preprocess_weights(weights, input_size, output_size);
|
||||
|
||||
Self {
|
||||
input_size,
|
||||
output_size,
|
||||
bias: scaled_bias,
|
||||
weights: preprocessed_weights,
|
||||
vector_math,
|
||||
activation,
|
||||
output: [0.0; FC_LAYER_MAX_UNITS],
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the input size.
|
||||
pub(crate) fn input_size(&self) -> usize {
|
||||
self.input_size
|
||||
}
|
||||
|
||||
/// Returns the output as a slice.
|
||||
pub(crate) fn output(&self) -> &[f32] {
|
||||
&self.output[..self.output_size]
|
||||
}
|
||||
|
||||
/// Returns the output size.
|
||||
pub(crate) fn size(&self) -> usize {
|
||||
self.output_size
|
||||
}
|
||||
|
||||
/// Computes the fully-connected layer output.
|
||||
pub(crate) fn compute_output(&mut self, input: &[f32]) {
|
||||
debug_assert_eq!(input.len(), self.input_size);
|
||||
|
||||
let activation_fn: fn(f32) -> f32 = match self.activation {
|
||||
ActivationFunction::TansigApproximated => tansig_approximated,
|
||||
ActivationFunction::SigmoidApproximated => sigmoid_approximated,
|
||||
};
|
||||
|
||||
for o in 0..self.output_size {
|
||||
let w_start = o * self.input_size;
|
||||
let w_end = w_start + self.input_size;
|
||||
self.output[o] = activation_fn(
|
||||
self.bias[o]
|
||||
+ self
|
||||
.vector_math
|
||||
.dot_product(input, &self.weights[w_start..w_end]),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scales i8 parameters to f32.
|
||||
fn scale_params(params: &[i8]) -> Vec<f32> {
|
||||
params.iter().map(|&x| WEIGHTS_SCALE * x as f32).collect()
|
||||
}
|
||||
|
||||
/// Transposes and scales weight matrix from i8 to f32.
|
||||
///
|
||||
/// C++ stores weights in column-major order (input_size rows x output_size cols).
|
||||
/// We transpose to row-major (output_size rows x input_size cols) so that each
|
||||
/// output neuron's weights are contiguous for efficient dot product.
|
||||
fn preprocess_weights(weights: &[i8], input_size: usize, output_size: usize) -> Vec<f32> {
|
||||
if output_size == 1 {
|
||||
return scale_params(weights);
|
||||
}
|
||||
let mut w = vec![0.0_f32; weights.len()];
|
||||
for o in 0..output_size {
|
||||
for i in 0..input_size {
|
||||
w[o * input_size + i] = WEIGHTS_SCALE * weights[i * output_size + o] as f32;
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rnn_vad::weights;
|
||||
use sonora_simd::detect_backend;
|
||||
|
||||
const FC_INPUT: [f32; 42] = [
|
||||
-1.00131, -0.627069, -7.81097, 7.86285, -2.87145, 3.32365, -0.653161, 0.529839, -0.425307,
|
||||
0.25583, 0.235094, 0.230527, -0.144687, 0.182785, 0.57102, 0.125039, 0.479482, -0.0255439,
|
||||
-0.0073141, -0.147346, -0.217106, -0.0846906, -8.34943, 3.09065, 1.42628, -0.85235,
|
||||
-0.220207, -0.811163, 2.09032, -2.01425, -0.690268, -0.925327, -0.541354, 0.58455,
|
||||
-0.606726, -0.0372358, 0.565991, 0.435854, 0.420812, 0.162198, -2.13, 10.0089,
|
||||
];
|
||||
|
||||
const FC_EXPECTED_OUTPUT: [f32; 24] = [
|
||||
-0.623293, -0.988299, 0.999378, 0.967168, 0.103087, -0.978545, -0.856347, 0.346675, 1.0,
|
||||
-0.717442, -0.544176, 0.960363, 0.983443, 0.999991, -0.824335, 0.984742, 0.990208,
|
||||
0.938179, 0.875092, 0.999846, 0.997707, -0.999382, 0.973153, -0.966605,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn fully_connected_layer_output() {
|
||||
let vector_math = VectorMath::new(detect_backend());
|
||||
let mut fc = FullyConnectedLayer::new(
|
||||
42,
|
||||
24,
|
||||
&weights::INPUT_DENSE_BIAS,
|
||||
&weights::INPUT_DENSE_WEIGHTS,
|
||||
ActivationFunction::TansigApproximated,
|
||||
vector_math,
|
||||
);
|
||||
fc.compute_output(&FC_INPUT);
|
||||
let output = fc.output();
|
||||
for (i, (&expected, &actual)) in FC_EXPECTED_OUTPUT.iter().zip(output.iter()).enumerate() {
|
||||
assert!(
|
||||
(expected - actual).abs() < 1e-5,
|
||||
"output[{i}]: expected {expected}, got {actual}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fully_connected_layer_scalar() {
|
||||
let vector_math = VectorMath::new(sonora_simd::SimdBackend::Scalar);
|
||||
let mut fc = FullyConnectedLayer::new(
|
||||
42,
|
||||
24,
|
||||
&weights::INPUT_DENSE_BIAS,
|
||||
&weights::INPUT_DENSE_WEIGHTS,
|
||||
ActivationFunction::TansigApproximated,
|
||||
vector_math,
|
||||
);
|
||||
fc.compute_output(&FC_INPUT);
|
||||
let output = fc.output();
|
||||
for (i, (&expected, &actual)) in FC_EXPECTED_OUTPUT.iter().zip(output.iter()).enumerate() {
|
||||
assert!(
|
||||
(expected - actual).abs() < 1e-5,
|
||||
"scalar output[{i}]: expected {expected}, got {actual}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Feature extractor to feed the VAD RNN.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/features_extraction.cc`.
|
||||
|
||||
use super::common::{
|
||||
BUF_SIZE_24K_HZ, FRAME_SIZE_10MS_24K_HZ, FRAME_SIZE_20MS_24K_HZ, FeatureVector,
|
||||
MAX_PITCH_24K_HZ,
|
||||
};
|
||||
use super::lp_residual::{
|
||||
NUM_LPC_COEFFICIENTS, compute_and_post_process_lpc_coefficients, compute_lp_residual,
|
||||
};
|
||||
use super::pitch_search::PitchEstimator;
|
||||
use super::sequence_buffer::SequenceBuffer;
|
||||
use super::spectral_features::SpectralFeaturesExtractor;
|
||||
use sonora_simd::SimdBackend;
|
||||
|
||||
/// Feature extractor to feed the VAD RNN.
|
||||
///
|
||||
/// Processes 10 ms frames at 24 kHz and produces a 42-element feature vector.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FeaturesExtractor {
|
||||
pitch_buf_24k_hz: SequenceBuffer<BUF_SIZE_24K_HZ, FRAME_SIZE_10MS_24K_HZ>,
|
||||
lp_residual: Vec<f32>,
|
||||
pitch_estimator: PitchEstimator,
|
||||
spectral_features_extractor: SpectralFeaturesExtractor,
|
||||
pitch_period_48k_hz: i32,
|
||||
}
|
||||
|
||||
impl FeaturesExtractor {
|
||||
/// Creates a new feature extractor.
|
||||
pub(crate) fn new(backend: SimdBackend) -> Self {
|
||||
Self {
|
||||
pitch_buf_24k_hz: SequenceBuffer::default(),
|
||||
lp_residual: vec![0.0; BUF_SIZE_24K_HZ],
|
||||
pitch_estimator: PitchEstimator::new(backend),
|
||||
spectral_features_extractor: SpectralFeaturesExtractor::default(),
|
||||
pitch_period_48k_hz: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets internal state.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.pitch_buf_24k_hz.reset();
|
||||
self.spectral_features_extractor.reset();
|
||||
}
|
||||
|
||||
/// Analyzes the samples, computes the feature vector and returns `true` if
|
||||
/// silence is detected.
|
||||
///
|
||||
/// When silence is detected, `feature_vector` is partially written and
|
||||
/// must not be used to feed the VAD RNN.
|
||||
pub(crate) fn check_silence_compute_features(
|
||||
&mut self,
|
||||
samples: &[f32],
|
||||
feature_vector: &mut FeatureVector,
|
||||
) -> bool {
|
||||
debug_assert_eq!(samples.len(), FRAME_SIZE_10MS_24K_HZ);
|
||||
|
||||
// Feed buffer with samples (HPF disabled, matching C++ default).
|
||||
let samples_arr: &[f32; FRAME_SIZE_10MS_24K_HZ] = samples.try_into().unwrap();
|
||||
self.pitch_buf_24k_hz.push(samples_arr);
|
||||
|
||||
// Extract the LP residual.
|
||||
let pitch_buf_view = self.pitch_buf_24k_hz.get_buffer_view();
|
||||
let mut lpc_coeffs = [0.0_f32; NUM_LPC_COEFFICIENTS];
|
||||
compute_and_post_process_lpc_coefficients(pitch_buf_view, &mut lpc_coeffs);
|
||||
compute_lp_residual(&lpc_coeffs, pitch_buf_view, &mut self.lp_residual);
|
||||
|
||||
// Estimate pitch on the LP-residual and write the normalized pitch
|
||||
// period (normalization based on training data stats).
|
||||
self.pitch_period_48k_hz = self.pitch_estimator.estimate(&self.lp_residual);
|
||||
feature_vector.pitch_period = 0.01 * (self.pitch_period_48k_hz - 300) as f32;
|
||||
|
||||
// Extract lagged frame (according to the estimated pitch period).
|
||||
debug_assert!(self.pitch_period_48k_hz / 2 <= MAX_PITCH_24K_HZ as i32);
|
||||
let lag_offset = MAX_PITCH_24K_HZ - self.pitch_period_48k_hz as usize / 2;
|
||||
let lagged_frame = &pitch_buf_view[lag_offset..lag_offset + FRAME_SIZE_20MS_24K_HZ];
|
||||
|
||||
// Reference frame is the most recent 20 ms.
|
||||
let reference_frame: &[f32; FRAME_SIZE_20MS_24K_HZ] =
|
||||
self.pitch_buf_24k_hz.get_most_recent_values_view();
|
||||
|
||||
// Analyze reference and lagged frames, check silence, write features.
|
||||
let Some(features) = self
|
||||
.spectral_features_extractor
|
||||
.check_silence_compute_features(reference_frame, lagged_frame)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
feature_vector.higher_bands_cepstrum = features.higher_bands_cepstrum;
|
||||
feature_vector.average = features.average;
|
||||
feature_vector.first_derivative = features.first_derivative;
|
||||
feature_vector.second_derivative = features.second_derivative;
|
||||
feature_vector.bands_cross_correlation = features.bands_cross_correlation;
|
||||
feature_vector.spectral_variability = features.variability;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::common::SAMPLE_RATE_24K_HZ;
|
||||
use super::*;
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
/// Number of 10 ms frames required to fill the pitch buffer.
|
||||
const NUM_TEST_DATA_FRAMES: usize = BUF_SIZE_24K_HZ.div_ceil(FRAME_SIZE_10MS_24K_HZ);
|
||||
const NUM_TEST_DATA_SIZE: usize = NUM_TEST_DATA_FRAMES * FRAME_SIZE_10MS_24K_HZ;
|
||||
|
||||
fn pitch_is_valid(pitch_hz: f32) -> bool {
|
||||
use super::super::common::INITIAL_MIN_PITCH_24K_HZ;
|
||||
let pitch_period = (SAMPLE_RATE_24K_HZ as f32 / pitch_hz) as usize;
|
||||
(INITIAL_MIN_PITCH_24K_HZ..=MAX_PITCH_24K_HZ).contains(&pitch_period)
|
||||
}
|
||||
|
||||
fn create_pure_tone(amplitude: f32, freq_hz: f32, dst: &mut [f32]) {
|
||||
for (i, s) in dst.iter_mut().enumerate() {
|
||||
*s = amplitude * (TAU * freq_hz * i as f32 / SAMPLE_RATE_24K_HZ as f32).sin();
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds `features_extractor` with `samples` splitting it in 10 ms frames.
|
||||
fn feed_test_data(
|
||||
features_extractor: &mut FeaturesExtractor,
|
||||
samples: &[f32],
|
||||
feature_vector: &mut FeatureVector,
|
||||
) -> bool {
|
||||
let mut is_silence = true;
|
||||
let num_frames = samples.len() / FRAME_SIZE_10MS_24K_HZ;
|
||||
for i in 0..num_frames {
|
||||
let start = i * FRAME_SIZE_10MS_24K_HZ;
|
||||
let end = start + FRAME_SIZE_10MS_24K_HZ;
|
||||
is_silence = features_extractor
|
||||
.check_silence_compute_features(&samples[start..end], feature_vector);
|
||||
}
|
||||
is_silence
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_extraction_low_high_pitch() {
|
||||
let amplitude = 1000.0_f32;
|
||||
let low_pitch_hz = 150.0_f32;
|
||||
let high_pitch_hz = 250.0_f32;
|
||||
assert!(pitch_is_valid(low_pitch_hz));
|
||||
assert!(pitch_is_valid(high_pitch_hz));
|
||||
|
||||
let backend = sonora_simd::detect_backend();
|
||||
let mut features_extractor = FeaturesExtractor::new(backend);
|
||||
let mut samples = vec![0.0_f32; NUM_TEST_DATA_SIZE];
|
||||
let mut feature_vector = FeatureVector::default();
|
||||
|
||||
// Low frequency tone → high period.
|
||||
create_pure_tone(amplitude, low_pitch_hz, &mut samples);
|
||||
assert!(!feed_test_data(
|
||||
&mut features_extractor,
|
||||
&samples,
|
||||
&mut feature_vector
|
||||
));
|
||||
let high_pitch_period = feature_vector.pitch_period;
|
||||
|
||||
// High frequency tone → low period.
|
||||
features_extractor.reset();
|
||||
create_pure_tone(amplitude, high_pitch_hz, &mut samples);
|
||||
assert!(!feed_test_data(
|
||||
&mut features_extractor,
|
||||
&samples,
|
||||
&mut feature_vector
|
||||
));
|
||||
let low_pitch_period = feature_vector.pitch_period;
|
||||
|
||||
assert!(
|
||||
low_pitch_period < high_pitch_period,
|
||||
"Expected low_pitch_period ({low_pitch_period}) < high_pitch_period ({high_pitch_period})"
|
||||
);
|
||||
}
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
//! Gated Recurrent Unit (GRU) neural network layer.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/rnn_gru.cc`.
|
||||
|
||||
use super::activations::sigmoid_approximated;
|
||||
use super::vector_math::VectorMath;
|
||||
use super::weights::WEIGHTS_SCALE;
|
||||
|
||||
/// Maximum number of units for a GRU layer.
|
||||
pub(crate) const GRU_LAYER_MAX_UNITS: usize = 24;
|
||||
|
||||
/// Number of gates in a GRU (update, reset, output).
|
||||
const NUM_GRU_GATES: usize = 3;
|
||||
|
||||
/// Recurrent layer with gated recurrent units (GRUs).
|
||||
///
|
||||
/// Uses sigmoid for update/reset gates and ReLU for the output gate.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct GatedRecurrentLayer {
|
||||
input_size: usize,
|
||||
output_size: usize,
|
||||
bias: Vec<f32>,
|
||||
weights: Vec<f32>,
|
||||
recurrent_weights: Vec<f32>,
|
||||
vector_math: VectorMath,
|
||||
state: [f32; GRU_LAYER_MAX_UNITS],
|
||||
}
|
||||
|
||||
impl GatedRecurrentLayer {
|
||||
/// Creates a new GRU layer.
|
||||
///
|
||||
/// `bias`, `weights`, and `recurrent_weights` are i8 quantized values
|
||||
/// that get scaled, transposed, and rearranged during construction.
|
||||
pub(crate) fn new(
|
||||
input_size: usize,
|
||||
output_size: usize,
|
||||
bias: &[i8],
|
||||
weights: &[i8],
|
||||
recurrent_weights: &[i8],
|
||||
vector_math: VectorMath,
|
||||
) -> Self {
|
||||
debug_assert!(output_size <= GRU_LAYER_MAX_UNITS);
|
||||
debug_assert_eq!(bias.len(), NUM_GRU_GATES * output_size);
|
||||
debug_assert_eq!(weights.len(), NUM_GRU_GATES * input_size * output_size);
|
||||
debug_assert_eq!(
|
||||
recurrent_weights.len(),
|
||||
NUM_GRU_GATES * output_size * output_size
|
||||
);
|
||||
|
||||
let preprocessed_bias = preprocess_gru_tensor(bias, output_size);
|
||||
let preprocessed_weights = preprocess_gru_tensor(weights, output_size);
|
||||
let preprocessed_recurrent = preprocess_gru_tensor(recurrent_weights, output_size);
|
||||
|
||||
let mut layer = Self {
|
||||
input_size,
|
||||
output_size,
|
||||
bias: preprocessed_bias,
|
||||
weights: preprocessed_weights,
|
||||
recurrent_weights: preprocessed_recurrent,
|
||||
vector_math,
|
||||
state: [0.0; GRU_LAYER_MAX_UNITS],
|
||||
};
|
||||
layer.reset();
|
||||
layer
|
||||
}
|
||||
|
||||
/// Returns the input size.
|
||||
pub(crate) fn input_size(&self) -> usize {
|
||||
self.input_size
|
||||
}
|
||||
|
||||
/// Returns the output (state) as a slice.
|
||||
pub(crate) fn output(&self) -> &[f32] {
|
||||
&self.state[..self.output_size]
|
||||
}
|
||||
|
||||
/// Returns the output size.
|
||||
pub(crate) fn size(&self) -> usize {
|
||||
self.output_size
|
||||
}
|
||||
|
||||
/// Resets the GRU state to zero.
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.state.fill(0.0);
|
||||
}
|
||||
|
||||
/// Computes the recurrent layer output and updates the state.
|
||||
pub(crate) fn compute_output(&mut self, input: &[f32]) {
|
||||
debug_assert_eq!(input.len(), self.input_size);
|
||||
|
||||
let stride_weights = self.input_size * self.output_size;
|
||||
let stride_recurrent = self.output_size * self.output_size;
|
||||
|
||||
// Update gate: u = sigmoid(W_u * input + R_u * state + b_u)
|
||||
let mut update = [0.0_f32; GRU_LAYER_MAX_UNITS];
|
||||
self.compute_update_reset_gate(
|
||||
input,
|
||||
0, // gate offset
|
||||
stride_weights,
|
||||
stride_recurrent,
|
||||
&mut update,
|
||||
);
|
||||
|
||||
// Reset gate: r = sigmoid(W_r * input + R_r * state + b_r)
|
||||
let mut reset = [0.0_f32; GRU_LAYER_MAX_UNITS];
|
||||
self.compute_update_reset_gate(
|
||||
input,
|
||||
1, // gate offset
|
||||
stride_weights,
|
||||
stride_recurrent,
|
||||
&mut reset,
|
||||
);
|
||||
|
||||
// State gate: s' = u * s + (1-u) * relu(W_o * input + R_o * (s*r) + b_o)
|
||||
self.compute_state_gate(input, &update, &reset, stride_weights, stride_recurrent);
|
||||
}
|
||||
|
||||
/// Computes update or reset gate: `g = sigmoid(W*input + R*state + b)`.
|
||||
fn compute_update_reset_gate(
|
||||
&self,
|
||||
input: &[f32],
|
||||
gate_index: usize,
|
||||
stride_weights: usize,
|
||||
stride_recurrent: usize,
|
||||
gate: &mut [f32; GRU_LAYER_MAX_UNITS],
|
||||
) {
|
||||
let bias_offset = gate_index * self.output_size;
|
||||
let w_offset = gate_index * stride_weights;
|
||||
let r_offset = gate_index * stride_recurrent;
|
||||
let state = &self.state[..self.output_size];
|
||||
|
||||
for (o, gate_val) in gate.iter_mut().enumerate().take(self.output_size) {
|
||||
let mut x = self.bias[bias_offset + o];
|
||||
x += self.vector_math.dot_product(
|
||||
input,
|
||||
&self.weights[w_offset + o * self.input_size..w_offset + (o + 1) * self.input_size],
|
||||
);
|
||||
x += self.vector_math.dot_product(
|
||||
state,
|
||||
&self.recurrent_weights
|
||||
[r_offset + o * self.output_size..r_offset + (o + 1) * self.output_size],
|
||||
);
|
||||
*gate_val = sigmoid_approximated(x);
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes state gate: `s' = u * s + (1-u) * relu(W*input + R*(s*r) + b)`.
|
||||
fn compute_state_gate(
|
||||
&mut self,
|
||||
input: &[f32],
|
||||
update: &[f32; GRU_LAYER_MAX_UNITS],
|
||||
reset: &[f32; GRU_LAYER_MAX_UNITS],
|
||||
stride_weights: usize,
|
||||
stride_recurrent: usize,
|
||||
) {
|
||||
let bias_offset = 2 * self.output_size;
|
||||
let w_offset = 2 * stride_weights;
|
||||
let r_offset = 2 * stride_recurrent;
|
||||
|
||||
// Compute reset_x_state = state * reset
|
||||
let mut reset_x_state = [0.0_f32; GRU_LAYER_MAX_UNITS];
|
||||
for o in 0..self.output_size {
|
||||
reset_x_state[o] = self.state[o] * reset[o];
|
||||
}
|
||||
|
||||
for (o, &u) in update.iter().enumerate().take(self.output_size) {
|
||||
let mut x = self.bias[bias_offset + o];
|
||||
x += self.vector_math.dot_product(
|
||||
input,
|
||||
&self.weights[w_offset + o * self.input_size..w_offset + (o + 1) * self.input_size],
|
||||
);
|
||||
x += self.vector_math.dot_product(
|
||||
&reset_x_state[..self.output_size],
|
||||
&self.recurrent_weights
|
||||
[r_offset + o * self.output_size..r_offset + (o + 1) * self.output_size],
|
||||
);
|
||||
// ReLU activation + state update
|
||||
self.state[o] = u * self.state[o] + (1.0 - u) * x.max(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Preprocesses a GRU tensor: transposes, casts i8→f32, and scales.
|
||||
///
|
||||
/// The source tensor has layout `[n, NUM_GRU_GATES, output_size]` where `n`
|
||||
/// is inferred from the tensor size. The output is rearranged to
|
||||
/// `[NUM_GRU_GATES, output_size, n]` with each element scaled by `WEIGHTS_SCALE`.
|
||||
fn preprocess_gru_tensor(tensor_src: &[i8], output_size: usize) -> Vec<f32> {
|
||||
let n = tensor_src.len() / (output_size * NUM_GRU_GATES);
|
||||
debug_assert_eq!(tensor_src.len(), n * output_size * NUM_GRU_GATES);
|
||||
|
||||
let stride_src = NUM_GRU_GATES * output_size;
|
||||
let stride_dst = n * output_size;
|
||||
|
||||
let mut tensor_dst = vec![0.0_f32; tensor_src.len()];
|
||||
for g in 0..NUM_GRU_GATES {
|
||||
for o in 0..output_size {
|
||||
for i in 0..n {
|
||||
tensor_dst[g * stride_dst + o * n + i] =
|
||||
WEIGHTS_SCALE * tensor_src[i * stride_src + g * output_size + o] as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
tensor_dst
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sonora_simd::detect_backend;
|
||||
|
||||
const GRU_INPUT_SIZE: usize = 5;
|
||||
const GRU_OUTPUT_SIZE: usize = 4;
|
||||
|
||||
const GRU_BIAS: [i8; 12] = [96, -99, -81, -114, 49, 119, -118, 68, -76, 91, 121, 125];
|
||||
|
||||
const GRU_WEIGHTS: [i8; 60] = [
|
||||
// Input 0.
|
||||
124, 9, 1, 116, // Update.
|
||||
-66, -21, -118, -110, // Reset.
|
||||
104, 75, -23, -51, // Output.
|
||||
// Input 1.
|
||||
-72, -111, 47, 93, // Update.
|
||||
77, -98, 41, -8, // Reset.
|
||||
40, -23, -43, -107, // Output.
|
||||
// Input 2.
|
||||
9, -73, 30, -32, // Update.
|
||||
-2, 64, -26, 91, // Reset.
|
||||
-48, -24, -28, -104, // Output.
|
||||
// Input 3.
|
||||
74, -46, 116, 15, // Update.
|
||||
32, 52, -126, -38, // Reset.
|
||||
-121, 12, -16, 110, // Output.
|
||||
// Input 4.
|
||||
-95, 66, -103, -35, // Update.
|
||||
-38, 3, -126, -61, // Reset.
|
||||
28, 98, -117, -43, // Output.
|
||||
];
|
||||
|
||||
const GRU_RECURRENT_WEIGHTS: [i8; 48] = [
|
||||
// Output 0.
|
||||
-3, 87, 50, 51, // Update.
|
||||
-22, 27, -39, 62, // Reset.
|
||||
31, -83, -52, -48, // Output.
|
||||
// Output 1.
|
||||
-6, 83, -19, 104, // Update.
|
||||
105, 48, 23, 68, // Reset.
|
||||
23, 40, 7, -120, // Output.
|
||||
// Output 2.
|
||||
64, -62, 117, 85, // Update.
|
||||
51, -43, 54, -105, // Reset.
|
||||
120, 56, -128, -107, // Output.
|
||||
// Output 3.
|
||||
39, 50, -17, -47, // Update.
|
||||
-117, 14, 108, 12, // Reset.
|
||||
-7, -72, 103, -87, // Output.
|
||||
];
|
||||
|
||||
const GRU_INPUT_SEQUENCE: [f32; 20] = [
|
||||
0.89395463, 0.93224651, 0.55788344, 0.32341808, 0.93355054, 0.13475326, 0.97370994,
|
||||
0.14253306, 0.93710381, 0.76093364, 0.65780413, 0.41657975, 0.49403164, 0.46843281,
|
||||
0.75138855, 0.24517593, 0.47657707, 0.57064998, 0.435184, 0.19319285,
|
||||
];
|
||||
|
||||
const GRU_EXPECTED_OUTPUT_SEQUENCE: [f32; 16] = [
|
||||
0.0239123, 0.5773077, 0.0, 0.0, 0.01282811, 0.64330572, 0.0, 0.04863098, 0.00781069,
|
||||
0.75267816, 0.0, 0.02579715, 0.00471378, 0.59162533, 0.11087593, 0.01334511,
|
||||
];
|
||||
|
||||
fn test_gated_recurrent_layer(mut gru: GatedRecurrentLayer) {
|
||||
let input_sequence_length = GRU_INPUT_SEQUENCE.len() / gru.input_size();
|
||||
let output_sequence_length = GRU_EXPECTED_OUTPUT_SEQUENCE.len() / gru.size();
|
||||
assert_eq!(input_sequence_length, output_sequence_length);
|
||||
|
||||
gru.reset();
|
||||
for i in 0..input_sequence_length {
|
||||
let input_start = i * gru.input_size();
|
||||
let input_end = input_start + gru.input_size();
|
||||
gru.compute_output(&GRU_INPUT_SEQUENCE[input_start..input_end]);
|
||||
|
||||
let output_start = i * gru.size();
|
||||
let expected = &GRU_EXPECTED_OUTPUT_SEQUENCE[output_start..output_start + gru.size()];
|
||||
let actual = gru.output();
|
||||
for (j, (&exp, &act)) in expected.iter().zip(actual.iter()).enumerate() {
|
||||
assert!(
|
||||
(exp - act).abs() < 3e-6,
|
||||
"step {i}, output[{j}]: expected {exp}, got {act}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gated_recurrent_layer_output() {
|
||||
let vector_math = VectorMath::new(detect_backend());
|
||||
let gru = GatedRecurrentLayer::new(
|
||||
GRU_INPUT_SIZE,
|
||||
GRU_OUTPUT_SIZE,
|
||||
&GRU_BIAS,
|
||||
&GRU_WEIGHTS,
|
||||
&GRU_RECURRENT_WEIGHTS,
|
||||
vector_math,
|
||||
);
|
||||
test_gated_recurrent_layer(gru);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gated_recurrent_layer_scalar() {
|
||||
let vector_math = VectorMath::new(sonora_simd::SimdBackend::Scalar);
|
||||
let gru = GatedRecurrentLayer::new(
|
||||
GRU_INPUT_SIZE,
|
||||
GRU_OUTPUT_SIZE,
|
||||
&GRU_BIAS,
|
||||
&GRU_WEIGHTS,
|
||||
&GRU_RECURRENT_WEIGHTS,
|
||||
vector_math,
|
||||
);
|
||||
test_gated_recurrent_layer(gru);
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
//! Linear prediction residual computation.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/lp_residual.cc`.
|
||||
|
||||
/// Number of LPC coefficients.
|
||||
pub(crate) const NUM_LPC_COEFFICIENTS: usize = 5;
|
||||
|
||||
/// Computes and post-processes LPC coefficients tailored for pitch estimation.
|
||||
pub(crate) fn compute_and_post_process_lpc_coefficients(
|
||||
x: &[f32],
|
||||
lpc_coeffs: &mut [f32; NUM_LPC_COEFFICIENTS],
|
||||
) {
|
||||
let mut auto_corr = [0.0_f32; NUM_LPC_COEFFICIENTS];
|
||||
compute_auto_correlation(x, &mut auto_corr);
|
||||
|
||||
if auto_corr[0] == 0.0 {
|
||||
// Empty frame.
|
||||
lpc_coeffs.fill(0.0);
|
||||
return;
|
||||
}
|
||||
|
||||
denoise_auto_correlation(&mut auto_corr);
|
||||
let mut lpc_coeffs_pre = [0.0_f32; NUM_LPC_COEFFICIENTS - 1];
|
||||
compute_initial_inverse_filter_coefficients(&auto_corr, &mut lpc_coeffs_pre);
|
||||
|
||||
// LPC coefficients post-processing.
|
||||
lpc_coeffs_pre[0] *= 0.9;
|
||||
lpc_coeffs_pre[1] *= 0.9 * 0.9;
|
||||
lpc_coeffs_pre[2] *= 0.9 * 0.9 * 0.9;
|
||||
lpc_coeffs_pre[3] *= 0.9 * 0.9 * 0.9 * 0.9;
|
||||
|
||||
const C: f32 = 0.8;
|
||||
lpc_coeffs[0] = lpc_coeffs_pre[0] + C;
|
||||
lpc_coeffs[1] = lpc_coeffs_pre[1] + C * lpc_coeffs_pre[0];
|
||||
lpc_coeffs[2] = lpc_coeffs_pre[2] + C * lpc_coeffs_pre[1];
|
||||
lpc_coeffs[3] = lpc_coeffs_pre[3] + C * lpc_coeffs_pre[2];
|
||||
lpc_coeffs[4] = C * lpc_coeffs_pre[3];
|
||||
}
|
||||
|
||||
/// Computes the LP residual for the input frame `x` and the LPC coefficients.
|
||||
///
|
||||
/// `y` and `x` can point to the same slice for in-place computation.
|
||||
pub(crate) fn compute_lp_residual(
|
||||
lpc_coeffs: &[f32; NUM_LPC_COEFFICIENTS],
|
||||
x: &[f32],
|
||||
y: &mut [f32],
|
||||
) {
|
||||
debug_assert!(x.len() > NUM_LPC_COEFFICIENTS);
|
||||
debug_assert_eq!(x.len(), y.len());
|
||||
|
||||
// y[i] = x[i] + sum(lpc_coeffs[k] * x[i-1-k] for k in 0..NUM_LPC_COEFFICIENTS)
|
||||
// Edge case: i < NUM_LPC_COEFFICIENTS.
|
||||
y[0] = x[0];
|
||||
for i in 1..NUM_LPC_COEFFICIENTS {
|
||||
let mut sum = x[i];
|
||||
for k in 0..i {
|
||||
sum += lpc_coeffs[k] * x[i - 1 - k];
|
||||
}
|
||||
y[i] = sum;
|
||||
}
|
||||
// Regular case.
|
||||
for i in NUM_LPC_COEFFICIENTS..x.len() {
|
||||
let mut sum = x[i];
|
||||
for k in 0..NUM_LPC_COEFFICIENTS {
|
||||
sum += lpc_coeffs[k] * x[i - 1 - k];
|
||||
}
|
||||
y[i] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes auto-correlation coefficients for `x`.
|
||||
fn compute_auto_correlation(x: &[f32], auto_corr: &mut [f32; NUM_LPC_COEFFICIENTS]) {
|
||||
debug_assert!(x.len() > NUM_LPC_COEFFICIENTS);
|
||||
for lag in 0..NUM_LPC_COEFFICIENTS {
|
||||
auto_corr[lag] = x[..x.len() - lag]
|
||||
.iter()
|
||||
.zip(x[lag..].iter())
|
||||
.map(|(&a, &b)| a * b)
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies denoising to the auto-correlation coefficients.
|
||||
fn denoise_auto_correlation(auto_corr: &mut [f32; NUM_LPC_COEFFICIENTS]) {
|
||||
// Assume -40 dB white noise floor.
|
||||
auto_corr[0] *= 1.0001;
|
||||
// Hard-coded values: [np.float32((0.008*0.008*i*i)) for i in range(1,5)]
|
||||
auto_corr[1] -= auto_corr[1] * 0.000064;
|
||||
auto_corr[2] -= auto_corr[2] * 0.000256;
|
||||
auto_corr[3] -= auto_corr[3] * 0.000576;
|
||||
auto_corr[4] -= auto_corr[4] * 0.001024;
|
||||
}
|
||||
|
||||
/// Computes the initial inverse filter coefficients given auto-correlation coefficients.
|
||||
/// Uses the Levinson-Durbin algorithm.
|
||||
fn compute_initial_inverse_filter_coefficients(
|
||||
auto_corr: &[f32; NUM_LPC_COEFFICIENTS],
|
||||
lpc_coeffs: &mut [f32; NUM_LPC_COEFFICIENTS - 1],
|
||||
) {
|
||||
let mut error = auto_corr[0];
|
||||
for i in 0..NUM_LPC_COEFFICIENTS - 1 {
|
||||
let mut reflection_coeff = 0.0_f32;
|
||||
for j in 0..i {
|
||||
reflection_coeff += lpc_coeffs[j] * auto_corr[i - j];
|
||||
}
|
||||
reflection_coeff += auto_corr[i + 1];
|
||||
|
||||
// Avoid division by numbers close to zero.
|
||||
const MIN_ERROR_MAGNITUDE: f32 = 1e-6;
|
||||
if error.abs() < MIN_ERROR_MAGNITUDE {
|
||||
error = error.signum() * MIN_ERROR_MAGNITUDE;
|
||||
}
|
||||
|
||||
reflection_coeff /= -error;
|
||||
// Update LPC coefficients and total error.
|
||||
lpc_coeffs[i] = reflection_coeff;
|
||||
for j in 0..((i + 1) >> 1) {
|
||||
let tmp1 = lpc_coeffs[j];
|
||||
let tmp2 = lpc_coeffs[i - 1 - j];
|
||||
lpc_coeffs[j] = tmp1 + reflection_coeff * tmp2;
|
||||
lpc_coeffs[i - 1 - j] = tmp2 + reflection_coeff * tmp1;
|
||||
}
|
||||
error -= reflection_coeff * reflection_coeff * error;
|
||||
if error < 0.001 * auto_corr[0] {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lp_residual_of_empty_frame() {
|
||||
let frame = [0.0_f32; 320];
|
||||
let mut lpc_coeffs = [0.0_f32; NUM_LPC_COEFFICIENTS];
|
||||
compute_and_post_process_lpc_coefficients(&frame, &mut lpc_coeffs);
|
||||
assert_eq!(lpc_coeffs, [0.0; NUM_LPC_COEFFICIENTS]);
|
||||
|
||||
let mut residual = vec![0.0_f32; 320];
|
||||
compute_lp_residual(&lpc_coeffs, &frame, &mut residual);
|
||||
for &r in &residual {
|
||||
assert_eq!(r, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lp_residual_of_unit_impulse() {
|
||||
// A frame with an impulse at the start should produce non-trivial LPC.
|
||||
let mut frame = [0.0_f32; 320];
|
||||
frame[0] = 1.0;
|
||||
let mut lpc_coeffs = [0.0_f32; NUM_LPC_COEFFICIENTS];
|
||||
compute_and_post_process_lpc_coefficients(&frame, &mut lpc_coeffs);
|
||||
// LPC coeffs should not all be zero (the frame has energy).
|
||||
assert!(lpc_coeffs.iter().any(|&c| c != 0.0));
|
||||
|
||||
let mut residual = vec![0.0_f32; 320];
|
||||
compute_lp_residual(&lpc_coeffs, &frame, &mut residual);
|
||||
// First element should be the impulse value.
|
||||
assert_eq!(residual[0], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lp_residual_preserves_length() {
|
||||
let frame = vec![1.0_f32; 480];
|
||||
let mut lpc_coeffs = [0.0_f32; NUM_LPC_COEFFICIENTS];
|
||||
compute_and_post_process_lpc_coefficients(&frame, &mut lpc_coeffs);
|
||||
|
||||
let mut residual = vec![0.0_f32; 480];
|
||||
compute_lp_residual(&lpc_coeffs, &frame, &mut residual);
|
||||
assert_eq!(residual.len(), 480);
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
//! Pitch estimator for the RNN VAD.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/pitch_search.cc`.
|
||||
|
||||
use super::auto_correlation::AutoCorrelationCalculator;
|
||||
use super::common::{BUF_SIZE_24K_HZ, MAX_PITCH_48K_HZ, NUM_LAGS_12K_HZ, REFINE_NUM_LAGS_24K_HZ};
|
||||
use super::pitch_search_internal::{
|
||||
PitchInfo, compute_extended_pitch_period_48k_hz, compute_pitch_period_12k_hz,
|
||||
compute_pitch_period_48k_hz, compute_sliding_frame_square_energies_24k_hz, decimate_2x,
|
||||
};
|
||||
use sonora_simd::SimdBackend;
|
||||
|
||||
/// Pitch estimator.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PitchEstimator {
|
||||
backend: SimdBackend,
|
||||
last_pitch_48k_hz: PitchInfo,
|
||||
auto_corr_calculator: AutoCorrelationCalculator,
|
||||
y_energy_24k_hz: Vec<f32>,
|
||||
pitch_buffer_12k_hz: Vec<f32>,
|
||||
auto_correlation_12k_hz: Vec<f32>,
|
||||
}
|
||||
|
||||
impl PitchEstimator {
|
||||
/// Creates a new pitch estimator.
|
||||
pub(crate) fn new(backend: SimdBackend) -> Self {
|
||||
Self {
|
||||
backend,
|
||||
last_pitch_48k_hz: PitchInfo::default(),
|
||||
auto_corr_calculator: AutoCorrelationCalculator::default(),
|
||||
y_energy_24k_hz: vec![0.0; REFINE_NUM_LAGS_24K_HZ],
|
||||
pitch_buffer_12k_hz: vec![0.0; BUF_SIZE_24K_HZ / 2],
|
||||
auto_correlation_12k_hz: vec![0.0; NUM_LAGS_12K_HZ],
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the estimated pitch period at 48 kHz.
|
||||
pub(crate) fn estimate(&mut self, pitch_buffer: &[f32]) -> i32 {
|
||||
debug_assert_eq!(pitch_buffer.len(), BUF_SIZE_24K_HZ);
|
||||
|
||||
// Perform the initial pitch search at 12 kHz.
|
||||
decimate_2x(pitch_buffer, &mut self.pitch_buffer_12k_hz);
|
||||
self.auto_corr_calculator
|
||||
.compute_on_pitch_buffer(&self.pitch_buffer_12k_hz, &mut self.auto_correlation_12k_hz);
|
||||
let mut pitch_periods = compute_pitch_period_12k_hz(
|
||||
&self.pitch_buffer_12k_hz,
|
||||
&self.auto_correlation_12k_hz,
|
||||
self.backend,
|
||||
);
|
||||
// Adapt inverted lags from 12 to 24 kHz.
|
||||
pitch_periods.best *= 2;
|
||||
pitch_periods.second_best *= 2;
|
||||
|
||||
// Refine from 12 kHz to 48 kHz.
|
||||
compute_sliding_frame_square_energies_24k_hz(
|
||||
pitch_buffer,
|
||||
&mut self.y_energy_24k_hz,
|
||||
self.backend,
|
||||
);
|
||||
|
||||
let pitch_lag_48k_hz = compute_pitch_period_48k_hz(
|
||||
pitch_buffer,
|
||||
&self.y_energy_24k_hz,
|
||||
pitch_periods,
|
||||
self.backend,
|
||||
);
|
||||
|
||||
self.last_pitch_48k_hz = compute_extended_pitch_period_48k_hz(
|
||||
pitch_buffer,
|
||||
&self.y_energy_24k_hz,
|
||||
MAX_PITCH_48K_HZ as i32 - pitch_lag_48k_hz,
|
||||
self.last_pitch_48k_hz,
|
||||
self.backend,
|
||||
);
|
||||
|
||||
self.last_pitch_48k_hz.period
|
||||
}
|
||||
|
||||
/// Returns the last pitch strength (for testing).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn last_pitch_strength(&self) -> f32 {
|
||||
self.last_pitch_48k_hz.strength
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn test_resources_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/resources/rnn_vad")
|
||||
}
|
||||
|
||||
/// Loads a binary file as a Vec of little-endian f32 values.
|
||||
fn read_f32_le(path: &Path) -> Vec<f32> {
|
||||
let mut file =
|
||||
File::open(path).unwrap_or_else(|e| panic!("Failed to open {}: {e}", path.display()));
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
bytes
|
||||
.chunks_exact(4)
|
||||
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pitch_search_within_tolerance() {
|
||||
let pitch_info_size = 2; // period + strength
|
||||
let chunk_size = BUF_SIZE_24K_HZ + pitch_info_size;
|
||||
|
||||
// Use ARM64-specific reference data on ARM64 platforms.
|
||||
let resource_name = if cfg!(target_arch = "aarch64") {
|
||||
"pitch_lp_res_arm64.dat"
|
||||
} else {
|
||||
"pitch_lp_res.dat"
|
||||
};
|
||||
|
||||
let path = test_resources_dir().join(resource_name);
|
||||
let data = read_f32_le(&path);
|
||||
|
||||
let backend = sonora_simd::detect_backend();
|
||||
let mut pitch_estimator = PitchEstimator::new(backend);
|
||||
|
||||
// Max 3 s (300 frames).
|
||||
for (i, chunk) in data.chunks_exact(chunk_size).take(300).enumerate() {
|
||||
let lp_residual = &chunk[..BUF_SIZE_24K_HZ];
|
||||
let expected_pitch_period = chunk[BUF_SIZE_24K_HZ];
|
||||
let expected_pitch_strength = chunk[BUF_SIZE_24K_HZ + 1];
|
||||
|
||||
let pitch_period = pitch_estimator.estimate(lp_residual);
|
||||
assert_eq!(
|
||||
expected_pitch_period, pitch_period as f32,
|
||||
"Pitch period mismatch at frame {i}"
|
||||
);
|
||||
assert!(
|
||||
(expected_pitch_strength - pitch_estimator.last_pitch_strength()).abs() < 15e-6,
|
||||
"Pitch strength mismatch at frame {i}: expected {expected_pitch_strength}, got {}",
|
||||
pitch_estimator.last_pitch_strength()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,739 @@
|
||||
//! Internal pitch search helpers.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.cc`.
|
||||
|
||||
use super::common::{
|
||||
BUF_SIZE_24K_HZ, FRAME_SIZE_20MS_12K_HZ, FRAME_SIZE_20MS_24K_HZ, INITIAL_NUM_LAGS_24K_HZ,
|
||||
MAX_PITCH_24K_HZ, MAX_PITCH_48K_HZ, MIN_PITCH_24K_HZ, MIN_PITCH_48K_HZ, NUM_LAGS_12K_HZ,
|
||||
REFINE_NUM_LAGS_24K_HZ,
|
||||
};
|
||||
use sonora_simd::SimdBackend;
|
||||
|
||||
/// Performs 2x decimation without any anti-aliasing filter.
|
||||
pub(crate) fn decimate_2x(src: &[f32], dst: &mut [f32]) {
|
||||
debug_assert_eq!(src.len(), BUF_SIZE_24K_HZ);
|
||||
debug_assert_eq!(dst.len(), BUF_SIZE_24K_HZ / 2);
|
||||
for (i, d) in dst.iter_mut().enumerate() {
|
||||
*d = src[2 * i];
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-2 pitch period candidates (inverted lags).
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct CandidatePitchPeriods {
|
||||
pub best: i32,
|
||||
pub second_best: i32,
|
||||
}
|
||||
|
||||
/// Pitch period and strength.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct PitchInfo {
|
||||
pub period: i32,
|
||||
pub strength: f32,
|
||||
}
|
||||
|
||||
fn compute_auto_correlation_single(
|
||||
inverted_lag: usize,
|
||||
pitch_buffer: &[f32],
|
||||
backend: SimdBackend,
|
||||
) -> f32 {
|
||||
debug_assert!(inverted_lag < BUF_SIZE_24K_HZ);
|
||||
debug_assert!(inverted_lag < REFINE_NUM_LAGS_24K_HZ);
|
||||
let x = &pitch_buffer[MAX_PITCH_24K_HZ..MAX_PITCH_24K_HZ + FRAME_SIZE_20MS_24K_HZ];
|
||||
let y = &pitch_buffer[inverted_lag..inverted_lag + FRAME_SIZE_20MS_24K_HZ];
|
||||
backend.dot_product(x, y)
|
||||
}
|
||||
|
||||
/// Pseudo-interpolation offset: returns -1, 0, or +1.
|
||||
fn get_pitch_pseudo_interpolation_offset(
|
||||
prev_auto_correlation: f32,
|
||||
curr_auto_correlation: f32,
|
||||
next_auto_correlation: f32,
|
||||
) -> i32 {
|
||||
if (next_auto_correlation - prev_auto_correlation)
|
||||
> 0.7 * (curr_auto_correlation - prev_auto_correlation)
|
||||
{
|
||||
1
|
||||
} else if (prev_auto_correlation - next_auto_correlation)
|
||||
> 0.7 * (curr_auto_correlation - next_auto_correlation)
|
||||
{
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Refines a pitch period `lag` with pseudo-interpolation. Output rate is 2x.
|
||||
fn pitch_pseudo_interpolation_lag(lag: i32, pitch_buffer: &[f32], backend: SimdBackend) -> i32 {
|
||||
let mut offset = 0;
|
||||
if lag > 0 && lag < MAX_PITCH_24K_HZ as i32 {
|
||||
let inverted_lag = MAX_PITCH_24K_HZ as i32 - lag;
|
||||
offset = get_pitch_pseudo_interpolation_offset(
|
||||
compute_auto_correlation_single((inverted_lag + 1) as usize, pitch_buffer, backend),
|
||||
compute_auto_correlation_single(inverted_lag as usize, pitch_buffer, backend),
|
||||
compute_auto_correlation_single((inverted_lag - 1) as usize, pitch_buffer, backend),
|
||||
);
|
||||
}
|
||||
2 * lag + offset
|
||||
}
|
||||
|
||||
/// Integer multipliers used when looking for sub-harmonics.
|
||||
const SUB_HARMONIC_MULTIPLIERS: [i32; 14] = [3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2];
|
||||
|
||||
/// Number of analyzed pitches to the left/right of a pitch candidate.
|
||||
const PITCH_NEIGHBORHOOD_RADIUS: i32 = 2;
|
||||
|
||||
/// Maximum number of analyzed pitch periods.
|
||||
const NUM_PITCH_CANDIDATES: usize = 2;
|
||||
const MAX_PITCH_PERIODS_24K_HZ: usize =
|
||||
NUM_PITCH_CANDIDATES * (2 * PITCH_NEIGHBORHOOD_RADIUS as usize + 1);
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Range {
|
||||
min: i32,
|
||||
max: i32,
|
||||
}
|
||||
|
||||
fn create_inverted_lag_range(inverted_lag: i32) -> Range {
|
||||
Range {
|
||||
min: (inverted_lag - PITCH_NEIGHBORHOOD_RADIUS).max(0),
|
||||
max: (inverted_lag + PITCH_NEIGHBORHOOD_RADIUS).min(INITIAL_NUM_LAGS_24K_HZ as i32 - 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Collection of inverted lags.
|
||||
struct InvertedLagsIndex {
|
||||
inverted_lags: [i32; MAX_PITCH_PERIODS_24K_HZ],
|
||||
num_entries: usize,
|
||||
}
|
||||
|
||||
impl InvertedLagsIndex {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
inverted_lags: [0; MAX_PITCH_PERIODS_24K_HZ],
|
||||
num_entries: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn append(&mut self, inverted_lag: i32) {
|
||||
debug_assert!(self.num_entries < MAX_PITCH_PERIODS_24K_HZ);
|
||||
self.inverted_lags[self.num_entries] = inverted_lag;
|
||||
self.num_entries += 1;
|
||||
}
|
||||
|
||||
fn as_slice(&self) -> &[i32] {
|
||||
&self.inverted_lags[..self.num_entries]
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes auto-correlation for inverted lags in a range.
|
||||
fn compute_auto_correlation_range(
|
||||
inverted_lags: Range,
|
||||
pitch_buffer: &[f32],
|
||||
auto_correlation: &mut [f32],
|
||||
inverted_lags_index: &mut InvertedLagsIndex,
|
||||
backend: SimdBackend,
|
||||
) {
|
||||
debug_assert!(inverted_lags.min <= inverted_lags.max);
|
||||
// Trick to avoid zero initialization — needed by pseudo-interpolation.
|
||||
if inverted_lags.min > 0 {
|
||||
auto_correlation[inverted_lags.min as usize - 1] = 0.0;
|
||||
}
|
||||
if (inverted_lags.max as usize) < INITIAL_NUM_LAGS_24K_HZ - 1 {
|
||||
auto_correlation[inverted_lags.max as usize + 1] = 0.0;
|
||||
}
|
||||
debug_assert!(inverted_lags.min >= 0);
|
||||
debug_assert!((inverted_lags.max as usize) < INITIAL_NUM_LAGS_24K_HZ);
|
||||
for inverted_lag in inverted_lags.min..=inverted_lags.max {
|
||||
auto_correlation[inverted_lag as usize] =
|
||||
compute_auto_correlation_single(inverted_lag as usize, pitch_buffer, backend);
|
||||
inverted_lags_index.append(inverted_lag);
|
||||
}
|
||||
}
|
||||
|
||||
/// Searches the strongest pitch period at 24 kHz and returns its inverted lag
|
||||
/// at 48 kHz.
|
||||
fn compute_pitch_period_48k_hz_from_lags(
|
||||
inverted_lags: &[i32],
|
||||
auto_correlation: &[f32],
|
||||
y_energy: &[f32],
|
||||
) -> i32 {
|
||||
let mut best_inverted_lag = 0_i32;
|
||||
let mut best_numerator = -1.0_f32;
|
||||
let mut best_denominator = 0.0_f32;
|
||||
for &inverted_lag in inverted_lags {
|
||||
let il = inverted_lag as usize;
|
||||
if auto_correlation[il] > 0.0 {
|
||||
let numerator = auto_correlation[il] * auto_correlation[il];
|
||||
let denominator = y_energy[il];
|
||||
if numerator * best_denominator > best_numerator * denominator {
|
||||
best_inverted_lag = inverted_lag;
|
||||
best_numerator = numerator;
|
||||
best_denominator = denominator;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pseudo-interpolation to transform to 48 kHz.
|
||||
if best_inverted_lag == 0 || best_inverted_lag >= INITIAL_NUM_LAGS_24K_HZ as i32 - 1 {
|
||||
return best_inverted_lag * 2;
|
||||
}
|
||||
let il = best_inverted_lag as usize;
|
||||
let offset = get_pitch_pseudo_interpolation_offset(
|
||||
auto_correlation[il + 1],
|
||||
auto_correlation[il],
|
||||
auto_correlation[il - 1],
|
||||
);
|
||||
2 * best_inverted_lag + offset
|
||||
}
|
||||
|
||||
/// Returns an alternative pitch period for `pitch_period` given a `multiplier`
|
||||
/// and a `divisor`.
|
||||
const fn get_alternative_pitch_period(pitch_period: i32, multiplier: i32, divisor: i32) -> i32 {
|
||||
(2 * multiplier * pitch_period + divisor) / (2 * divisor)
|
||||
}
|
||||
|
||||
/// Returns true if the alternative pitch period is stronger than the initial one.
|
||||
fn is_alternative_pitch_stronger_than_initial(
|
||||
last: PitchInfo,
|
||||
initial: PitchInfo,
|
||||
alternative: PitchInfo,
|
||||
period_divisor: i32,
|
||||
) -> bool {
|
||||
// Computed as [5*k*k for k in range(16)].
|
||||
const INITIAL_PITCH_PERIOD_THRESHOLDS: [i32; 14] = [
|
||||
20, 45, 80, 125, 180, 245, 320, 405, 500, 605, 720, 845, 980, 1125,
|
||||
];
|
||||
|
||||
debug_assert!(last.period >= 0);
|
||||
debug_assert!(initial.period >= 0);
|
||||
debug_assert!(alternative.period >= 0);
|
||||
debug_assert!(period_divisor >= 2);
|
||||
|
||||
// Pitch tracking term.
|
||||
let mut lower_threshold_term = 0.0_f32;
|
||||
if (alternative.period - last.period).abs() <= 1 {
|
||||
lower_threshold_term = last.strength;
|
||||
} else if (alternative.period - last.period).abs() == 2
|
||||
&& initial.period > INITIAL_PITCH_PERIOD_THRESHOLDS[(period_divisor - 2) as usize]
|
||||
{
|
||||
lower_threshold_term = 0.5 * last.strength;
|
||||
}
|
||||
|
||||
let mut threshold = (0.7 * initial.strength - lower_threshold_term).max(0.3);
|
||||
if alternative.period < 3 * MIN_PITCH_24K_HZ as i32 {
|
||||
threshold = (0.85 * initial.strength - lower_threshold_term).max(0.4);
|
||||
} else if alternative.period < 2 * MIN_PITCH_24K_HZ as i32 {
|
||||
threshold = (0.9 * initial.strength - lower_threshold_term).max(0.5);
|
||||
}
|
||||
alternative.strength > threshold
|
||||
}
|
||||
|
||||
/// Computes the sum of squared samples for every sliding frame `y` in the
|
||||
/// pitch buffer.
|
||||
pub(crate) fn compute_sliding_frame_square_energies_24k_hz(
|
||||
pitch_buffer: &[f32],
|
||||
y_energy: &mut [f32],
|
||||
backend: SimdBackend,
|
||||
) {
|
||||
debug_assert_eq!(pitch_buffer.len(), BUF_SIZE_24K_HZ);
|
||||
debug_assert_eq!(y_energy.len(), REFINE_NUM_LAGS_24K_HZ);
|
||||
|
||||
let frame_view = &pitch_buffer[..FRAME_SIZE_20MS_24K_HZ];
|
||||
let mut yy = backend.dot_product(frame_view, frame_view);
|
||||
y_energy[0] = yy;
|
||||
for inverted_lag in 0..MAX_PITCH_24K_HZ {
|
||||
yy -= pitch_buffer[inverted_lag] * pitch_buffer[inverted_lag];
|
||||
yy += pitch_buffer[inverted_lag + FRAME_SIZE_20MS_24K_HZ]
|
||||
* pitch_buffer[inverted_lag + FRAME_SIZE_20MS_24K_HZ];
|
||||
yy = yy.max(1.0);
|
||||
y_energy[inverted_lag + 1] = yy;
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the candidate pitch periods at 12 kHz.
|
||||
pub(crate) fn compute_pitch_period_12k_hz(
|
||||
pitch_buffer: &[f32],
|
||||
auto_correlation: &[f32],
|
||||
backend: SimdBackend,
|
||||
) -> CandidatePitchPeriods {
|
||||
debug_assert_eq!(pitch_buffer.len(), BUF_SIZE_24K_HZ / 2);
|
||||
debug_assert_eq!(auto_correlation.len(), NUM_LAGS_12K_HZ);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct PitchCandidate {
|
||||
period_inverted_lag: i32,
|
||||
strength_numerator: f32,
|
||||
strength_denominator: f32,
|
||||
}
|
||||
|
||||
impl PitchCandidate {
|
||||
fn has_stronger_pitch_than(&self, b: &Self) -> bool {
|
||||
self.strength_numerator * b.strength_denominator
|
||||
> b.strength_numerator * self.strength_denominator
|
||||
}
|
||||
}
|
||||
|
||||
let frame_view = &pitch_buffer[..FRAME_SIZE_20MS_12K_HZ + 1];
|
||||
let mut denominator = 1.0 + backend.dot_product(frame_view, frame_view);
|
||||
|
||||
let mut best = PitchCandidate {
|
||||
period_inverted_lag: 0,
|
||||
strength_numerator: -1.0,
|
||||
strength_denominator: 0.0,
|
||||
};
|
||||
let mut second_best = PitchCandidate {
|
||||
period_inverted_lag: 1,
|
||||
strength_numerator: -1.0,
|
||||
strength_denominator: 0.0,
|
||||
};
|
||||
|
||||
for inverted_lag in 0..NUM_LAGS_12K_HZ {
|
||||
if auto_correlation[inverted_lag] > 0.0 {
|
||||
let candidate = PitchCandidate {
|
||||
period_inverted_lag: inverted_lag as i32,
|
||||
strength_numerator: auto_correlation[inverted_lag] * auto_correlation[inverted_lag],
|
||||
strength_denominator: denominator,
|
||||
};
|
||||
if candidate.has_stronger_pitch_than(&second_best) {
|
||||
if candidate.has_stronger_pitch_than(&best) {
|
||||
second_best = best;
|
||||
best = candidate;
|
||||
} else {
|
||||
second_best = candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Update energy for the next inverted lag.
|
||||
let y_old = pitch_buffer[inverted_lag];
|
||||
let y_new = pitch_buffer[inverted_lag + FRAME_SIZE_20MS_12K_HZ];
|
||||
denominator -= y_old * y_old;
|
||||
denominator += y_new * y_new;
|
||||
denominator = denominator.max(0.0);
|
||||
}
|
||||
|
||||
CandidatePitchPeriods {
|
||||
best: best.period_inverted_lag,
|
||||
second_best: second_best.period_inverted_lag,
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the pitch period at 48 kHz given the 24 kHz pitch buffer,
|
||||
/// sliding frame energies and pitch period candidates at 24 kHz.
|
||||
pub(crate) fn compute_pitch_period_48k_hz(
|
||||
pitch_buffer: &[f32],
|
||||
y_energy: &[f32],
|
||||
pitch_candidates: CandidatePitchPeriods,
|
||||
backend: SimdBackend,
|
||||
) -> i32 {
|
||||
debug_assert_eq!(pitch_buffer.len(), BUF_SIZE_24K_HZ);
|
||||
debug_assert_eq!(y_energy.len(), REFINE_NUM_LAGS_24K_HZ);
|
||||
|
||||
let mut auto_correlation = [0.0_f32; INITIAL_NUM_LAGS_24K_HZ];
|
||||
let mut inverted_lags_index = InvertedLagsIndex::new();
|
||||
|
||||
// Create two inverted lag ranges so that r1 precedes r2.
|
||||
let swap = pitch_candidates.best > pitch_candidates.second_best;
|
||||
let r1 = create_inverted_lag_range(if swap {
|
||||
pitch_candidates.second_best
|
||||
} else {
|
||||
pitch_candidates.best
|
||||
});
|
||||
let r2 = create_inverted_lag_range(if swap {
|
||||
pitch_candidates.best
|
||||
} else {
|
||||
pitch_candidates.second_best
|
||||
});
|
||||
|
||||
debug_assert!(r1.min <= r1.max);
|
||||
debug_assert!(r2.min <= r2.max);
|
||||
debug_assert!(r1.min <= r2.min);
|
||||
debug_assert!(r1.max <= r2.max);
|
||||
|
||||
if r1.max + 1 >= r2.min {
|
||||
// Overlapping or adjacent ranges.
|
||||
compute_auto_correlation_range(
|
||||
Range {
|
||||
min: r1.min,
|
||||
max: r2.max,
|
||||
},
|
||||
pitch_buffer,
|
||||
&mut auto_correlation,
|
||||
&mut inverted_lags_index,
|
||||
backend,
|
||||
);
|
||||
} else {
|
||||
// Disjoint ranges.
|
||||
compute_auto_correlation_range(
|
||||
r1,
|
||||
pitch_buffer,
|
||||
&mut auto_correlation,
|
||||
&mut inverted_lags_index,
|
||||
backend,
|
||||
);
|
||||
compute_auto_correlation_range(
|
||||
r2,
|
||||
pitch_buffer,
|
||||
&mut auto_correlation,
|
||||
&mut inverted_lags_index,
|
||||
backend,
|
||||
);
|
||||
}
|
||||
|
||||
compute_pitch_period_48k_hz_from_lags(
|
||||
inverted_lags_index.as_slice(),
|
||||
&auto_correlation,
|
||||
y_energy,
|
||||
)
|
||||
}
|
||||
|
||||
/// Computes the pitch period at 48 kHz searching in an extended pitch range.
|
||||
pub(crate) fn compute_extended_pitch_period_48k_hz(
|
||||
pitch_buffer: &[f32],
|
||||
y_energy: &[f32],
|
||||
initial_pitch_period_48k_hz: i32,
|
||||
last_pitch_48k_hz: PitchInfo,
|
||||
backend: SimdBackend,
|
||||
) -> PitchInfo {
|
||||
debug_assert_eq!(pitch_buffer.len(), BUF_SIZE_24K_HZ);
|
||||
debug_assert_eq!(y_energy.len(), REFINE_NUM_LAGS_24K_HZ);
|
||||
debug_assert!(MIN_PITCH_48K_HZ as i32 <= initial_pitch_period_48k_hz);
|
||||
debug_assert!(initial_pitch_period_48k_hz <= MAX_PITCH_48K_HZ as i32);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct RefinedPitchCandidate {
|
||||
period: i32,
|
||||
strength: f32,
|
||||
xy: f32,
|
||||
y_energy: f32,
|
||||
}
|
||||
|
||||
let x_energy = y_energy[MAX_PITCH_24K_HZ];
|
||||
let pitch_strength = |xy: f32, ye: f32| -> f32 {
|
||||
debug_assert!(x_energy * ye >= 0.0);
|
||||
xy / (1.0 + x_energy * ye).sqrt()
|
||||
};
|
||||
|
||||
// Initialize the best pitch candidate.
|
||||
let initial_period = (initial_pitch_period_48k_hz / 2).min(MAX_PITCH_24K_HZ as i32 - 1);
|
||||
let initial_xy = compute_auto_correlation_single(
|
||||
(MAX_PITCH_24K_HZ as i32 - initial_period) as usize,
|
||||
pitch_buffer,
|
||||
backend,
|
||||
);
|
||||
let initial_ye = y_energy[(MAX_PITCH_24K_HZ as i32 - initial_period) as usize];
|
||||
let initial_str = pitch_strength(initial_xy, initial_ye);
|
||||
|
||||
let mut best_pitch = RefinedPitchCandidate {
|
||||
period: initial_period,
|
||||
strength: initial_str,
|
||||
xy: initial_xy,
|
||||
y_energy: initial_ye,
|
||||
};
|
||||
|
||||
let initial_pitch = PitchInfo {
|
||||
period: best_pitch.period,
|
||||
strength: best_pitch.strength,
|
||||
};
|
||||
let last_pitch = PitchInfo {
|
||||
period: last_pitch_48k_hz.period / 2,
|
||||
strength: last_pitch_48k_hz.strength,
|
||||
};
|
||||
|
||||
// Find max_period_divisor.
|
||||
let max_period_divisor = (2 * initial_pitch.period) / (2 * MIN_PITCH_24K_HZ as i32 - 1);
|
||||
for period_divisor in 2..=max_period_divisor {
|
||||
let alt_period = get_alternative_pitch_period(initial_pitch.period, 1, period_divisor);
|
||||
debug_assert!(alt_period >= MIN_PITCH_24K_HZ as i32);
|
||||
|
||||
let mut dual_alt_period = get_alternative_pitch_period(
|
||||
initial_pitch.period,
|
||||
SUB_HARMONIC_MULTIPLIERS[(period_divisor - 2) as usize],
|
||||
period_divisor,
|
||||
);
|
||||
debug_assert!(dual_alt_period > 0);
|
||||
if period_divisor == 2 && dual_alt_period > MAX_PITCH_24K_HZ as i32 {
|
||||
dual_alt_period = initial_pitch.period;
|
||||
}
|
||||
debug_assert_ne!(alt_period, dual_alt_period);
|
||||
|
||||
let xy_primary = compute_auto_correlation_single(
|
||||
(MAX_PITCH_24K_HZ as i32 - alt_period) as usize,
|
||||
pitch_buffer,
|
||||
backend,
|
||||
);
|
||||
let xy_secondary = compute_auto_correlation_single(
|
||||
(MAX_PITCH_24K_HZ as i32 - dual_alt_period) as usize,
|
||||
pitch_buffer,
|
||||
backend,
|
||||
);
|
||||
let xy = 0.5 * (xy_primary + xy_secondary);
|
||||
let yy = 0.5
|
||||
* (y_energy[(MAX_PITCH_24K_HZ as i32 - alt_period) as usize]
|
||||
+ y_energy[(MAX_PITCH_24K_HZ as i32 - dual_alt_period) as usize]);
|
||||
|
||||
let alternative_pitch = PitchInfo {
|
||||
period: alt_period,
|
||||
strength: pitch_strength(xy, yy),
|
||||
};
|
||||
|
||||
if is_alternative_pitch_stronger_than_initial(
|
||||
last_pitch,
|
||||
initial_pitch,
|
||||
alternative_pitch,
|
||||
period_divisor,
|
||||
) {
|
||||
best_pitch = RefinedPitchCandidate {
|
||||
period: alternative_pitch.period,
|
||||
strength: alternative_pitch.strength,
|
||||
xy,
|
||||
y_energy: yy,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Final pitch strength and period.
|
||||
best_pitch.xy = best_pitch.xy.max(0.0);
|
||||
debug_assert!(best_pitch.y_energy >= 0.0);
|
||||
let mut final_pitch_strength = if best_pitch.y_energy <= best_pitch.xy {
|
||||
1.0
|
||||
} else {
|
||||
best_pitch.xy / (best_pitch.y_energy + 1.0)
|
||||
};
|
||||
final_pitch_strength = best_pitch.strength.min(final_pitch_strength);
|
||||
|
||||
let final_pitch_period_48k_hz = (MIN_PITCH_48K_HZ as i32).max(pitch_pseudo_interpolation_lag(
|
||||
best_pitch.period,
|
||||
pitch_buffer,
|
||||
backend,
|
||||
));
|
||||
|
||||
PitchInfo {
|
||||
period: final_pitch_period_48k_hz,
|
||||
strength: final_pitch_strength,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rnn_vad::common::BUF_SIZE_12K_HZ;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn test_resources_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/resources/rnn_vad")
|
||||
}
|
||||
|
||||
/// Loads PitchTestData from `pitch_search_int.dat`.
|
||||
struct PitchTestData {
|
||||
pitch_buffer_24k: Vec<f32>,
|
||||
square_energies_24k: Vec<f32>,
|
||||
auto_correlation_12k: Vec<f32>,
|
||||
}
|
||||
|
||||
impl PitchTestData {
|
||||
fn load() -> Self {
|
||||
let path = test_resources_dir().join("pitch_search_int.dat");
|
||||
let mut file = fs::File::open(&path)
|
||||
.unwrap_or_else(|e| panic!("Failed to open {}: {e}", path.display()));
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
let floats: Vec<f32> = bytes
|
||||
.chunks_exact(4)
|
||||
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
|
||||
.collect();
|
||||
|
||||
let mut offset = 0;
|
||||
let pitch_buffer_24k = floats[offset..offset + BUF_SIZE_24K_HZ].to_vec();
|
||||
offset += BUF_SIZE_24K_HZ;
|
||||
let mut square_energies_24k = floats[offset..offset + REFINE_NUM_LAGS_24K_HZ].to_vec();
|
||||
offset += REFINE_NUM_LAGS_24K_HZ;
|
||||
let auto_correlation_12k = floats[offset..offset + NUM_LAGS_12K_HZ].to_vec();
|
||||
// Reverse (required after WebRTC CL 191703).
|
||||
square_energies_24k.reverse();
|
||||
|
||||
Self {
|
||||
pitch_buffer_24k,
|
||||
square_energies_24k,
|
||||
auto_correlation_12k,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_near_absolute(expected: &[f32], actual: &[f32], tolerance: f32) {
|
||||
assert_eq!(expected.len(), actual.len());
|
||||
for (i, (&e, &a)) in expected.iter().zip(actual.iter()).enumerate() {
|
||||
assert!(
|
||||
(e - a).abs() <= tolerance,
|
||||
"Mismatch at index {i}: expected {e}, got {a}, diff {}",
|
||||
(e - a).abs()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_sliding_frame_square_energies_24k_hz_within_tolerance() {
|
||||
let test_data = PitchTestData::load();
|
||||
let mut computed = vec![0.0_f32; REFINE_NUM_LAGS_24K_HZ];
|
||||
let backend = sonora_simd::detect_backend();
|
||||
compute_sliding_frame_square_energies_24k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&mut computed,
|
||||
backend,
|
||||
);
|
||||
expect_near_absolute(&test_data.square_energies_24k, &computed, 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pitch_period_12k_hz_bit_exactness() {
|
||||
let test_data = PitchTestData::load();
|
||||
let mut pitch_buf_decimated = vec![0.0_f32; BUF_SIZE_12K_HZ];
|
||||
decimate_2x(&test_data.pitch_buffer_24k, &mut pitch_buf_decimated);
|
||||
let backend = sonora_simd::detect_backend();
|
||||
let candidates = compute_pitch_period_12k_hz(
|
||||
&pitch_buf_decimated,
|
||||
&test_data.auto_correlation_12k,
|
||||
backend,
|
||||
);
|
||||
assert_eq!(candidates.best, 140);
|
||||
assert_eq!(candidates.second_best, 142);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pitch_period_48k_hz_bit_exactness() {
|
||||
let test_data = PitchTestData::load();
|
||||
let mut y_energy = vec![0.0_f32; REFINE_NUM_LAGS_24K_HZ];
|
||||
let backend = sonora_simd::detect_backend();
|
||||
compute_sliding_frame_square_energies_24k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&mut y_energy,
|
||||
backend,
|
||||
);
|
||||
assert_eq!(
|
||||
compute_pitch_period_48k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&y_energy,
|
||||
CandidatePitchPeriods {
|
||||
best: 280,
|
||||
second_best: 284,
|
||||
},
|
||||
backend,
|
||||
),
|
||||
560
|
||||
);
|
||||
assert_eq!(
|
||||
compute_pitch_period_48k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&y_energy,
|
||||
CandidatePitchPeriods {
|
||||
best: 260,
|
||||
second_best: 284,
|
||||
},
|
||||
backend,
|
||||
),
|
||||
568
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pitch_period_48k_hz_order_does_not_matter() {
|
||||
let test_data = PitchTestData::load();
|
||||
let mut y_energy = vec![0.0_f32; REFINE_NUM_LAGS_24K_HZ];
|
||||
let backend = sonora_simd::detect_backend();
|
||||
compute_sliding_frame_square_energies_24k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&mut y_energy,
|
||||
backend,
|
||||
);
|
||||
|
||||
let test_cases: &[(i32, i32)] = &[
|
||||
(0, 2),
|
||||
(260, 284),
|
||||
(280, 284),
|
||||
(
|
||||
INITIAL_NUM_LAGS_24K_HZ as i32 - 2,
|
||||
INITIAL_NUM_LAGS_24K_HZ as i32 - 1,
|
||||
),
|
||||
];
|
||||
|
||||
for &(best, second_best) in test_cases {
|
||||
let result1 = compute_pitch_period_48k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&y_energy,
|
||||
CandidatePitchPeriods { best, second_best },
|
||||
backend,
|
||||
);
|
||||
let result2 = compute_pitch_period_48k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&y_energy,
|
||||
CandidatePitchPeriods {
|
||||
best: second_best,
|
||||
second_best: best,
|
||||
},
|
||||
backend,
|
||||
);
|
||||
assert_eq!(
|
||||
result1, result2,
|
||||
"Order matters for candidates ({best}, {second_best})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const TEST_PITCH_PERIODS_LOW: i32 = 3 * MIN_PITCH_48K_HZ as i32 / 2;
|
||||
const TEST_PITCH_PERIODS_HIGH: i32 =
|
||||
(3 * MIN_PITCH_48K_HZ as i32 + MAX_PITCH_48K_HZ as i32) / 2;
|
||||
const TEST_PITCH_STRENGTH_LOW: f32 = 0.35;
|
||||
const TEST_PITCH_STRENGTH_HIGH: f32 = 0.75;
|
||||
|
||||
#[test]
|
||||
fn extended_pitch_period_search() {
|
||||
let test_data = PitchTestData::load();
|
||||
let mut y_energy = vec![0.0_f32; REFINE_NUM_LAGS_24K_HZ];
|
||||
let backend = sonora_simd::detect_backend();
|
||||
compute_sliding_frame_square_energies_24k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&mut y_energy,
|
||||
backend,
|
||||
);
|
||||
|
||||
for &last_pitch_period in &[TEST_PITCH_PERIODS_LOW, TEST_PITCH_PERIODS_HIGH] {
|
||||
for &last_pitch_strength in &[TEST_PITCH_STRENGTH_LOW, TEST_PITCH_STRENGTH_HIGH] {
|
||||
let last_pitch = PitchInfo {
|
||||
period: last_pitch_period,
|
||||
strength: last_pitch_strength,
|
||||
};
|
||||
|
||||
// Test with low initial pitch period.
|
||||
let result = compute_extended_pitch_period_48k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&y_energy,
|
||||
TEST_PITCH_PERIODS_LOW,
|
||||
last_pitch,
|
||||
backend,
|
||||
);
|
||||
assert_eq!(result.period, 91);
|
||||
assert!(
|
||||
(result.strength - (-0.0188608_f32)).abs() < 1e-6,
|
||||
"Strength mismatch: expected -0.0188608, got {}",
|
||||
result.strength
|
||||
);
|
||||
|
||||
// Test with high initial pitch period.
|
||||
let result = compute_extended_pitch_period_48k_hz(
|
||||
&test_data.pitch_buffer_24k,
|
||||
&y_energy,
|
||||
TEST_PITCH_PERIODS_HIGH,
|
||||
last_pitch,
|
||||
backend,
|
||||
);
|
||||
assert_eq!(result.period, 475);
|
||||
assert!(
|
||||
(result.strength - (-0.0904344_f32)).abs() < 1e-6,
|
||||
"Strength mismatch: expected -0.0904344, got {}",
|
||||
result.strength
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
//! Fixed-size ring buffer for arrays.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/ring_buffer.h`.
|
||||
|
||||
/// Ring buffer for `N` arrays each with size `S`.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RingBuffer<const S: usize, const N: usize> {
|
||||
tail: usize,
|
||||
buffer: Vec<f32>,
|
||||
}
|
||||
|
||||
impl<const S: usize, const N: usize> Default for RingBuffer<S, N> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tail: 0,
|
||||
buffer: vec![0.0; S * N],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize, const N: usize> RingBuffer<S, N> {
|
||||
/// Set all buffer values to zero.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.buffer.fill(0.0);
|
||||
}
|
||||
|
||||
/// Replace the least recently pushed array with `new_values`.
|
||||
pub(crate) fn push(&mut self, new_values: &[f32; S]) {
|
||||
let start = S * self.tail;
|
||||
self.buffer[start..start + S].copy_from_slice(new_values);
|
||||
self.tail += 1;
|
||||
if self.tail == N {
|
||||
self.tail = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a reference to the array with the given delay.
|
||||
///
|
||||
/// Delay 0 returns the most recently pushed array.
|
||||
/// Delay N-1 returns the least recently pushed array.
|
||||
pub(crate) fn get_array_view(&self, delay: usize) -> &[f32; S] {
|
||||
debug_assert!(delay < N);
|
||||
let mut offset = self.tail as isize - 1 - delay as isize;
|
||||
if offset < 0 {
|
||||
offset += N as isize;
|
||||
}
|
||||
let start = S * offset as usize;
|
||||
self.buffer[start..start + S].try_into().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ring_buffer_basic() {
|
||||
let mut ring_buf = RingBuffer::<2, 3>::default();
|
||||
|
||||
// Push [1, 1]
|
||||
ring_buf.push(&[1.0, 1.0]);
|
||||
assert_eq!(ring_buf.get_array_view(0), &[1.0, 1.0]);
|
||||
|
||||
// Push [2, 2]
|
||||
ring_buf.push(&[2.0, 2.0]);
|
||||
assert_eq!(ring_buf.get_array_view(0), &[2.0, 2.0]);
|
||||
assert_eq!(ring_buf.get_array_view(1), &[1.0, 1.0]);
|
||||
|
||||
// Push [3, 3]
|
||||
ring_buf.push(&[3.0, 3.0]);
|
||||
assert_eq!(ring_buf.get_array_view(0), &[3.0, 3.0]);
|
||||
assert_eq!(ring_buf.get_array_view(1), &[2.0, 2.0]);
|
||||
assert_eq!(ring_buf.get_array_view(2), &[1.0, 1.0]);
|
||||
|
||||
// Push [4, 4] — wraps around, overwrites [1, 1]
|
||||
ring_buf.push(&[4.0, 4.0]);
|
||||
assert_eq!(ring_buf.get_array_view(0), &[4.0, 4.0]);
|
||||
assert_eq!(ring_buf.get_array_view(1), &[3.0, 3.0]);
|
||||
assert_eq!(ring_buf.get_array_view(2), &[2.0, 2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_buffer_array_views_differ() {
|
||||
let mut ring_buf = RingBuffer::<3, 4>::default();
|
||||
let pushed = [1.0; 3];
|
||||
for _ in 0..=4 {
|
||||
for i in 0..4 {
|
||||
let view_i = ring_buf.get_array_view(i);
|
||||
for j in (i + 1)..4 {
|
||||
let view_j = ring_buf.get_array_view(j);
|
||||
assert_ne!(view_i as *const _ as usize, view_j as *const _ as usize);
|
||||
}
|
||||
}
|
||||
ring_buf.push(&pushed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_buffer_single_element() {
|
||||
let mut ring_buf = RingBuffer::<1, 1>::default();
|
||||
ring_buf.push(&[42.0]);
|
||||
assert_eq!(ring_buf.get_array_view(0), &[42.0]);
|
||||
ring_buf.push(&[99.0]);
|
||||
assert_eq!(ring_buf.get_array_view(0), &[99.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_buffer_full_cycle() {
|
||||
let mut ring_buf = RingBuffer::<5, 5>::default();
|
||||
for v in 0..5u32 {
|
||||
ring_buf.push(&[v as f32; 5]);
|
||||
}
|
||||
for delay in 0..5 {
|
||||
assert_eq!(ring_buf.get_array_view(delay), &[(4 - delay) as f32; 5]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_buffer_reset() {
|
||||
let mut ring_buf = RingBuffer::<3, 2>::default();
|
||||
ring_buf.push(&[1.0, 2.0, 3.0]);
|
||||
ring_buf.reset();
|
||||
assert_eq!(ring_buf.get_array_view(0), &[0.0, 0.0, 0.0]);
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
//! RNN model for voice activity detection.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/rnn.cc`.
|
||||
|
||||
use super::common::FeatureVector;
|
||||
use super::fc_layer::{ActivationFunction, FullyConnectedLayer};
|
||||
use super::gru_layer::GatedRecurrentLayer;
|
||||
use super::vector_math::VectorMath;
|
||||
use super::weights::{
|
||||
HIDDEN_GRU_BIAS, HIDDEN_GRU_RECURRENT_WEIGHTS, HIDDEN_GRU_WEIGHTS, HIDDEN_LAYER_OUTPUT_SIZE,
|
||||
INPUT_DENSE_BIAS, INPUT_DENSE_WEIGHTS, INPUT_LAYER_INPUT_SIZE, INPUT_LAYER_OUTPUT_SIZE,
|
||||
OUTPUT_DENSE_BIAS, OUTPUT_DENSE_WEIGHTS, OUTPUT_LAYER_OUTPUT_SIZE,
|
||||
};
|
||||
use sonora_simd::SimdBackend;
|
||||
|
||||
/// Recurrent network with hard-coded architecture and weights for VAD.
|
||||
///
|
||||
/// Architecture: FC(42→24, tanh) → GRU(24→24) → FC(24→1, sigmoid)
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RnnVad {
|
||||
input: FullyConnectedLayer,
|
||||
hidden: GatedRecurrentLayer,
|
||||
output: FullyConnectedLayer,
|
||||
}
|
||||
|
||||
impl RnnVad {
|
||||
/// Creates a new RNN VAD model.
|
||||
pub(crate) fn new(backend: SimdBackend) -> Self {
|
||||
let vector_math = VectorMath::new(backend);
|
||||
let input = FullyConnectedLayer::new(
|
||||
INPUT_LAYER_INPUT_SIZE,
|
||||
INPUT_LAYER_OUTPUT_SIZE,
|
||||
&INPUT_DENSE_BIAS,
|
||||
&INPUT_DENSE_WEIGHTS,
|
||||
ActivationFunction::TansigApproximated,
|
||||
vector_math,
|
||||
);
|
||||
let hidden = GatedRecurrentLayer::new(
|
||||
INPUT_LAYER_OUTPUT_SIZE,
|
||||
HIDDEN_LAYER_OUTPUT_SIZE,
|
||||
&HIDDEN_GRU_BIAS,
|
||||
&HIDDEN_GRU_WEIGHTS,
|
||||
&HIDDEN_GRU_RECURRENT_WEIGHTS,
|
||||
vector_math,
|
||||
);
|
||||
// The output layer is just 24x1. The unoptimized code is faster.
|
||||
let scalar_math = VectorMath::new(SimdBackend::Scalar);
|
||||
let output = FullyConnectedLayer::new(
|
||||
HIDDEN_LAYER_OUTPUT_SIZE,
|
||||
OUTPUT_LAYER_OUTPUT_SIZE,
|
||||
&OUTPUT_DENSE_BIAS,
|
||||
&OUTPUT_DENSE_WEIGHTS,
|
||||
ActivationFunction::SigmoidApproximated,
|
||||
scalar_math,
|
||||
);
|
||||
debug_assert_eq!(input.size(), hidden.input_size());
|
||||
debug_assert_eq!(hidden.size(), output.input_size());
|
||||
Self {
|
||||
input,
|
||||
hidden,
|
||||
output,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the hidden state.
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.hidden.reset();
|
||||
}
|
||||
|
||||
/// Observes `feature_vector` and `is_silence`, updates the RNN and returns
|
||||
/// the current voice probability.
|
||||
pub(crate) fn compute_vad_probability(
|
||||
&mut self,
|
||||
feature_vector: &FeatureVector,
|
||||
is_silence: bool,
|
||||
) -> f32 {
|
||||
if is_silence {
|
||||
self.reset();
|
||||
return 0.0;
|
||||
}
|
||||
self.input.compute_output(feature_vector.as_slice());
|
||||
self.hidden.compute_output(self.input.output());
|
||||
self.output.compute_output(self.hidden.output());
|
||||
debug_assert_eq!(self.output.size(), 1);
|
||||
self.output.output()[0]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FEATURES: FeatureVector = FeatureVector {
|
||||
average: [-1.00131, -0.627069, -7.81097, 7.86285, -2.87145, 3.32365],
|
||||
higher_bands_cepstrum: [
|
||||
-0.653161, 0.529839, -0.425307, 0.25583, 0.235094, 0.230527, -0.144687, 0.182785,
|
||||
0.57102, 0.125039, 0.479482, -0.0255439, -0.0073141, -0.147346, -0.217106, -0.0846906,
|
||||
],
|
||||
first_derivative: [-8.34943, 3.09065, 1.42628, -0.85235, -0.220207, -0.811163],
|
||||
second_derivative: [2.09032, -2.01425, -0.690268, -0.925327, -0.541354, 0.58455],
|
||||
bands_cross_correlation: [
|
||||
-0.606726, -0.0372358, 0.565991, 0.435854, 0.420812, 0.162198,
|
||||
],
|
||||
pitch_period: -2.13,
|
||||
spectral_variability: 10.0089,
|
||||
};
|
||||
|
||||
fn warm_up_rnn_vad(rnn_vad: &mut RnnVad) {
|
||||
for _ in 0..10 {
|
||||
rnn_vad.compute_vad_probability(&FEATURES, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_zero_probability_with_silence() {
|
||||
let backend = sonora_simd::detect_backend();
|
||||
let mut rnn_vad = RnnVad::new(backend);
|
||||
warm_up_rnn_vad(&mut rnn_vad);
|
||||
assert_eq!(rnn_vad.compute_vad_probability(&FEATURES, true), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_rnn_vad_reset() {
|
||||
let backend = sonora_simd::detect_backend();
|
||||
let mut rnn_vad = RnnVad::new(backend);
|
||||
warm_up_rnn_vad(&mut rnn_vad);
|
||||
let pre = rnn_vad.compute_vad_probability(&FEATURES, false);
|
||||
rnn_vad.reset();
|
||||
warm_up_rnn_vad(&mut rnn_vad);
|
||||
let post = rnn_vad.compute_vad_probability(&FEATURES, false);
|
||||
assert_eq!(pre, post);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_rnn_vad_silence() {
|
||||
let backend = sonora_simd::detect_backend();
|
||||
let mut rnn_vad = RnnVad::new(backend);
|
||||
warm_up_rnn_vad(&mut rnn_vad);
|
||||
let pre = rnn_vad.compute_vad_probability(&FEATURES, false);
|
||||
rnn_vad.compute_vad_probability(&FEATURES, true);
|
||||
warm_up_rnn_vad(&mut rnn_vad);
|
||||
let post = rnn_vad.compute_vad_probability(&FEATURES, false);
|
||||
assert_eq!(pre, post);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Linear sequence buffer with push semantics.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/sequence_buffer.h`.
|
||||
|
||||
/// Linear buffer to push fixed-size chunks of sequential data and view
|
||||
/// contiguous parts of the buffer.
|
||||
///
|
||||
/// The buffer has size `S` and pushed chunks have size `N`. When pushed,
|
||||
/// the buffer shifts left by `N` and the new chunk fills the rightmost
|
||||
/// `N` positions. For instance, when `S = 2*N` the first half is replaced
|
||||
/// with the second half, and new values are written at the end.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SequenceBuffer<const S: usize, const N: usize> {
|
||||
buffer: Vec<f32>,
|
||||
}
|
||||
|
||||
impl<const S: usize, const N: usize> Default for SequenceBuffer<S, N> {
|
||||
fn default() -> Self {
|
||||
const { assert!(N <= S, "Chunk size cannot be larger than buffer size") };
|
||||
Self {
|
||||
buffer: vec![0.0; S],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize, const N: usize> SequenceBuffer<S, N> {
|
||||
/// Returns the buffer size.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn size(&self) -> usize {
|
||||
S
|
||||
}
|
||||
|
||||
/// Returns the chunk size.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn chunks_size(&self) -> usize {
|
||||
N
|
||||
}
|
||||
|
||||
/// Sets all buffer values to zero.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.buffer.fill(0.0);
|
||||
}
|
||||
|
||||
/// Returns a view on the whole buffer.
|
||||
pub(crate) fn get_buffer_view(&self) -> &[f32] {
|
||||
&self.buffer
|
||||
}
|
||||
|
||||
/// Returns a view on the `M` most recent values of the buffer.
|
||||
pub(crate) fn get_most_recent_values_view<const M: usize>(&self) -> &[f32; M] {
|
||||
const { assert!(M <= S, "Most recent values cannot exceed buffer size") };
|
||||
self.buffer[S - M..].try_into().unwrap()
|
||||
}
|
||||
|
||||
/// Shifts the buffer left by `N` items and adds new `N` items at the end.
|
||||
pub(crate) fn push(&mut self, new_values: &[f32; N]) {
|
||||
if S > N {
|
||||
self.buffer.copy_within(N.., 0);
|
||||
}
|
||||
self.buffer[S - N..].copy_from_slice(new_values);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_push_op<const S: usize, const N: usize>() {
|
||||
let mut seq_buf = SequenceBuffer::<S, N>::default();
|
||||
let _buf_view_ptr = seq_buf.buffer.as_ptr();
|
||||
|
||||
// Check that a chunk is fully gone after ceil(S / N) push ops.
|
||||
let ones = [1.0_f32; N];
|
||||
seq_buf.push(&ones);
|
||||
let zeros = [0.0_f32; N];
|
||||
let required_push_ops = if !S.is_multiple_of(N) {
|
||||
S / N + 1
|
||||
} else {
|
||||
S / N
|
||||
};
|
||||
for _ in 0..required_push_ops - 1 {
|
||||
seq_buf.push(&zeros);
|
||||
let max = seq_buf
|
||||
.buffer
|
||||
.iter()
|
||||
.cloned()
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
assert_eq!(max, 1.0, "Value should still be in buffer");
|
||||
}
|
||||
// Gone after another push.
|
||||
seq_buf.push(&zeros);
|
||||
let max = seq_buf
|
||||
.buffer
|
||||
.iter()
|
||||
.cloned()
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
assert_eq!(max, 0.0, "Value should be gone");
|
||||
|
||||
// Check that the last item moves left by N positions after a push.
|
||||
if S > N {
|
||||
let mut chunk = [0.0_f32; N];
|
||||
for (i, val) in chunk.iter_mut().enumerate() {
|
||||
*val = (i + 1) as f32;
|
||||
}
|
||||
seq_buf.push(&chunk);
|
||||
let last = chunk[N - 1];
|
||||
let mut chunk2 = [0.0_f32; N];
|
||||
for (i, val) in chunk2.iter_mut().enumerate() {
|
||||
*val = last + (i + 1) as f32;
|
||||
}
|
||||
seq_buf.push(&chunk2);
|
||||
assert_eq!(seq_buf.buffer[S - N - 1], last);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_buffer_getters() {
|
||||
let mut seq_buf = SequenceBuffer::<8, 8>::default();
|
||||
assert_eq!(seq_buf.size(), 8);
|
||||
assert_eq!(seq_buf.chunks_size(), 8);
|
||||
|
||||
let view = seq_buf.get_buffer_view();
|
||||
assert_eq!(view[0], 0.0);
|
||||
assert_eq!(view[view.len() - 1], 0.0);
|
||||
|
||||
let chunk: [f32; 8] = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0];
|
||||
seq_buf.push(&chunk);
|
||||
let view = seq_buf.get_buffer_view();
|
||||
assert_eq!(view[0], 10.0);
|
||||
assert_eq!(view[view.len() - 1], 80.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_buffer_push_25_percent() {
|
||||
test_push_op::<32, 8>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_buffer_push_50_percent() {
|
||||
test_push_op::<32, 16>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_buffer_push_100_percent() {
|
||||
test_push_op::<32, 32>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_buffer_push_non_integer_ratio() {
|
||||
test_push_op::<23, 7>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_buffer_most_recent() {
|
||||
let mut seq_buf = SequenceBuffer::<8, 4>::default();
|
||||
seq_buf.push(&[1.0, 2.0, 3.0, 4.0]);
|
||||
let recent: &[f32; 4] = seq_buf.get_most_recent_values_view::<4>();
|
||||
assert_eq!(recent, &[1.0, 2.0, 3.0, 4.0]);
|
||||
|
||||
seq_buf.push(&[5.0, 6.0, 7.0, 8.0]);
|
||||
let recent: &[f32; 4] = seq_buf.get_most_recent_values_view::<4>();
|
||||
assert_eq!(recent, &[5.0, 6.0, 7.0, 8.0]);
|
||||
|
||||
let all: &[f32; 8] = seq_buf.get_most_recent_values_view::<8>();
|
||||
assert_eq!(all, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! Spectral feature extraction for the RNN VAD.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/spectral_features.cc`.
|
||||
|
||||
use super::common::{
|
||||
CEPSTRAL_COEFFS_HISTORY_SIZE, FRAME_SIZE_20MS_24K_HZ, NUM_BANDS, NUM_HIGHER_BANDS,
|
||||
NUM_LOWER_BANDS,
|
||||
};
|
||||
use super::ring_buffer::RingBuffer;
|
||||
use super::spectral_features_internal::{
|
||||
OPUS_BANDS_24K_HZ, SpectralCorrelator, compute_dct, compute_dct_table,
|
||||
compute_smoothed_log_magnitude_spectrum,
|
||||
};
|
||||
use super::symmetric_matrix_buffer::SymmetricMatrixBuffer;
|
||||
use sonora_fft::pffft::{FftType, Pffft, PffftBuffer};
|
||||
use std::f32::consts::FRAC_PI_2;
|
||||
|
||||
const SILENCE_THRESHOLD: f32 = 0.04;
|
||||
|
||||
/// Output of spectral feature extraction for a non-silent frame.
|
||||
pub(crate) struct SpectralFeaturesOutput {
|
||||
pub higher_bands_cepstrum: [f32; NUM_HIGHER_BANDS],
|
||||
pub average: [f32; NUM_LOWER_BANDS],
|
||||
pub first_derivative: [f32; NUM_LOWER_BANDS],
|
||||
pub second_derivative: [f32; NUM_LOWER_BANDS],
|
||||
pub bands_cross_correlation: [f32; NUM_LOWER_BANDS],
|
||||
pub variability: f32,
|
||||
}
|
||||
|
||||
/// Spectral feature extractor for 20 ms frames at 24 kHz.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SpectralFeaturesExtractor {
|
||||
half_window: Vec<f32>,
|
||||
fft: Pffft,
|
||||
fft_buffer: PffftBuffer,
|
||||
reference_frame_fft: PffftBuffer,
|
||||
lagged_frame_fft: PffftBuffer,
|
||||
spectral_correlator: SpectralCorrelator,
|
||||
reference_frame_bands_energy: [f32; OPUS_BANDS_24K_HZ],
|
||||
lagged_frame_bands_energy: [f32; OPUS_BANDS_24K_HZ],
|
||||
bands_cross_corr: [f32; OPUS_BANDS_24K_HZ],
|
||||
dct_table: [f32; NUM_BANDS * NUM_BANDS],
|
||||
cepstral_coeffs_ring_buf: RingBuffer<NUM_BANDS, CEPSTRAL_COEFFS_HISTORY_SIZE>,
|
||||
cepstral_diffs_buf: SymmetricMatrixBuffer<CEPSTRAL_COEFFS_HISTORY_SIZE>,
|
||||
}
|
||||
|
||||
impl Default for SpectralFeaturesExtractor {
|
||||
fn default() -> Self {
|
||||
let scaling = 1.0 / FRAME_SIZE_20MS_24K_HZ as f32;
|
||||
let half_window = compute_scaled_half_vorbis_window(scaling);
|
||||
let fft = Pffft::new(FRAME_SIZE_20MS_24K_HZ, FftType::Real);
|
||||
let fft_buffer = fft.create_buffer();
|
||||
let reference_frame_fft = fft.create_buffer();
|
||||
let lagged_frame_fft = fft.create_buffer();
|
||||
|
||||
Self {
|
||||
half_window,
|
||||
fft,
|
||||
fft_buffer,
|
||||
reference_frame_fft,
|
||||
lagged_frame_fft,
|
||||
spectral_correlator: SpectralCorrelator::default(),
|
||||
reference_frame_bands_energy: [0.0; OPUS_BANDS_24K_HZ],
|
||||
lagged_frame_bands_energy: [0.0; OPUS_BANDS_24K_HZ],
|
||||
bands_cross_corr: [0.0; OPUS_BANDS_24K_HZ],
|
||||
dct_table: compute_dct_table(),
|
||||
cepstral_coeffs_ring_buf: RingBuffer::default(),
|
||||
cepstral_diffs_buf: SymmetricMatrixBuffer::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SpectralFeaturesExtractor {
|
||||
/// Resets internal state.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.cepstral_coeffs_ring_buf.reset();
|
||||
self.cepstral_diffs_buf.reset();
|
||||
}
|
||||
|
||||
/// Analyzes a pair of reference and lagged frames, detects silence and
|
||||
/// computes features.
|
||||
///
|
||||
/// Returns `None` if silence is detected, otherwise returns the computed
|
||||
/// spectral features.
|
||||
pub(crate) fn check_silence_compute_features(
|
||||
&mut self,
|
||||
reference_frame: &[f32],
|
||||
lagged_frame: &[f32],
|
||||
) -> Option<SpectralFeaturesOutput> {
|
||||
debug_assert_eq!(reference_frame.len(), FRAME_SIZE_20MS_24K_HZ);
|
||||
debug_assert_eq!(lagged_frame.len(), FRAME_SIZE_20MS_24K_HZ);
|
||||
|
||||
// Compute the Opus band energies for the reference frame.
|
||||
self.compute_windowed_forward_fft(reference_frame, true);
|
||||
self.spectral_correlator.compute_auto_correlation(
|
||||
self.reference_frame_fft.as_slice(),
|
||||
&mut self.reference_frame_bands_energy,
|
||||
);
|
||||
|
||||
// Check if the reference frame has silence.
|
||||
let tot_energy: f32 = self.reference_frame_bands_energy.iter().sum();
|
||||
if tot_energy < SILENCE_THRESHOLD {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Compute the Opus band energies for the lagged frame.
|
||||
self.compute_windowed_forward_fft(lagged_frame, false);
|
||||
self.spectral_correlator.compute_auto_correlation(
|
||||
self.lagged_frame_fft.as_slice(),
|
||||
&mut self.lagged_frame_bands_energy,
|
||||
);
|
||||
|
||||
// Log of the band energies for the reference frame.
|
||||
let mut log_bands_energy = [0.0_f32; NUM_BANDS];
|
||||
compute_smoothed_log_magnitude_spectrum(
|
||||
&self.reference_frame_bands_energy,
|
||||
&mut log_bands_energy,
|
||||
);
|
||||
|
||||
// Reference frame cepstrum.
|
||||
let mut cepstrum = [0.0_f32; NUM_BANDS];
|
||||
compute_dct(&log_bands_energy, &self.dct_table, &mut cepstrum);
|
||||
// Ad-hoc correction terms for the first two cepstral coefficients.
|
||||
cepstrum[0] -= 12.0;
|
||||
cepstrum[1] -= 4.0;
|
||||
|
||||
// Update the ring buffer and the cepstral difference stats.
|
||||
self.cepstral_coeffs_ring_buf.push(&cepstrum);
|
||||
self.update_cepstral_difference_stats(&cepstrum);
|
||||
|
||||
// Compute remaining features.
|
||||
let mut average = [0.0_f32; NUM_LOWER_BANDS];
|
||||
let mut first_derivative = [0.0_f32; NUM_LOWER_BANDS];
|
||||
let mut second_derivative = [0.0_f32; NUM_LOWER_BANDS];
|
||||
self.compute_avg_and_derivatives(
|
||||
&mut average,
|
||||
&mut first_derivative,
|
||||
&mut second_derivative,
|
||||
);
|
||||
|
||||
let mut bands_cross_correlation = [0.0_f32; NUM_LOWER_BANDS];
|
||||
self.compute_normalized_cepstral_correlation(&mut bands_cross_correlation);
|
||||
|
||||
let mut higher_bands_cepstrum = [0.0_f32; NUM_HIGHER_BANDS];
|
||||
higher_bands_cepstrum.copy_from_slice(&cepstrum[NUM_LOWER_BANDS..]);
|
||||
|
||||
Some(SpectralFeaturesOutput {
|
||||
higher_bands_cepstrum,
|
||||
average,
|
||||
first_derivative,
|
||||
second_derivative,
|
||||
bands_cross_correlation,
|
||||
variability: self.compute_variability(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies windowing and computes forward FFT.
|
||||
fn compute_windowed_forward_fft(&mut self, frame: &[f32], is_reference: bool) {
|
||||
debug_assert_eq!(frame.len(), FRAME_SIZE_20MS_24K_HZ);
|
||||
let half_size = FRAME_SIZE_20MS_24K_HZ / 2;
|
||||
|
||||
let buf = self.fft_buffer.as_mut_slice();
|
||||
for i in 0..half_size {
|
||||
let j = FRAME_SIZE_20MS_24K_HZ - 1 - i;
|
||||
buf[i] = frame[i] * self.half_window[i];
|
||||
buf[j] = frame[j] * self.half_window[i];
|
||||
}
|
||||
|
||||
let output = if is_reference {
|
||||
&mut self.reference_frame_fft
|
||||
} else {
|
||||
&mut self.lagged_frame_fft
|
||||
};
|
||||
self.fft.forward(&self.fft_buffer, output, true);
|
||||
// Set the Nyquist frequency coefficient to zero.
|
||||
output.as_mut_slice()[1] = 0.0;
|
||||
}
|
||||
|
||||
/// Computes average and first/second derivatives of cepstral coefficients.
|
||||
fn compute_avg_and_derivatives(
|
||||
&self,
|
||||
average: &mut [f32],
|
||||
first_derivative: &mut [f32],
|
||||
second_derivative: &mut [f32],
|
||||
) {
|
||||
let curr = self.cepstral_coeffs_ring_buf.get_array_view(0);
|
||||
let prev1 = self.cepstral_coeffs_ring_buf.get_array_view(1);
|
||||
let prev2 = self.cepstral_coeffs_ring_buf.get_array_view(2);
|
||||
|
||||
for i in 0..NUM_LOWER_BANDS {
|
||||
// Average, kernel: [1, 1, 1].
|
||||
average[i] = curr[i] + prev1[i] + prev2[i];
|
||||
// First derivative, kernel: [1, 0, -1].
|
||||
first_derivative[i] = curr[i] - prev2[i];
|
||||
// Second derivative, Laplacian kernel: [1, -2, 1].
|
||||
second_derivative[i] = curr[i] - 2.0 * prev1[i] + prev2[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes normalized cepstral correlation between reference and lagged frames.
|
||||
fn compute_normalized_cepstral_correlation(&mut self, bands_cross_corr_out: &mut [f32]) {
|
||||
self.spectral_correlator.compute_cross_correlation(
|
||||
self.reference_frame_fft.as_slice(),
|
||||
self.lagged_frame_fft.as_slice(),
|
||||
&mut self.bands_cross_corr,
|
||||
);
|
||||
|
||||
// Normalize.
|
||||
for i in 0..OPUS_BANDS_24K_HZ {
|
||||
self.bands_cross_corr[i] /= (0.001
|
||||
+ self.reference_frame_bands_energy[i] * self.lagged_frame_bands_energy[i])
|
||||
.sqrt();
|
||||
}
|
||||
|
||||
// Cepstrum.
|
||||
compute_dct(
|
||||
&self.bands_cross_corr,
|
||||
&self.dct_table,
|
||||
bands_cross_corr_out,
|
||||
);
|
||||
// Ad-hoc correction terms for the first two cepstral coefficients.
|
||||
bands_cross_corr_out[0] -= 1.3;
|
||||
bands_cross_corr_out[1] -= 0.9;
|
||||
}
|
||||
|
||||
/// Computes cepstral variability score.
|
||||
fn compute_variability(&self) -> f32 {
|
||||
let mut variability = 0.0_f32;
|
||||
for delay1 in 0..CEPSTRAL_COEFFS_HISTORY_SIZE {
|
||||
let mut min_dist = f32::MAX;
|
||||
for delay2 in 0..CEPSTRAL_COEFFS_HISTORY_SIZE {
|
||||
if delay1 == delay2 {
|
||||
continue;
|
||||
}
|
||||
min_dist = min_dist.min(self.cepstral_diffs_buf.get_value(delay1, delay2));
|
||||
}
|
||||
variability += min_dist;
|
||||
}
|
||||
// Normalize (based on training set stats).
|
||||
variability / CEPSTRAL_COEFFS_HISTORY_SIZE as f32 - 2.1
|
||||
}
|
||||
|
||||
/// Updates cepstral difference stats in the symmetric matrix buffer.
|
||||
fn update_cepstral_difference_stats(&mut self, new_cepstral_coeffs: &[f32; NUM_BANDS]) {
|
||||
let mut distances = [0.0_f32; CEPSTRAL_COEFFS_HISTORY_SIZE - 1];
|
||||
for (i, dist) in distances.iter_mut().enumerate() {
|
||||
let delay = i + 1;
|
||||
let old_coeffs = self.cepstral_coeffs_ring_buf.get_array_view(delay);
|
||||
*dist = 0.0;
|
||||
for k in 0..NUM_BANDS {
|
||||
let c = new_cepstral_coeffs[k] - old_coeffs[k];
|
||||
*dist += c * c;
|
||||
}
|
||||
}
|
||||
self.cepstral_diffs_buf.push(&distances);
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the first half of the Vorbis window with scaling.
|
||||
fn compute_scaled_half_vorbis_window(scaling: f32) -> Vec<f32> {
|
||||
let half_size = FRAME_SIZE_20MS_24K_HZ / 2;
|
||||
let mut half_window = vec![0.0_f32; half_size];
|
||||
for (i, w) in half_window.iter_mut().enumerate() {
|
||||
let sin_arg = FRAC_PI_2 * (i as f32 + 0.5) / half_size as f32;
|
||||
*w = scaling * (FRAC_PI_2 * sin_arg.sin() * sin_arg.sin()).sin();
|
||||
}
|
||||
half_window
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn silence_detection_on_zero_frame() {
|
||||
let mut extractor = SpectralFeaturesExtractor::default();
|
||||
let frame = [0.0_f32; FRAME_SIZE_20MS_24K_HZ];
|
||||
|
||||
let result = extractor.check_silence_compute_features(&frame, &frame);
|
||||
assert!(result.is_none(), "Zero frame should be detected as silence");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_silence_frame_produces_features() {
|
||||
use std::f32::consts::TAU;
|
||||
let mut extractor = SpectralFeaturesExtractor::default();
|
||||
// Create a non-trivial frame with enough energy.
|
||||
let mut frame = [0.0_f32; FRAME_SIZE_20MS_24K_HZ];
|
||||
for (i, s) in frame.iter_mut().enumerate() {
|
||||
*s = (TAU * 440.0 * i as f32 / 24000.0).sin();
|
||||
}
|
||||
|
||||
// Feed multiple frames to fill the cepstral history.
|
||||
let mut last_output = None;
|
||||
for _ in 0..CEPSTRAL_COEFFS_HISTORY_SIZE + 1 {
|
||||
let result = extractor.check_silence_compute_features(&frame, &frame);
|
||||
assert!(result.is_some(), "Non-zero frame should not be silence");
|
||||
last_output = result;
|
||||
}
|
||||
|
||||
// After enough frames, features should have finite values.
|
||||
let features = last_output.unwrap();
|
||||
assert!(features.average.iter().all(|v| v.is_finite()));
|
||||
assert!(features.first_derivative.iter().all(|v| v.is_finite()));
|
||||
assert!(features.second_derivative.iter().all(|v| v.is_finite()));
|
||||
assert!(
|
||||
features
|
||||
.bands_cross_correlation
|
||||
.iter()
|
||||
.all(|v| v.is_finite())
|
||||
);
|
||||
assert!(features.variability.is_finite());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_input_zero_derivative() {
|
||||
let mut extractor = SpectralFeaturesExtractor::default();
|
||||
// Create a constant non-zero frame (amplitude must exceed silence threshold).
|
||||
let frame = [1.0_f32; FRAME_SIZE_20MS_24K_HZ];
|
||||
|
||||
// Feed the same frame multiple times.
|
||||
let mut last_output = None;
|
||||
for _ in 0..CEPSTRAL_COEFFS_HISTORY_SIZE + 1 {
|
||||
let result = extractor.check_silence_compute_features(&frame, &frame);
|
||||
if result.is_some() {
|
||||
last_output = result;
|
||||
}
|
||||
}
|
||||
|
||||
// With constant input, derivatives should be zero.
|
||||
let features = last_output.expect("expected non-silent output");
|
||||
for (i, &deriv) in features.first_derivative.iter().enumerate() {
|
||||
assert!(
|
||||
deriv.abs() < 1e-5,
|
||||
"first_derivative[{i}] = {deriv}, expected ~0"
|
||||
);
|
||||
}
|
||||
for (i, &deriv) in features.second_derivative.iter().enumerate() {
|
||||
assert!(
|
||||
deriv.abs() < 1e-5,
|
||||
"second_derivative[{i}] = {deriv}, expected ~0"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Internal helpers for spectral feature computation.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/spectral_features_internal.cc`.
|
||||
|
||||
use super::common::{FRAME_SIZE_20MS_24K_HZ, NUM_BANDS};
|
||||
use std::f64::consts::PI;
|
||||
use std::ptr;
|
||||
|
||||
/// Number of Opus bands at 24 kHz (last 3 Opus bands are beyond Nyquist,
|
||||
/// but band #19 gets contributions from band #18 due to the symmetric
|
||||
/// triangular filter with peak response at 12 kHz).
|
||||
pub(crate) const OPUS_BANDS_24K_HZ: usize = 20;
|
||||
|
||||
/// Number of FFT frequency bins covered by each band in the Opus scale at
|
||||
/// 24 kHz for 20 ms frames.
|
||||
pub(crate) const OPUS_SCALE_NUM_BINS_24K_HZ_20MS: [usize; OPUS_BANDS_24K_HZ - 1] = [
|
||||
4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 16, 16, 16, 24, 24, 32, 48,
|
||||
];
|
||||
|
||||
/// Weights for each FFT coefficient for each Opus band (Nyquist excluded).
|
||||
const OPUS_BAND_WEIGHTS_24K_HZ_20MS: [f32; FRAME_SIZE_20MS_24K_HZ / 2] = [
|
||||
// Band 0
|
||||
0.0, 0.25, 0.5, 0.75, // Band 1
|
||||
0.0, 0.25, 0.5, 0.75, // Band 2
|
||||
0.0, 0.25, 0.5, 0.75, // Band 3
|
||||
0.0, 0.25, 0.5, 0.75, // Band 4
|
||||
0.0, 0.25, 0.5, 0.75, // Band 5
|
||||
0.0, 0.25, 0.5, 0.75, // Band 6
|
||||
0.0, 0.25, 0.5, 0.75, // Band 7
|
||||
0.0, 0.25, 0.5, 0.75, // Band 8
|
||||
0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, // Band 9
|
||||
0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, // Band 10
|
||||
0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, // Band 11
|
||||
0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, // Band 12
|
||||
0.0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625, 0.6875, 0.75,
|
||||
0.8125, 0.875, 0.9375, // Band 13
|
||||
0.0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625, 0.6875, 0.75,
|
||||
0.8125, 0.875, 0.9375, // Band 14
|
||||
0.0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625, 0.6875, 0.75,
|
||||
0.8125, 0.875, 0.9375, // Band 15
|
||||
0.0, 0.0416667, 0.0833333, 0.125, 0.166667, 0.208333, 0.25, 0.291667, 0.333333, 0.375,
|
||||
0.416667, 0.458333, 0.5, 0.541667, 0.583333, 0.625, 0.666667, 0.708333, 0.75, 0.791667,
|
||||
0.833333, 0.875, 0.916667, 0.958333, // Band 16
|
||||
0.0, 0.0416667, 0.0833333, 0.125, 0.166667, 0.208333, 0.25, 0.291667, 0.333333, 0.375,
|
||||
0.416667, 0.458333, 0.5, 0.541667, 0.583333, 0.625, 0.666667, 0.708333, 0.75, 0.791667,
|
||||
0.833333, 0.875, 0.916667, 0.958333, // Band 17
|
||||
0.0, 0.03125, 0.0625, 0.09375, 0.125, 0.15625, 0.1875, 0.21875, 0.25, 0.28125, 0.3125, 0.34375,
|
||||
0.375, 0.40625, 0.4375, 0.46875, 0.5, 0.53125, 0.5625, 0.59375, 0.625, 0.65625, 0.6875,
|
||||
0.71875, 0.75, 0.78125, 0.8125, 0.84375, 0.875, 0.90625, 0.9375, 0.96875, // Band 18
|
||||
0.0, 0.0208333, 0.0416667, 0.0625, 0.0833333, 0.104167, 0.125, 0.145833, 0.166667, 0.1875,
|
||||
0.208333, 0.229167, 0.25, 0.270833, 0.291667, 0.3125, 0.333333, 0.354167, 0.375, 0.395833,
|
||||
0.416667, 0.4375, 0.458333, 0.479167, 0.5, 0.520833, 0.541667, 0.5625, 0.583333, 0.604167,
|
||||
0.625, 0.645833, 0.666667, 0.6875, 0.708333, 0.729167, 0.75, 0.770833, 0.791667, 0.8125,
|
||||
0.833333, 0.854167, 0.875, 0.895833, 0.916667, 0.9375, 0.958333, 0.979167,
|
||||
];
|
||||
|
||||
/// Computes band-wise spectral correlations using triangular filters in the
|
||||
/// Opus scale.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SpectralCorrelator {
|
||||
weights: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Default for SpectralCorrelator {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
weights: OPUS_BAND_WEIGHTS_24K_HZ_20MS.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SpectralCorrelator {
|
||||
/// Computes band-wise spectral auto-correlation.
|
||||
pub(crate) fn compute_auto_correlation(
|
||||
&self,
|
||||
x: &[f32],
|
||||
auto_corr: &mut [f32; OPUS_BANDS_24K_HZ],
|
||||
) {
|
||||
self.compute_cross_correlation(x, x, auto_corr);
|
||||
}
|
||||
|
||||
/// Computes band-wise spectral cross-correlation.
|
||||
///
|
||||
/// `x` and `y` must have size `FRAME_SIZE_20MS_24K_HZ` and be encoded as
|
||||
/// interleaved real-complex FFT coefficients where `x[1] = y[1] = 0`.
|
||||
pub(crate) fn compute_cross_correlation(
|
||||
&self,
|
||||
x: &[f32],
|
||||
y: &[f32],
|
||||
cross_corr: &mut [f32; OPUS_BANDS_24K_HZ],
|
||||
) {
|
||||
debug_assert_eq!(x.len(), FRAME_SIZE_20MS_24K_HZ);
|
||||
debug_assert_eq!(y.len(), FRAME_SIZE_20MS_24K_HZ);
|
||||
debug_assert_eq!(x[1], 0.0, "The Nyquist coefficient must be zeroed.");
|
||||
debug_assert_eq!(y[1], 0.0, "The Nyquist coefficient must be zeroed.");
|
||||
|
||||
let mut k = 0_usize; // Next Fourier coefficient index.
|
||||
cross_corr[0] = 0.0;
|
||||
for (i, &num_bins) in OPUS_SCALE_NUM_BINS_24K_HZ_20MS.iter().enumerate() {
|
||||
cross_corr[i + 1] = 0.0;
|
||||
for _ in 0..num_bins {
|
||||
let v = x[2 * k] * y[2 * k] + x[2 * k + 1] * y[2 * k + 1];
|
||||
let tmp = self.weights[k] * v;
|
||||
cross_corr[i] += v - tmp;
|
||||
cross_corr[i + 1] += tmp;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
cross_corr[0] *= 2.0; // The first band only gets half contribution.
|
||||
debug_assert_eq!(k, FRAME_SIZE_20MS_24K_HZ / 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the smoothed log magnitude spectrum from band energies.
|
||||
pub(crate) fn compute_smoothed_log_magnitude_spectrum(
|
||||
bands_energy: &[f32],
|
||||
log_bands_energy: &mut [f32; NUM_BANDS],
|
||||
) {
|
||||
debug_assert!(bands_energy.len() <= NUM_BANDS);
|
||||
const ONE_BY_HUNDRED: f32 = 1e-2;
|
||||
const LOG_ONE_BY_HUNDRED: f32 = -2.0;
|
||||
|
||||
let mut log_max = LOG_ONE_BY_HUNDRED;
|
||||
let mut follow = LOG_ONE_BY_HUNDRED;
|
||||
|
||||
let smooth = |x: f32, log_max: &mut f32, follow: &mut f32| -> f32 {
|
||||
let x = x.max(*log_max - 7.0).max(*follow - 1.5);
|
||||
*log_max = log_max.max(x);
|
||||
*follow = follow.max(x).max(*follow - 1.5);
|
||||
x
|
||||
};
|
||||
|
||||
// Smoothing over the bands for which the band energy is defined.
|
||||
for (i, &energy) in bands_energy.iter().enumerate() {
|
||||
log_bands_energy[i] = smooth((ONE_BY_HUNDRED + energy).log10(), &mut log_max, &mut follow);
|
||||
}
|
||||
// Smoothing over the remaining bands (zero energy).
|
||||
for lbe in log_bands_energy
|
||||
.iter_mut()
|
||||
.take(NUM_BANDS)
|
||||
.skip(bands_energy.len())
|
||||
{
|
||||
*lbe = smooth(LOG_ONE_BY_HUNDRED, &mut log_max, &mut follow);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DCT table for arrays having size equal to `NUM_BANDS`.
|
||||
pub(crate) fn compute_dct_table() -> [f32; NUM_BANDS * NUM_BANDS] {
|
||||
let mut dct_table = [0.0_f32; NUM_BANDS * NUM_BANDS];
|
||||
let k = (0.5_f64).sqrt();
|
||||
for i in 0..NUM_BANDS {
|
||||
for j in 0..NUM_BANDS {
|
||||
dct_table[i * NUM_BANDS + j] =
|
||||
((i as f64 + 0.5) * j as f64 * PI / NUM_BANDS as f64).cos() as f32;
|
||||
}
|
||||
dct_table[i * NUM_BANDS] *= k as f32;
|
||||
}
|
||||
dct_table
|
||||
}
|
||||
|
||||
/// Computes DCT for `input` given a pre-computed DCT table.
|
||||
///
|
||||
/// In-place computation is not allowed. `output` can be smaller than `input`
|
||||
/// to compute only the first DCT coefficients.
|
||||
pub(crate) fn compute_dct(
|
||||
input: &[f32],
|
||||
dct_table: &[f32; NUM_BANDS * NUM_BANDS],
|
||||
output: &mut [f32],
|
||||
) {
|
||||
// DCT scaling factor: sqrt(2 / NUM_BANDS).
|
||||
const DCT_SCALING_FACTOR: f32 = 0.301511345;
|
||||
|
||||
debug_assert!(!ptr::eq(input.as_ptr(), output.as_ptr()));
|
||||
debug_assert!(input.len() <= NUM_BANDS);
|
||||
debug_assert!(!output.is_empty());
|
||||
debug_assert!(output.len() <= input.len());
|
||||
|
||||
for (i, out) in output.iter_mut().enumerate() {
|
||||
*out = 0.0;
|
||||
for (j, &inp) in input.iter().enumerate() {
|
||||
*out += inp * dct_table[j * NUM_BANDS + i];
|
||||
}
|
||||
*out *= DCT_SCALING_FACTOR;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn opus_scale_boundaries_sum_to_half_frame() {
|
||||
let total_bins: usize = OPUS_SCALE_NUM_BINS_24K_HZ_20MS.iter().sum();
|
||||
assert_eq!(total_bins, FRAME_SIZE_20MS_24K_HZ / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spectral_correlator_valid_output() {
|
||||
let correlator = SpectralCorrelator::default();
|
||||
// Create a simple test signal: unit energy at each frequency bin.
|
||||
let mut x = vec![0.0_f32; FRAME_SIZE_20MS_24K_HZ];
|
||||
for i in 0..FRAME_SIZE_20MS_24K_HZ / 2 {
|
||||
x[2 * i] = 1.0; // Real part.
|
||||
}
|
||||
x[1] = 0.0; // Nyquist coefficient must be zero.
|
||||
|
||||
let mut auto_corr = [0.0_f32; OPUS_BANDS_24K_HZ];
|
||||
correlator.compute_auto_correlation(&x, &mut auto_corr);
|
||||
|
||||
// Auto-correlation of a signal with itself must be non-negative.
|
||||
for (i, &ac) in auto_corr.iter().enumerate() {
|
||||
assert!(ac >= 0.0, "auto_corr[{i}] = {ac} < 0");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoothed_log_magnitude_spectrum_basic() {
|
||||
let bands_energy = [1.0_f32; OPUS_BANDS_24K_HZ];
|
||||
let mut log_bands_energy = [0.0_f32; NUM_BANDS];
|
||||
compute_smoothed_log_magnitude_spectrum(&bands_energy, &mut log_bands_energy);
|
||||
|
||||
// log10(1e-2 + 1.0) ≈ 0.00432
|
||||
for (i, &lbe) in log_bands_energy.iter().enumerate().take(OPUS_BANDS_24K_HZ) {
|
||||
assert!(
|
||||
lbe > -0.1 && lbe < 0.1,
|
||||
"log_bands_energy[{i}] = {lbe}, expected ~0"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dct_of_constant_input() {
|
||||
let dct_table = compute_dct_table();
|
||||
let input = [1.0_f32; NUM_BANDS];
|
||||
let mut output = [0.0_f32; NUM_BANDS];
|
||||
compute_dct(&input, &dct_table, &mut output);
|
||||
|
||||
// DC coefficient should be non-zero, higher coefficients should be ~0.
|
||||
assert!(output[0].abs() > 0.1, "DC coefficient should be non-zero");
|
||||
for (i, &o) in output.iter().enumerate().skip(1) {
|
||||
assert!(
|
||||
o.abs() < 1e-5,
|
||||
"output[{i}] = {o}, expected ~0 for constant input"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Buffer for pair-wise comparison results in a symmetric matrix.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h`.
|
||||
|
||||
/// Buffer for results of pair-wise comparisons between items stored in a ring
|
||||
/// buffer.
|
||||
///
|
||||
/// Every time the oldest item is replaced in a ring buffer, the new one is
|
||||
/// compared to the remaining items. The results are buffered here and
|
||||
/// automatically evicted when one of the corresponding items leaves the ring
|
||||
/// buffer.
|
||||
///
|
||||
/// The comparison is assumed symmetric and comparing an item with itself is not
|
||||
/// needed.
|
||||
///
|
||||
/// Internally stores the upper-right triangular matrix (excluding diagonal)
|
||||
/// encoded as a `(S-1) x (S-1)` square array, allowing `Push` to shift data
|
||||
/// with a single `copy_within`.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SymmetricMatrixBuffer<const S: usize> {
|
||||
buf: Vec<f32>,
|
||||
}
|
||||
|
||||
impl<const S: usize> Default for SymmetricMatrixBuffer<S> {
|
||||
fn default() -> Self {
|
||||
const { assert!(S > 2) };
|
||||
Self {
|
||||
buf: vec![0.0; (S - 1) * (S - 1)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize> SymmetricMatrixBuffer<S> {
|
||||
/// Sets all buffer values to zero.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.buf.fill(0.0);
|
||||
}
|
||||
|
||||
/// Pushes the results from the comparison between the most recent item
|
||||
/// and those still in the ring buffer.
|
||||
///
|
||||
/// `values` must have length `S - 1`.
|
||||
/// `values[0]` is the comparison between the most recent item and the
|
||||
/// second most recent one; `values[S-2]` is the comparison with the
|
||||
/// oldest one.
|
||||
pub(crate) fn push(&mut self, values: &[f32]) {
|
||||
debug_assert_eq!(values.len(), S - 1);
|
||||
// Move the lower-right sub-matrix of size (S-2)x(S-2) one row up
|
||||
// and one column left.
|
||||
self.buf.copy_within(S.., 0);
|
||||
// Copy new values in the last column in the right order.
|
||||
for (i, &val) in values.iter().enumerate().take(S - 1) {
|
||||
let index = (S - 1 - i) * (S - 1) - 1;
|
||||
debug_assert!(index < self.buf.len());
|
||||
self.buf[index] = val;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the value corresponding to the comparison of two items in the
|
||||
/// ring buffer having delay `delay1` and `delay2`.
|
||||
///
|
||||
/// The two arguments must not be equal and both must be in `0..S`.
|
||||
pub(crate) fn get_value(&self, delay1: usize, delay2: usize) -> f32 {
|
||||
use std::mem;
|
||||
debug_assert_ne!(delay1, delay2, "The diagonal cannot be accessed.");
|
||||
let mut row = S - 1 - delay1;
|
||||
let mut col = S - 1 - delay2;
|
||||
if row > col {
|
||||
mem::swap(&mut row, &mut col);
|
||||
}
|
||||
debug_assert!(row < S - 1);
|
||||
debug_assert!(col >= 1 && col < S);
|
||||
let index = row * (S - 1) + (col - 1);
|
||||
debug_assert!(index < self.buf.len());
|
||||
self.buf[index]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rnn_vad::ring_buffer::RingBuffer;
|
||||
|
||||
fn check_symmetry<const S: usize>(sym_matrix_buf: &SymmetricMatrixBuffer<S>) {
|
||||
for row in 0..S - 1 {
|
||||
for col in row + 1..S {
|
||||
assert_eq!(
|
||||
sym_matrix_buf.get_value(row, col),
|
||||
sym_matrix_buf.get_value(col, row),
|
||||
"Asymmetry at ({row}, {col})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Test that shows how to combine RingBuffer and SymmetricMatrixBuffer to
|
||||
/// efficiently compute pair-wise scores. Verifies that the evolution of a
|
||||
/// SymmetricMatrixBuffer instance follows that of RingBuffer.
|
||||
///
|
||||
/// This is a simplified adaptation of the C++ test which uses `PairType`.
|
||||
/// Since our RingBuffer is f32-only, we store single float values and
|
||||
/// verify the matrix tracks pair-wise products correctly.
|
||||
#[test]
|
||||
fn symmetric_matrix_buffer_use_case() {
|
||||
const RING_BUF_SIZE: usize = 10;
|
||||
let mut ring_buf = RingBuffer::<1, RING_BUF_SIZE>::default();
|
||||
let mut sym_matrix_buf = SymmetricMatrixBuffer::<RING_BUF_SIZE>::default();
|
||||
|
||||
for t in 1..=100u32 {
|
||||
let t_f = t as f32;
|
||||
ring_buf.push(&[t_f]);
|
||||
|
||||
// The head of the ring buffer is `t`.
|
||||
assert_eq!(ring_buf.get_array_view(0), &[t_f]);
|
||||
|
||||
// Create comparisons: encode pair (older, newer) as older * 1000 + newer.
|
||||
let mut new_comparisons = [0.0_f32; RING_BUF_SIZE - 1];
|
||||
for (i, cmp) in new_comparisons.iter_mut().enumerate() {
|
||||
let delay = i + 1;
|
||||
let t_prev = ring_buf.get_array_view(delay)[0];
|
||||
*cmp = t_prev * 1000.0 + t_f;
|
||||
}
|
||||
sym_matrix_buf.push(&new_comparisons);
|
||||
|
||||
// Check symmetry.
|
||||
check_symmetry(&sym_matrix_buf);
|
||||
|
||||
// Check that the pairs resulting from the ring buffer content are
|
||||
// in the right position.
|
||||
for delay1 in 0..RING_BUF_SIZE - 1 {
|
||||
for delay2 in delay1 + 1..RING_BUF_SIZE {
|
||||
let t1 = ring_buf.get_array_view(delay1)[0];
|
||||
let t2 = ring_buf.get_array_view(delay2)[0];
|
||||
assert!(t2 <= t1);
|
||||
let val = sym_matrix_buf.get_value(delay1, delay2);
|
||||
let expected = t2 * 1000.0 + t1;
|
||||
assert_eq!(
|
||||
val, expected,
|
||||
"Mismatch at t={t}, delay1={delay1}, delay2={delay2}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Optimized vector math operations for the RNN VAD.
|
||||
//!
|
||||
//! Delegates to [`sonora_simd`] for SIMD-accelerated dot product.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/rnn_vad/vector_math.h`.
|
||||
|
||||
use sonora_simd::SimdBackend;
|
||||
|
||||
/// Provides optimized mathematical operations on vectors.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct VectorMath {
|
||||
backend: SimdBackend,
|
||||
}
|
||||
|
||||
impl VectorMath {
|
||||
/// Creates a new `VectorMath` using the given SIMD backend.
|
||||
pub(crate) fn new(backend: SimdBackend) -> Self {
|
||||
Self { backend }
|
||||
}
|
||||
|
||||
/// Computes the dot product between two equally sized slices.
|
||||
pub(crate) fn dot_product(&self, x: &[f32], y: &[f32]) -> f32 {
|
||||
self.backend.dot_product(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sonora_simd::detect_backend;
|
||||
|
||||
const X: [f32; 19] = [
|
||||
0.31593041,
|
||||
0.9350786,
|
||||
-0.25252445,
|
||||
-0.86956251,
|
||||
-0.9673632,
|
||||
0.54571901,
|
||||
-0.72504495,
|
||||
-0.79509912,
|
||||
-0.25525012,
|
||||
-0.73340473,
|
||||
0.15747377,
|
||||
-0.04370565,
|
||||
0.76135145,
|
||||
-0.57239645,
|
||||
0.68616848,
|
||||
0.3740298,
|
||||
0.34710799,
|
||||
-0.92207423,
|
||||
0.10738454,
|
||||
];
|
||||
const ENERGY_OF_X: f32 = 7.315563958160327;
|
||||
const ENERGY_OF_X_SUBSPAN: f32 = 6.333327669592963;
|
||||
const SIZE_OF_X_SUBSPAN: usize = 16;
|
||||
|
||||
#[test]
|
||||
fn dot_product_scalar() {
|
||||
let vector_math = VectorMath::new(SimdBackend::Scalar);
|
||||
let energy = vector_math.dot_product(&X, &X);
|
||||
assert!(
|
||||
(energy - ENERGY_OF_X).abs() < 1e-5,
|
||||
"scalar full: {energy} != {ENERGY_OF_X}"
|
||||
);
|
||||
let energy_sub = vector_math.dot_product(&X[..SIZE_OF_X_SUBSPAN], &X[..SIZE_OF_X_SUBSPAN]);
|
||||
assert!(
|
||||
(energy_sub - ENERGY_OF_X_SUBSPAN).abs() < 1e-5,
|
||||
"scalar subspan: {energy_sub} != {ENERGY_OF_X_SUBSPAN}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_product_detected_backend() {
|
||||
let backend = detect_backend();
|
||||
let vector_math = VectorMath::new(backend);
|
||||
let energy = vector_math.dot_product(&X, &X);
|
||||
assert!(
|
||||
(energy - ENERGY_OF_X).abs() < 1e-5,
|
||||
"{}: full: {energy} != {ENERGY_OF_X}",
|
||||
backend.name()
|
||||
);
|
||||
let energy_sub = vector_math.dot_product(&X[..SIZE_OF_X_SUBSPAN], &X[..SIZE_OF_X_SUBSPAN]);
|
||||
assert!(
|
||||
(energy_sub - ENERGY_OF_X_SUBSPAN).abs() < 1e-5,
|
||||
"{}: subspan: {energy_sub} != {ENERGY_OF_X_SUBSPAN}",
|
||||
backend.name()
|
||||
);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
//! Neural network weight tables for the RNN VAD.
|
||||
//!
|
||||
//! Ported from `webrtc/third_party/rnnoise/src/rnn_vad_weights.cc`.
|
||||
|
||||
/// Weights scaling factor.
|
||||
pub(crate) const WEIGHTS_SCALE: f32 = 1.0 / 256.0;
|
||||
|
||||
// Input layer (dense).
|
||||
pub(crate) const INPUT_LAYER_INPUT_SIZE: usize = 42;
|
||||
pub(crate) const INPUT_LAYER_OUTPUT_SIZE: usize = 24;
|
||||
|
||||
pub(crate) const INPUT_DENSE_WEIGHTS: [i8; INPUT_LAYER_INPUT_SIZE * INPUT_LAYER_OUTPUT_SIZE] = [
|
||||
-10, 0, -3, 1, -8, -6, 3, -13, 1, 0, -3, -7, -5, -3, 6, -1, -6, 0, -6, -4, -1, -2, 1, 1, -7, 2,
|
||||
21, 10, -5, -20, 24, 23, 37, 8, -2, 33, -6, 22, 13, -2, 50, 8, 13, 1, -15, 30, -10, 30, 0, 3,
|
||||
5, 27, 1, 4, -3, 41, 56, 35, -2, 49, -13, 11, 13, -2, -47, 5, -16, -60, -15, 77, -17, 26, -3,
|
||||
14, -21, 19, -5, -19, -13, 0, 10, 14, 9, 31, -13, -41, -10, 4, 22, 18, -48, -6, -10, 62, -3,
|
||||
-18, -14, 12, 26, -28, 3, 14, 25, -13, -19, 6, 5, 36, -3, -65, -12, 0, 31, -7, -9, 101, -4, 26,
|
||||
16, 17, -12, -12, 14, -36, -3, 5, -15, 21, 2, 30, -3, 38, -4, 1, -6, 7, -7, 14, 38, -22, -30,
|
||||
-3, -7, 3, -39, -70, -126, 25, 34, 94, -67, -22, -33, 83, -47, -118, 4, 70, 33, 25, 62, -128,
|
||||
-76, -118, -113, 49, -12, -100, -18, -114, -33, 43, 32, 61, 40, -9, -106, 2, 36, -100, -40, -5,
|
||||
20, -75, 61, -51, -9, 126, -27, -52, 5, -24, -21, -126, -114, -12, 15, 106, -2, 73, -125, 50,
|
||||
13, -120, 35, 35, 4, -61, 29, -124, 6, -53, -69, -125, 64, -89, 36, -107, -103, -7, 27, 121,
|
||||
69, 77, -35, 35, 95, -125, -49, 97, -45, -43, -23, 23, -28, -65, -118, 2, 8, -126, 27, -97, 92,
|
||||
5, 55, 82, 17, -57, -115, 37, 8, -106, -46, 41, -2, 21, -44, 8, -73, -58, -39, 34, 89, -95, 95,
|
||||
-117, 120, -58, 31, 123, 1, -32, -109, -110, 60, -120, -43, -74, 5, 91, 26, 21, 114, 82, -83,
|
||||
-126, 123, 22, -16, -67, 25, -83, 46, 48, -34, -121, -124, -63, -35, -9, 31, 82, 123, 6, -3,
|
||||
117, 93, -2, -13, -36, 124, -112, -6, -102, -5, -33, -15, 44, -69, -127, -23, -40, -34, -85,
|
||||
68, 83, -1, 40, 8, 84, 118, -58, -55, -102, 123, -55, -14, -123, 44, -63, -14, 21, 35, 16, 24,
|
||||
-126, -13, -114, 35, 20, -36, 61, -9, 97, 34, 19, -32, -109, 76, -104, 99, -119, 45, -125, -51,
|
||||
-28, -8, -69, -8, 125, -45, -93, 113, 103, -41, -82, 52, 7, 126, 0, -40, 104, 55, -58, 17,
|
||||
-124, -93, -58, 8, -45, 1, 56, -123, 108, -47, -23, 115, 127, 17, -68, -13, 116, -82, -44, 45,
|
||||
67, -120, -101, -15, -125, 120, -113, 17, -48, -73, 126, -64, -86, -118, -19, 112, -1, -66,
|
||||
-27, -62, 121, -86, -58, 50, 89, -38, -75, 95, -111, 12, -113, 2, -68, 2, -94, -121, 91, -5, 0,
|
||||
79, 43, -7, -18, 79, 35, -38, 47, 1, -45, 83, -50, 102, 32, 55, -96, 15, -122, -69, 45, -27,
|
||||
91, -62, -30, 46, -95, 22, -72, -97, -1, 14, -122, 28, 127, 61, -126, 121, 9, 68, -120, 49,
|
||||
-60, 90, 3, 43, 68, 54, 34, -10, 28, 21, -24, -54, 22, -113, -12, 82, -2, -17, -9, 127, 8, 116,
|
||||
-92, 0, -70, -33, 123, 66, 116, -74, -4, 74, -72, -22, -47, 1, -83, -60, -124, 1, 122, -57,
|
||||
-43, 49, 40, -126, -128, -8, -29, 28, -24, -123, -121, -70, -93, -37, -126, 11, -125, -37, 11,
|
||||
-31, -51, -124, 116, -128, 8, -25, 109, 75, -12, 7, 8, 10, 117, 124, -128, -128, 29, -26, 101,
|
||||
21, -128, 87, 8, -39, 23, -128, 127, -127, 74, -55, 74, 112, 127, 4, 55, 44, -92, 123, 34, -93,
|
||||
47, -21, -92, 17, 49, -121, 92, 7, -126, -125, 124, -74, 3, -59, 18, -91, 3, -9, 9, 56, 116, 7,
|
||||
-29, 33, 87, -21, -128, -13, 57, 74, 9, -29, -61, -97, -21, -95, -12, -114, 16, 82, 125, -7,
|
||||
10, -24, 9, 77, -128, -102, -25, 3, -126, 10, 13, -18, 51, 26, 127, -79, 35, 51, 12, -50, -24,
|
||||
1, -7, 22, 81, 65, 120, -30, -38, 85, 122, -4, -106, -11, 27, 53, 41, 8, -104, -66, -38, -124,
|
||||
10, 12, 76, 117, -109, 9, 11, 2, -18, 3, 113, -16, -79, -39, -123, -20, -128, 2, 13, -33, -58,
|
||||
10, 84, -104, 13, 64, 109, 1, 54, -12, 28, 24, 63, -126, 118, -82, 46, -12, -15, 14, -43, 60,
|
||||
22, -32, -19, -46, 91, -107, 24, -94, 26, -47, 125, 6, 58, -15, -75, -26, -38, -35, 103, -16,
|
||||
-17, -13, 63, -2, 45, -45, -73, -23, 70, -87, 51, -17, 53, 76, 14, -18, -31, -14, 103, 8, 21,
|
||||
-28, -33, -20, -47, 6, 39, 40, -30, 7, -76, 55, 31, -20, -21, -59, 1, 25, -11, 17, 5, -13, -39,
|
||||
0, -76, 50, -33, -29, -50, -16, -11, -12, -1, -46, 40, -10, 65, -19, 21, -41, -32, -83, -19,
|
||||
-4, 49, -60, 118, -24, -46, 9, 102, -20, 8, -19, 25, 31, -3, -37, 0, 25, 7, 29, 2, -39, 127,
|
||||
-64, -20, 64, 115, -30, 36, 100, 35, 122, 127, 127, -127, 127, -127, 19, 127, -89, -79, -32,
|
||||
39, -127, 125, -80, 126, -127, 26, 8, 98, -8, -57, -90, -50, 126, 61, 127, -126, 40, -106, -68,
|
||||
104, -125, -119, 11, 10, -127, 66, -56, -12, -126, -104, 27, 75, 38, -124, -126, -125, 84,
|
||||
-123, -45, -114, -128, 127, 103, -101, -124, 127, -11, -23, -123, 92, -123, 24, 126, 41, -2,
|
||||
-39, -27, -94, 40, -112, -48, 127, 58, 14, 38, -75, -64, 73, 117, 100, -119, -11, 6, 32, -126,
|
||||
-14, 35, 121, -10, 54, -60, 89, -3, 69, -25, -20, 43, -86, -34, 24, 27, 7, -81, -99, -23, -16,
|
||||
-26, 13, 35, -97, 80, -29, -13, -121, -12, -65, -94, 70, -89, -126, -95, 88, 33, 96, 29, -90,
|
||||
69, 114, -78, 65, 90, -47, -47, 89, 1, -12, 3, 8, 30, 5, 2, -30, -1, 6, -7, 10, -4, 46, -27,
|
||||
-40, 22, -6, -17, 45, 24, -9, 23, -14, -63, -26, -12, -57, 27, 25, 55, -76, -47, 21, 34, 33,
|
||||
26, 17, 14, 6, 9, 26, 25, -25, -25, -18,
|
||||
];
|
||||
|
||||
pub(crate) const INPUT_DENSE_BIAS: [i8; INPUT_LAYER_OUTPUT_SIZE] = [
|
||||
38, -6, 127, 127, 127, -43, -127, 78, 127, 5, 127, 123, 127, 127, -128, -76, -126, 28, 127,
|
||||
125, -30, 127, -89, -20,
|
||||
];
|
||||
|
||||
// Hidden layer (GRU).
|
||||
pub(crate) const HIDDEN_LAYER_OUTPUT_SIZE: usize = 24;
|
||||
|
||||
pub(crate) const HIDDEN_GRU_WEIGHTS: [i8; 3 * HIDDEN_LAYER_OUTPUT_SIZE * HIDDEN_LAYER_OUTPUT_SIZE] =
|
||||
include!("weights_hidden_gru.inc");
|
||||
|
||||
pub(crate) const HIDDEN_GRU_RECURRENT_WEIGHTS: [i8; 3
|
||||
* HIDDEN_LAYER_OUTPUT_SIZE
|
||||
* HIDDEN_LAYER_OUTPUT_SIZE] = include!("weights_hidden_gru_recurrent.inc");
|
||||
|
||||
pub(crate) const HIDDEN_GRU_BIAS: [i8; 3 * HIDDEN_LAYER_OUTPUT_SIZE] = [
|
||||
124, 125, -57, -126, 53, 123, 127, -75, 68, 102, -2, 116, 124, 127, 124, 125, 126, 123, -16,
|
||||
48, 125, 126, 78, 85, 11, 126, -30, -30, -64, -3, -105, -29, -17, 69, 63, 2, -32, -10, -62,
|
||||
113, -52, 112, -109, 112, 7, -40, 73, 53, 62, 6, -2, 0, 0, 100, -16, 26, -24, 56, 26, -10, -33,
|
||||
41, 70, 109, -29, 127, 34, -66, 49, 53, 27, 62,
|
||||
];
|
||||
|
||||
// Output layer (dense).
|
||||
pub(crate) const OUTPUT_LAYER_OUTPUT_SIZE: usize = 1;
|
||||
|
||||
pub(crate) const OUTPUT_DENSE_WEIGHTS: [i8; HIDDEN_LAYER_OUTPUT_SIZE * OUTPUT_LAYER_OUTPUT_SIZE] = [
|
||||
127, 127, 127, 127, 127, 20, 127, -126, -126, -54, 14, 125, -126, -126, 127, -125, -126, 127,
|
||||
-127, -127, -57, -30, 127, 80,
|
||||
];
|
||||
|
||||
pub(crate) const OUTPUT_DENSE_BIAS: [i8; OUTPUT_LAYER_OUTPUT_SIZE] = [-50];
|
||||
@@ -0,0 +1,146 @@
|
||||
[
|
||||
-124, 23, -123, -33, -95, -4, 8, -84, 4, 101, -119, 116,
|
||||
-4, 123, 103, -51, 29, -124, -114, -49, 31, 9, 75, -128,
|
||||
0, -49, 37, -50, 46, -21, -63, -104, 54, 82, 33, 21,
|
||||
70, 127, -9, -79, -39, -23, -127, 107, 122, -96, -46, -18,
|
||||
-39, 13, -28, -48, 14, 56, -52, 49, -1, -121, 25, -18,
|
||||
-36, -52, -57, -30, 54, -124, -26, -47, 10, 39, 12, 2,
|
||||
9, -127, -128, 102, 21, 11, -64, -71, 89, -113, -111, 54,
|
||||
31, 94, 121, -40, 30, 40, -109, 73, -9, 108, -92, 2,
|
||||
-127, 116, 127, 127, -122, 95, 127, -37, -127, 28, 89, 10,
|
||||
24, -104, -62, -67, -14, 38, 14, -71, 22, -41, 20, -50,
|
||||
39, 63, 86, 127, -18, 79, 4, -51, 2, 33, 117, -113,
|
||||
-78, 56, -91, 37, 34, -45, -44, -22, 21, -16, 56, 30,
|
||||
-84, -79, 38, -74, 127, 9, -25, 2, 82, 61, 25, -26,
|
||||
26, 11, 117, -65, 12, -58, 42, -62, -93, 11, 11, 124,
|
||||
-123, 80, -125, 11, -90, 42, 94, 4, -109, -1, 85, -52,
|
||||
45, -26, -27, 77, -5, 30, 90, 0, 95, -7, 53, 29,
|
||||
-82, 22, -9, 74, 2, -12, -73, 114, 97, -64, 122, -77,
|
||||
43, 91, 86, 126, 106, 72, 90, -43, 46, 96, -51, 21,
|
||||
22, 68, 22, 41, 79, 75, -46, -105, 23, -116, 127, -123,
|
||||
102, 57, 85, 10, -29, 34, 125, 126, 124, 81, -15, 54,
|
||||
96, -128, 39, -124, 103, 74, 126, 127, -50, -71, -122, -64,
|
||||
93, -75, 71, 105, 122, 123, 126, 122, -127, 33, -63, -74,
|
||||
124, -71, 33, 41, -56, 19, 6, 65, 41, 90, -116, -3,
|
||||
-46, 75, -13, 98, -74, -42, 74, -95, -96, 81, 24, 32,
|
||||
-19, -123, 74, 55, 109, 115, 0, 32, 33, 12, -20, 9,
|
||||
127, 127, -61, 79, -48, -54, -49, 101, -9, 27, -106, 74,
|
||||
119, 77, 87, -126, -24, 127, 124, 31, 34, 127, 40, 3,
|
||||
-90, 127, 23, 57, -53, 127, -69, -88, -33, 127, 19, -46,
|
||||
-9, -125, 13, -126, -113, 127, -41, 46, 106, -62, 3, -10,
|
||||
111, 49, -34, -24, -20, -112, 11, 101, -50, -34, 50, 65,
|
||||
-64, -106, 70, -48, 60, 9, -122, -45, 15, -112, -26, -4,
|
||||
1, 39, 23, 58, -45, -80, 127, 82, 58, 30, -94, -119,
|
||||
51, -89, 95, -107, 30, 127, 125, 58, -52, -42, -38, -20,
|
||||
-122, 115, 39, -26, 5, 73, 13, -39, 43, -23, -20, -125,
|
||||
23, 35, 53, -61, -66, 72, -20, 33, 8, 35, 4, 7,
|
||||
18, 19, 16, -45, -50, -71, 31, -29, -41, -27, 10, 14,
|
||||
27, 9, -23, 98, 6, -94, 92, 127, -114, 59, -26, -100,
|
||||
-62, -127, -17, -85, -60, 126, -42, -6, 33, -120, -26, -126,
|
||||
-127, -35, -114, -31, 25, -126, -100, -126, -64, -46, -31, 30,
|
||||
25, -74, -111, -97, -81, -104, -114, -19, -9, -116, -69, 22,
|
||||
30, 59, 8, -51, 16, -97, 18, -4, -89, 80, -50, 3,
|
||||
36, -67, 56, 69, -26, 107, -10, 58, -28, -4, -57, -72,
|
||||
-111, 0, -75, -119, 14, -75, -49, -66, -49, 8, -121, 22,
|
||||
-54, 121, 30, 54, -26, -126, -123, 56, 5, 48, 21, -127,
|
||||
-11, 23, 25, -82, 6, -25, 119, 78, 4, -104, 27, 61,
|
||||
-48, 37, -13, -52, 50, -50, 44, -1, -22, -43, -59, -78,
|
||||
-67, -32, -26, 9, -3, 40, 16, 19, 3, -9, 20, -6,
|
||||
-37, 28, 39, 17, -19, -10, 1, 6, -59, 74, 47, 3,
|
||||
-119, 0, -128, -107, -25, -22, -69, -23, -111, -42, -93, -120,
|
||||
90, -85, -54, -118, 76, -79, 124, 101, -77, -75, -17, -71,
|
||||
-114, 68, 55, 79, -1, -123, -20, 127, -65, -123, -128, -87,
|
||||
123, 9, -115, -14, 7, -4, 127, -79, -115, 125, -28, 89,
|
||||
-83, 49, 89, 119, -69, -5, 12, -49, 60, 57, -24, -99,
|
||||
-110, 76, -83, 125, 73, 81, 11, 8, -45, 1, 83, 13,
|
||||
-70, -2, 97, 112, -97, 53, -9, -94, 124, 44, -49, -24,
|
||||
52, 76, -110, -70, -114, -12, 72, -4, -114, 43, -43, 81,
|
||||
102, -84, -27, 62, -40, 52, 58, 124, -35, -51, -123, -43,
|
||||
56, -75, -34, -35, -106, 93, -43, 14, -16, 46, 62, -97,
|
||||
21, 30, -53, 21, -11, -33, -20, -95, 4, -126, 12, 45,
|
||||
20, 108, 85, 11, 20, -40, 99, 4, -25, -18, -23, -12,
|
||||
-126, -55, -20, -44, -51, 91, -127, 127, -44, 7, 127, 78,
|
||||
38, 125, -6, -94, -103, 73, 126, -126, 18, 59, -46, 106,
|
||||
76, 116, -31, 75, -4, 92, 102, 32, -31, 73, 42, -21,
|
||||
-28, 57, 127, -8, -107, 115, 124, -94, -4, -128, 29, -57,
|
||||
70, -82, 50, -13, -44, 38, 67, -93, 6, -39, -46, 56,
|
||||
68, 27, 61, 26, 18, -72, 127, 22, 18, -31, 127, 61,
|
||||
-65, -38, 1, -67, -1, 8, -73, 46, -116, -94, 58, -49,
|
||||
71, -40, -63, -82, -20, -60, 93, 76, 69, -106, 34, -31,
|
||||
4, -25, 107, -18, 45, 4, -61, 126, 54, -126, -125, 41,
|
||||
19, 44, 32, -98, 125, -24, 125, -96, -125, 15, 87, -4,
|
||||
-90, 18, -40, 28, -69, 67, 22, 41, 39, 7, -48, -44,
|
||||
12, 69, -13, 2, 44, -38, 111, -7, -126, -22, -9, 74,
|
||||
-128, -36, -7, -123, -15, -79, -91, -37, -127, -122, 104, 30,
|
||||
7, 98, -37, 111, -116, -47, 127, -45, 118, -111, -123, -120,
|
||||
-77, -64, -125, 124, 77, 111, 77, 18, -113, 117, -9, 67,
|
||||
-77, 126, 49, -20, -124, 39, 41, -124, -34, 114, -87, -126,
|
||||
98, -20, 59, -17, -24, 125, 107, 54, 35, 33, -44, 12,
|
||||
-29, 125, -71, -28, -63, -114, 28, -17, 121, -36, 127, 89,
|
||||
-122, -49, -18, -48, 17, 24, 19, -64, -128, 13, 86, 45,
|
||||
13, -49, 55, 84, 48, 80, -39, 99, -127, 70, -33, 30,
|
||||
50, 126, -65, -117, -13, -20, -24, 127, 115, -72, -104, 63,
|
||||
126, -42, 57, 17, 46, 21, 119, 110, -100, -60, -112, 62,
|
||||
-33, 28, 26, -22, -60, -33, -54, 78, 25, 32, -114, 86,
|
||||
44, 26, 43, 76, 121, 19, 97, -2, -3, -73, -68, 6,
|
||||
-116, 6, -43, -97, 46, -128, -120, -31, -119, -29, 16, 16,
|
||||
-126, -128, -126, -46, -9, -3, 92, -31, -76, -126, -3, -107,
|
||||
-12, -23, -69, 5, 51, 27, -42, 23, -70, -128, -29, 22,
|
||||
29, -126, -55, 50, -71, -3, 127, 44, -27, -70, -63, -66,
|
||||
-70, 104, 86, 115, 29, -92, 41, -90, 44, -11, -28, 20,
|
||||
-11, -63, -16, 43, 31, 17, -73, -31, -1, -17, -11, -39,
|
||||
56, 18, 124, 72, -14, 28, 69, -121, -125, 34, 127, 63,
|
||||
86, -80, -126, -125, -124, -47, 124, 77, 124, -19, 23, -7,
|
||||
-50, 96, -128, -93, 102, -53, -36, -87, 119, -125, 92, -126,
|
||||
118, 102, 72, -2, 125, 10, 97, 124, -125, 125, 71, -20,
|
||||
-47, -116, -121, -4, -9, -32, 79, -124, -36, 33, -128, -74,
|
||||
125, 23, 127, -29, -115, -32, 124, -89, 32, -107, 43, -17,
|
||||
24, 24, 18, 29, -13, -15, -36, 62, -91, 4, -41, 95,
|
||||
28, -23, 6, 46, 84, 66, 77, 68, -70, -1, -23, -6,
|
||||
65, 70, -21, 9, 77, -12, 2, -118, 4, 9, -108, 84,
|
||||
52, 2, 52, 13, -10, 58, -110, 18, 66, -95, -23, 70,
|
||||
31, -3, 56, 56, -3, -7, 1, -27, -48, -61, 41, -4,
|
||||
10, -62, 32, -7, -24, 9, -48, -60, -4, 79, -20, -38,
|
||||
-76, 68, -49, -97, 0, -15, 5, -100, -49, -95, -99, -115,
|
||||
-9, -40, 10, 104, 13, 56, 127, -27, -109, -94, -118, -102,
|
||||
-44, -85, 52, 127, -4, 14, 62, 121, -122, -26, -79, -42,
|
||||
-34, 1, 25, -38, -79, -58, -31, -31, -90, -30, -123, 32,
|
||||
-56, 125, 66, 124, -1, 3, 91, -103, -7, 23, 78, -18,
|
||||
9, 69, -69, 76, -38, -33, -2, -98, 18, 106, 84, 55,
|
||||
87, -47, 35, -124, 64, 41, -14, 46, 25, -2, 120, -21,
|
||||
82, 19, -79, -37, -3, -8, -16, 21, 19, -5, -28, -112,
|
||||
39, -6, -30, 53, -69, 53, 46, 127, 123, 78, 20, 28,
|
||||
-7, 73, 72, 17, -40, 41, 111, 57, 32, -95, 29, 28,
|
||||
-39, -65, 54, -20, -63, 29, -67, 3, 44, -57, -47, 11,
|
||||
61, -22, -44, 61, 48, -100, 20, 125, 96, -24, -16, 3,
|
||||
-69, -126, 74, -125, 9, 45, -67, -123, -59, -72, 118, 69,
|
||||
45, 50, -57, 67, 13, -66, -106, 47, 62, 22, -1, -22,
|
||||
-25, -40, -125, 3, 125, 32, 102, -56, -25, -75, -30, 122,
|
||||
60, -13, 36, -73, 7, -84, 124, 40, -118, 17, -87, -118,
|
||||
-8, 3, -27, 111, -40, 40, -51, 127, 125, -45, -30, -54,
|
||||
46, 80, -1, -30, 101, -17, 18, 26, 54, 7, -12, 1,
|
||||
-127, 123, -122, -27, -75, 64, 10, 25, -15, -44, 127, -127,
|
||||
5, -84, -81, -7, 19, -26, 126, 15, 116, -126, 14, -76,
|
||||
44, 62, -110, -124, 125, -29, -87, -3, -69, 82, 90, 57,
|
||||
-123, 123, 100, -19, -51, -32, 69, 37, -57, -128, -124, -72,
|
||||
-13, 51, -7, -45, -73, 5, 99, -26, -117, -96, -109, 4,
|
||||
-31, -12, 0, 31, -42, -27, 12, -81, 118, 39, 83, 14,
|
||||
41, -126, 107, -82, 94, -116, -122, -47, -109, -84, -128, -35,
|
||||
-56, 66, 8, -65, 19, 42, -46, -72, -109, 41, 43, -127,
|
||||
-113, 58, 127, 42, -75, -1, 65, 117, -55, -113, -123, 124,
|
||||
43, -96, -115, -19, 68, 15, 94, 3, 75, 0, 34, 9,
|
||||
42, 110, -48, 92, -76, 99, -17, 27, 32, 13, 125, 50,
|
||||
-17, 56, 4, 53, 34, -8, 99, 80, -126, -21, -65, -11,
|
||||
-46, 44, -81, -3, -121, 123, 66, -81, -84, 119, 127, 84,
|
||||
105, 45, -66, -42, -23, 32, -25, 12, 111, 127, 88, 125,
|
||||
30, 24, -127, -9, -54, 127, -116, -119, 88, 70, 94, -120,
|
||||
35, -93, 15, 22, -21, 25, -110, -123, -45, 8, -109, 125,
|
||||
-122, -86, -126, 8, -14, -120, -45, -45, 69, -125, -122, 6,
|
||||
81, 86, 125, 95, 54, 77, 54, -123, 126, -85, -117, 56,
|
||||
11, 0, -61, -91, -12, -2, -113, -3, -15, -122, -63, -91,
|
||||
10, 84, -111, 125, 93, 21, 62, -78, -116, 13, -57, 28,
|
||||
-124, 126, 110, 12, 15, 95, 15, -19, -125, -97, 52, -7,
|
||||
101, 9, 20, -125, -26, -56, 72, 77, 12, -126, 22, -29,
|
||||
47, 62, 95, 112, 69, 32, 97, -83, -8, -5, 67, -63,
|
||||
-123, 79, 59, 0, -6, -17, 4, -111, -52, 27, 65, 0,
|
||||
]
|
||||
@@ -0,0 +1,146 @@
|
||||
[
|
||||
65, 83, 35, 56, 24, -34, -28, -2, 125, 19, 42, -9,
|
||||
124, -53, 24, -87, 11, 35, -81, -35, -125, -31, 123, -21,
|
||||
33, -91, 113, -93, 45, -6, 53, 38, -92, 8, -27, 87,
|
||||
4, 43, 43, 10, -128, -128, -46, 127, -38, -45, 25, -87,
|
||||
19, 5, 52, -96, -23, -29, 121, -126, -24, -20, -2, 69,
|
||||
-50, 6, 71, -81, -125, 90, -94, 1, -38, 36, 89, 17,
|
||||
-60, 71, -48, 18, -15, 44, -18, 59, 11, 114, -51, 32,
|
||||
110, 1, 4, 109, -24, 127, 27, 60, 88, 24, 45, -59,
|
||||
75, -36, 8, 57, -32, -25, 13, 126, -89, -61, -76, 127,
|
||||
18, -62, -68, 23, -113, 5, 126, 43, -88, 26, -78, 18,
|
||||
75, 21, 9, -74, 20, 41, 126, -118, -15, 9, 116, 126,
|
||||
-127, 34, -6, 126, -128, -53, -54, -55, -121, 70, 127, -12,
|
||||
-68, 82, -25, 104, -126, 126, -21, -26, 124, -75, -127, -120,
|
||||
13, 61, -64, -108, -63, -65, -44, -35, -61, -39, 109, -74,
|
||||
113, -3, 108, -30, 125, 120, 39, 125, -128, -95, -99, 111,
|
||||
9, 25, 114, -75, -92, -54, -12, -32, -38, 10, 31, 10,
|
||||
63, 51, 40, -99, 74, 4, 50, -128, -36, -35, -11, -28,
|
||||
-126, -7, 66, -58, -126, -22, -83, -61, -127, 49, 126, -8,
|
||||
7, 62, 36, -11, -32, -44, 63, 116, 41, 65, -127, 126,
|
||||
63, -30, -96, 74, -92, 127, 38, -18, -128, 68, -5, 101,
|
||||
-4, 85, 58, 79, 0, -58, 8, 119, -70, -1, -79, -68,
|
||||
114, -28, -90, -6, -112, 2, 127, -8, 10, 55, -59, -126,
|
||||
127, 125, 80, 72, 35, -54, 95, -124, -124, 79, 23, -46,
|
||||
-61, -127, -100, 99, -77, 8, -87, 5, -2, 49, 85, 7,
|
||||
-71, 82, 53, -41, 22, -22, -93, -103, 6, 52, -56, 14,
|
||||
-8, -111, 85, 16, 54, 32, -118, -24, 61, -53, 96, -70,
|
||||
-5, -17, -67, -84, -7, -82, -107, -96, 21, -83, -58, 50,
|
||||
12, -126, -1, -28, 34, -126, 115, 17, 91, 1, -127, 72,
|
||||
11, 126, -81, 6, 96, -8, 77, 15, -6, 63, -27, 20,
|
||||
-123, -109, 85, -79, -17, 126, -92, 2, -61, 20, 14, 17,
|
||||
121, 123, 30, 57, 120, 127, 57, 42, 117, 98, 67, 39,
|
||||
-20, -70, 100, 7, 125, 122, 40, 16, -79, 125, 83, 41,
|
||||
-106, -57, 24, 55, 27, -66, -111, -44, -7, -43, -66, 121,
|
||||
42, -128, -45, 35, 15, -127, 34, -35, -34, -40, -18, -6,
|
||||
63, 111, 31, 116, 127, 19, 24, -71, -39, 34, 11, 19,
|
||||
-40, 27, 12, 106, -10, 56, -82, -106, -2, -50, -52, 114,
|
||||
-126, -34, -43, -68, 10, 76, 57, -118, -128, 37, -104, 76,
|
||||
125, 3, -76, 127, -29, 84, -94, -15, 55, 125, 79, 127,
|
||||
-57, -125, 104, -68, 126, 126, -77, 51, 45, 33, -109, 115,
|
||||
-11, 1, 95, -121, -5, -9, -126, -114, 39, 68, -126, -107,
|
||||
-51, -42, 24, -8, 51, -27, -43, 66, -45, 62, -98, -109,
|
||||
69, 67, 0, -125, -128, 49, 31, 126, -122, 2, -55, -67,
|
||||
-126, -70, -128, -125, -77, 25, 16, -8, -102, 11, -75, 82,
|
||||
38, -5, 5, 19, 34, 47, -127, -93, 21, 24, -97, -18,
|
||||
31, 39, 34, -20, 22, 123, 7, -77, -81, -46, -9, 1,
|
||||
23, 39, -127, -43, -8, -50, 10, -21, 59, -9, -4, -13,
|
||||
-27, 44, 127, 52, -47, 70, -43, 52, 101, -49, 27, 45,
|
||||
49, 33, -125, 55, 114, 20, -1, 76, -24, -96, 105, 24,
|
||||
126, 75, -21, -105, 13, -42, 40, 126, -30, -39, -95, 125,
|
||||
-63, 11, 6, 125, 125, -14, 5, 42, -61, -4, 49, 88,
|
||||
6, -107, -28, 19, -29, 47, 126, 6, -46, -89, -18, 91,
|
||||
-20, -6, 118, -21, -22, 39, 115, 11, -42, 54, 73, -55,
|
||||
-77, 62, -27, -59, -99, -12, -127, -40, 56, -3, -124, -91,
|
||||
71, -111, 6, -19, 82, -24, -35, 102, -42, 7, -126, -126,
|
||||
-125, 18, 98, -52, 127, 105, -52, 40, -83, 126, -122, 109,
|
||||
5, 127, 48, 6, 5, -125, 100, -16, 29, 85, -89, 8,
|
||||
4, 41, 62, -127, 62, 122, 85, 122, -107, 8, -125, 93,
|
||||
-127, 127, 102, 19, 19, -66, 41, -42, 114, 127, -48, -117,
|
||||
-29, -6, -73, -102, -3, -19, 0, 88, 42, 87, -117, -20,
|
||||
2, 122, 28, 63, 71, 66, 120, 93, 124, -43, 49, 103,
|
||||
31, 90, -91, -22, -126, 26, -24, -21, 51, -126, 87, -103,
|
||||
-69, -10, -66, -23, 20, 97, 36, 25, -127, 30, -20, -63,
|
||||
30, 51, -116, 23, 40, -39, 36, -83, -77, -25, -50, 110,
|
||||
14, 13, -109, 125, -65, -55, -87, 124, -126, -32, -72, -108,
|
||||
127, 127, -125, -124, 61, 121, 102, -128, -127, 16, 100, 127,
|
||||
-124, -68, 72, -93, -128, 43, -93, -19, -125, -97, -113, -33,
|
||||
83, 127, -44, 127, -75, 127, 16, 44, 50, -122, 23, 118,
|
||||
46, 19, 26, -128, 10, 4, 99, -14, -82, -13, 30, 125,
|
||||
57, 65, 60, -71, 35, 98, 28, 7, 1, 43, 89, 70,
|
||||
75, 121, -59, 82, -126, -53, -16, -116, -65, 52, -52, 0,
|
||||
80, 35, 45, -61, 46, 8, 107, 27, -26, -118, 90, 57,
|
||||
-10, 7, -15, 0, -39, -4, 12, 29, -1, 116, 84, 79,
|
||||
119, 125, -59, 28, -6, -25, -43, 2, 90, 79, 67, 103,
|
||||
-82, 2, -6, 125, 19, 73, 0, -105, 112, -17, 104, 107,
|
||||
124, 106, 19, 56, -44, 55, -112, 6, -39, -83, 126, -93,
|
||||
-98, 57, -120, -23, -38, 2, -31, -48, 106, 127, 127, 69,
|
||||
16, 110, 71, 104, 62, -12, -22, 42, -37, -94, 34, -1,
|
||||
-32, -12, -124, -47, -13, 60, -75, -66, 58, -127, -2, 64,
|
||||
76, -106, 73, -49, -31, 127, 126, 31, 16, 127, -110, 107,
|
||||
-16, -53, 20, 69, -14, -125, 59, -44, 15, 120, 125, 125,
|
||||
43, 6, 19, -58, 127, 127, 43, 16, 82, 97, -127, 127,
|
||||
-93, -41, 88, 0, 77, -15, 116, 16, -124, -31, -3, 95,
|
||||
-40, -126, -54, -126, -83, -8, -59, 6, 67, -29, 4, 124,
|
||||
-10, 112, -28, -8, 85, -21, 45, 84, 6, -8, 11, 72,
|
||||
32, 84, -62, 77, 2, -36, 75, 31, -50, 116, 126, 119,
|
||||
-88, -55, -14, -37, 126, 40, -108, -6, -6, 57, 64, -28,
|
||||
-76, 30, -117, -93, 31, -92, -44, -64, 94, 58, 65, 114,
|
||||
41, 47, 71, 42, -26, 99, -126, 57, -5, 74, -19, -113,
|
||||
-1, 67, -21, 126, 1, -3, 33, 60, -82, 37, -48, 89,
|
||||
114, -38, 127, -114, 35, 58, -5, 21, -46, 121, -123, -43,
|
||||
127, 115, 123, 122, -101, 126, 127, 81, 52, 89, -127, 102,
|
||||
42, 117, -9, -2, 125, 127, 110, 96, 120, 66, 70, 124,
|
||||
55, 84, -38, -58, 119, -127, -16, -79, 123, 18, -127, -50,
|
||||
-38, 120, -85, 1, 7, -56, 108, -77, -2, 21, 37, 1,
|
||||
13, -105, -69, 28, -87, 33, -104, -51, 126, 41, 3, -121,
|
||||
28, 71, 58, 86, -8, 127, 94, -55, 125, 40, -19, 127,
|
||||
-33, -87, -23, 7, -111, -68, 9, 84, -119, 55, -82, 78,
|
||||
-37, -20, -9, -23, 53, -13, 15, -46, 116, 126, -127, 56,
|
||||
-126, 125, -7, -1, 45, 26, 125, 121, 29, 47, -86, 30,
|
||||
10, 76, -125, -7, 23, 92, -12, -39, -18, 92, -97, -8,
|
||||
-85, -41, 49, -50, 123, -37, -126, -30, 14, 79, -49, -65,
|
||||
9, -36, -38, -96, 85, -24, -13, 37, -25, -5, -64, -127,
|
||||
55, -60, -18, -61, -63, 127, 56, 67, 15, 124, 72, 120,
|
||||
127, 40, -10, 114, 24, -23, 46, 78, -53, 125, 86, 124,
|
||||
86, 0, 38, 93, 21, 127, 123, 75, -72, 13, 48, 33,
|
||||
83, -51, 15, -32, -49, -33, 120, 64, 7, 9, 65, 60,
|
||||
21, -21, -61, -53, -113, 84, -97, 101, 37, -114, -27, 41,
|
||||
73, 126, -10, 59, 61, -15, 70, -13, 82, -4, 69, 56,
|
||||
94, -91, -50, 92, -74, -48, 53, -7, -107, 127, 28, 30,
|
||||
-26, -21, -61, 77, 82, 64, -91, -125, 122, -104, 127, 123,
|
||||
122, 123, 76, -126, 127, -6, -80, 7, 40, -66, -65, 54,
|
||||
-2, 23, 96, -64, 74, 2, -53, -12, -123, 39, 60, -20,
|
||||
16, -17, -97, 23, -4, -53, -122, 32, -16, -54, -95, 43,
|
||||
71, -1, -67, -33, 41, 18, 72, 28, -83, 31, -100, -91,
|
||||
-27, 10, -128, -106, 2, 76, -13, 42, 34, 112, -19, 44,
|
||||
40, -9, -11, 65, 92, -43, -125, 2, 47, -32, 25, 122,
|
||||
-29, 12, 101, -8, -126, -23, 43, 7, 125, -20, -124, 82,
|
||||
-2, 13, -73, -106, 115, 31, 116, -23, -44, -71, 84, 3,
|
||||
47, 91, 127, 127, -15, 95, 7, 93, 5, 113, -50, 54,
|
||||
11, 13, -127, 17, 72, 43, -23, 5, -70, 20, 15, -27,
|
||||
99, 69, -109, -122, -94, 16, 127, 0, 116, 104, 45, 108,
|
||||
-34, 87, 72, -14, 118, 46, 42, 109, -26, 95, 93, 127,
|
||||
60, 127, -93, -54, -122, 34, -105, 56, 55, 103, 125, -71,
|
||||
-50, 95, -72, 127, 107, 21, 73, 126, 61, 127, 127, 24,
|
||||
-62, 90, 73, 90, -46, -78, -124, 72, 123, -42, 50, -107,
|
||||
17, -32, -62, -89, 124, 1, 80, -2, 117, 119, -65, -127,
|
||||
-95, -121, -52, 103, 66, 75, -3, -62, -127, 127, -74, 124,
|
||||
79, 49, 40, 105, -67, -71, -70, 43, 127, 119, -4, 66,
|
||||
43, 23, 91, -126, 15, 63, -119, 112, 103, 15, -99, 31,
|
||||
-127, 69, 116, -46, -67, 2, -126, -29, 30, 30, -69, -98,
|
||||
-47, -87, -70, -127, 23, -73, 30, -7, 94, -52, -65, 98,
|
||||
-45, 97, 53, 23, -9, -22, -52, -47, 6, -1, -85, -15,
|
||||
-61, -14, 68, 110, -10, -121, -25, -35, -15, -94, -123, 27,
|
||||
75, 48, -66, -56, -44, 93, 109, 67, -36, 24, 70, -126,
|
||||
8, -127, 126, 52, 11, -32, 120, -13, -26, -28, -125, 127,
|
||||
106, -50, 124, 36, -126, -12, 0, -23, 76, -71, -126, -12,
|
||||
-17, -82, 12, 124, 57, 33, 4, 77, -46, 71, -34, 72,
|
||||
125, -128, 124, -24, -128, 75, -120, 69, -45, 55, 33, 127,
|
||||
-33, 4, -105, -41, -59, -91, 123, 44, -127, 127, -67, 52,
|
||||
25, -125, -65, 100, -25, 123, 6, 11, -123, -92, -33, 126,
|
||||
-17, -4, 29, 33, 127, 96, 3, 87, -48, -18, -70, 123,
|
||||
58, -127, -3, -52, -1, -36, -41, 127, 51, -52, -27, 46,
|
||||
-83, 57, 9, 126, 127, 94, 79, -37, -127, -40, 67, 52,
|
||||
82, -66, 122, -13, -73, 127, -8, -80, 46, -48, 4, -54,
|
||||
]
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
//! Saturation protector that recommends headroom based on recent peaks.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/saturation_protector.h/.cc`.
|
||||
|
||||
use crate::common::{FRAME_DURATION_MS, MIN_LEVEL_DBFS, VAD_CONFIDENCE_THRESHOLD};
|
||||
use crate::saturation_protector_buffer::SaturationProtectorBuffer;
|
||||
|
||||
const PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS: i32 = 400;
|
||||
const MIN_MARGIN_DB: f32 = 12.0;
|
||||
const MAX_MARGIN_DB: f32 = 25.0;
|
||||
const ATTACK: f32 = 0.998_849_4;
|
||||
const DECAY: f32 = 0.999_769_75;
|
||||
|
||||
/// Saturation protector state. Used for check-pointing and restore ops.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct SaturationProtectorState {
|
||||
headroom_db: f32,
|
||||
peak_delay_buffer: SaturationProtectorBuffer,
|
||||
max_peaks_dbfs: f32,
|
||||
time_since_push_ms: i32,
|
||||
}
|
||||
|
||||
/// Resets the saturation protector state.
|
||||
fn reset_saturation_protector_state(
|
||||
initial_headroom_db: f32,
|
||||
state: &mut SaturationProtectorState,
|
||||
) {
|
||||
state.headroom_db = initial_headroom_db;
|
||||
state.peak_delay_buffer.reset();
|
||||
state.max_peaks_dbfs = MIN_LEVEL_DBFS;
|
||||
state.time_since_push_ms = 0;
|
||||
}
|
||||
|
||||
/// Updates `state` by analyzing the estimated speech level and the peak level.
|
||||
fn update_saturation_protector_state(
|
||||
peak_dbfs: f32,
|
||||
speech_level_dbfs: f32,
|
||||
state: &mut SaturationProtectorState,
|
||||
) {
|
||||
// Get the max peak over `PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS` ms.
|
||||
state.max_peaks_dbfs = state.max_peaks_dbfs.max(peak_dbfs);
|
||||
state.time_since_push_ms += FRAME_DURATION_MS;
|
||||
if state.time_since_push_ms > PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS {
|
||||
// Push `max_peaks_dbfs` back into the ring buffer.
|
||||
state.peak_delay_buffer.push_back(state.max_peaks_dbfs);
|
||||
// Reset.
|
||||
state.max_peaks_dbfs = MIN_LEVEL_DBFS;
|
||||
state.time_since_push_ms = 0;
|
||||
}
|
||||
|
||||
// Update the headroom by comparing the estimated speech level and the delayed
|
||||
// max speech peak.
|
||||
let delayed_peak_dbfs = state
|
||||
.peak_delay_buffer
|
||||
.front()
|
||||
.unwrap_or(state.max_peaks_dbfs);
|
||||
let difference_db = delayed_peak_dbfs - speech_level_dbfs;
|
||||
if difference_db > state.headroom_db {
|
||||
// Attack.
|
||||
state.headroom_db = state.headroom_db * ATTACK + difference_db * (1.0 - ATTACK);
|
||||
} else {
|
||||
// Decay.
|
||||
state.headroom_db = state.headroom_db * DECAY + difference_db * (1.0 - DECAY);
|
||||
}
|
||||
|
||||
state.headroom_db = state.headroom_db.clamp(MIN_MARGIN_DB, MAX_MARGIN_DB);
|
||||
}
|
||||
|
||||
/// Saturation protector which recommends a headroom based on the recent peaks.
|
||||
#[derive(Debug)]
|
||||
pub struct SaturationProtector {
|
||||
initial_headroom_db: f32,
|
||||
adjacent_speech_frames_threshold: i32,
|
||||
num_adjacent_speech_frames: i32,
|
||||
headroom_db: f32,
|
||||
preliminary_state: SaturationProtectorState,
|
||||
reliable_state: SaturationProtectorState,
|
||||
}
|
||||
|
||||
impl SaturationProtector {
|
||||
/// Creates a new saturation protector that starts at `initial_headroom_db`.
|
||||
pub fn new(initial_headroom_db: f32, adjacent_speech_frames_threshold: i32) -> Self {
|
||||
let mut sp = Self {
|
||||
initial_headroom_db,
|
||||
adjacent_speech_frames_threshold,
|
||||
num_adjacent_speech_frames: 0,
|
||||
headroom_db: initial_headroom_db,
|
||||
preliminary_state: SaturationProtectorState {
|
||||
headroom_db: initial_headroom_db,
|
||||
peak_delay_buffer: SaturationProtectorBuffer::default(),
|
||||
max_peaks_dbfs: MIN_LEVEL_DBFS,
|
||||
time_since_push_ms: 0,
|
||||
},
|
||||
reliable_state: SaturationProtectorState {
|
||||
headroom_db: initial_headroom_db,
|
||||
peak_delay_buffer: SaturationProtectorBuffer::default(),
|
||||
max_peaks_dbfs: MIN_LEVEL_DBFS,
|
||||
time_since_push_ms: 0,
|
||||
},
|
||||
};
|
||||
sp.reset();
|
||||
sp
|
||||
}
|
||||
|
||||
/// Returns the recommended headroom in dB.
|
||||
pub fn headroom_db(&self) -> f32 {
|
||||
self.headroom_db
|
||||
}
|
||||
|
||||
/// Analyzes the peak level of a 10 ms frame along with its speech probability
|
||||
/// and the current speech level estimate to update the recommended headroom.
|
||||
pub fn analyze(&mut self, speech_probability: f32, peak_dbfs: f32, speech_level_dbfs: f32) {
|
||||
if speech_probability < VAD_CONFIDENCE_THRESHOLD {
|
||||
// Not a speech frame.
|
||||
if self.adjacent_speech_frames_threshold > 1 {
|
||||
if self.num_adjacent_speech_frames >= self.adjacent_speech_frames_threshold {
|
||||
// First non-speech frame after a long enough sequence of speech
|
||||
// frames. Update the reliable state.
|
||||
self.reliable_state = self.preliminary_state.clone();
|
||||
} else if self.num_adjacent_speech_frames > 0 {
|
||||
// First non-speech frame after a too short sequence of speech
|
||||
// frames. Reset to the last reliable state.
|
||||
self.preliminary_state = self.reliable_state.clone();
|
||||
}
|
||||
}
|
||||
self.num_adjacent_speech_frames = 0;
|
||||
} else {
|
||||
// Speech frame observed.
|
||||
self.num_adjacent_speech_frames += 1;
|
||||
|
||||
// Update preliminary level estimate.
|
||||
update_saturation_protector_state(
|
||||
peak_dbfs,
|
||||
speech_level_dbfs,
|
||||
&mut self.preliminary_state,
|
||||
);
|
||||
|
||||
if self.num_adjacent_speech_frames >= self.adjacent_speech_frames_threshold {
|
||||
// `preliminary_state` is now reliable. Update the headroom.
|
||||
self.headroom_db = self.preliminary_state.headroom_db;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the internal state.
|
||||
pub fn reset(&mut self) {
|
||||
self.num_adjacent_speech_frames = 0;
|
||||
self.headroom_db = self.initial_headroom_db;
|
||||
reset_saturation_protector_state(self.initial_headroom_db, &mut self.preliminary_state);
|
||||
reset_saturation_protector_state(self.initial_headroom_db, &mut self.reliable_state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::common::FRAME_DURATION_MS;
|
||||
|
||||
const INITIAL_HEADROOM_DB: f32 = 20.0;
|
||||
const NO_ADJACENT_SPEECH_FRAMES_REQUIRED: i32 = 1;
|
||||
const MAX_SPEECH_PROBABILITY: f32 = 1.0;
|
||||
|
||||
/// Calls `analyze` `num_iterations` times and returns the largest
|
||||
/// headroom difference between two consecutive calls.
|
||||
fn run_on_constant_level(
|
||||
num_iterations: i32,
|
||||
speech_probability: f32,
|
||||
peak_dbfs: f32,
|
||||
speech_level_dbfs: f32,
|
||||
saturation_protector: &mut SaturationProtector,
|
||||
) -> f32 {
|
||||
let mut last_headroom = saturation_protector.headroom_db();
|
||||
let mut max_difference = 0.0_f32;
|
||||
for _ in 0..num_iterations {
|
||||
saturation_protector.analyze(speech_probability, peak_dbfs, speech_level_dbfs);
|
||||
let new_headroom = saturation_protector.headroom_db();
|
||||
max_difference = max_difference.max((new_headroom - last_headroom).abs());
|
||||
last_headroom = new_headroom;
|
||||
}
|
||||
max_difference
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset() {
|
||||
let mut sp =
|
||||
SaturationProtector::new(INITIAL_HEADROOM_DB, NO_ADJACENT_SPEECH_FRAMES_REQUIRED);
|
||||
let initial_headroom_db = sp.headroom_db();
|
||||
run_on_constant_level(10, MAX_SPEECH_PROBABILITY, 0.0, -10.0, &mut sp);
|
||||
// Make sure that there are side-effects.
|
||||
assert_ne!(initial_headroom_db, sp.headroom_db());
|
||||
sp.reset();
|
||||
assert_eq!(initial_headroom_db, sp.headroom_db());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimates_crest_ratio() {
|
||||
let num_iterations = 2000;
|
||||
let peak_level_dbfs = -20.0;
|
||||
let crest_factor_db = INITIAL_HEADROOM_DB + 1.0;
|
||||
let speech_level_dbfs = peak_level_dbfs - crest_factor_db;
|
||||
let max_difference_db = 0.5 * (INITIAL_HEADROOM_DB - crest_factor_db).abs();
|
||||
|
||||
let mut sp =
|
||||
SaturationProtector::new(INITIAL_HEADROOM_DB, NO_ADJACENT_SPEECH_FRAMES_REQUIRED);
|
||||
run_on_constant_level(
|
||||
num_iterations,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
peak_level_dbfs,
|
||||
speech_level_dbfs,
|
||||
&mut sp,
|
||||
);
|
||||
assert!(
|
||||
(sp.headroom_db() - crest_factor_db).abs() <= max_difference_db,
|
||||
"headroom {} should be near crest_factor {}",
|
||||
sp.headroom_db(),
|
||||
crest_factor_db
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_slowly() {
|
||||
let num_iterations = 1000;
|
||||
let peak_level_dbfs = -20.0;
|
||||
let crest_factor_db = INITIAL_HEADROOM_DB - 5.0;
|
||||
let other_crest_factor_db = INITIAL_HEADROOM_DB;
|
||||
let speech_level_dbfs = peak_level_dbfs - crest_factor_db;
|
||||
let other_speech_level_dbfs = peak_level_dbfs - other_crest_factor_db;
|
||||
|
||||
let mut sp =
|
||||
SaturationProtector::new(INITIAL_HEADROOM_DB, NO_ADJACENT_SPEECH_FRAMES_REQUIRED);
|
||||
let mut max_difference_db = run_on_constant_level(
|
||||
num_iterations,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
peak_level_dbfs,
|
||||
speech_level_dbfs,
|
||||
&mut sp,
|
||||
);
|
||||
max_difference_db = max_difference_db.max(run_on_constant_level(
|
||||
num_iterations,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
peak_level_dbfs,
|
||||
other_speech_level_dbfs,
|
||||
&mut sp,
|
||||
));
|
||||
let max_change_speed_db_per_second = 0.5; // 1 db / 2 seconds.
|
||||
assert!(
|
||||
max_difference_db <= max_change_speed_db_per_second / 1000.0 * FRAME_DURATION_MS as f32,
|
||||
"max_difference_db {max_difference_db} exceeds max change speed"
|
||||
);
|
||||
}
|
||||
|
||||
// Parametrized tests for adjacent_speech_frames_threshold = 2, 9, 17.
|
||||
|
||||
#[test]
|
||||
fn do_not_adapt_to_short_speech_segments_threshold_2() {
|
||||
do_not_adapt_to_short_speech_segments(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_adapt_to_short_speech_segments_threshold_9() {
|
||||
do_not_adapt_to_short_speech_segments(9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_adapt_to_short_speech_segments_threshold_17() {
|
||||
do_not_adapt_to_short_speech_segments(17);
|
||||
}
|
||||
|
||||
fn do_not_adapt_to_short_speech_segments(threshold: i32) {
|
||||
let mut sp = SaturationProtector::new(INITIAL_HEADROOM_DB, threshold);
|
||||
let initial_headroom_db = sp.headroom_db();
|
||||
run_on_constant_level(threshold - 1, MAX_SPEECH_PROBABILITY, 0.0, -10.0, &mut sp);
|
||||
// No adaptation expected.
|
||||
assert_eq!(initial_headroom_db, sp.headroom_db());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapt_to_enough_speech_segments_threshold_2() {
|
||||
adapt_to_enough_speech_segments(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapt_to_enough_speech_segments_threshold_9() {
|
||||
adapt_to_enough_speech_segments(9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapt_to_enough_speech_segments_threshold_17() {
|
||||
adapt_to_enough_speech_segments(17);
|
||||
}
|
||||
|
||||
fn adapt_to_enough_speech_segments(threshold: i32) {
|
||||
let mut sp = SaturationProtector::new(INITIAL_HEADROOM_DB, threshold);
|
||||
let initial_headroom_db = sp.headroom_db();
|
||||
run_on_constant_level(threshold + 1, MAX_SPEECH_PROBABILITY, 0.0, -10.0, &mut sp);
|
||||
// Adaptation expected.
|
||||
assert_ne!(initial_headroom_db, sp.headroom_db());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Ring buffer for the saturation protector.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/saturation_protector_buffer.h/.cc`.
|
||||
|
||||
use crate::common::SATURATION_PROTECTOR_BUFFER_SIZE;
|
||||
|
||||
/// Ring buffer that supports push back and read oldest item.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SaturationProtectorBuffer {
|
||||
buffer: [f32; SATURATION_PROTECTOR_BUFFER_SIZE],
|
||||
next: usize,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
impl Default for SaturationProtectorBuffer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
buffer: [0.0; SATURATION_PROTECTOR_BUFFER_SIZE],
|
||||
next: 0,
|
||||
size: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for SaturationProtectorBuffer {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
if self.size != other.size {
|
||||
return false;
|
||||
}
|
||||
let mut i0 = self.front_index();
|
||||
let mut i1 = other.front_index();
|
||||
#[allow(clippy::explicit_counter_loop, reason = "upstream logic")]
|
||||
for _ in 0..self.size {
|
||||
if self.buffer[i0 % SATURATION_PROTECTOR_BUFFER_SIZE]
|
||||
!= other.buffer[i1 % SATURATION_PROTECTOR_BUFFER_SIZE]
|
||||
{
|
||||
return false;
|
||||
}
|
||||
i0 += 1;
|
||||
i1 += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for SaturationProtectorBuffer {}
|
||||
|
||||
impl SaturationProtectorBuffer {
|
||||
/// Returns the number of items currently in the buffer.
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
|
||||
/// Returns the total capacity of the buffer.
|
||||
pub fn capacity(&self) -> usize {
|
||||
SATURATION_PROTECTOR_BUFFER_SIZE
|
||||
}
|
||||
|
||||
/// Resets the buffer to empty.
|
||||
pub fn reset(&mut self) {
|
||||
self.next = 0;
|
||||
self.size = 0;
|
||||
}
|
||||
|
||||
/// Pushes `v` to the back. If full, the oldest value is replaced.
|
||||
pub fn push_back(&mut self, v: f32) {
|
||||
self.buffer[self.next] = v;
|
||||
self.next += 1;
|
||||
if self.next == SATURATION_PROTECTOR_BUFFER_SIZE {
|
||||
self.next = 0;
|
||||
}
|
||||
if self.size < SATURATION_PROTECTOR_BUFFER_SIZE {
|
||||
self.size += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the oldest item, or `None` if empty.
|
||||
pub fn front(&self) -> Option<f32> {
|
||||
if self.size == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(self.buffer[self.front_index()])
|
||||
}
|
||||
|
||||
fn front_index(&self) -> usize {
|
||||
if self.size == SATURATION_PROTECTOR_BUFFER_SIZE {
|
||||
self.next
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn push_and_front() {
|
||||
let mut buffer = SaturationProtectorBuffer::default();
|
||||
buffer.push_back(1.0);
|
||||
assert_eq!(buffer.size, 1);
|
||||
assert_eq!(buffer.front(), Some(1.0));
|
||||
|
||||
buffer.push_back(2.0);
|
||||
assert_eq!(buffer.size, 2);
|
||||
assert_eq!(buffer.front(), Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_around() {
|
||||
let mut buffer = SaturationProtectorBuffer::default();
|
||||
for i in 0..SATURATION_PROTECTOR_BUFFER_SIZE {
|
||||
buffer.push_back(i as f32);
|
||||
}
|
||||
assert_eq!(buffer.size, SATURATION_PROTECTOR_BUFFER_SIZE);
|
||||
assert_eq!(buffer.front(), Some(0.0));
|
||||
|
||||
// Overflow: oldest (0.0) is replaced.
|
||||
buffer.push_back(100.0);
|
||||
assert_eq!(buffer.size, SATURATION_PROTECTOR_BUFFER_SIZE);
|
||||
assert_eq!(buffer.front(), Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset() {
|
||||
let mut buffer = SaturationProtectorBuffer::default();
|
||||
buffer.push_back(1.0);
|
||||
buffer.push_back(2.0);
|
||||
buffer.reset();
|
||||
assert_eq!(buffer.size, 0);
|
||||
assert_eq!(buffer.front(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equality() {
|
||||
let mut a = SaturationProtectorBuffer::default();
|
||||
let mut b = SaturationProtectorBuffer::default();
|
||||
assert_eq!(a, b);
|
||||
|
||||
a.push_back(1.0);
|
||||
assert_ne!(a, b);
|
||||
|
||||
b.push_back(1.0);
|
||||
assert_eq!(a, b);
|
||||
|
||||
// Same logical content but different internal state.
|
||||
a.push_back(2.0);
|
||||
a.push_back(3.0);
|
||||
b.push_back(2.0);
|
||||
b.push_back(3.0);
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
//! Speech level estimator based on framewise RMS and speech probability.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/speech_level_estimator_impl.h/.cc`.
|
||||
//!
|
||||
//! The C++ code has a factory pattern with a field trial for an experimental
|
||||
//! implementation. We port only the default `SpeechLevelEstimatorImpl`.
|
||||
|
||||
use crate::common::{
|
||||
FRAME_DURATION_MS, LEVEL_ESTIMATOR_LEAK_FACTOR, LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS,
|
||||
SATURATION_PROTECTOR_INITIAL_HEADROOM_DB, VAD_CONFIDENCE_THRESHOLD,
|
||||
};
|
||||
|
||||
fn clamp_level_estimate_dbfs(level_estimate_dbfs: f32) -> f32 {
|
||||
level_estimate_dbfs.clamp(-90.0, 30.0)
|
||||
}
|
||||
|
||||
/// Configuration for the adaptive digital gain controller.
|
||||
///
|
||||
/// Mirrors `AudioProcessing::Config::GainController2::AdaptiveDigital` from C++.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AdaptiveDigitalConfig {
|
||||
pub headroom_db: f32,
|
||||
pub max_gain_db: f32,
|
||||
pub initial_gain_db: f32,
|
||||
pub max_gain_change_db_per_second: f32,
|
||||
pub max_output_noise_level_dbfs: f32,
|
||||
}
|
||||
|
||||
impl Default for AdaptiveDigitalConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
headroom_db: 5.0,
|
||||
max_gain_db: 50.0,
|
||||
initial_gain_db: 15.0,
|
||||
max_gain_change_db_per_second: 6.0,
|
||||
max_output_noise_level_dbfs: -50.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the initial speech level estimate needed to apply the initial gain.
|
||||
fn get_initial_speech_level_estimate_dbfs(config: &AdaptiveDigitalConfig) -> f32 {
|
||||
clamp_level_estimate_dbfs(
|
||||
-SATURATION_PROTECTOR_INITIAL_HEADROOM_DB - config.initial_gain_db - config.headroom_db,
|
||||
)
|
||||
}
|
||||
|
||||
/// Part of the level estimator state used for check-pointing and restore ops.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct LevelEstimatorState {
|
||||
/// Time remaining until the estimator becomes confident.
|
||||
time_to_confidence_ms: i32,
|
||||
/// Weighted ratio for level estimation.
|
||||
level_dbfs: Ratio,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Ratio {
|
||||
numerator: f32,
|
||||
denominator: f32,
|
||||
}
|
||||
|
||||
impl Ratio {
|
||||
fn get_ratio(&self) -> f32 {
|
||||
debug_assert!(self.denominator != 0.0);
|
||||
self.numerator / self.denominator
|
||||
}
|
||||
}
|
||||
|
||||
/// Active speech level estimator based on the analysis of the following
|
||||
/// framewise properties: RMS level (dBFS), speech probability.
|
||||
#[derive(Debug)]
|
||||
pub struct SpeechLevelEstimator {
|
||||
initial_speech_level_dbfs: f32,
|
||||
adjacent_speech_frames_threshold: i32,
|
||||
preliminary_state: LevelEstimatorState,
|
||||
reliable_state: LevelEstimatorState,
|
||||
level_dbfs: f32,
|
||||
is_confident: bool,
|
||||
num_adjacent_speech_frames: i32,
|
||||
}
|
||||
|
||||
impl SpeechLevelEstimator {
|
||||
/// Creates a new speech level estimator.
|
||||
pub fn new(config: &AdaptiveDigitalConfig, adjacent_speech_frames_threshold: i32) -> Self {
|
||||
debug_assert!(adjacent_speech_frames_threshold >= 1);
|
||||
let initial_speech_level_dbfs = get_initial_speech_level_estimate_dbfs(config);
|
||||
let mut est = Self {
|
||||
initial_speech_level_dbfs,
|
||||
adjacent_speech_frames_threshold,
|
||||
preliminary_state: LevelEstimatorState {
|
||||
time_to_confidence_ms: 0,
|
||||
level_dbfs: Ratio {
|
||||
numerator: 0.0,
|
||||
denominator: 1.0,
|
||||
},
|
||||
},
|
||||
reliable_state: LevelEstimatorState {
|
||||
time_to_confidence_ms: 0,
|
||||
level_dbfs: Ratio {
|
||||
numerator: 0.0,
|
||||
denominator: 1.0,
|
||||
},
|
||||
},
|
||||
level_dbfs: initial_speech_level_dbfs,
|
||||
is_confident: false,
|
||||
num_adjacent_speech_frames: 0,
|
||||
};
|
||||
est.reset();
|
||||
est
|
||||
}
|
||||
|
||||
/// Updates the level estimation.
|
||||
pub fn update(&mut self, rms_dbfs: f32, speech_probability: f32) {
|
||||
debug_assert!(rms_dbfs > -150.0);
|
||||
debug_assert!(rms_dbfs < 50.0);
|
||||
debug_assert!(speech_probability >= 0.0);
|
||||
debug_assert!(speech_probability <= 1.0);
|
||||
|
||||
if speech_probability < VAD_CONFIDENCE_THRESHOLD {
|
||||
// Not a speech frame.
|
||||
if self.adjacent_speech_frames_threshold > 1 {
|
||||
// When two or more adjacent speech frames are required in order to
|
||||
// update the state, we need to decide whether to discard or confirm
|
||||
// the updates based on the speech sequence length.
|
||||
if self.num_adjacent_speech_frames >= self.adjacent_speech_frames_threshold {
|
||||
// First non-speech frame after a long enough sequence of speech
|
||||
// frames. Update the reliable state.
|
||||
self.reliable_state = self.preliminary_state;
|
||||
} else if self.num_adjacent_speech_frames > 0 {
|
||||
// First non-speech frame after a too short sequence of speech
|
||||
// frames. Reset to the last reliable state.
|
||||
self.preliminary_state = self.reliable_state;
|
||||
}
|
||||
}
|
||||
self.num_adjacent_speech_frames = 0;
|
||||
} else {
|
||||
// Speech frame observed.
|
||||
self.num_adjacent_speech_frames += 1;
|
||||
|
||||
// Update preliminary level estimate.
|
||||
debug_assert!(self.preliminary_state.time_to_confidence_ms >= 0);
|
||||
let buffer_is_full = self.preliminary_state.time_to_confidence_ms == 0;
|
||||
if !buffer_is_full {
|
||||
self.preliminary_state.time_to_confidence_ms -= FRAME_DURATION_MS;
|
||||
}
|
||||
// Weighted average of levels with speech probability as weight.
|
||||
debug_assert!(speech_probability > 0.0);
|
||||
let leak_factor = if buffer_is_full {
|
||||
LEVEL_ESTIMATOR_LEAK_FACTOR
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
self.preliminary_state.level_dbfs.numerator =
|
||||
self.preliminary_state.level_dbfs.numerator * leak_factor
|
||||
+ rms_dbfs * speech_probability;
|
||||
self.preliminary_state.level_dbfs.denominator =
|
||||
self.preliminary_state.level_dbfs.denominator * leak_factor + speech_probability;
|
||||
|
||||
let level_dbfs = self.preliminary_state.level_dbfs.get_ratio();
|
||||
|
||||
if self.num_adjacent_speech_frames >= self.adjacent_speech_frames_threshold {
|
||||
// `preliminary_state` is now reliable. Update the last level estimation.
|
||||
self.level_dbfs = clamp_level_estimate_dbfs(level_dbfs);
|
||||
}
|
||||
}
|
||||
self.update_is_confident();
|
||||
}
|
||||
|
||||
/// Returns the estimated speech plus noise level.
|
||||
pub fn level_dbfs(&self) -> f32 {
|
||||
self.level_dbfs
|
||||
}
|
||||
|
||||
/// Returns true if the estimator is confident on its current estimate.
|
||||
pub fn is_confident(&self) -> bool {
|
||||
self.is_confident
|
||||
}
|
||||
|
||||
/// Resets the estimator.
|
||||
pub fn reset(&mut self) {
|
||||
self.preliminary_state = self.make_initial_state();
|
||||
self.reliable_state = self.make_initial_state();
|
||||
self.level_dbfs = self.initial_speech_level_dbfs;
|
||||
self.is_confident = false;
|
||||
self.num_adjacent_speech_frames = 0;
|
||||
}
|
||||
|
||||
fn update_is_confident(&mut self) {
|
||||
if self.adjacent_speech_frames_threshold == 1 {
|
||||
// Ignore `reliable_state` when a single frame is enough to update the
|
||||
// level estimate (because it is not used).
|
||||
self.is_confident = self.preliminary_state.time_to_confidence_ms == 0;
|
||||
return;
|
||||
}
|
||||
// Once confident, it remains confident.
|
||||
// During the first long enough speech sequence, `reliable_state` must be
|
||||
// ignored since `preliminary_state` is used.
|
||||
self.is_confident = self.reliable_state.time_to_confidence_ms == 0
|
||||
|| (self.num_adjacent_speech_frames >= self.adjacent_speech_frames_threshold
|
||||
&& self.preliminary_state.time_to_confidence_ms == 0);
|
||||
}
|
||||
|
||||
fn make_initial_state(&self) -> LevelEstimatorState {
|
||||
LevelEstimatorState {
|
||||
time_to_confidence_ms: LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS as i32,
|
||||
level_dbfs: Ratio {
|
||||
numerator: self.initial_speech_level_dbfs,
|
||||
denominator: 1.0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Number of speech frames that the level estimator must observe in order to
|
||||
/// become confident about the estimated level.
|
||||
const NUM_FRAMES_TO_CONFIDENCE: i32 =
|
||||
LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS as i32 / FRAME_DURATION_MS;
|
||||
|
||||
const CONVERGENCE_SPEED_TESTS_LEVEL_TOLERANCE: f32 = 0.5;
|
||||
|
||||
const NO_SPEECH_PROBABILITY: f32 = 0.0;
|
||||
const LOW_SPEECH_PROBABILITY: f32 = VAD_CONFIDENCE_THRESHOLD / 2.0;
|
||||
const MAX_SPEECH_PROBABILITY: f32 = 1.0;
|
||||
|
||||
/// Provides the level values `num_iterations` times to `level_estimator`.
|
||||
fn run_on_constant_level(
|
||||
num_iterations: i32,
|
||||
rms_dbfs: f32,
|
||||
speech_probability: f32,
|
||||
level_estimator: &mut SpeechLevelEstimator,
|
||||
) {
|
||||
for _ in 0..num_iterations {
|
||||
level_estimator.update(rms_dbfs, speech_probability);
|
||||
}
|
||||
}
|
||||
|
||||
/// Level estimator helper for tests.
|
||||
struct TestLevelEstimator {
|
||||
estimator: SpeechLevelEstimator,
|
||||
initial_speech_level_dbfs: f32,
|
||||
level_rms_dbfs: f32,
|
||||
level_peak_dbfs: f32,
|
||||
}
|
||||
|
||||
impl TestLevelEstimator {
|
||||
fn new(adjacent_speech_frames_threshold: i32) -> Self {
|
||||
let config = AdaptiveDigitalConfig::default();
|
||||
let estimator = SpeechLevelEstimator::new(&config, adjacent_speech_frames_threshold);
|
||||
let initial_speech_level_dbfs = estimator.level_dbfs();
|
||||
let level_rms_dbfs = initial_speech_level_dbfs / 2.0;
|
||||
let level_peak_dbfs = initial_speech_level_dbfs / 3.0;
|
||||
debug_assert!(level_rms_dbfs < level_peak_dbfs);
|
||||
debug_assert!(initial_speech_level_dbfs < level_rms_dbfs);
|
||||
debug_assert!(
|
||||
level_rms_dbfs - initial_speech_level_dbfs > 5.0,
|
||||
"Adjust `level_rms_dbfs` so that the difference from the initial \
|
||||
level is wide enough for the tests"
|
||||
);
|
||||
Self {
|
||||
estimator,
|
||||
initial_speech_level_dbfs,
|
||||
level_rms_dbfs,
|
||||
level_peak_dbfs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn level_stabilizes() {
|
||||
let mut t = TestLevelEstimator::new(1);
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
let estimated_level_dbfs = t.estimator.level_dbfs();
|
||||
run_on_constant_level(
|
||||
1,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
assert!(
|
||||
(t.estimator.level_dbfs() - estimated_level_dbfs).abs() < 0.1,
|
||||
"level {} should be near {}",
|
||||
t.estimator.level_dbfs(),
|
||||
estimated_level_dbfs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_not_confident() {
|
||||
let mut t = TestLevelEstimator::new(1);
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE / 2,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
assert!(!t.estimator.is_confident());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_confident() {
|
||||
let mut t = TestLevelEstimator::new(1);
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
assert!(t.estimator.is_confident());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimator_ignores_non_speech_frames() {
|
||||
let mut t = TestLevelEstimator::new(1);
|
||||
// Simulate speech.
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
let estimated_level_dbfs = t.estimator.level_dbfs();
|
||||
// Simulate full-scale non-speech.
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE,
|
||||
0.0,
|
||||
NO_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
// No estimated level change is expected.
|
||||
assert_eq!(t.estimator.level_dbfs(), estimated_level_dbfs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convergence_speed_before_confidence() {
|
||||
let mut t = TestLevelEstimator::new(1);
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
assert!(
|
||||
(t.estimator.level_dbfs() - t.level_rms_dbfs).abs()
|
||||
<= CONVERGENCE_SPEED_TESTS_LEVEL_TOLERANCE,
|
||||
"level {} should be near {}",
|
||||
t.estimator.level_dbfs(),
|
||||
t.level_rms_dbfs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convergence_speed_after_confidence() {
|
||||
let mut t = TestLevelEstimator::new(1);
|
||||
// Reach confidence using the initial level estimate.
|
||||
run_on_constant_level(
|
||||
NUM_FRAMES_TO_CONFIDENCE,
|
||||
t.initial_speech_level_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
// No estimate change should occur, but confidence is achieved.
|
||||
assert_eq!(t.estimator.level_dbfs(), t.initial_speech_level_dbfs);
|
||||
assert!(t.estimator.is_confident());
|
||||
// After confidence.
|
||||
let convergence_time_after_confidence_num_frames = 700; // 7 seconds.
|
||||
assert!(convergence_time_after_confidence_num_frames > NUM_FRAMES_TO_CONFIDENCE);
|
||||
run_on_constant_level(
|
||||
convergence_time_after_confidence_num_frames,
|
||||
t.level_rms_dbfs,
|
||||
MAX_SPEECH_PROBABILITY,
|
||||
&mut t.estimator,
|
||||
);
|
||||
assert!(
|
||||
(t.estimator.level_dbfs() - t.level_rms_dbfs).abs()
|
||||
<= CONVERGENCE_SPEED_TESTS_LEVEL_TOLERANCE,
|
||||
"level {} should be near {}",
|
||||
t.estimator.level_dbfs(),
|
||||
t.level_rms_dbfs
|
||||
);
|
||||
}
|
||||
|
||||
// Parametrized tests for adjacent_speech_frames_threshold = 1, 9, 17.
|
||||
|
||||
#[test]
|
||||
fn do_not_adapt_to_short_speech_segments_threshold_1() {
|
||||
do_not_adapt_to_short_speech_segments(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_adapt_to_short_speech_segments_threshold_9() {
|
||||
do_not_adapt_to_short_speech_segments(9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_not_adapt_to_short_speech_segments_threshold_17() {
|
||||
do_not_adapt_to_short_speech_segments(17);
|
||||
}
|
||||
|
||||
fn do_not_adapt_to_short_speech_segments(threshold: i32) {
|
||||
let mut t = TestLevelEstimator::new(threshold);
|
||||
let initial_level = t.estimator.level_dbfs();
|
||||
assert!(initial_level < t.level_peak_dbfs);
|
||||
for _ in 0..threshold - 1 {
|
||||
t.estimator.update(t.level_rms_dbfs, MAX_SPEECH_PROBABILITY);
|
||||
assert_eq!(
|
||||
initial_level,
|
||||
t.estimator.level_dbfs(),
|
||||
"level should not change before threshold"
|
||||
);
|
||||
}
|
||||
t.estimator.update(t.level_rms_dbfs, LOW_SPEECH_PROBABILITY);
|
||||
assert_eq!(
|
||||
initial_level,
|
||||
t.estimator.level_dbfs(),
|
||||
"level should not change after low-probability frame"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapt_to_enough_speech_segments_threshold_1() {
|
||||
adapt_to_enough_speech_segments(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapt_to_enough_speech_segments_threshold_9() {
|
||||
adapt_to_enough_speech_segments(9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapt_to_enough_speech_segments_threshold_17() {
|
||||
adapt_to_enough_speech_segments(17);
|
||||
}
|
||||
|
||||
fn adapt_to_enough_speech_segments(threshold: i32) {
|
||||
let mut t = TestLevelEstimator::new(threshold);
|
||||
let initial_level = t.estimator.level_dbfs();
|
||||
assert!(initial_level < t.level_peak_dbfs);
|
||||
for _ in 0..threshold {
|
||||
t.estimator.update(t.level_rms_dbfs, MAX_SPEECH_PROBABILITY);
|
||||
}
|
||||
assert!(
|
||||
initial_level < t.estimator.level_dbfs(),
|
||||
"level should increase after enough speech frames"
|
||||
);
|
||||
}
|
||||
}
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
//! Voice Activity Detector wrapper with resampling and periodic reset.
|
||||
//!
|
||||
//! Ported from `webrtc/modules/audio_processing/agc2/vad_wrapper.cc`.
|
||||
|
||||
use crate::common::{FRAME_DURATION_MS, VAD_RESET_PERIOD_MS};
|
||||
use crate::rnn_vad::common::{FRAME_SIZE_10MS_24K_HZ, FeatureVector, SAMPLE_RATE_24K_HZ};
|
||||
use crate::rnn_vad::features_extraction::FeaturesExtractor;
|
||||
use crate::rnn_vad::rnn::RnnVad;
|
||||
use sonora_common_audio::push_resampler::PushResampler;
|
||||
use sonora_simd::SimdBackend;
|
||||
|
||||
const NUM_FRAMES_PER_SECOND: i32 = 100;
|
||||
|
||||
/// Single-channel VAD interface.
|
||||
///
|
||||
/// The default implementation uses the RNN VAD. A mock can be injected for
|
||||
/// testing.
|
||||
pub trait MonoVad: Send + Sync {
|
||||
/// Returns the sample rate (Hz) required for input frames.
|
||||
fn sample_rate_hz(&self) -> i32;
|
||||
/// Resets the internal state.
|
||||
fn reset(&mut self);
|
||||
/// Analyzes an audio frame and returns the speech probability.
|
||||
fn analyze(&mut self, frame: &[f32]) -> f32;
|
||||
}
|
||||
|
||||
/// Default RNN-based mono VAD implementation.
|
||||
struct RnnMonoVad {
|
||||
features_extractor: FeaturesExtractor,
|
||||
rnn_vad: RnnVad,
|
||||
feature_vector: FeatureVector,
|
||||
}
|
||||
|
||||
impl RnnMonoVad {
|
||||
fn new(backend: SimdBackend) -> Self {
|
||||
Self {
|
||||
features_extractor: FeaturesExtractor::new(backend),
|
||||
rnn_vad: RnnVad::new(backend),
|
||||
feature_vector: bytemuck::Zeroable::zeroed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MonoVad for RnnMonoVad {
|
||||
fn sample_rate_hz(&self) -> i32 {
|
||||
SAMPLE_RATE_24K_HZ
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.rnn_vad.reset();
|
||||
}
|
||||
|
||||
fn analyze(&mut self, frame: &[f32]) -> f32 {
|
||||
debug_assert_eq!(frame.len(), FRAME_SIZE_10MS_24K_HZ);
|
||||
let is_silence = self
|
||||
.features_extractor
|
||||
.check_silence_compute_features(frame, &mut self.feature_vector);
|
||||
self.rnn_vad
|
||||
.compute_vad_probability(&self.feature_vector, is_silence)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a single-channel VAD with resampling and periodic reset.
|
||||
///
|
||||
/// Analyzes the first channel of input audio frames, resampling to the
|
||||
/// VAD's expected sample rate if necessary.
|
||||
#[derive(derive_more::Debug)]
|
||||
pub struct VoiceActivityDetectorWrapper {
|
||||
vad_reset_period_frames: i32,
|
||||
frame_size: usize,
|
||||
time_to_vad_reset: i32,
|
||||
#[debug(skip)]
|
||||
vad: Box<dyn MonoVad>,
|
||||
#[debug(skip)]
|
||||
resampled_buffer: Vec<f32>,
|
||||
#[debug(skip)]
|
||||
resampler: PushResampler<f32>,
|
||||
}
|
||||
|
||||
impl VoiceActivityDetectorWrapper {
|
||||
/// Creates a new wrapper using the default RNN VAD and default reset
|
||||
/// period.
|
||||
pub fn new(backend: SimdBackend, sample_rate_hz: i32) -> Self {
|
||||
Self::with_reset_period(VAD_RESET_PERIOD_MS, backend, sample_rate_hz)
|
||||
}
|
||||
|
||||
/// Creates a new wrapper using the default RNN VAD with a custom reset
|
||||
/// period.
|
||||
pub fn with_reset_period(
|
||||
vad_reset_period_ms: i32,
|
||||
backend: SimdBackend,
|
||||
sample_rate_hz: i32,
|
||||
) -> Self {
|
||||
Self::with_vad(
|
||||
vad_reset_period_ms,
|
||||
Box::new(RnnMonoVad::new(backend)),
|
||||
sample_rate_hz,
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a new wrapper with a custom VAD implementation.
|
||||
pub fn with_vad(
|
||||
vad_reset_period_ms: i32,
|
||||
mut vad: Box<dyn MonoVad>,
|
||||
sample_rate_hz: i32,
|
||||
) -> Self {
|
||||
let vad_reset_period_frames = vad_reset_period_ms / FRAME_DURATION_MS;
|
||||
debug_assert!(vad_reset_period_frames > 1);
|
||||
let frame_size = (sample_rate_hz / NUM_FRAMES_PER_SECOND) as usize;
|
||||
let resampled_size = (vad.sample_rate_hz() / NUM_FRAMES_PER_SECOND) as usize;
|
||||
|
||||
let resampler = PushResampler::new(frame_size, resampled_size, 1);
|
||||
|
||||
vad.reset();
|
||||
|
||||
Self {
|
||||
vad_reset_period_frames,
|
||||
frame_size,
|
||||
time_to_vad_reset: vad_reset_period_frames,
|
||||
vad,
|
||||
resampled_buffer: vec![0.0; resampled_size],
|
||||
resampler,
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyzes the first channel of `frame` and returns the speech
|
||||
/// probability.
|
||||
///
|
||||
/// `frame` must contain at least `frame_size` samples (the first channel
|
||||
/// of a 10 ms frame at the configured sample rate).
|
||||
pub fn analyze(&mut self, frame: &[f32]) -> f32 {
|
||||
// Periodically reset the VAD.
|
||||
self.time_to_vad_reset -= 1;
|
||||
if self.time_to_vad_reset <= 0 {
|
||||
self.vad.reset();
|
||||
self.time_to_vad_reset = self.vad_reset_period_frames;
|
||||
}
|
||||
|
||||
// Resample the first channel.
|
||||
debug_assert!(frame.len() >= self.frame_size);
|
||||
let src = &frame[..self.frame_size];
|
||||
self.resampler
|
||||
.resample_mono(src, &mut self.resampled_buffer);
|
||||
|
||||
self.vad.analyze(&self.resampled_buffer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const SAMPLE_RATE_8K_HZ: i32 = 8000;
|
||||
const NO_VAD_PERIODIC_RESET: i32 = FRAME_DURATION_MS * (i32::MAX / FRAME_DURATION_MS);
|
||||
|
||||
/// Mock VAD that records calls and returns pre-configured probabilities.
|
||||
struct MockVad {
|
||||
sample_rate: i32,
|
||||
probabilities: Vec<f32>,
|
||||
prob_index: usize,
|
||||
state: Arc<Mutex<MockVadState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockVadState {
|
||||
reset_count: usize,
|
||||
analyze_frames: Vec<usize>,
|
||||
}
|
||||
|
||||
impl MockVad {
|
||||
fn new(sample_rate: i32, probabilities: Vec<f32>, state: Arc<Mutex<MockVadState>>) -> Self {
|
||||
Self {
|
||||
sample_rate,
|
||||
probabilities,
|
||||
prob_index: 0,
|
||||
state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MonoVad for MockVad {
|
||||
fn sample_rate_hz(&self) -> i32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.state.lock().unwrap().reset_count += 1;
|
||||
}
|
||||
|
||||
fn analyze(&mut self, frame: &[f32]) -> f32 {
|
||||
self.state.lock().unwrap().analyze_frames.push(frame.len());
|
||||
let p = self.probabilities[self.prob_index % self.probabilities.len()];
|
||||
self.prob_index += 1;
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
fn create_mock_vad_wrapper(
|
||||
vad_reset_period_ms: i32,
|
||||
sample_rate_hz: i32,
|
||||
probabilities: Vec<f32>,
|
||||
state: Arc<Mutex<MockVadState>>,
|
||||
) -> VoiceActivityDetectorWrapper {
|
||||
let vad = MockVad::new(sample_rate_hz, probabilities, state);
|
||||
VoiceActivityDetectorWrapper::with_vad(vad_reset_period_ms, Box::new(vad), sample_rate_hz)
|
||||
}
|
||||
|
||||
fn make_frame(sample_rate_hz: i32) -> Vec<f32> {
|
||||
vec![0.0_f32; (sample_rate_hz / NUM_FRAMES_PER_SECOND) as usize]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_speech_probabilities() {
|
||||
let probabilities = vec![
|
||||
0.709, 0.484, 0.882, 0.167, 0.44, 0.525, 0.858, 0.314, 0.653, 0.965, 0.413, 0.0,
|
||||
];
|
||||
let state = Arc::new(Mutex::new(MockVadState::default()));
|
||||
let mut wrapper = create_mock_vad_wrapper(
|
||||
NO_VAD_PERIODIC_RESET,
|
||||
SAMPLE_RATE_8K_HZ,
|
||||
probabilities.clone(),
|
||||
Arc::clone(&state),
|
||||
);
|
||||
let frame = make_frame(SAMPLE_RATE_8K_HZ);
|
||||
for (i, &expected) in probabilities.iter().enumerate() {
|
||||
let actual = wrapper.analyze(&frame);
|
||||
assert_eq!(
|
||||
expected, actual,
|
||||
"mismatch at frame {i}: expected {expected}, got {actual}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vad_no_periodic_reset() {
|
||||
let num_frames = 19;
|
||||
let state = Arc::new(Mutex::new(MockVadState::default()));
|
||||
let mut wrapper = create_mock_vad_wrapper(
|
||||
NO_VAD_PERIODIC_RESET,
|
||||
SAMPLE_RATE_8K_HZ,
|
||||
vec![1.0],
|
||||
Arc::clone(&state),
|
||||
);
|
||||
let frame = make_frame(SAMPLE_RATE_8K_HZ);
|
||||
for _ in 0..num_frames {
|
||||
wrapper.analyze(&frame);
|
||||
}
|
||||
// Only the initial reset from the constructor.
|
||||
assert_eq!(state.lock().unwrap().reset_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vad_periodic_reset() {
|
||||
let test_cases: Vec<(i32, i32)> = vec![
|
||||
(1, 2),
|
||||
(1, 5),
|
||||
(1, 20),
|
||||
(1, 53),
|
||||
(19, 2),
|
||||
(19, 5),
|
||||
(19, 20),
|
||||
(19, 53),
|
||||
(123, 2),
|
||||
(123, 5),
|
||||
(123, 20),
|
||||
(123, 53),
|
||||
];
|
||||
|
||||
for (num_frames, vad_reset_period_frames) in test_cases {
|
||||
let vad_reset_period_ms = vad_reset_period_frames * FRAME_DURATION_MS;
|
||||
let state = Arc::new(Mutex::new(MockVadState::default()));
|
||||
let mut wrapper = create_mock_vad_wrapper(
|
||||
vad_reset_period_ms,
|
||||
SAMPLE_RATE_8K_HZ,
|
||||
vec![1.0],
|
||||
Arc::clone(&state),
|
||||
);
|
||||
let frame = make_frame(SAMPLE_RATE_8K_HZ);
|
||||
for _ in 0..num_frames {
|
||||
wrapper.analyze(&frame);
|
||||
}
|
||||
let expected_resets = 1 + num_frames / vad_reset_period_frames;
|
||||
assert_eq!(
|
||||
state.lock().unwrap().reset_count,
|
||||
expected_resets as usize,
|
||||
"num_frames={num_frames}, period={vad_reset_period_frames}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_resampled_frame_size() {
|
||||
let input_rates = [8000, 16000, 44100, 48000];
|
||||
let vad_rates = [6000, 8000, 12000, 16000, 24000];
|
||||
|
||||
for &input_rate in &input_rates {
|
||||
for &vad_rate in &vad_rates {
|
||||
let state = Arc::new(Mutex::new(MockVadState::default()));
|
||||
let vad = MockVad::new(vad_rate, vec![1.0], Arc::clone(&state));
|
||||
let mut wrapper = VoiceActivityDetectorWrapper::with_vad(
|
||||
NO_VAD_PERIODIC_RESET,
|
||||
Box::new(vad),
|
||||
input_rate,
|
||||
);
|
||||
let frame = make_frame(input_rate);
|
||||
wrapper.analyze(&frame);
|
||||
|
||||
let expected_frame_size = (vad_rate / NUM_FRAMES_PER_SECOND) as usize;
|
||||
assert_eq!(
|
||||
state.lock().unwrap().analyze_frames[0],
|
||||
expected_frame_size,
|
||||
"input_rate={input_rate}, vad_rate={vad_rate}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
|
||||
},
|
||||
"path_in_vcs": "crates/sonora"
|
||||
}
|
||||
+1647
File diff suppressed because it is too large.
Load diff
Vendored
+149
@@ -0,0 +1,149 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
name = "sonora"
|
||||
version = "0.2.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "WebRTC Audio Processing — pure Rust port with echo cancellation, noise suppression, and AGC"
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"audio",
|
||||
"webrtc",
|
||||
"echo-cancellation",
|
||||
"noise-suppression",
|
||||
"agc",
|
||||
]
|
||||
categories = ["multimedia::audio"]
|
||||
license = "BSD-3-Clause"
|
||||
repository = "https://github.com/dignifiedquire/sonora"
|
||||
|
||||
[features]
|
||||
examples = [
|
||||
"dep:anyhow",
|
||||
"dep:clap",
|
||||
"dep:cpal",
|
||||
"dep:ctrlc",
|
||||
"dep:hound",
|
||||
"dep:ringbuf",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "sonora"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[example]]
|
||||
name = "karaoke"
|
||||
path = "examples/karaoke.rs"
|
||||
required-features = ["examples"]
|
||||
|
||||
[[example]]
|
||||
name = "recording"
|
||||
path = "examples/recording.rs"
|
||||
required-features = ["examples"]
|
||||
|
||||
[[example]]
|
||||
name = "simple"
|
||||
path = "examples/simple.rs"
|
||||
|
||||
[[bench]]
|
||||
name = "pipeline"
|
||||
path = "benches/pipeline.rs"
|
||||
harness = false
|
||||
|
||||
[dependencies.anyhow]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[dependencies.clap]
|
||||
version = "4"
|
||||
features = ["derive"]
|
||||
optional = true
|
||||
|
||||
[dependencies.cpal]
|
||||
version = "0.18"
|
||||
optional = true
|
||||
|
||||
[dependencies.ctrlc]
|
||||
version = "3"
|
||||
features = ["termination"]
|
||||
optional = true
|
||||
|
||||
[dependencies.hound]
|
||||
version = "3"
|
||||
optional = true
|
||||
|
||||
[dependencies.ringbuf]
|
||||
version = "0.5"
|
||||
optional = true
|
||||
|
||||
[dependencies.sonora-aec3]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-agc2]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-common-audio]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-ns]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-simd]
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
|
||||
[dev-dependencies.criterion]
|
||||
version = "0.8"
|
||||
features = ["html_reports"]
|
||||
|
||||
[dev-dependencies.sonora-fft]
|
||||
version = "0.2.0"
|
||||
|
||||
[dev-dependencies.tracing-subscriber]
|
||||
version = "0.3"
|
||||
features = ["env-filter"]
|
||||
|
||||
[lints.clippy]
|
||||
absolute_paths = "warn"
|
||||
allow_attributes_without_reason = "warn"
|
||||
approx_constant = "allow"
|
||||
excessive_precision = "allow"
|
||||
manual_let_else = "warn"
|
||||
mod_module_files = "deny"
|
||||
or_fun_call = "warn"
|
||||
unused_async = "warn"
|
||||
use_self = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
missing_debug_implementations = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
|
||||
[lints.rust.unexpected_cfgs]
|
||||
level = "deny"
|
||||
priority = 0
|
||||
check-cfg = ["cfg(docsrs)"]
|
||||
|
||||
[workspace]
|
||||
|
||||
[patch.crates-io]
|
||||
sonora-agc2 = { path = "../sonora-agc2" }
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
[package]
|
||||
name = "sonora"
|
||||
version = "0.2.0"
|
||||
description = "WebRTC Audio Processing — pure Rust port with echo cancellation, noise suppression, and AGC"
|
||||
keywords = ["audio", "webrtc", "echo-cancellation", "noise-suppression", "agc"]
|
||||
categories = ["multimedia::audio"]
|
||||
readme = "README.md"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
autoexamples = false
|
||||
|
||||
[features]
|
||||
examples = ["dep:anyhow", "dep:clap", "dep:cpal", "dep:ctrlc", "dep:hound", "dep:ringbuf"]
|
||||
|
||||
[dependencies]
|
||||
sonora-common-audio = { workspace = true }
|
||||
sonora-aec3 = { workspace = true }
|
||||
sonora-agc2 = { workspace = true }
|
||||
sonora-ns = { workspace = true }
|
||||
sonora-simd = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
# Optional deps for examples
|
||||
anyhow = { workspace = true, optional = true }
|
||||
clap = { workspace = true, optional = true }
|
||||
cpal = { workspace = true, optional = true }
|
||||
ctrlc = { workspace = true, optional = true }
|
||||
hound = { workspace = true, optional = true }
|
||||
ringbuf = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { workspace = true }
|
||||
sonora-fft = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bench]]
|
||||
name = "pipeline"
|
||||
harness = false
|
||||
|
||||
[[example]]
|
||||
name = "simple"
|
||||
|
||||
[[example]]
|
||||
name = "karaoke"
|
||||
required-features = ["examples"]
|
||||
|
||||
[[example]]
|
||||
name = "recording"
|
||||
required-features = ["examples"]
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
Copyright (c) 2011, The WebRTC Project Authors. All rights reserved.
|
||||
Copyright (c) 2016, Arun Raghavan and contributors. All rights reserved.
|
||||
Copyright (c) 2026, dignifiedquire. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
# Sonora
|
||||
|
||||
[![crate][crate-image]][crate-link]
|
||||
[![docs][docs-image]][docs-link]
|
||||
![BSD-3-Clause licensed][license-image]
|
||||
![Rust Version][rustc-image]
|
||||
[![Build Status][build-image]][build-link]
|
||||
|
||||
Pure Rust implementation of [WebRTC] audio processing -- the full pipeline with
|
||||
echo cancellation (AEC3), noise suppression, automatic gain control (AGC2),
|
||||
and high-pass filtering.
|
||||
|
||||
Provides a Rust API. A C API is available via the separate [`sonora-ffi`](https://crates.io/crates/sonora-ffi) crate.
|
||||
|
||||
## Usage
|
||||
|
||||
```rust
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
use sonora::config::{EchoCanceller, NoiseSuppression, GainController2};
|
||||
|
||||
let config = Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
noise_suppression: Some(NoiseSuppression::default()),
|
||||
gain_controller2: Some(GainController2::default()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut apm = AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(StreamConfig::new(48000, 1))
|
||||
.render_config(StreamConfig::new(48000, 1))
|
||||
.build();
|
||||
|
||||
// Process 10ms frames (48kHz * 10ms = 480 samples)
|
||||
let src = vec![0.0f32; 480];
|
||||
let mut dest = vec![0.0f32; 480];
|
||||
apm.process_capture_f32(&[&src], &mut [&mut dest]).unwrap();
|
||||
```
|
||||
|
||||
See the [workspace README] for benchmarks, platform support, and the full crate listing.
|
||||
|
||||
## License
|
||||
|
||||
BSD-3-Clause. See [LICENSE] for details.
|
||||
|
||||
[//]: # (badges)
|
||||
|
||||
[crate-image]: https://img.shields.io/crates/v/sonora.svg
|
||||
[crate-link]: https://crates.io/crates/sonora
|
||||
[docs-image]: https://docs.rs/sonora/badge.svg
|
||||
[docs-link]: https://docs.rs/sonora/
|
||||
[license-image]: https://img.shields.io/badge/license-BSD--3--Clause-blue.svg
|
||||
[rustc-image]: https://img.shields.io/badge/rustc-1.91+-blue.svg
|
||||
[build-image]: https://github.com/dignifiedquire/sonora/actions/workflows/ci.yml/badge.svg?branch=main
|
||||
[build-link]: https://github.com/dignifiedquire/sonora/actions/workflows/ci.yml?query=branch:main
|
||||
|
||||
[//]: # (general links)
|
||||
|
||||
[WebRTC]: https://webrtc.org
|
||||
[workspace README]: https://github.com/dignifiedquire/sonora#readme
|
||||
[LICENSE]: https://github.com/dignifiedquire/sonora/blob/main/LICENSE
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
//! Benchmarks for the Sonora audio processing pipeline and components.
|
||||
|
||||
use std::slice;
|
||||
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use sonora::config::{EchoCanceller, GainController2, NoiseSuppression};
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
use sonora_common_audio::sinc_resampler::{SincResampler, SincResamplerCallback};
|
||||
use sonora_fft::pffft::{FftType, Pffft};
|
||||
use sonora_ns::config::{NS_FRAME_SIZE, SuppressionLevel};
|
||||
use sonora_ns::noise_suppressor::NoiseSuppressor;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Full pipeline benchmarks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn make_apm(sample_rate: u32, channels: u16) -> (AudioProcessing, StreamConfig) {
|
||||
let config = Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
noise_suppression: Some(NoiseSuppression::default()),
|
||||
gain_controller2: Some(GainController2::default()),
|
||||
..Default::default()
|
||||
};
|
||||
let mut apm = AudioProcessing::builder().config(config).build();
|
||||
let stream = StreamConfig::new(sample_rate, channels);
|
||||
|
||||
// Warm up the internal state with a few frames so we bench steady-state.
|
||||
let samples = stream.num_frames();
|
||||
let nch = channels as usize;
|
||||
let src_ch: Vec<f32> = (0..samples)
|
||||
.map(|i| (i as f32 * 0.01).sin() * 0.1)
|
||||
.collect();
|
||||
let src: Vec<&[f32]> = (0..nch).map(|_| src_ch.as_slice()).collect();
|
||||
let mut dst_ch = vec![0.0f32; samples];
|
||||
let mut dst: Vec<&mut [f32]> = (0..nch)
|
||||
.map(|_| {
|
||||
// SAFETY: each slice is independent; we just need the borrow checker to cooperate
|
||||
unsafe { slice::from_raw_parts_mut(dst_ch.as_mut_ptr(), samples) }
|
||||
})
|
||||
.collect();
|
||||
|
||||
for _ in 0..20 {
|
||||
let _ = apm.process_capture_f32_with_config(&src, &stream, &stream, &mut dst);
|
||||
}
|
||||
(apm, stream)
|
||||
}
|
||||
|
||||
fn bench_process_stream(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("process_stream");
|
||||
|
||||
// 16kHz mono
|
||||
{
|
||||
let (mut apm, stream) = make_apm(16000, 1);
|
||||
let samples = stream.num_frames();
|
||||
let src_data: Vec<f32> = (0..samples)
|
||||
.map(|i| (i as f32 * 0.01).sin() * 0.1)
|
||||
.collect();
|
||||
let src = [src_data.as_slice()];
|
||||
let mut dst_data = vec![0.0f32; samples];
|
||||
|
||||
group.bench_function("16k_mono", |b| {
|
||||
b.iter(|| {
|
||||
let mut dst = [dst_data.as_mut_slice()];
|
||||
apm.process_capture_f32_with_config(black_box(&src), &stream, &stream, &mut dst)
|
||||
.unwrap();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 48kHz mono
|
||||
{
|
||||
let (mut apm, stream) = make_apm(48000, 1);
|
||||
let samples = stream.num_frames();
|
||||
let src_data: Vec<f32> = (0..samples)
|
||||
.map(|i| (i as f32 * 0.01).sin() * 0.1)
|
||||
.collect();
|
||||
let src = [src_data.as_slice()];
|
||||
let mut dst_data = vec![0.0f32; samples];
|
||||
|
||||
group.bench_function("48k_mono", |b| {
|
||||
b.iter(|| {
|
||||
let mut dst = [dst_data.as_mut_slice()];
|
||||
apm.process_capture_f32_with_config(black_box(&src), &stream, &stream, &mut dst)
|
||||
.unwrap();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 48kHz stereo
|
||||
{
|
||||
let (mut apm, stream) = make_apm(48000, 2);
|
||||
let samples = stream.num_frames();
|
||||
let src_data: Vec<f32> = (0..samples)
|
||||
.map(|i| (i as f32 * 0.01).sin() * 0.1)
|
||||
.collect();
|
||||
let src = [src_data.as_slice(), src_data.as_slice()];
|
||||
let mut dst_data_l = vec![0.0f32; samples];
|
||||
let mut dst_data_r = vec![0.0f32; samples];
|
||||
|
||||
group.bench_function("48k_stereo", |b| {
|
||||
b.iter(|| {
|
||||
let mut dst = [dst_data_l.as_mut_slice(), dst_data_r.as_mut_slice()];
|
||||
apm.process_capture_f32_with_config(black_box(&src), &stream, &stream, &mut dst)
|
||||
.unwrap();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component benchmarks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn bench_noise_suppressor(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("noise_suppressor");
|
||||
let mut ns = NoiseSuppressor::with_level(SuppressionLevel::K12dB);
|
||||
|
||||
let mut frame = [0.0f32; NS_FRAME_SIZE];
|
||||
for (i, s) in frame.iter_mut().enumerate() {
|
||||
*s = (i as f32 * 0.05).sin() * 0.1;
|
||||
}
|
||||
|
||||
// Warm up
|
||||
for _ in 0..50 {
|
||||
ns.analyze(&frame);
|
||||
ns.process(&mut frame);
|
||||
}
|
||||
|
||||
group.bench_function("analyze_and_process", |b| {
|
||||
b.iter(|| {
|
||||
ns.analyze(black_box(&frame));
|
||||
ns.process(black_box(&mut frame));
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn bench_pffft(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("pffft");
|
||||
|
||||
for &size in &[128, 256, 512] {
|
||||
let mut fft = Pffft::new(size, FftType::Real);
|
||||
let mut input = fft.create_buffer();
|
||||
let mut output = fft.create_buffer();
|
||||
for (i, s) in input.as_mut_slice().iter_mut().enumerate() {
|
||||
*s = (i as f32 * 0.01).sin();
|
||||
}
|
||||
|
||||
group.bench_function(format!("forward_{size}"), |b| {
|
||||
b.iter(|| {
|
||||
fft.forward(black_box(&input), &mut output, true);
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_function(format!("roundtrip_{size}"), |b| {
|
||||
b.iter(|| {
|
||||
fft.forward(black_box(&input), &mut output, true);
|
||||
fft.backward(&output, &mut input, true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
struct ZeroCallback;
|
||||
impl SincResamplerCallback for ZeroCallback {
|
||||
fn run(&mut self, frames: usize, destination: &mut [f32]) {
|
||||
for s in &mut destination[..frames] {
|
||||
*s = 0.001;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_sinc_resampler(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("sinc_resampler");
|
||||
|
||||
// 48kHz -> 16kHz (ratio = 48/16 = 3.0, but SincResampler uses io ratio = output/input)
|
||||
let ratio = 16000.0 / 48000.0;
|
||||
let request_frames = 160; // 10ms at 16kHz
|
||||
let mut resampler = SincResampler::new(ratio, request_frames);
|
||||
let mut output = vec![0.0f32; request_frames];
|
||||
let mut cb = ZeroCallback;
|
||||
|
||||
// Warm up
|
||||
for _ in 0..20 {
|
||||
resampler.resample(request_frames, &mut output, &mut cb);
|
||||
}
|
||||
|
||||
group.bench_function("48k_to_16k", |b| {
|
||||
b.iter(|| {
|
||||
resampler.resample(black_box(request_frames), &mut output, &mut cb);
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(
|
||||
benches,
|
||||
bench_process_stream,
|
||||
bench_noise_suppressor,
|
||||
bench_pffft,
|
||||
bench_sinc_resampler,
|
||||
);
|
||||
criterion_main!(benches);
|
||||
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
//! Helpers shared by multiple examples.
|
||||
|
||||
/// Deinterleave an interleaved multi-channel buffer into per-channel vectors.
|
||||
///
|
||||
/// ```text
|
||||
/// Interleaved (stereo, 3 samples):
|
||||
/// [L0, R0, L1, R1, L2, R2]
|
||||
///
|
||||
/// Deinterleaved:
|
||||
/// [[L0, L1, L2],
|
||||
/// [R0, R1, R2]]
|
||||
/// ```
|
||||
pub(crate) fn deinterleave(src: &[f32], dst: &mut [Vec<f32>]) {
|
||||
let num_channels = dst.len();
|
||||
let num_samples = src.len() / num_channels;
|
||||
assert_eq!(src.len(), num_channels * num_samples);
|
||||
for ch in dst.iter_mut() {
|
||||
ch.resize(num_samples, 0.0);
|
||||
}
|
||||
for (i, &sample) in src.iter().enumerate() {
|
||||
dst[i % num_channels][i / num_channels] = sample;
|
||||
}
|
||||
}
|
||||
|
||||
/// Interleave per-channel vectors into a flat interleaved buffer.
|
||||
pub(crate) fn interleave(src: &[Vec<f32>], dst: &mut [f32]) {
|
||||
let num_channels = src.len();
|
||||
let num_samples = src[0].len();
|
||||
assert_eq!(dst.len(), num_channels * num_samples);
|
||||
for ch in 0..num_channels {
|
||||
for s in 0..num_samples {
|
||||
dst[s * num_channels + ch] = src[ch][s];
|
||||
}
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
//! Microphone loopback with echo cancellation, creating a karaoke-like effect.
|
||||
//!
|
||||
//! Uses cpal for audio I/O and ring buffers to shuttle samples between the
|
||||
//! input/output callbacks and a processing thread.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p sonora --features examples --example karaoke
|
||||
//! ```
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use ringbuf::HeapRb;
|
||||
use ringbuf::traits::{Consumer, Observer, Producer, Split};
|
||||
|
||||
use sonora::config::EchoCanceller;
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
|
||||
#[allow(dead_code, reason = "shared helpers for multi-channel examples")]
|
||||
mod common;
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const NUM_CHANNELS: u16 = 1;
|
||||
const FRAME_SIZE: usize = (SAMPLE_RATE / 100) as usize; // 10 ms
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
|
||||
ctrlc::set_handler({
|
||||
let running = running.clone();
|
||||
move || running.store(false, Ordering::SeqCst)
|
||||
})?;
|
||||
|
||||
let host = cpal::default_host();
|
||||
let input_device = host
|
||||
.default_input_device()
|
||||
.context("no input device available")?;
|
||||
let output_device = host
|
||||
.default_output_device()
|
||||
.context("no output device available")?;
|
||||
|
||||
println!("Input: {}", input_device.description()?.name());
|
||||
println!("Output: {}", output_device.description()?.name());
|
||||
|
||||
let cpal_config = cpal::StreamConfig {
|
||||
channels: NUM_CHANNELS,
|
||||
sample_rate: SAMPLE_RATE,
|
||||
buffer_size: cpal::BufferSize::Default,
|
||||
};
|
||||
|
||||
// Ring buffers: input callback → processing thread → output callback.
|
||||
let ring_size = FRAME_SIZE * 8;
|
||||
let (mut in_prod, mut in_cons) = HeapRb::<f32>::new(ring_size).split();
|
||||
let (mut out_prod, mut out_cons) = HeapRb::<f32>::new(ring_size).split();
|
||||
|
||||
// Input stream: push mic samples into ring buffer.
|
||||
let input_stream = input_device.build_input_stream(
|
||||
cpal_config,
|
||||
move |data: &[f32], _: &cpal::InputCallbackInfo| {
|
||||
in_prod.push_slice(data);
|
||||
},
|
||||
|err| eprintln!("input error: {err}"),
|
||||
None,
|
||||
)?;
|
||||
|
||||
// Output stream: pull processed samples from ring buffer.
|
||||
let output_stream = output_device.build_output_stream(
|
||||
cpal_config,
|
||||
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
||||
let filled = out_cons.pop_slice(data);
|
||||
data[filled..].fill(0.0);
|
||||
},
|
||||
|err| eprintln!("output error: {err}"),
|
||||
None,
|
||||
)?;
|
||||
|
||||
input_stream.play()?;
|
||||
output_stream.play()?;
|
||||
|
||||
// Processing thread: read 10 ms frames, apply AEC, push to output.
|
||||
let running_proc = running.clone();
|
||||
let proc_thread = thread::spawn(move || {
|
||||
let stream_config = StreamConfig::new(SAMPLE_RATE, NUM_CHANNELS);
|
||||
let config = Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
..Default::default()
|
||||
};
|
||||
let mut apm = AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(stream_config)
|
||||
.render_config(stream_config)
|
||||
.build();
|
||||
|
||||
let mut input_buf = vec![0.0f32; FRAME_SIZE];
|
||||
let mut capture_out = vec![0.0f32; FRAME_SIZE];
|
||||
let mut render_out = vec![0.0f32; FRAME_SIZE];
|
||||
|
||||
while running_proc.load(Ordering::SeqCst) {
|
||||
if in_cons.occupied_len() < FRAME_SIZE {
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
continue;
|
||||
}
|
||||
in_cons.pop_slice(&mut input_buf);
|
||||
|
||||
// Process capture (apply AEC to mic input).
|
||||
apm.process_capture_f32(&[&input_buf], &mut [&mut capture_out])
|
||||
.unwrap();
|
||||
|
||||
// Tell AEC what we are sending to the speakers.
|
||||
apm.process_render_f32(&[&capture_out], &mut [&mut render_out])
|
||||
.unwrap();
|
||||
|
||||
out_prod.push_slice(&capture_out);
|
||||
}
|
||||
});
|
||||
|
||||
println!("Looping mic -> AEC -> speakers (Ctrl+C to stop)");
|
||||
|
||||
while running.load(Ordering::SeqCst) {
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
drop(input_stream);
|
||||
drop(output_stream);
|
||||
proc_thread.join().unwrap();
|
||||
|
||||
println!("\nDone.");
|
||||
Ok(())
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
//! Record microphone audio, process it through sonora, and write WAV files.
|
||||
//!
|
||||
//! Writes both raw (unprocessed) and processed audio to separate files so you
|
||||
//! can compare them.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p sonora --features examples --example recording -- --duration 5 --ns --agc
|
||||
//! ```
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use hound::WavWriter;
|
||||
use ringbuf::HeapRb;
|
||||
use ringbuf::traits::{Consumer, Observer, Producer, Split};
|
||||
|
||||
use sonora::config::{EchoCanceller, GainController2, NoiseSuppression};
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
|
||||
#[allow(dead_code, reason = "shared helpers for multi-channel examples")]
|
||||
mod common;
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const NUM_CHANNELS: u16 = 1;
|
||||
const FRAME_SIZE: usize = (SAMPLE_RATE / 100) as usize; // 10 ms
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(about = "Record and process microphone audio through sonora")]
|
||||
struct Args {
|
||||
/// Recording duration in seconds.
|
||||
#[arg(short, long, default_value_t = 5)]
|
||||
duration: u64,
|
||||
|
||||
/// Path for the raw (unprocessed) recording.
|
||||
#[arg(long, default_value = "raw.wav")]
|
||||
raw_output: String,
|
||||
|
||||
/// Path for the processed recording.
|
||||
#[arg(long, default_value = "processed.wav")]
|
||||
processed_output: String,
|
||||
|
||||
/// Enable echo cancellation.
|
||||
#[arg(long)]
|
||||
aec: bool,
|
||||
|
||||
/// Enable noise suppression.
|
||||
#[arg(long)]
|
||||
ns: bool,
|
||||
|
||||
/// Enable automatic gain control.
|
||||
#[arg(long)]
|
||||
agc: bool,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
|
||||
ctrlc::set_handler({
|
||||
let running = running.clone();
|
||||
move || running.store(false, Ordering::SeqCst)
|
||||
})?;
|
||||
|
||||
let host = cpal::default_host();
|
||||
let input_device = host
|
||||
.default_input_device()
|
||||
.context("no input device available")?;
|
||||
println!("Recording from: {}", input_device.description()?.name());
|
||||
|
||||
let cpal_config = cpal::StreamConfig {
|
||||
channels: NUM_CHANNELS,
|
||||
sample_rate: SAMPLE_RATE,
|
||||
buffer_size: cpal::BufferSize::Default,
|
||||
};
|
||||
|
||||
let ring_size = FRAME_SIZE * 8;
|
||||
let (mut prod, mut cons) = HeapRb::<f32>::new(ring_size).split();
|
||||
|
||||
let input_stream = input_device.build_input_stream(
|
||||
cpal_config,
|
||||
move |data: &[f32], _: &cpal::InputCallbackInfo| {
|
||||
prod.push_slice(data);
|
||||
},
|
||||
|err| eprintln!("input error: {err}"),
|
||||
None,
|
||||
)?;
|
||||
|
||||
input_stream.play()?;
|
||||
|
||||
// Build config from CLI flags.
|
||||
let config = Config {
|
||||
echo_canceller: if args.aec {
|
||||
Some(EchoCanceller::default())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
noise_suppression: if args.ns {
|
||||
Some(NoiseSuppression::default())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
gain_controller2: if args.agc {
|
||||
Some(GainController2::default())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let stream_config = StreamConfig::new(SAMPLE_RATE, NUM_CHANNELS);
|
||||
let mut apm = AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(stream_config)
|
||||
.render_config(stream_config)
|
||||
.build();
|
||||
|
||||
let spec = hound::WavSpec {
|
||||
channels: NUM_CHANNELS,
|
||||
sample_rate: SAMPLE_RATE,
|
||||
bits_per_sample: 32,
|
||||
sample_format: hound::SampleFormat::Float,
|
||||
};
|
||||
|
||||
let mut raw_writer = WavWriter::create(&args.raw_output, spec)?;
|
||||
let mut proc_writer = WavWriter::create(&args.processed_output, spec)?;
|
||||
|
||||
println!(
|
||||
"Recording for {} seconds (Ctrl+C to stop early)...",
|
||||
args.duration
|
||||
);
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(args.duration);
|
||||
let mut input_buf = vec![0.0f32; FRAME_SIZE];
|
||||
let mut output_buf = vec![0.0f32; FRAME_SIZE];
|
||||
|
||||
while running.load(Ordering::SeqCst) && Instant::now() < deadline {
|
||||
if cons.occupied_len() < FRAME_SIZE {
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
continue;
|
||||
}
|
||||
|
||||
cons.pop_slice(&mut input_buf);
|
||||
|
||||
// Write raw samples.
|
||||
for &s in &input_buf {
|
||||
raw_writer.write_sample(s)?;
|
||||
}
|
||||
|
||||
// Process through sonora.
|
||||
apm.process_capture_f32(&[&input_buf], &mut [&mut output_buf])
|
||||
.unwrap();
|
||||
|
||||
// Write processed samples.
|
||||
for &s in &output_buf {
|
||||
proc_writer.write_sample(s)?;
|
||||
}
|
||||
}
|
||||
|
||||
raw_writer.finalize()?;
|
||||
proc_writer.finalize()?;
|
||||
|
||||
println!("Wrote {} and {}", args.raw_output, args.processed_output);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
//! Minimal echo cancellation demo.
|
||||
//!
|
||||
//! Creates synthetic stereo render and capture signals, processes them through
|
||||
//! the AEC pipeline, and verifies that the capture signal was modified.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p sonora --example simple
|
||||
//! ```
|
||||
|
||||
use sonora::config::EchoCanceller;
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
|
||||
fn main() {
|
||||
let sample_rate_hz = 48_000;
|
||||
let num_channels = 2;
|
||||
let stream_config = StreamConfig::new(sample_rate_hz, num_channels);
|
||||
let num_frames = stream_config.num_frames();
|
||||
|
||||
let config = Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut apm = AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(stream_config)
|
||||
.render_config(stream_config)
|
||||
.build();
|
||||
|
||||
// Generate synthetic stereo signals that simulate a microphone picking up
|
||||
// speaker output (the render signal leaks into the capture signal).
|
||||
let (render_ch0, render_ch1, capture_ch0, capture_ch1) = sample_stereo_frames(num_frames);
|
||||
|
||||
// Process the render frame (tell the AEC what is being played through speakers).
|
||||
let mut render_out_ch0 = vec![0.0f32; num_frames];
|
||||
let mut render_out_ch1 = vec![0.0f32; num_frames];
|
||||
apm.process_render_f32(
|
||||
&[&render_ch0, &render_ch1],
|
||||
&mut [&mut render_out_ch0, &mut render_out_ch1],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
render_ch0, render_out_ch0,
|
||||
"render channel 0 should not be modified"
|
||||
);
|
||||
assert_eq!(
|
||||
render_ch1, render_out_ch1,
|
||||
"render channel 1 should not be modified"
|
||||
);
|
||||
|
||||
// Process the capture frame (apply echo cancellation to microphone input).
|
||||
let mut capture_out_ch0 = vec![0.0f32; num_frames];
|
||||
let mut capture_out_ch1 = vec![0.0f32; num_frames];
|
||||
apm.process_capture_f32(
|
||||
&[&capture_ch0, &capture_ch1],
|
||||
&mut [&mut capture_out_ch0, &mut capture_out_ch1],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(
|
||||
capture_ch0, capture_out_ch0,
|
||||
"echo cancellation should have modified capture channel 0"
|
||||
);
|
||||
assert_ne!(
|
||||
capture_ch1, capture_out_ch1,
|
||||
"echo cancellation should have modified capture channel 1"
|
||||
);
|
||||
|
||||
println!("Successfully processed render and capture frames through sonora AEC.");
|
||||
}
|
||||
|
||||
/// Generate example stereo frames that simulate a microphone (capture) picking
|
||||
/// up the speaker (render) output.
|
||||
fn sample_stereo_frames(num_frames: usize) -> (Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>) {
|
||||
let mut render_ch0 = vec![0.0f32; num_frames];
|
||||
let mut render_ch1 = vec![0.0f32; num_frames];
|
||||
let mut capture_ch0 = vec![0.0f32; num_frames];
|
||||
let mut capture_ch1 = vec![0.0f32; num_frames];
|
||||
|
||||
for i in 0..num_frames {
|
||||
render_ch0[i] = (i as f32 / 40.0).cos() * 0.4;
|
||||
render_ch1[i] = (i as f32 / 40.0).cos() * 0.2;
|
||||
capture_ch0[i] = (i as f32 / 20.0).sin() * 0.4 + render_ch0[i] * 0.2;
|
||||
capture_ch1[i] = (i as f32 / 20.0).sin() * 0.2 + render_ch1[i] * 0.2;
|
||||
}
|
||||
|
||||
(render_ch0, render_ch1, capture_ch0, capture_ch1)
|
||||
}
|
||||
+665
@@ -0,0 +1,665 @@
|
||||
//! Central audio buffer for the audio processing pipeline.
|
||||
//!
|
||||
//! `AudioBuffer` stores audio data in a format suitable for the audio processing
|
||||
//! module to operate on, handling resampling, downmixing, and band splitting.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/audio_buffer.h/cc`.
|
||||
|
||||
use sonora_common_audio::audio_util;
|
||||
use sonora_common_audio::channel_buffer::ChannelBuffer;
|
||||
use sonora_common_audio::push_sinc_resampler::PushSincResampler;
|
||||
|
||||
use crate::splitting_filter::SplittingFilter;
|
||||
use crate::stream_config::StreamConfig;
|
||||
|
||||
fn num_bands_from_frames_per_channel(num_frames: usize) -> usize {
|
||||
match num_frames {
|
||||
320 => 2,
|
||||
480 => 3,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio buffer for the processing pipeline.
|
||||
///
|
||||
/// Handles resampling between input/buffer/output rates, downmixing from
|
||||
/// multi-channel to mono, and frequency band splitting for sub-band processing.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AudioBuffer {
|
||||
input_num_frames: usize,
|
||||
input_num_channels: usize,
|
||||
buffer_num_frames: usize,
|
||||
buffer_num_channels: usize,
|
||||
output_num_frames: usize,
|
||||
|
||||
num_channels: usize,
|
||||
num_bands: usize,
|
||||
num_split_frames: usize,
|
||||
|
||||
data: ChannelBuffer<f32>,
|
||||
split_data: Option<ChannelBuffer<f32>>,
|
||||
splitting_filter: Option<SplittingFilter>,
|
||||
input_resamplers: Vec<PushSincResampler>,
|
||||
output_resamplers: Vec<PushSincResampler>,
|
||||
downmix_by_averaging: bool,
|
||||
channel_for_downmixing: usize,
|
||||
}
|
||||
|
||||
impl AudioBuffer {
|
||||
/// Create a new audio buffer.
|
||||
///
|
||||
/// - `input_rate`: sample rate of incoming audio
|
||||
/// - `input_num_channels`: number of input channels
|
||||
/// - `buffer_rate`: internal processing sample rate
|
||||
/// - `buffer_num_channels`: number of internal processing channels
|
||||
/// - `output_rate`: sample rate of outgoing audio
|
||||
pub(crate) fn new(
|
||||
input_rate: usize,
|
||||
input_num_channels: usize,
|
||||
buffer_rate: usize,
|
||||
buffer_num_channels: usize,
|
||||
output_rate: usize,
|
||||
) -> Self {
|
||||
let input_num_frames = input_rate / 100;
|
||||
let buffer_num_frames = buffer_rate / 100;
|
||||
let output_num_frames = output_rate / 100;
|
||||
let num_bands = num_bands_from_frames_per_channel(buffer_num_frames);
|
||||
let num_split_frames = buffer_num_frames / num_bands;
|
||||
|
||||
debug_assert!(input_num_frames > 0);
|
||||
debug_assert!(buffer_num_frames > 0);
|
||||
debug_assert!(output_num_frames > 0);
|
||||
debug_assert!(input_num_channels > 0);
|
||||
debug_assert!(buffer_num_channels > 0);
|
||||
debug_assert!(buffer_num_channels <= input_num_channels);
|
||||
|
||||
let data = ChannelBuffer::new(buffer_num_frames, buffer_num_channels, 1);
|
||||
|
||||
let input_resamplers = if input_num_frames != buffer_num_frames {
|
||||
(0..buffer_num_channels)
|
||||
.map(|_| PushSincResampler::new(input_num_frames, buffer_num_frames))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let output_resamplers = if output_num_frames != buffer_num_frames {
|
||||
(0..buffer_num_channels)
|
||||
.map(|_| PushSincResampler::new(buffer_num_frames, output_num_frames))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let (split_data, splitting_filter) = if num_bands > 1 {
|
||||
(
|
||||
Some(ChannelBuffer::new(
|
||||
buffer_num_frames,
|
||||
buffer_num_channels,
|
||||
num_bands,
|
||||
)),
|
||||
Some(SplittingFilter::new(buffer_num_channels, num_bands)),
|
||||
)
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
Self {
|
||||
input_num_frames,
|
||||
input_num_channels,
|
||||
buffer_num_frames,
|
||||
buffer_num_channels,
|
||||
output_num_frames,
|
||||
num_channels: buffer_num_channels,
|
||||
num_bands,
|
||||
num_split_frames,
|
||||
data,
|
||||
split_data,
|
||||
splitting_filter,
|
||||
input_resamplers,
|
||||
output_resamplers,
|
||||
downmix_by_averaging: true,
|
||||
channel_for_downmixing: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of visible channels (may be less than buffer_num_channels).
|
||||
#[inline]
|
||||
pub(crate) fn num_channels(&self) -> usize {
|
||||
self.num_channels
|
||||
}
|
||||
|
||||
/// Number of frames in the buffer (at buffer rate).
|
||||
#[inline]
|
||||
pub(crate) fn num_frames(&self) -> usize {
|
||||
self.buffer_num_frames
|
||||
}
|
||||
|
||||
/// Number of frames per frequency band.
|
||||
#[inline]
|
||||
pub(crate) fn num_frames_per_band(&self) -> usize {
|
||||
self.num_split_frames
|
||||
}
|
||||
|
||||
/// Number of frequency bands.
|
||||
#[inline]
|
||||
pub(crate) fn num_bands(&self) -> usize {
|
||||
self.num_bands
|
||||
}
|
||||
|
||||
/// Get a slice for a specific channel (full-band).
|
||||
#[inline]
|
||||
pub(crate) fn channel(&self, channel: usize) -> &[f32] {
|
||||
self.data.bands(channel)
|
||||
}
|
||||
|
||||
/// Get a mutable slice for a specific channel (full-band).
|
||||
#[inline]
|
||||
pub(crate) fn channel_mut(&mut self, channel: usize) -> &mut [f32] {
|
||||
self.data.bands_mut(channel)
|
||||
}
|
||||
|
||||
/// Get split band data for a specific channel and band.
|
||||
pub(crate) fn split_band(&self, channel: usize, band: usize) -> &[f32] {
|
||||
if let Some(ref split) = self.split_data {
|
||||
split.channel(band, channel)
|
||||
} else {
|
||||
self.data.channel(band, channel)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get mutable split band data for a specific channel and band.
|
||||
pub(crate) fn split_band_mut(&mut self, channel: usize, band: usize) -> &mut [f32] {
|
||||
if let Some(ref mut split) = self.split_data {
|
||||
split.channel_mut(band, channel)
|
||||
} else {
|
||||
self.data.channel_mut(band, channel)
|
||||
}
|
||||
}
|
||||
|
||||
/// Set downmixing mode to select a specific channel.
|
||||
pub(crate) fn set_downmixing_to_specific_channel(&mut self, channel: usize) {
|
||||
self.downmix_by_averaging = false;
|
||||
debug_assert!(self.input_num_channels > channel);
|
||||
self.channel_for_downmixing = channel.min(self.input_num_channels - 1);
|
||||
}
|
||||
|
||||
/// Set downmixing mode to average all channels.
|
||||
pub(crate) fn set_downmixing_by_averaging(&mut self) {
|
||||
self.downmix_by_averaging = true;
|
||||
}
|
||||
|
||||
/// Set the number of visible channels.
|
||||
pub(crate) fn set_num_channels(&mut self, num_channels: usize) {
|
||||
debug_assert!(self.buffer_num_channels >= num_channels);
|
||||
self.num_channels = num_channels;
|
||||
self.data.set_num_channels(num_channels);
|
||||
if let Some(ref mut split) = self.split_data {
|
||||
split.set_num_channels(num_channels);
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the number of channels to the buffer's allocated count.
|
||||
pub(crate) fn restore_num_channels(&mut self) {
|
||||
self.num_channels = self.buffer_num_channels;
|
||||
self.data.set_num_channels(self.buffer_num_channels);
|
||||
if let Some(ref mut split) = self.split_data {
|
||||
split.set_num_channels(self.buffer_num_channels);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy deinterleaved float data into the buffer.
|
||||
///
|
||||
/// The input is in float [-1, 1] range and is converted to FloatS16 internally.
|
||||
pub(crate) fn copy_from_float(
|
||||
&mut self,
|
||||
stacked_data: &[&[f32]],
|
||||
stream_config: &StreamConfig,
|
||||
) {
|
||||
debug_assert_eq!(stream_config.num_frames(), self.input_num_frames);
|
||||
debug_assert_eq!(
|
||||
stream_config.num_channels() as usize,
|
||||
self.input_num_channels
|
||||
);
|
||||
self.restore_num_channels();
|
||||
|
||||
let downmix_needed = self.input_num_channels > 1 && self.num_channels == 1;
|
||||
let resampling_needed = self.input_num_frames != self.buffer_num_frames;
|
||||
|
||||
if downmix_needed {
|
||||
let mut downmix = vec![0.0f32; self.input_num_frames];
|
||||
|
||||
if self.downmix_by_averaging {
|
||||
let scale = 1.0 / self.input_num_channels as f32;
|
||||
for (i, d) in downmix.iter_mut().enumerate() {
|
||||
let mut value = stacked_data[0][i];
|
||||
for sd in &stacked_data[1..self.input_num_channels] {
|
||||
value += sd[i];
|
||||
}
|
||||
*d = value * scale;
|
||||
}
|
||||
} else {
|
||||
downmix.copy_from_slice(
|
||||
&stacked_data[self.channel_for_downmixing][..self.input_num_frames],
|
||||
);
|
||||
}
|
||||
|
||||
let downmixed_data = if self.downmix_by_averaging {
|
||||
&downmix
|
||||
} else {
|
||||
&stacked_data[self.channel_for_downmixing][..self.input_num_frames]
|
||||
};
|
||||
|
||||
if resampling_needed {
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
self.input_resamplers[0].resample(downmixed_data, ch0);
|
||||
// Convert in-place.
|
||||
audio_util::float_to_float_s16_slice_inplace(ch0);
|
||||
} else {
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
audio_util::float_to_float_s16_slice(downmixed_data, ch0);
|
||||
}
|
||||
} else if resampling_needed {
|
||||
for (i, sd) in stacked_data.iter().enumerate().take(self.num_channels) {
|
||||
let ch = self.data.bands_mut(i);
|
||||
self.input_resamplers[i].resample(&sd[..self.input_num_frames], ch);
|
||||
audio_util::float_to_float_s16_slice_inplace(ch);
|
||||
}
|
||||
} else {
|
||||
for (i, sd) in stacked_data.iter().enumerate().take(self.num_channels) {
|
||||
let ch = self.data.bands_mut(i);
|
||||
audio_util::float_to_float_s16_slice(&sd[..self.input_num_frames], ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy data from the buffer to deinterleaved float output.
|
||||
///
|
||||
/// Data is converted from FloatS16 back to float [-1, 1] range.
|
||||
pub(crate) fn copy_to_float(
|
||||
&mut self,
|
||||
stream_config: &StreamConfig,
|
||||
stacked_data: &mut [&mut [f32]],
|
||||
) {
|
||||
debug_assert_eq!(stream_config.num_frames(), self.output_num_frames);
|
||||
|
||||
let resampling_needed = self.output_num_frames != self.buffer_num_frames;
|
||||
|
||||
if resampling_needed {
|
||||
for (i, sd) in stacked_data.iter_mut().enumerate().take(self.num_channels) {
|
||||
// Convert from FloatS16 to float first, then resample.
|
||||
let ch = self.data.bands_mut(i);
|
||||
audio_util::float_s16_to_float_slice_inplace(ch);
|
||||
self.output_resamplers[i].resample(ch, &mut sd[..self.output_num_frames]);
|
||||
}
|
||||
} else {
|
||||
for (i, sd) in stacked_data.iter_mut().enumerate().take(self.num_channels) {
|
||||
let ch = self.data.bands(i);
|
||||
audio_util::float_s16_to_float_slice(ch, &mut sd[..self.output_num_frames]);
|
||||
}
|
||||
}
|
||||
|
||||
// Copy channel 0 to any extra output channels.
|
||||
if self.num_channels < stream_config.num_channels() as usize {
|
||||
let (first, rest) = stacked_data.split_at_mut(1);
|
||||
for i in self.num_channels..stream_config.num_channels() as usize {
|
||||
rest[i - 1][..self.output_num_frames]
|
||||
.copy_from_slice(&first[0][..self.output_num_frames]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy data from this buffer to another AudioBuffer (with optional resampling).
|
||||
pub(crate) fn copy_to_buffer(&mut self, buffer: &mut Self) {
|
||||
debug_assert_eq!(buffer.num_frames(), self.output_num_frames);
|
||||
|
||||
let resampling_needed = self.output_num_frames != self.buffer_num_frames;
|
||||
|
||||
let buf_frames = buffer.num_frames();
|
||||
if resampling_needed {
|
||||
for i in 0..self.num_channels {
|
||||
let src = self.data.bands(i);
|
||||
let mut temp = vec![0.0f32; buf_frames];
|
||||
self.output_resamplers[i].resample(src, &mut temp);
|
||||
buffer.channel_mut(i)[..buf_frames].copy_from_slice(&temp);
|
||||
}
|
||||
} else {
|
||||
for i in 0..self.num_channels {
|
||||
let len = self.buffer_num_frames;
|
||||
buffer.channel_mut(i)[..len].copy_from_slice(&self.data.bands(i)[..len]);
|
||||
}
|
||||
}
|
||||
|
||||
// Copy channel 0 to extra channels in destination.
|
||||
let num_frames = buffer.data.num_frames();
|
||||
let len = self.output_num_frames;
|
||||
for i in self.num_channels..buffer.num_channels() {
|
||||
let src_start = 0; // channel 0
|
||||
let dst_start = i * num_frames;
|
||||
buffer
|
||||
.data
|
||||
.data_mut()
|
||||
.copy_within(src_start..src_start + len, dst_start);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy interleaved i16 data into the buffer.
|
||||
pub(crate) fn copy_from_interleaved_i16(
|
||||
&mut self,
|
||||
interleaved_data: &[i16],
|
||||
stream_config: &StreamConfig,
|
||||
) {
|
||||
debug_assert_eq!(
|
||||
stream_config.num_channels() as usize,
|
||||
self.input_num_channels
|
||||
);
|
||||
debug_assert_eq!(stream_config.num_frames(), self.input_num_frames);
|
||||
self.restore_num_channels();
|
||||
|
||||
let resampling_required = self.input_num_frames != self.buffer_num_frames;
|
||||
|
||||
if self.num_channels == 1 {
|
||||
if self.input_num_channels == 1 {
|
||||
// Mono to mono.
|
||||
if resampling_required {
|
||||
let mut float_buffer = vec![0.0f32; self.input_num_frames];
|
||||
audio_util::s16_to_float_s16_slice(
|
||||
&interleaved_data[..self.input_num_frames],
|
||||
&mut float_buffer,
|
||||
);
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
self.input_resamplers[0].resample(&float_buffer, ch0);
|
||||
} else {
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
audio_util::s16_to_float_s16_slice(
|
||||
&interleaved_data[..self.input_num_frames],
|
||||
ch0,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Multi-channel to mono (downmix).
|
||||
let mut downmixed = vec![0.0f32; self.input_num_frames];
|
||||
|
||||
if self.downmix_by_averaging {
|
||||
for (j, sample) in downmixed.iter_mut().enumerate().take(self.input_num_frames)
|
||||
{
|
||||
let mut sum: i32 = 0;
|
||||
for ch in 0..self.input_num_channels {
|
||||
sum += interleaved_data[j * self.input_num_channels + ch] as i32;
|
||||
}
|
||||
*sample = sum as f32 / self.input_num_channels as f32;
|
||||
}
|
||||
} else {
|
||||
for j in 0..self.input_num_frames {
|
||||
downmixed[j] = interleaved_data
|
||||
[j * self.input_num_channels + self.channel_for_downmixing]
|
||||
as f32;
|
||||
}
|
||||
}
|
||||
|
||||
if resampling_required {
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
self.input_resamplers[0].resample(&downmixed, ch0);
|
||||
} else {
|
||||
self.data.bands_mut(0)[..self.input_num_frames].copy_from_slice(&downmixed);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Multi-channel, deinterleave.
|
||||
if resampling_required {
|
||||
let mut float_buffer = vec![0.0f32; self.input_num_frames];
|
||||
for i in 0..self.num_channels {
|
||||
// Deinterleave channel i.
|
||||
for (j, sample) in float_buffer
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.take(self.input_num_frames)
|
||||
{
|
||||
*sample = interleaved_data[j * self.input_num_channels + i] as f32;
|
||||
}
|
||||
let ch = self.data.bands_mut(i);
|
||||
self.input_resamplers[i].resample(&float_buffer, ch);
|
||||
}
|
||||
} else {
|
||||
for i in 0..self.num_channels {
|
||||
let ch = self.data.bands_mut(i);
|
||||
for j in 0..self.input_num_frames {
|
||||
ch[j] = interleaved_data[j * self.input_num_channels + i] as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy data from the buffer to interleaved i16 output.
|
||||
pub(crate) fn copy_to_interleaved_i16(
|
||||
&mut self,
|
||||
stream_config: &StreamConfig,
|
||||
interleaved_data: &mut [i16],
|
||||
) {
|
||||
let config_num_channels = stream_config.num_channels() as usize;
|
||||
debug_assert!(config_num_channels == self.num_channels || self.num_channels == 1);
|
||||
debug_assert_eq!(stream_config.num_frames(), self.output_num_frames);
|
||||
|
||||
let resampling_required = self.buffer_num_frames != self.output_num_frames;
|
||||
|
||||
if self.num_channels == 1 {
|
||||
let mut float_buffer = vec![0.0f32; self.output_num_frames];
|
||||
|
||||
if resampling_required {
|
||||
let ch0 = self.data.bands(0);
|
||||
self.output_resamplers[0].resample(ch0, &mut float_buffer);
|
||||
} else {
|
||||
float_buffer.copy_from_slice(&self.data.bands(0)[..self.output_num_frames]);
|
||||
}
|
||||
|
||||
if config_num_channels == 1 {
|
||||
for (dst, &src) in interleaved_data.iter_mut().zip(float_buffer.iter()) {
|
||||
*dst = audio_util::float_s16_to_s16(src);
|
||||
}
|
||||
} else {
|
||||
let mut k = 0;
|
||||
for &fb in &float_buffer[..self.output_num_frames] {
|
||||
let tmp = audio_util::float_s16_to_s16(fb);
|
||||
for _ in 0..config_num_channels {
|
||||
interleaved_data[k] = tmp;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if resampling_required {
|
||||
for i in 0..self.num_channels {
|
||||
let mut float_buffer = vec![0.0f32; self.output_num_frames];
|
||||
let ch = self.data.bands(i);
|
||||
self.output_resamplers[i].resample(ch, &mut float_buffer);
|
||||
for (k, sample) in float_buffer.iter().enumerate().take(self.output_num_frames)
|
||||
{
|
||||
interleaved_data[k * config_num_channels + i] =
|
||||
audio_util::float_s16_to_s16(*sample);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i in 0..self.num_channels {
|
||||
let ch = self.data.bands(i);
|
||||
for j in 0..self.output_num_frames {
|
||||
interleaved_data[j * config_num_channels + i] =
|
||||
audio_util::float_s16_to_s16(ch[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Copy extra channels from channel 0.
|
||||
for i in self.num_channels..config_num_channels {
|
||||
for j in 0..self.output_num_frames {
|
||||
interleaved_data[j * config_num_channels + i] =
|
||||
interleaved_data[j * config_num_channels + (i % self.num_channels)];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Split the buffer data into frequency bands.
|
||||
pub(crate) fn split_into_frequency_bands(&mut self) {
|
||||
if let (Some(filter), Some(split)) = (&mut self.splitting_filter, &mut self.split_data) {
|
||||
filter.analysis(&self.data, split);
|
||||
}
|
||||
}
|
||||
|
||||
/// Recombine frequency bands into full-band signal.
|
||||
pub(crate) fn merge_frequency_bands(&mut self) {
|
||||
if let (Some(filter), Some(split)) = (&mut self.splitting_filter, &mut self.split_data) {
|
||||
filter.synthesis(split, &mut self.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn copy_without_resampling() {
|
||||
let mut ab1 = AudioBuffer::new(32000, 2, 32000, 2, 32000);
|
||||
let mut ab2 = AudioBuffer::new(32000, 2, 32000, 2, 32000);
|
||||
|
||||
// Fill first buffer.
|
||||
let num_ch = ab1.num_channels();
|
||||
let num_fr = ab1.num_frames();
|
||||
for ch in 0..num_ch {
|
||||
let channel = ab1.channel_mut(ch);
|
||||
for (i, sample) in channel.iter_mut().enumerate().take(num_fr) {
|
||||
*sample = (i + ch) as f32;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy to second buffer.
|
||||
ab1.copy_to_buffer(&mut ab2);
|
||||
|
||||
// Verify content.
|
||||
for ch in 0..ab2.num_channels() {
|
||||
let channel = ab2.channel(ch);
|
||||
for (i, &sample) in channel.iter().enumerate() {
|
||||
assert_eq!(sample, (i + ch) as f32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_with_resampling() {
|
||||
let mut ab1 = AudioBuffer::new(32000, 2, 32000, 2, 48000);
|
||||
let mut ab2 = AudioBuffer::new(48000, 2, 48000, 2, 48000);
|
||||
|
||||
use std::f32::consts::PI;
|
||||
|
||||
let mut energy_ab1 = 0.0f32;
|
||||
let num_ch = ab1.num_channels();
|
||||
let num_fr = ab1.num_frames();
|
||||
|
||||
// Put a sine and compute energy of first buffer.
|
||||
for ch in 0..num_ch {
|
||||
let channel = ab1.channel_mut(ch);
|
||||
for (i, sample) in channel.iter_mut().enumerate().take(num_fr) {
|
||||
*sample = (2.0 * PI * 100.0 / 32000.0 * i as f32).sin();
|
||||
energy_ab1 += *sample * *sample;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy to second buffer (resamples 32k → 48k).
|
||||
ab1.copy_to_buffer(&mut ab2);
|
||||
|
||||
// Compute energy of second buffer.
|
||||
let mut energy_ab2 = 0.0f32;
|
||||
for ch in 0..ab2.num_channels() {
|
||||
let channel = ab2.channel(ch);
|
||||
for &sample in channel.iter() {
|
||||
energy_ab2 += sample * sample;
|
||||
}
|
||||
}
|
||||
|
||||
// Verify energies match (accounting for rate difference).
|
||||
let expected = energy_ab2 * 32000.0 / 48000.0;
|
||||
assert!(
|
||||
(energy_ab1 - expected).abs() < 0.01 * energy_ab1,
|
||||
"energy mismatch: ab1={energy_ab1}, ab2_scaled={expected}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn band_splitting() {
|
||||
let mut ab = AudioBuffer::new(48000, 1, 48000, 1, 48000);
|
||||
assert_eq!(ab.num_bands(), 3);
|
||||
assert_eq!(ab.num_frames_per_band(), 160);
|
||||
|
||||
// Fill with a signal.
|
||||
let channel = ab.channel_mut(0);
|
||||
for (i, sample) in channel.iter_mut().enumerate() {
|
||||
*sample = (i as f32 / 48.0).sin() * 8192.0;
|
||||
}
|
||||
|
||||
ab.split_into_frequency_bands();
|
||||
|
||||
// Band 0 should have some energy.
|
||||
let band0 = ab.split_band(0, 0);
|
||||
let energy: f32 = band0.iter().map(|x| x * x).sum();
|
||||
assert!(energy > 0.0, "band 0 should have energy after splitting");
|
||||
|
||||
ab.merge_frequency_bands();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_band_no_splitting_filter() {
|
||||
let ab = AudioBuffer::new(16000, 1, 16000, 1, 16000);
|
||||
assert_eq!(ab.num_bands(), 1);
|
||||
assert_eq!(ab.num_frames(), 160);
|
||||
assert_eq!(ab.num_frames_per_band(), 160);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_band_32khz() {
|
||||
let ab = AudioBuffer::new(32000, 1, 32000, 1, 32000);
|
||||
assert_eq!(ab.num_bands(), 2);
|
||||
assert_eq!(ab.num_frames(), 320);
|
||||
assert_eq!(ab.num_frames_per_band(), 160);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downmix_by_averaging() {
|
||||
let mut ab = AudioBuffer::new(16000, 2, 16000, 1, 16000);
|
||||
ab.set_downmixing_by_averaging();
|
||||
|
||||
let ch0 = vec![0.25f32; 160];
|
||||
let ch1 = vec![0.75f32; 160];
|
||||
let channels: Vec<&[f32]> = vec![&ch0, &ch1];
|
||||
let config = StreamConfig::new(16000, 2);
|
||||
|
||||
ab.copy_from_float(&channels, &config);
|
||||
|
||||
// After downmixing: (0.25 + 0.75) / 2 = 0.5 → FloatS16: 0.5 * 32768 = 16384
|
||||
let channel = ab.channel(0);
|
||||
for &s in channel.iter() {
|
||||
let expected = 0.5 * 32768.0;
|
||||
assert!((s - expected).abs() < 1.0, "expected ~{expected}, got {s}",);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downmix_specific_channel() {
|
||||
let mut ab = AudioBuffer::new(16000, 2, 16000, 1, 16000);
|
||||
ab.set_downmixing_to_specific_channel(1);
|
||||
|
||||
let ch0 = vec![0.25f32; 160];
|
||||
let ch1 = vec![0.75f32; 160];
|
||||
let channels: Vec<&[f32]> = vec![&ch0, &ch1];
|
||||
let config = StreamConfig::new(16000, 2);
|
||||
|
||||
ab.copy_from_float(&channels, &config);
|
||||
|
||||
// After selecting channel 1: 0.75 → FloatS16: 0.75 * 32768 = 24576
|
||||
let channel = ab.channel(0);
|
||||
for &s in channel.iter() {
|
||||
let expected = 0.75 * 32768.0;
|
||||
assert!((s - expected).abs() < 1.0, "expected ~{expected}, got {s}",);
|
||||
}
|
||||
}
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
//! Format conversion (remixing and resampling) for audio.
|
||||
//!
|
||||
//! Ported from `common_audio/audio_converter.h/cc`.
|
||||
//!
|
||||
//! Only simple remixing conversions are supported: downmix to mono
|
||||
//! (`dst_channels == 1`) or upmix from mono (`src_channels == 1`).
|
||||
|
||||
use sonora_common_audio::channel_buffer::ChannelBuffer;
|
||||
use sonora_common_audio::push_sinc_resampler::PushSincResampler;
|
||||
|
||||
/// Audio format converter supporting remixing and resampling.
|
||||
///
|
||||
/// The source and destination chunks have the same duration in time; specifying
|
||||
/// the number of frames is equivalent to specifying the sample rates.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AudioConverter {
|
||||
src_channels: usize,
|
||||
src_frames: usize,
|
||||
dst_channels: usize,
|
||||
dst_frames: usize,
|
||||
kind: ConverterKind,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ConverterKind {
|
||||
/// Same channels, same frames — just copy.
|
||||
Copy,
|
||||
/// Mono → multichannel upmix.
|
||||
Upmix,
|
||||
/// Multichannel → mono downmix.
|
||||
Downmix,
|
||||
/// Same channels, different frames — resample.
|
||||
Resample { resamplers: Vec<PushSincResampler> },
|
||||
/// Composition of two converters with intermediate buffer.
|
||||
Composition {
|
||||
first: Box<AudioConverter>,
|
||||
second: Box<AudioConverter>,
|
||||
buffer: ChannelBuffer<f32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl AudioConverter {
|
||||
/// Creates a new `AudioConverter` for the given format.
|
||||
///
|
||||
/// Only supports: same channel count, downmix to mono, or upmix from mono.
|
||||
pub(crate) fn new(
|
||||
src_channels: usize,
|
||||
src_frames: usize,
|
||||
dst_channels: usize,
|
||||
dst_frames: usize,
|
||||
) -> Self {
|
||||
debug_assert!(
|
||||
dst_channels == src_channels || dst_channels == 1 || src_channels == 1,
|
||||
"Only same channels, downmix to mono, or upmix from mono supported"
|
||||
);
|
||||
|
||||
let kind = if src_channels > dst_channels {
|
||||
// Downmix (+ optional resample).
|
||||
if src_frames != dst_frames {
|
||||
let first = Box::new(Self::new_with_kind(
|
||||
src_channels,
|
||||
src_frames,
|
||||
dst_channels,
|
||||
src_frames,
|
||||
ConverterKind::Downmix,
|
||||
));
|
||||
let resamplers = (0..dst_channels)
|
||||
.map(|_| PushSincResampler::new(src_frames, dst_frames))
|
||||
.collect();
|
||||
let second = Box::new(Self::new_with_kind(
|
||||
dst_channels,
|
||||
src_frames,
|
||||
dst_channels,
|
||||
dst_frames,
|
||||
ConverterKind::Resample { resamplers },
|
||||
));
|
||||
let buffer = ChannelBuffer::new_single_band(src_frames, dst_channels);
|
||||
ConverterKind::Composition {
|
||||
first,
|
||||
second,
|
||||
buffer,
|
||||
}
|
||||
} else {
|
||||
ConverterKind::Downmix
|
||||
}
|
||||
} else if src_channels < dst_channels {
|
||||
// Upmix (+ optional resample).
|
||||
if src_frames != dst_frames {
|
||||
let resamplers = (0..src_channels)
|
||||
.map(|_| PushSincResampler::new(src_frames, dst_frames))
|
||||
.collect();
|
||||
let first = Box::new(Self::new_with_kind(
|
||||
src_channels,
|
||||
src_frames,
|
||||
src_channels,
|
||||
dst_frames,
|
||||
ConverterKind::Resample { resamplers },
|
||||
));
|
||||
let second = Box::new(Self::new_with_kind(
|
||||
src_channels,
|
||||
dst_frames,
|
||||
dst_channels,
|
||||
dst_frames,
|
||||
ConverterKind::Upmix,
|
||||
));
|
||||
let buffer = ChannelBuffer::new_single_band(dst_frames, src_channels);
|
||||
ConverterKind::Composition {
|
||||
first,
|
||||
second,
|
||||
buffer,
|
||||
}
|
||||
} else {
|
||||
ConverterKind::Upmix
|
||||
}
|
||||
} else if src_frames != dst_frames {
|
||||
// Same channels, different frames — resample only.
|
||||
let resamplers = (0..src_channels)
|
||||
.map(|_| PushSincResampler::new(src_frames, dst_frames))
|
||||
.collect();
|
||||
ConverterKind::Resample { resamplers }
|
||||
} else {
|
||||
// Everything matches — just copy.
|
||||
ConverterKind::Copy
|
||||
};
|
||||
|
||||
Self {
|
||||
src_channels,
|
||||
src_frames,
|
||||
dst_channels,
|
||||
dst_frames,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_with_kind(
|
||||
src_channels: usize,
|
||||
src_frames: usize,
|
||||
dst_channels: usize,
|
||||
dst_frames: usize,
|
||||
kind: ConverterKind,
|
||||
) -> Self {
|
||||
Self {
|
||||
src_channels,
|
||||
src_frames,
|
||||
dst_channels,
|
||||
dst_frames,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts `src` to `dst`.
|
||||
///
|
||||
/// `src` contains `src_channels` slices of `src_frames` samples each.
|
||||
/// `dst` contains `dst_channels` slices of `dst_frames` samples each.
|
||||
pub(crate) fn convert(&mut self, src: &[&[f32]], dst: &mut [&mut [f32]]) {
|
||||
debug_assert_eq!(src.len(), self.src_channels);
|
||||
debug_assert_eq!(dst.len(), self.dst_channels);
|
||||
for s in src.iter() {
|
||||
debug_assert_eq!(s.len(), self.src_frames);
|
||||
}
|
||||
for d in dst.iter() {
|
||||
debug_assert_eq!(d.len(), self.dst_frames);
|
||||
}
|
||||
|
||||
match &mut self.kind {
|
||||
ConverterKind::Copy => {
|
||||
for (i, src_ch) in src.iter().enumerate() {
|
||||
dst[i].copy_from_slice(src_ch);
|
||||
}
|
||||
}
|
||||
ConverterKind::Upmix => {
|
||||
for i in 0..self.dst_frames {
|
||||
let value = src[0][i];
|
||||
for dst_ch in dst.iter_mut() {
|
||||
dst_ch[i] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
ConverterKind::Downmix => {
|
||||
let scale = 1.0 / self.src_channels as f32;
|
||||
for i in 0..self.src_frames {
|
||||
let mut sum = 0.0_f32;
|
||||
for src_ch in src.iter() {
|
||||
sum += src_ch[i];
|
||||
}
|
||||
dst[0][i] = sum * scale;
|
||||
}
|
||||
}
|
||||
ConverterKind::Resample { resamplers } => {
|
||||
for (i, resampler) in resamplers.iter_mut().enumerate() {
|
||||
resampler.resample(src[i], dst[i]);
|
||||
}
|
||||
}
|
||||
ConverterKind::Composition {
|
||||
first,
|
||||
second,
|
||||
buffer,
|
||||
} => {
|
||||
let first_dst_channels = first.dst_channels;
|
||||
let first_dst_frames = first.dst_frames;
|
||||
let frames_per_ch = buffer.num_frames();
|
||||
|
||||
// First stage: convert into intermediate buffer.
|
||||
{
|
||||
let data = buffer.bands_mut(0);
|
||||
let mut buf_slices: Vec<&mut [f32]> = Vec::with_capacity(first_dst_channels);
|
||||
let mut remainder = &mut data[..];
|
||||
for _ in 0..first_dst_channels {
|
||||
let (chunk, rest) = remainder.split_at_mut(frames_per_ch);
|
||||
buf_slices.push(&mut chunk[..first_dst_frames]);
|
||||
remainder = rest;
|
||||
}
|
||||
first.convert(src, &mut buf_slices);
|
||||
}
|
||||
|
||||
// Second stage: convert from intermediate buffer to dst.
|
||||
{
|
||||
let data = buffer.bands(0);
|
||||
let buf_refs: Vec<&[f32]> = (0..first_dst_channels)
|
||||
.map(|ch| {
|
||||
let start = ch * frames_per_ch;
|
||||
&data[start..start + first_dst_frames]
|
||||
})
|
||||
.collect();
|
||||
second.convert(&buf_refs, dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn create_buffer(data: &[f32], frames: usize) -> ChannelBuffer<f32> {
|
||||
let num_channels = data.len();
|
||||
let mut buf = ChannelBuffer::new_single_band(frames, num_channels);
|
||||
for (i, &scale) in data.iter().enumerate() {
|
||||
for j in 0..frames {
|
||||
buf.channel_mut(0, i)[j] = scale * j as f32;
|
||||
}
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
fn compute_snr(
|
||||
ref_buf: &ChannelBuffer<f32>,
|
||||
test_buf: &ChannelBuffer<f32>,
|
||||
expected_delay: usize,
|
||||
) -> f32 {
|
||||
assert_eq!(ref_buf.num_channels(), test_buf.num_channels());
|
||||
assert_eq!(ref_buf.num_frames(), test_buf.num_frames());
|
||||
|
||||
let mut best_snr = 0.0_f32;
|
||||
let min_delay = expected_delay.saturating_sub(1);
|
||||
let max_delay = (expected_delay + 1).min(ref_buf.num_frames());
|
||||
|
||||
for delay in min_delay..=max_delay {
|
||||
let mut mse = 0.0_f32;
|
||||
let mut variance = 0.0_f32;
|
||||
let mut mean = 0.0_f32;
|
||||
|
||||
for i in 0..ref_buf.num_channels() {
|
||||
let ref_ch = ref_buf.channel(0, i);
|
||||
let test_ch = test_buf.channel(0, i);
|
||||
for j in 0..ref_buf.num_frames() - delay {
|
||||
let error = ref_ch[j] - test_ch[j + delay];
|
||||
mse += error * error;
|
||||
variance += ref_ch[j] * ref_ch[j];
|
||||
mean += ref_ch[j];
|
||||
}
|
||||
}
|
||||
|
||||
let length = ref_buf.num_channels() * (ref_buf.num_frames() - delay);
|
||||
if length == 0 {
|
||||
continue;
|
||||
}
|
||||
let length_f = length as f32;
|
||||
mse /= length_f;
|
||||
variance /= length_f;
|
||||
mean /= length_f;
|
||||
variance -= mean * mean;
|
||||
let snr = if mse > 0.0 {
|
||||
10.0 * (variance / mse).log10()
|
||||
} else {
|
||||
100.0
|
||||
};
|
||||
if snr > best_snr {
|
||||
best_snr = snr;
|
||||
}
|
||||
}
|
||||
best_snr
|
||||
}
|
||||
|
||||
fn run_audio_converter_test(
|
||||
src_channels: usize,
|
||||
src_sample_rate_hz: usize,
|
||||
dst_channels: usize,
|
||||
dst_sample_rate_hz: usize,
|
||||
) {
|
||||
let src_left = 0.0002_f32;
|
||||
let src_right = 0.0001_f32;
|
||||
let resampling_factor = src_sample_rate_hz as f32 / dst_sample_rate_hz as f32;
|
||||
let dst_left = resampling_factor * src_left;
|
||||
let dst_right = resampling_factor * src_right;
|
||||
let dst_mono = (dst_left + dst_right) / 2.0;
|
||||
let src_frames = src_sample_rate_hz / 100;
|
||||
let dst_frames = dst_sample_rate_hz / 100;
|
||||
|
||||
let mut src_data = vec![src_left];
|
||||
if src_channels == 2 {
|
||||
src_data.push(src_right);
|
||||
}
|
||||
let src_buffer = create_buffer(&src_data, src_frames);
|
||||
|
||||
let ref_data = if dst_channels == 1 {
|
||||
if src_channels == 1 {
|
||||
vec![dst_left]
|
||||
} else {
|
||||
vec![dst_mono]
|
||||
}
|
||||
} else if src_channels == 1 {
|
||||
vec![dst_left, dst_left]
|
||||
} else {
|
||||
vec![dst_left, dst_right]
|
||||
};
|
||||
|
||||
let mut dst_buffer = create_buffer(&vec![0.0; dst_channels], dst_frames);
|
||||
let ref_buffer = create_buffer(&ref_data, dst_frames);
|
||||
|
||||
let delay_frames = if src_sample_rate_hz == dst_sample_rate_hz {
|
||||
0
|
||||
} else {
|
||||
(PushSincResampler::algorithmic_delay_seconds(src_sample_rate_hz as u32)
|
||||
* dst_sample_rate_hz as f32) as usize
|
||||
};
|
||||
|
||||
let mut converter = AudioConverter::new(src_channels, src_frames, dst_channels, dst_frames);
|
||||
|
||||
let src_refs: Vec<&[f32]> = (0..src_channels)
|
||||
.map(|ch| src_buffer.channel(0, ch))
|
||||
.collect();
|
||||
|
||||
// Extract dst channels into temporary vecs, convert, then copy back.
|
||||
let mut dst_vecs: Vec<Vec<f32>> = (0..dst_channels)
|
||||
.map(|ch| dst_buffer.channel(0, ch).to_vec())
|
||||
.collect();
|
||||
{
|
||||
let mut dst_slices: Vec<&mut [f32]> =
|
||||
dst_vecs.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
converter.convert(&src_refs, &mut dst_slices);
|
||||
}
|
||||
for (ch, vec) in dst_vecs.iter().enumerate() {
|
||||
dst_buffer.channel_mut(0, ch).copy_from_slice(vec);
|
||||
}
|
||||
|
||||
let snr = compute_snr(&ref_buffer, &dst_buffer, delay_frames);
|
||||
assert!(
|
||||
snr > 43.0,
|
||||
"SNR={snr:.1} dB too low for ({src_channels}, {src_sample_rate_hz} Hz) -> ({dst_channels}, {dst_sample_rate_hz} Hz)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversions_pass_snr_threshold() {
|
||||
let sample_rates = [8000, 11025, 16000, 22050, 32000, 44100, 48000];
|
||||
let channels = [1, 2];
|
||||
for &src_rate in &sample_rates {
|
||||
for &dst_rate in &sample_rates {
|
||||
for &src_ch in &channels {
|
||||
for &dst_ch in &channels {
|
||||
run_audio_converter_test(src_ch, src_rate, dst_ch, dst_rate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_preserves_signal() {
|
||||
let mut converter = AudioConverter::new(1, 160, 1, 160);
|
||||
let src = vec![1.0_f32; 160];
|
||||
let mut dst = vec![0.0_f32; 160];
|
||||
converter.convert(&[&src], &mut [&mut dst]);
|
||||
assert_eq!(src, dst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upmix_duplicates_mono() {
|
||||
let mut converter = AudioConverter::new(1, 160, 2, 160);
|
||||
let src: Vec<f32> = (0..160).map(|i| i as f32).collect();
|
||||
let mut dst0 = vec![0.0_f32; 160];
|
||||
let mut dst1 = vec![0.0_f32; 160];
|
||||
converter.convert(&[&src], &mut [&mut dst0, &mut dst1]);
|
||||
assert_eq!(src, dst0);
|
||||
assert_eq!(src, dst1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downmix_averages_channels() {
|
||||
let mut converter = AudioConverter::new(2, 160, 1, 160);
|
||||
let src0: Vec<f32> = (0..160).map(|i| i as f32 * 2.0).collect();
|
||||
let src1: Vec<f32> = (0..160).map(|i| i as f32).collect();
|
||||
let mut dst = vec![0.0_f32; 160];
|
||||
converter.convert(&[&src0, &src1], &mut [&mut dst]);
|
||||
for i in 0..160 {
|
||||
let expected = (src0[i] + src1[i]) / 2.0;
|
||||
assert!(
|
||||
(dst[i] - expected).abs() < 1e-6,
|
||||
"sample {i}: expected {expected}, got {}",
|
||||
dst[i]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1488
File diff suppressed because it is too large.
Load diff
+1618
File diff suppressed because it is too large.
Load diff
+352
@@ -0,0 +1,352 @@
|
||||
//! Audio samples scaler — applies gain with linear ramping.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.h/cc`.
|
||||
|
||||
use crate::audio_buffer::AudioBuffer;
|
||||
|
||||
const MIN_FLOAT_S16_VALUE: f32 = -32768.0;
|
||||
const MAX_FLOAT_S16_VALUE: f32 = 32767.0;
|
||||
|
||||
/// Applies a gain to audio samples with linear ramping over one frame.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AudioSamplesScaler {
|
||||
previous_gain: f32,
|
||||
target_gain: f32,
|
||||
samples_per_channel: i32,
|
||||
one_by_samples_per_channel: f32,
|
||||
}
|
||||
|
||||
impl AudioSamplesScaler {
|
||||
/// Create a new scaler with the given initial gain (applied immediately).
|
||||
pub(crate) fn new(initial_gain: f32) -> Self {
|
||||
Self {
|
||||
previous_gain: initial_gain,
|
||||
target_gain: initial_gain,
|
||||
samples_per_channel: -1,
|
||||
one_by_samples_per_channel: -1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the target gain. Changes take effect gradually over the next frame.
|
||||
pub(crate) fn set_gain(&mut self, gain: f32) {
|
||||
self.target_gain = gain;
|
||||
}
|
||||
|
||||
/// Apply gain to the audio buffer with linear ramping and S16 clamping.
|
||||
pub(crate) fn process(&mut self, audio_buffer: &mut AudioBuffer) {
|
||||
let num_frames = audio_buffer.num_frames();
|
||||
|
||||
if num_frames as i32 != self.samples_per_channel {
|
||||
debug_assert!(num_frames > 0);
|
||||
self.samples_per_channel = num_frames as i32;
|
||||
self.one_by_samples_per_channel = 1.0 / self.samples_per_channel as f32;
|
||||
}
|
||||
|
||||
if self.target_gain == 1.0 && self.previous_gain == self.target_gain {
|
||||
return;
|
||||
}
|
||||
|
||||
let num_channels = audio_buffer.num_channels();
|
||||
|
||||
if self.previous_gain == self.target_gain {
|
||||
// Apply constant gain.
|
||||
let gain = self.previous_gain;
|
||||
for channel in 0..num_channels {
|
||||
let data = audio_buffer.channel_mut(channel);
|
||||
for sample in data[..num_frames].iter_mut() {
|
||||
*sample *= gain;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let increment =
|
||||
(self.target_gain - self.previous_gain) * self.one_by_samples_per_channel;
|
||||
|
||||
if increment > 0.0 {
|
||||
// Apply increasing gain.
|
||||
for channel in 0..num_channels {
|
||||
let mut gain = self.previous_gain;
|
||||
let data = audio_buffer.channel_mut(channel);
|
||||
for sample in data[..num_frames].iter_mut() {
|
||||
gain = (gain + increment).min(self.target_gain);
|
||||
*sample *= gain;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Apply decreasing gain.
|
||||
for channel in 0..num_channels {
|
||||
let mut gain = self.previous_gain;
|
||||
let data = audio_buffer.channel_mut(channel);
|
||||
for sample in data[..num_frames].iter_mut() {
|
||||
gain = (gain + increment).max(self.target_gain);
|
||||
*sample *= gain;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.previous_gain = self.target_gain;
|
||||
|
||||
// Clamp to S16 range.
|
||||
for channel in 0..num_channels {
|
||||
let data = audio_buffer.channel_mut(channel);
|
||||
for sample in data[..num_frames].iter_mut() {
|
||||
*sample = sample.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_value_for_channel(channel: usize) -> f32 {
|
||||
100.0 + channel as f32
|
||||
}
|
||||
|
||||
fn populate_buffer(audio_buffer: &mut AudioBuffer) {
|
||||
let num_ch = audio_buffer.num_channels();
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_ch {
|
||||
let value = sample_value_for_channel(ch);
|
||||
let data = audio_buffer.channel_mut(ch);
|
||||
for sample in data[..num_fr].iter_mut() {
|
||||
*sample = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NUM_FRAMES_TO_PROCESS: usize = 10;
|
||||
|
||||
fn test_params() -> Vec<(usize, usize, f32)> {
|
||||
let mut params = Vec::new();
|
||||
for &rate in &[16000, 32000, 48000] {
|
||||
for &channels in &[1, 2, 4] {
|
||||
for &gain in &[0.1, 1.0, 2.0, 4.0] {
|
||||
params.push((rate, channels, gain));
|
||||
}
|
||||
}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_gain_is_respected() {
|
||||
for (sample_rate_hz, num_channels, initial_gain) in test_params() {
|
||||
let mut scaler = AudioSamplesScaler::new(initial_gain);
|
||||
let mut audio_buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
for _ in 0..NUM_FRAMES_TO_PROCESS {
|
||||
populate_buffer(&mut audio_buffer);
|
||||
scaler.process(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected = initial_gain * sample_value_for_channel(ch);
|
||||
let clamped = expected.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - clamped).abs() < 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}, gain={initial_gain}: expected {clamped}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_gain_adjustment() {
|
||||
for (sample_rate_hz, num_channels, higher_gain) in test_params() {
|
||||
let lower_gain = higher_gain / 2.0;
|
||||
let mut scaler = AudioSamplesScaler::new(lower_gain);
|
||||
let mut audio_buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
// Allow initial lower gain to take effect.
|
||||
populate_buffer(&mut audio_buffer);
|
||||
scaler.process(&mut audio_buffer);
|
||||
|
||||
// Set higher gain.
|
||||
scaler.set_gain(higher_gain);
|
||||
|
||||
// Gain should ramp up gradually over one frame.
|
||||
populate_buffer(&mut audio_buffer);
|
||||
scaler.process(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let target = higher_gain * sample_value_for_channel(ch);
|
||||
let clamped_target = target.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for i in 0..num_fr - 1 {
|
||||
assert!(
|
||||
data[i] <= clamped_target + 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}: sample[{i}]={} should be <= {clamped_target}",
|
||||
data[i],
|
||||
);
|
||||
assert!(
|
||||
data[i] <= data[i + 1] + 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}: samples should be non-decreasing",
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
data[num_fr - 1] <= clamped_target + 1e-4,
|
||||
"last sample should be <= target",
|
||||
);
|
||||
}
|
||||
|
||||
// After transition, gain should be stable at higher_gain.
|
||||
for _ in 0..NUM_FRAMES_TO_PROCESS {
|
||||
populate_buffer(&mut audio_buffer);
|
||||
scaler.process(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected = higher_gain * sample_value_for_channel(ch);
|
||||
let clamped = expected.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - clamped).abs() < 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}: expected stable {clamped}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set lower gain.
|
||||
scaler.set_gain(lower_gain);
|
||||
|
||||
// Gain should ramp down gradually.
|
||||
populate_buffer(&mut audio_buffer);
|
||||
scaler.process(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let target = lower_gain * sample_value_for_channel(ch);
|
||||
let clamped_target = target.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for i in 0..num_fr - 1 {
|
||||
assert!(
|
||||
data[i] >= clamped_target - 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}: sample[{i}]={} should be >= {clamped_target}",
|
||||
data[i],
|
||||
);
|
||||
assert!(
|
||||
data[i] >= data[i + 1] - 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}: samples should be non-increasing",
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
data[num_fr - 1] >= clamped_target - 1e-4,
|
||||
"last sample should be >= target",
|
||||
);
|
||||
}
|
||||
|
||||
// After transition, gain should be stable at lower_gain.
|
||||
for _ in 0..NUM_FRAMES_TO_PROCESS {
|
||||
populate_buffer(&mut audio_buffer);
|
||||
scaler.process(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected = lower_gain * sample_value_for_channel(ch);
|
||||
let clamped = expected.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - clamped).abs() < 1e-4,
|
||||
"rate={sample_rate_hz}, ch={ch}: expected stable {clamped}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upwards_clamping() {
|
||||
let sample_rate_hz = 48000;
|
||||
let num_channels = 1;
|
||||
let gain = 10.0f32;
|
||||
let max_clamped = MAX_FLOAT_S16_VALUE;
|
||||
|
||||
let mut scaler = AudioSamplesScaler::new(gain);
|
||||
let mut audio_buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for _ in 0..NUM_FRAMES_TO_PROCESS {
|
||||
// Fill with values near max that when multiplied by gain exceed max.
|
||||
for ch in 0..num_channels {
|
||||
let value = max_clamped - num_channels as f32 + 1.0 + ch as f32;
|
||||
let data = audio_buffer.channel_mut(ch);
|
||||
for sample in data[..num_fr].iter_mut() {
|
||||
*sample = value;
|
||||
}
|
||||
}
|
||||
|
||||
scaler.process(&mut audio_buffer);
|
||||
for ch in 0..num_channels {
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - max_clamped).abs() < 1e-4,
|
||||
"expected {max_clamped}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downwards_clamping() {
|
||||
let sample_rate_hz = 48000;
|
||||
let num_channels = 1;
|
||||
let gain = 10.0f32;
|
||||
let min_clamped = MIN_FLOAT_S16_VALUE;
|
||||
|
||||
let mut scaler = AudioSamplesScaler::new(gain);
|
||||
let mut audio_buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for _ in 0..NUM_FRAMES_TO_PROCESS {
|
||||
for ch in 0..num_channels {
|
||||
let value = min_clamped + num_channels as f32 - 1.0 + ch as f32;
|
||||
let data = audio_buffer.channel_mut(ch);
|
||||
for sample in data[..num_fr].iter_mut() {
|
||||
*sample = value;
|
||||
}
|
||||
}
|
||||
|
||||
scaler.process(&mut audio_buffer);
|
||||
for ch in 0..num_channels {
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - min_clamped).abs() < 1e-4,
|
||||
"expected {min_clamped}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
//! Capture levels adjuster — pre and post gain with emulated analog mic gain.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/capture_levels_adjuster/capture_levels_adjuster.h/cc`.
|
||||
|
||||
use crate::audio_buffer::AudioBuffer;
|
||||
use crate::audio_samples_scaler::AudioSamplesScaler;
|
||||
|
||||
const MIN_ANALOG_MIC_GAIN_LEVEL: i32 = 0;
|
||||
const MAX_ANALOG_MIC_GAIN_LEVEL: i32 = 255;
|
||||
|
||||
fn compute_level_based_gain(emulated_analog_mic_gain_level: i32) -> f32 {
|
||||
debug_assert!(emulated_analog_mic_gain_level >= MIN_ANALOG_MIC_GAIN_LEVEL);
|
||||
debug_assert!(emulated_analog_mic_gain_level <= MAX_ANALOG_MIC_GAIN_LEVEL);
|
||||
emulated_analog_mic_gain_level as f32 / MAX_ANALOG_MIC_GAIN_LEVEL as f32
|
||||
}
|
||||
|
||||
fn compute_pre_gain(
|
||||
pre_gain: f32,
|
||||
emulated_analog_mic_gain_level: i32,
|
||||
emulated_analog_mic_gain_enabled: bool,
|
||||
) -> f32 {
|
||||
if emulated_analog_mic_gain_enabled {
|
||||
pre_gain * compute_level_based_gain(emulated_analog_mic_gain_level)
|
||||
} else {
|
||||
pre_gain
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjusts capture signal levels with pre-gain, emulated analog mic gain, and post-gain.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CaptureLevelsAdjuster {
|
||||
emulated_analog_mic_gain_enabled: bool,
|
||||
emulated_analog_mic_gain_level: i32,
|
||||
pre_gain: f32,
|
||||
pre_adjustment_gain: f32,
|
||||
pre_scaler: AudioSamplesScaler,
|
||||
post_scaler: AudioSamplesScaler,
|
||||
}
|
||||
|
||||
impl CaptureLevelsAdjuster {
|
||||
pub(crate) fn new(
|
||||
emulated_analog_mic_gain_enabled: bool,
|
||||
emulated_analog_mic_gain_level: i32,
|
||||
pre_gain: f32,
|
||||
post_gain: f32,
|
||||
) -> Self {
|
||||
let pre_adjustment_gain = compute_pre_gain(
|
||||
pre_gain,
|
||||
emulated_analog_mic_gain_level,
|
||||
emulated_analog_mic_gain_enabled,
|
||||
);
|
||||
Self {
|
||||
emulated_analog_mic_gain_enabled,
|
||||
emulated_analog_mic_gain_level,
|
||||
pre_gain,
|
||||
pre_adjustment_gain,
|
||||
pre_scaler: AudioSamplesScaler::new(pre_adjustment_gain),
|
||||
post_scaler: AudioSamplesScaler::new(post_gain),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_pre_level_adjustment(&mut self, audio_buffer: &mut AudioBuffer) {
|
||||
self.pre_scaler.process(audio_buffer);
|
||||
}
|
||||
|
||||
pub(crate) fn apply_post_level_adjustment(&mut self, audio_buffer: &mut AudioBuffer) {
|
||||
self.post_scaler.process(audio_buffer);
|
||||
}
|
||||
|
||||
pub(crate) fn set_pre_gain(&mut self, pre_gain: f32) {
|
||||
self.pre_gain = pre_gain;
|
||||
self.update_pre_adjustment_gain();
|
||||
}
|
||||
|
||||
pub(crate) fn get_pre_adjustment_gain(&self) -> f32 {
|
||||
self.pre_adjustment_gain
|
||||
}
|
||||
|
||||
pub(crate) fn set_post_gain(&mut self, post_gain: f32) {
|
||||
self.post_scaler.set_gain(post_gain);
|
||||
}
|
||||
|
||||
pub(crate) fn set_analog_mic_gain_level(&mut self, level: i32) {
|
||||
debug_assert!(level >= MIN_ANALOG_MIC_GAIN_LEVEL);
|
||||
debug_assert!(level <= MAX_ANALOG_MIC_GAIN_LEVEL);
|
||||
let clamped = level.clamp(MIN_ANALOG_MIC_GAIN_LEVEL, MAX_ANALOG_MIC_GAIN_LEVEL);
|
||||
self.emulated_analog_mic_gain_level = clamped;
|
||||
self.update_pre_adjustment_gain();
|
||||
}
|
||||
|
||||
pub(crate) fn get_analog_mic_gain_level(&self) -> i32 {
|
||||
self.emulated_analog_mic_gain_level
|
||||
}
|
||||
|
||||
fn update_pre_adjustment_gain(&mut self) {
|
||||
self.pre_adjustment_gain = compute_pre_gain(
|
||||
self.pre_gain,
|
||||
self.emulated_analog_mic_gain_level,
|
||||
self.emulated_analog_mic_gain_enabled,
|
||||
);
|
||||
self.pre_scaler.set_gain(self.pre_adjustment_gain);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_value_for_channel(channel: usize) -> f32 {
|
||||
100.0 + channel as f32
|
||||
}
|
||||
|
||||
fn populate_buffer(audio_buffer: &mut AudioBuffer) {
|
||||
let num_ch = audio_buffer.num_channels();
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_ch {
|
||||
let value = sample_value_for_channel(ch);
|
||||
let data = audio_buffer.channel_mut(ch);
|
||||
for sample in data[..num_fr].iter_mut() {
|
||||
*sample = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compute_expected_pre_gain(
|
||||
emulated_enabled: bool,
|
||||
emulated_level: i32,
|
||||
pre_gain: f32,
|
||||
) -> f32 {
|
||||
if !emulated_enabled {
|
||||
return pre_gain;
|
||||
}
|
||||
pre_gain * emulated_level.min(255) as f32 / 255.0
|
||||
}
|
||||
|
||||
fn compute_expected_post_gain(
|
||||
emulated_enabled: bool,
|
||||
emulated_level: i32,
|
||||
pre_gain: f32,
|
||||
post_gain: f32,
|
||||
) -> f32 {
|
||||
post_gain * compute_expected_pre_gain(emulated_enabled, emulated_level, pre_gain)
|
||||
}
|
||||
|
||||
const NUM_FRAMES_TO_PROCESS: usize = 10;
|
||||
const MIN_FLOAT_S16_VALUE: f32 = -32768.0;
|
||||
const MAX_FLOAT_S16_VALUE: f32 = 32767.0;
|
||||
|
||||
fn test_params() -> Vec<(usize, usize, bool, i32, f32, f32)> {
|
||||
let mut params = Vec::new();
|
||||
for &rate in &[16000, 32000, 48000] {
|
||||
for &channels in &[1, 2, 4] {
|
||||
for &enabled in &[false, true] {
|
||||
for &level in &[21, 255] {
|
||||
for &pre in &[0.1, 1.0, 4.0] {
|
||||
for &post in &[0.1, 1.0, 4.0] {
|
||||
params.push((rate, channels, enabled, level, pre, post));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_gain_is_instantly_achieved() {
|
||||
for (sample_rate_hz, num_channels, emulated_enabled, emulated_level, pre_gain, post_gain) in
|
||||
test_params()
|
||||
{
|
||||
let mut adjuster =
|
||||
CaptureLevelsAdjuster::new(emulated_enabled, emulated_level, pre_gain, post_gain);
|
||||
|
||||
let mut audio_buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
let expected_pre =
|
||||
compute_expected_pre_gain(emulated_enabled, emulated_level, pre_gain);
|
||||
let expected_post =
|
||||
compute_expected_post_gain(emulated_enabled, emulated_level, pre_gain, post_gain);
|
||||
|
||||
for _ in 0..NUM_FRAMES_TO_PROCESS {
|
||||
populate_buffer(&mut audio_buffer);
|
||||
adjuster.apply_pre_level_adjustment(&mut audio_buffer);
|
||||
|
||||
assert!(
|
||||
(adjuster.get_pre_adjustment_gain() - expected_pre).abs() < 1e-6,
|
||||
"pre adjustment gain mismatch",
|
||||
);
|
||||
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected_val = (expected_pre * sample_value_for_channel(ch))
|
||||
.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - expected_val).abs() < 1e-3,
|
||||
"rate={sample_rate_hz}, ch={ch}, pre: expected {expected_val}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
adjuster.apply_post_level_adjustment(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected_val = (expected_post * sample_value_for_channel(ch))
|
||||
.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - expected_val).abs() < 1e-2,
|
||||
"rate={sample_rate_hz}, ch={ch}, post: expected {expected_val}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_gains_are_achieved() {
|
||||
for (sample_rate_hz, num_channels, emulated_enabled, emulated_level, pre_gain, post_gain) in
|
||||
test_params()
|
||||
{
|
||||
let lower_emulated_level = emulated_level;
|
||||
let lower_pre_gain = pre_gain;
|
||||
let lower_post_gain = post_gain;
|
||||
let higher_emulated_level = (lower_emulated_level * 2).min(255);
|
||||
let higher_pre_gain = lower_pre_gain * 2.0;
|
||||
let higher_post_gain = lower_post_gain * 2.0;
|
||||
|
||||
let mut adjuster = CaptureLevelsAdjuster::new(
|
||||
emulated_enabled,
|
||||
lower_emulated_level,
|
||||
lower_pre_gain,
|
||||
lower_post_gain,
|
||||
);
|
||||
|
||||
let mut audio_buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
let expected_pre =
|
||||
compute_expected_pre_gain(emulated_enabled, higher_emulated_level, higher_pre_gain);
|
||||
let expected_post = compute_expected_post_gain(
|
||||
emulated_enabled,
|
||||
higher_emulated_level,
|
||||
higher_pre_gain,
|
||||
higher_post_gain,
|
||||
);
|
||||
|
||||
adjuster.set_pre_gain(higher_pre_gain);
|
||||
adjuster.set_post_gain(higher_post_gain);
|
||||
adjuster.set_analog_mic_gain_level(higher_emulated_level);
|
||||
|
||||
// First frame: transition frame.
|
||||
populate_buffer(&mut audio_buffer);
|
||||
adjuster.apply_pre_level_adjustment(&mut audio_buffer);
|
||||
adjuster.apply_post_level_adjustment(&mut audio_buffer);
|
||||
assert_eq!(adjuster.get_analog_mic_gain_level(), higher_emulated_level);
|
||||
|
||||
// Subsequent frames: should be at stable new gain.
|
||||
for _ in 1..NUM_FRAMES_TO_PROCESS {
|
||||
populate_buffer(&mut audio_buffer);
|
||||
adjuster.apply_pre_level_adjustment(&mut audio_buffer);
|
||||
|
||||
assert!(
|
||||
(adjuster.get_pre_adjustment_gain() - expected_pre).abs() < 1e-6,
|
||||
"pre adjustment gain mismatch",
|
||||
);
|
||||
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected_val = (expected_pre * sample_value_for_channel(ch))
|
||||
.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - expected_val).abs() < 1e-3,
|
||||
"rate={sample_rate_hz}, ch={ch}, pre: expected {expected_val}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
adjuster.apply_post_level_adjustment(&mut audio_buffer);
|
||||
let num_fr = audio_buffer.num_frames();
|
||||
for ch in 0..num_channels {
|
||||
let expected_val = (expected_post * sample_value_for_channel(ch))
|
||||
.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
let data = audio_buffer.channel(ch);
|
||||
for &sample in &data[..num_fr] {
|
||||
assert!(
|
||||
(sample - expected_val).abs() < 1e-2,
|
||||
"rate={sample_rate_hz}, ch={ch}, post: expected {expected_val}, got {sample}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(adjuster.get_analog_mic_gain_level(), higher_emulated_level);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+341
@@ -0,0 +1,341 @@
|
||||
//! Audio processing configuration.
|
||||
//!
|
||||
//! Ported from `AudioProcessing::Config` in `api/audio/audio_processing.h`.
|
||||
|
||||
/// Top-level configuration for the audio processing pipeline.
|
||||
///
|
||||
/// This config is intended to be used during setup, and to enable/disable
|
||||
/// top-level processing effects. Use during processing may cause undesired
|
||||
/// submodule resets, affecting audio quality. Use the `set_capture_pre_gain`,
|
||||
/// `set_playout_volume`, and similar methods on
|
||||
/// [`AudioProcessing`](crate::AudioProcessing) for runtime changes.
|
||||
///
|
||||
/// All components are disabled (`None`) by default. Setting a component to
|
||||
/// `Some(...)` enables it and triggers memory allocation and initialization.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use sonora::Config;
|
||||
/// use sonora::config::{EchoCanceller, NoiseSuppression, NoiseSuppressionLevel};
|
||||
///
|
||||
/// let config = Config {
|
||||
/// echo_canceller: Some(EchoCanceller::default()),
|
||||
/// noise_suppression: Some(NoiseSuppression {
|
||||
/// level: NoiseSuppressionLevel::High,
|
||||
/// ..Default::default()
|
||||
/// }),
|
||||
/// ..Default::default()
|
||||
/// };
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Config {
|
||||
/// Pipeline processing properties.
|
||||
pub pipeline: Pipeline,
|
||||
/// Pre-amplifier settings. Amplifies the capture signal before any other
|
||||
/// processing. Set to `Some(...)` to enable.
|
||||
pub pre_amplifier: Option<PreAmplifier>,
|
||||
/// Capture-level adjustment settings. Should not be used together with
|
||||
/// [`PreAmplifier`]. Set to `Some(...)` to enable.
|
||||
pub capture_level_adjustment: Option<CaptureLevelAdjustment>,
|
||||
/// High-pass filter settings. Set to `Some(...)` to enable.
|
||||
pub high_pass_filter: Option<HighPassFilter>,
|
||||
/// Echo canceller (AEC3) settings. Set to `Some(...)` to enable.
|
||||
pub echo_canceller: Option<EchoCanceller>,
|
||||
/// Noise suppression settings. Set to `Some(...)` to enable.
|
||||
pub noise_suppression: Option<NoiseSuppression>,
|
||||
/// Automatic Gain Controller 2 (AGC2) settings. Combines input volume
|
||||
/// control, adaptive digital gain, fixed digital gain, and a limiter.
|
||||
/// Set to `Some(...)` to enable.
|
||||
pub gain_controller2: Option<GainController2>,
|
||||
}
|
||||
|
||||
/// Maximum internal processing rate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MaxProcessingRate {
|
||||
/// 32 kHz internal processing rate.
|
||||
Rate32kHz,
|
||||
/// 48 kHz internal processing rate.
|
||||
Rate48kHz,
|
||||
}
|
||||
|
||||
impl MaxProcessingRate {
|
||||
/// Returns the rate in Hz.
|
||||
pub fn as_hz(self) -> u32 {
|
||||
match self {
|
||||
Self::Rate32kHz => 32000,
|
||||
Self::Rate48kHz => 48000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pipeline processing properties.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Pipeline {
|
||||
/// Maximum allowed processing rate used internally.
|
||||
pub maximum_internal_processing_rate: MaxProcessingRate,
|
||||
/// Allow multi-channel processing of render audio.
|
||||
pub multi_channel_render: bool,
|
||||
/// Allow multi-channel processing of capture audio when AEC3 is active.
|
||||
pub multi_channel_capture: bool,
|
||||
/// How to downmix multi-channel capture audio to mono.
|
||||
pub capture_downmix_method: DownmixMethod,
|
||||
}
|
||||
|
||||
/// Ways to downmix a multi-channel track to mono.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DownmixMethod {
|
||||
/// Average across channels.
|
||||
AverageChannels,
|
||||
/// Use the first channel.
|
||||
UseFirstChannel,
|
||||
}
|
||||
|
||||
impl Default for Pipeline {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
maximum_internal_processing_rate: MaxProcessingRate::Rate32kHz,
|
||||
multi_channel_render: true,
|
||||
multi_channel_capture: true,
|
||||
capture_downmix_method: DownmixMethod::AverageChannels,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-amplifier settings. Amplifies the capture signal before any other
|
||||
/// processing.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PreAmplifier {
|
||||
/// Linear gain factor applied to the capture signal (default: 1.0).
|
||||
pub fixed_gain_factor: f32,
|
||||
}
|
||||
|
||||
impl Default for PreAmplifier {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fixed_gain_factor: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// General level adjustment in the capture pipeline. Should not be used
|
||||
/// together with the legacy [`PreAmplifier`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CaptureLevelAdjustment {
|
||||
/// Linear gain factor applied before any processing (default: 1.0).
|
||||
pub pre_gain_factor: f32,
|
||||
/// Linear gain factor applied after all processing (default: 1.0).
|
||||
pub post_gain_factor: f32,
|
||||
/// Analog mic gain emulation settings. Set to `Some(...)` to enable.
|
||||
pub analog_mic_gain_emulation: Option<AnalogMicGainEmulation>,
|
||||
}
|
||||
|
||||
impl Default for CaptureLevelAdjustment {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pre_gain_factor: 1.0,
|
||||
post_gain_factor: 1.0,
|
||||
analog_mic_gain_emulation: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Analog microphone gain emulation settings.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AnalogMicGainEmulation {
|
||||
/// Initial analog gain level to use for the emulated analog gain.
|
||||
/// Range: `0..=255` (default: 255).
|
||||
pub initial_level: u8,
|
||||
}
|
||||
|
||||
impl Default for AnalogMicGainEmulation {
|
||||
fn default() -> Self {
|
||||
Self { initial_level: 255 }
|
||||
}
|
||||
}
|
||||
|
||||
/// High-pass filter settings.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HighPassFilter {
|
||||
/// When true, the filter operates on the full-band signal rather than
|
||||
/// only the split band (default: true).
|
||||
pub apply_in_full_band: bool,
|
||||
}
|
||||
|
||||
impl Default for HighPassFilter {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
apply_in_full_band: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Echo canceller (AEC3) settings.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EchoCanceller {
|
||||
/// Enforce the highpass filter to be on (default: true). Has no effect
|
||||
/// in mobile mode.
|
||||
pub enforce_high_pass_filtering: bool,
|
||||
/// Which transparent mode algorithm to use (default: `Legacy`).
|
||||
///
|
||||
/// Transparent mode detects when no echo is present (e.g. headset use)
|
||||
/// and reduces suppression. The HMM variant uses Bayesian inference and
|
||||
/// is generally more responsive than the counter-based Legacy mode.
|
||||
pub transparent_mode: TransparentModeType,
|
||||
}
|
||||
|
||||
impl Default for EchoCanceller {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enforce_high_pass_filtering: true,
|
||||
transparent_mode: TransparentModeType::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use sonora_aec3::config::TransparentModeType;
|
||||
|
||||
/// Background noise suppression settings.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NoiseSuppression {
|
||||
/// Aggressiveness level for noise suppression (default: `Moderate`).
|
||||
pub level: NoiseSuppressionLevel,
|
||||
/// When true and linear AEC output is available, noise suppression
|
||||
/// analyzes the linear AEC output instead of the regular signal.
|
||||
pub analyze_linear_aec_output_when_available: bool,
|
||||
}
|
||||
|
||||
/// Noise suppression aggressiveness level.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NoiseSuppressionLevel {
|
||||
/// Low suppression (~6 dB).
|
||||
Low,
|
||||
/// Moderate suppression (~12 dB, default).
|
||||
Moderate,
|
||||
/// High suppression (~18 dB).
|
||||
High,
|
||||
/// Very high suppression (~21 dB).
|
||||
VeryHigh,
|
||||
}
|
||||
|
||||
impl Default for NoiseSuppression {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
level: NoiseSuppressionLevel::Moderate,
|
||||
analyze_linear_aec_output_when_available: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Automatic Gain Controller 2 (AGC2) settings.
|
||||
///
|
||||
/// AGC2 brings the captured audio signal to the desired level by combining
|
||||
/// three controllers (input volume, adaptive digital, and fixed digital)
|
||||
/// and a limiter.
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct GainController2 {
|
||||
/// Enable the input volume controller. Adjusts the input volume applied
|
||||
/// when audio is captured (e.g., microphone volume on a soundcard).
|
||||
pub input_volume_controller: bool,
|
||||
/// Adaptive digital controller settings. Set to `Some(...)` to enable.
|
||||
/// Adjusts and applies a digital gain after echo cancellation and
|
||||
/// noise suppression.
|
||||
pub adaptive_digital: Option<AdaptiveDigital>,
|
||||
/// Applies a fixed digital gain after the adaptive digital controller
|
||||
/// and before the limiter.
|
||||
pub fixed_digital: FixedDigital,
|
||||
}
|
||||
|
||||
/// Adaptive digital controller settings within AGC2.
|
||||
///
|
||||
/// Adjusts and applies a digital gain after echo cancellation and after
|
||||
/// noise suppression.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AdaptiveDigital {
|
||||
/// Headroom in dB (default: 5.0).
|
||||
pub headroom_db: f32,
|
||||
/// Maximum gain in dB (default: 50.0).
|
||||
pub max_gain_db: f32,
|
||||
/// Initial gain in dB (default: 15.0).
|
||||
pub initial_gain_db: f32,
|
||||
/// Maximum gain change rate in dB/second (default: 6.0).
|
||||
pub max_gain_change_db_per_second: f32,
|
||||
/// Maximum output noise level in dBFS (default: -50.0).
|
||||
pub max_output_noise_level_dbfs: f32,
|
||||
}
|
||||
|
||||
impl Default for AdaptiveDigital {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
headroom_db: 5.0,
|
||||
max_gain_db: 50.0,
|
||||
initial_gain_db: 15.0,
|
||||
max_gain_change_db_per_second: 6.0,
|
||||
max_output_noise_level_dbfs: -50.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed digital controller settings within AGC2.
|
||||
///
|
||||
/// Applies a fixed digital gain after the adaptive digital controller
|
||||
/// and before the limiter.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct FixedDigital {
|
||||
/// Fixed gain in dB (default: 0.0). Setting a value greater than zero
|
||||
/// turns the limiter into a compressor that first applies a fixed gain.
|
||||
pub gain_db: f32,
|
||||
}
|
||||
|
||||
/// Runtime settings that can be applied without reinitialization.
|
||||
///
|
||||
/// These are enqueued and applied at the next call to
|
||||
/// [`AudioProcessing::process_capture_f32()`](crate::AudioProcessing::process_capture_f32)
|
||||
/// or [`AudioProcessing::process_capture_i16()`](crate::AudioProcessing::process_capture_i16).
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum RuntimeSetting {
|
||||
/// Capture pre-gain linear factor.
|
||||
CapturePreGain(f32),
|
||||
/// Capture post-gain linear factor.
|
||||
CapturePostGain(f32),
|
||||
/// Fixed post-gain in dB. Must be in the range `0.0..=90.0`.
|
||||
CaptureFixedPostGain(f32),
|
||||
/// Playout (render) volume change. The value is the unnormalized volume.
|
||||
PlayoutVolumeChange(i32),
|
||||
/// Notifies that the playout (render) audio device has changed.
|
||||
/// Currently a no-op (no render pre-processor), but the data is
|
||||
/// preserved for future use.
|
||||
PlayoutAudioDeviceChange(PlayoutAudioDeviceInfo),
|
||||
/// Whether the capture output is used. When false, some components may
|
||||
/// optimize by skipping work.
|
||||
CaptureOutputUsed(bool),
|
||||
}
|
||||
|
||||
/// Play-out audio device properties.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct PlayoutAudioDeviceInfo {
|
||||
/// Identifies the audio device.
|
||||
pub id: i32,
|
||||
/// Maximum volume of the audio device.
|
||||
pub max_volume: i32,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capture_level_adjustment_equality() {
|
||||
let a = CaptureLevelAdjustment::default();
|
||||
let mut b = a.clone();
|
||||
assert_eq!(a, b);
|
||||
b.pre_gain_factor = 2.0;
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_processing_rate_as_hz() {
|
||||
assert_eq!(MaxProcessingRate::Rate32kHz.as_hz(), 32000);
|
||||
assert_eq!(MaxProcessingRate::Rate48kHz.as_hz(), 48000);
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
//! AEC3 config selector — chooses between mono and multichannel configurations.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/aec3/config_selector.h/cc`.
|
||||
|
||||
use sonora_aec3::config::EchoCanceller3Config;
|
||||
|
||||
/// Validates that the mono and the multichannel configs have compatible fields.
|
||||
fn compatible_configs(
|
||||
mono_config: &EchoCanceller3Config,
|
||||
multichannel_config: &EchoCanceller3Config,
|
||||
) -> bool {
|
||||
if mono_config.delay.fixed_capture_delay_samples
|
||||
!= multichannel_config.delay.fixed_capture_delay_samples
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if mono_config.filter.export_linear_aec_output
|
||||
!= multichannel_config.filter.export_linear_aec_output
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if mono_config.filter.high_pass_filter_echo_reference
|
||||
!= multichannel_config.filter.high_pass_filter_echo_reference
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if mono_config.multi_channel.detect_stereo_content
|
||||
!= multichannel_config.multi_channel.detect_stereo_content
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if mono_config
|
||||
.multi_channel
|
||||
.stereo_detection_timeout_threshold_seconds
|
||||
!= multichannel_config
|
||||
.multi_channel
|
||||
.stereo_detection_timeout_threshold_seconds
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Selects between mono and multichannel AEC3 configs.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ConfigSelector {
|
||||
config: EchoCanceller3Config,
|
||||
multichannel_config: Option<EchoCanceller3Config>,
|
||||
use_multichannel: bool,
|
||||
}
|
||||
|
||||
impl ConfigSelector {
|
||||
pub(crate) fn new(
|
||||
config: EchoCanceller3Config,
|
||||
multichannel_config: Option<EchoCanceller3Config>,
|
||||
num_render_input_channels: usize,
|
||||
) -> Self {
|
||||
if let Some(ref mc) = multichannel_config {
|
||||
debug_assert!(compatible_configs(&config, mc));
|
||||
}
|
||||
|
||||
let initial_multichannel =
|
||||
!config.multi_channel.detect_stereo_content && num_render_input_channels > 1;
|
||||
|
||||
let use_multichannel = initial_multichannel && multichannel_config.is_some();
|
||||
|
||||
Self {
|
||||
config,
|
||||
multichannel_config,
|
||||
use_multichannel,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the config selection based on the detection of multichannel
|
||||
/// content.
|
||||
pub(crate) fn update(&mut self, multichannel_content: bool) {
|
||||
self.use_multichannel = multichannel_content && self.multichannel_config.is_some();
|
||||
}
|
||||
|
||||
/// Returns the currently active configuration.
|
||||
pub(crate) fn active_config(&self) -> &EchoCanceller3Config {
|
||||
if self.use_multichannel {
|
||||
self.multichannel_config
|
||||
.as_ref()
|
||||
.expect("multichannel config must exist when use_multichannel is true")
|
||||
} else {
|
||||
&self.config
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Parametrized tests over (num_channels, detect_stereo_content).
|
||||
// C++ uses: Combine(Values(1, 2, 8), Values(false, true))
|
||||
|
||||
#[test]
|
||||
fn mono_config_selected_when_no_multichannel_config_present() {
|
||||
for &num_channels in &[1, 2, 8] {
|
||||
for &detect_stereo_content in &[false, true] {
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
config.multi_channel.detect_stereo_content = detect_stereo_content;
|
||||
|
||||
config.delay.default_delay += 1;
|
||||
let custom_delay = config.delay.default_delay;
|
||||
|
||||
let mut cs = ConfigSelector::new(config, None, num_channels);
|
||||
assert_eq!(cs.active_config().delay.default_delay, custom_delay);
|
||||
|
||||
cs.update(false);
|
||||
assert_eq!(cs.active_config().delay.default_delay, custom_delay);
|
||||
|
||||
cs.update(true);
|
||||
assert_eq!(cs.active_config().delay.default_delay, custom_delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn correct_initial_config_is_selected() {
|
||||
for &num_channels in &[1, 2, 8] {
|
||||
for &detect_stereo_content in &[false, true] {
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
config.multi_channel.detect_stereo_content = detect_stereo_content;
|
||||
let mut multichannel_config = config.clone();
|
||||
|
||||
config.delay.default_delay += 1;
|
||||
let custom_delay_config = config.delay.default_delay;
|
||||
multichannel_config.delay.default_delay += 2;
|
||||
let custom_delay_multichannel = multichannel_config.delay.default_delay;
|
||||
|
||||
let cs = ConfigSelector::new(config, Some(multichannel_config), num_channels);
|
||||
|
||||
if num_channels == 1 || detect_stereo_content {
|
||||
assert_eq!(
|
||||
cs.active_config().delay.default_delay,
|
||||
custom_delay_config,
|
||||
"num_channels={num_channels}, detect_stereo={detect_stereo_content}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
cs.active_config().delay.default_delay,
|
||||
custom_delay_multichannel,
|
||||
"num_channels={num_channels}, detect_stereo={detect_stereo_content}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parametrized over num_channels only (detect_stereo_content = true).
|
||||
// C++: Values(1, 2, 8)
|
||||
|
||||
#[test]
|
||||
fn correct_config_update_behavior() {
|
||||
for &num_channels in &[1, 2, 8] {
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
config.multi_channel.detect_stereo_content = true;
|
||||
let mut multichannel_config = config.clone();
|
||||
|
||||
config.delay.default_delay += 1;
|
||||
let custom_delay_config = config.delay.default_delay;
|
||||
multichannel_config.delay.default_delay += 2;
|
||||
let custom_delay_multichannel = multichannel_config.delay.default_delay;
|
||||
|
||||
let mut cs = ConfigSelector::new(config, Some(multichannel_config), num_channels);
|
||||
|
||||
cs.update(false);
|
||||
assert_eq!(
|
||||
cs.active_config().delay.default_delay,
|
||||
custom_delay_config,
|
||||
"num_channels={num_channels}"
|
||||
);
|
||||
|
||||
if num_channels == 1 {
|
||||
cs.update(false);
|
||||
assert_eq!(
|
||||
cs.active_config().delay.default_delay,
|
||||
custom_delay_config,
|
||||
"num_channels={num_channels}"
|
||||
);
|
||||
} else {
|
||||
cs.update(true);
|
||||
assert_eq!(
|
||||
cs.active_config().delay.default_delay,
|
||||
custom_delay_multichannel,
|
||||
"num_channels={num_channels}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+897
@@ -0,0 +1,897 @@
|
||||
//! Echo Canceller 3 (AEC3) — top-level wrapper.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/aec3/echo_canceller3.h/cc`.
|
||||
//!
|
||||
//! Coordinates the render/capture pipeline by splitting 10 ms frames into
|
||||
//! sub-frames, blocking them into 64-sample blocks, and forwarding to the
|
||||
//! underlying `BlockProcessor`. A `SwapQueue` bridges the render and capture
|
||||
//! paths.
|
||||
|
||||
use std::mem;
|
||||
|
||||
use sonora_aec3::api_call_jitter_metrics::ApiCallJitterMetrics;
|
||||
use sonora_aec3::block::Block;
|
||||
use sonora_aec3::block_framer::BlockFramer;
|
||||
use sonora_aec3::block_processor::{BlockProcessor, BlockProcessorMetricsOutput};
|
||||
use sonora_aec3::common::{
|
||||
MAX_NUM_BANDS, RENDER_TRANSFER_QUEUE_SIZE_FRAMES, SUB_FRAME_LENGTH, num_bands_for_rate,
|
||||
valid_full_band_rate,
|
||||
};
|
||||
use sonora_aec3::config::EchoCanceller3Config;
|
||||
use sonora_aec3::frame_blocker::FrameBlocker;
|
||||
use sonora_aec3::multi_channel_content_detector::MultiChannelContentDetector;
|
||||
|
||||
use crate::audio_buffer::AudioBuffer;
|
||||
use crate::config_selector::ConfigSelector;
|
||||
use crate::high_pass_filter::HighPassFilter;
|
||||
use crate::swap_queue::SwapQueue;
|
||||
|
||||
/// Split-band size (samples per band in a 10 ms frame at the internal rate).
|
||||
const SPLIT_BAND_SIZE: usize = 160;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BlockDelayBuffer — fixed capture delay
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Applies a fixed delay to the split-band audio in an `AudioBuffer`.
|
||||
///
|
||||
/// Ported from `modules/audio_processing/aec3/block_delay_buffer.h/cc`.
|
||||
#[derive(Debug)]
|
||||
struct BlockDelayBuffer {
|
||||
frame_length: usize,
|
||||
delay: usize,
|
||||
/// `buf[channel][band]` — circular delay line.
|
||||
buf: Vec<Vec<Vec<f32>>>,
|
||||
last_insert: usize,
|
||||
}
|
||||
|
||||
impl BlockDelayBuffer {
|
||||
fn new(
|
||||
num_channels: usize,
|
||||
num_bands: usize,
|
||||
frame_length: usize,
|
||||
delay_samples: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
frame_length,
|
||||
delay: delay_samples,
|
||||
buf: vec![vec![vec![0.0_f32; delay_samples]; num_bands]; num_channels],
|
||||
last_insert: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn delay_signal(&mut self, frame: &mut AudioBuffer) {
|
||||
debug_assert_eq!(self.buf.len(), frame.num_channels());
|
||||
if self.delay == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let num_bands = self.buf[0].len();
|
||||
let num_channels = self.buf.len();
|
||||
let delay = self.delay;
|
||||
|
||||
let mut i = self.last_insert;
|
||||
for ch in 0..num_channels {
|
||||
debug_assert_eq!(self.buf[ch].len(), frame.num_bands());
|
||||
debug_assert_eq!(self.buf[ch].len(), num_bands);
|
||||
|
||||
for band in 0..num_bands {
|
||||
debug_assert_eq!(delay, self.buf[ch][band].len());
|
||||
i = self.last_insert;
|
||||
|
||||
let frame_data = frame.split_band_mut(ch, band);
|
||||
let buf = &mut self.buf[ch][band];
|
||||
|
||||
for sample in &mut frame_data[..self.frame_length] {
|
||||
mem::swap(&mut buf[i], sample);
|
||||
i = if i < delay - 1 { i + 1 } else { 0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.last_insert = i;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RenderWriter — copies AudioBuffer into the render SwapQueue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Copies split-band render audio into the render transfer queue, optionally
|
||||
/// applying a high-pass filter to the echo reference.
|
||||
#[derive(Debug)]
|
||||
struct RenderWriter {
|
||||
num_bands: usize,
|
||||
num_channels: usize,
|
||||
high_pass_filter: Option<HighPassFilter>,
|
||||
/// `render_queue_input_frame[band][channel]` — temporary storage.
|
||||
render_queue_input_frame: Vec<Vec<Vec<f32>>>,
|
||||
}
|
||||
|
||||
impl RenderWriter {
|
||||
fn new(config: &EchoCanceller3Config, num_bands: usize, num_channels: usize) -> Self {
|
||||
let high_pass_filter = if config.filter.high_pass_filter_echo_reference {
|
||||
Some(HighPassFilter::new(16000, num_channels))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Self {
|
||||
num_bands,
|
||||
num_channels,
|
||||
high_pass_filter,
|
||||
render_queue_input_frame: vec![
|
||||
vec![vec![0.0_f32; SPLIT_BAND_SIZE]; num_channels];
|
||||
num_bands
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(
|
||||
&mut self,
|
||||
input: &AudioBuffer,
|
||||
render_transfer_queue: &mut SwapQueue<Vec<Vec<Vec<f32>>>>,
|
||||
) {
|
||||
debug_assert_eq!(SPLIT_BAND_SIZE, input.num_frames_per_band());
|
||||
debug_assert_eq!(self.num_bands, input.num_bands());
|
||||
debug_assert_eq!(self.num_channels, input.num_channels());
|
||||
|
||||
// Copy from AudioBuffer into the temporary frame.
|
||||
copy_buffer_into_frame(
|
||||
input,
|
||||
self.num_bands,
|
||||
self.num_channels,
|
||||
&mut self.render_queue_input_frame,
|
||||
);
|
||||
|
||||
// Optionally apply high-pass filter to band 0.
|
||||
if let Some(hpf) = &mut self.high_pass_filter {
|
||||
hpf.process_channels(&mut self.render_queue_input_frame[0]);
|
||||
}
|
||||
|
||||
let _ = render_transfer_queue.insert(&mut self.render_queue_input_frame);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: copy AudioBuffer → frame (Vec<Vec<Vec<f32>>>)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn copy_buffer_into_frame(
|
||||
buffer: &AudioBuffer,
|
||||
num_bands: usize,
|
||||
num_channels: usize,
|
||||
frame: &mut [Vec<Vec<f32>>],
|
||||
) {
|
||||
debug_assert_eq!(num_bands, frame.len());
|
||||
debug_assert_eq!(num_channels, frame[0].len());
|
||||
debug_assert_eq!(SPLIT_BAND_SIZE, frame[0][0].len());
|
||||
for (band, frame_band) in frame.iter_mut().enumerate().take(num_bands) {
|
||||
for (channel, frame_ch) in frame_band.iter_mut().enumerate().take(num_channels) {
|
||||
let src = buffer.split_band(channel, band);
|
||||
frame_ch[..SPLIT_BAND_SIZE].copy_from_slice(&src[..SPLIT_BAND_SIZE]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: detect microphone saturation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn detect_saturation(y: &[f32]) -> bool {
|
||||
y.iter().any(|&v| v >= 32700.0 || v <= -32700.0)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sub-frame fill helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Fills a sub-frame view from an `AudioBuffer`.
|
||||
///
|
||||
/// `sub_frame_view[band][channel]` will be populated with 80 samples starting
|
||||
/// at `sub_frame_index * SUB_FRAME_LENGTH` within each split band.
|
||||
fn fill_sub_frame_from_audio_buffer(
|
||||
frame: &AudioBuffer,
|
||||
sub_frame_index: usize,
|
||||
sub_frame_view: &mut [Vec<Vec<f32>>],
|
||||
) {
|
||||
debug_assert!(sub_frame_index <= 1);
|
||||
debug_assert_eq!(frame.num_bands(), sub_frame_view.len());
|
||||
debug_assert_eq!(frame.num_channels(), sub_frame_view[0].len());
|
||||
let offset = sub_frame_index * SUB_FRAME_LENGTH;
|
||||
for (band, sfv_band) in sub_frame_view.iter_mut().enumerate() {
|
||||
for (channel, sfv_ch) in sfv_band.iter_mut().enumerate() {
|
||||
let src = frame.split_band(channel, band);
|
||||
sfv_ch.copy_from_slice(&src[offset..offset + SUB_FRAME_LENGTH]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a sub-frame view back into an `AudioBuffer`.
|
||||
fn write_sub_frame_to_audio_buffer(
|
||||
sub_frame_view: &[Vec<Vec<f32>>],
|
||||
sub_frame_index: usize,
|
||||
frame: &mut AudioBuffer,
|
||||
) {
|
||||
let offset = sub_frame_index * SUB_FRAME_LENGTH;
|
||||
for (band, sfv_band) in sub_frame_view.iter().enumerate() {
|
||||
for (channel, sfv_ch) in sfv_band.iter().enumerate() {
|
||||
let dst = frame.split_band_mut(channel, band);
|
||||
dst[offset..offset + SUB_FRAME_LENGTH].copy_from_slice(sfv_ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a sub-frame view from a raw render frame, with optional downmixing.
|
||||
///
|
||||
/// `render_frame[band][channel]` contains SPLIT_BAND_SIZE samples.
|
||||
fn fill_sub_frame_from_render_frame(
|
||||
proper_downmix_needed: bool,
|
||||
render_frame: &mut [Vec<Vec<f32>>],
|
||||
sub_frame_index: usize,
|
||||
sub_frame_view: &mut [Vec<Vec<f32>>],
|
||||
) {
|
||||
debug_assert!(sub_frame_index <= 1);
|
||||
debug_assert_eq!(render_frame.len(), sub_frame_view.len());
|
||||
|
||||
let frame_num_channels = render_frame[0].len();
|
||||
let sub_frame_num_channels = sub_frame_view[0].len();
|
||||
let offset = sub_frame_index * SUB_FRAME_LENGTH;
|
||||
|
||||
if frame_num_channels > sub_frame_num_channels {
|
||||
debug_assert_eq!(sub_frame_num_channels, 1);
|
||||
if proper_downmix_needed {
|
||||
// Average all channels into channel 0.
|
||||
for band in render_frame.iter_mut() {
|
||||
for ch in 1..frame_num_channels {
|
||||
for k in 0..SUB_FRAME_LENGTH {
|
||||
band[0][offset + k] += band[ch][offset + k];
|
||||
}
|
||||
}
|
||||
let scale = 1.0 / frame_num_channels as f32;
|
||||
for k in 0..SUB_FRAME_LENGTH {
|
||||
band[0][offset + k] *= scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
for band in 0..render_frame.len() {
|
||||
sub_frame_view[band][0]
|
||||
.copy_from_slice(&render_frame[band][0][offset..offset + SUB_FRAME_LENGTH]);
|
||||
}
|
||||
} else {
|
||||
debug_assert_eq!(frame_num_channels, sub_frame_num_channels);
|
||||
for band in 0..render_frame.len() {
|
||||
for channel in 0..frame_num_channels {
|
||||
sub_frame_view[band][channel].copy_from_slice(
|
||||
&render_frame[band][channel][offset..offset + SUB_FRAME_LENGTH],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// EchoCanceller3
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Top-level echo canceller coordinating render/capture processing.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct EchoCanceller3 {
|
||||
sample_rate_hz: usize,
|
||||
num_bands: usize,
|
||||
num_render_input_channels: usize,
|
||||
num_render_channels_to_aec: usize,
|
||||
num_capture_channels: usize,
|
||||
|
||||
config_selector: ConfigSelector,
|
||||
multichannel_content_detector: MultiChannelContentDetector,
|
||||
|
||||
// Render path.
|
||||
render_writer: RenderWriter,
|
||||
render_transfer_queue: SwapQueue<Vec<Vec<Vec<f32>>>>,
|
||||
render_queue_output_frame: Vec<Vec<Vec<f32>>>,
|
||||
render_blocker: FrameBlocker,
|
||||
render_block: Block,
|
||||
render_sub_frame_view: Vec<Vec<Vec<f32>>>,
|
||||
|
||||
// Capture path.
|
||||
output_framer: BlockFramer,
|
||||
capture_blocker: FrameBlocker,
|
||||
capture_block: Block,
|
||||
capture_sub_frame_view: Vec<Vec<Vec<f32>>>,
|
||||
|
||||
// Optional linear output.
|
||||
linear_output_framer: Option<BlockFramer>,
|
||||
linear_output_block: Option<Block>,
|
||||
linear_output_sub_frame_view: Option<Vec<Vec<Vec<f32>>>>,
|
||||
|
||||
// Optional capture delay.
|
||||
block_delay_buffer: Option<BlockDelayBuffer>,
|
||||
|
||||
// Core processor.
|
||||
block_processor: BlockProcessor,
|
||||
|
||||
// State.
|
||||
saturated_microphone_signal: bool,
|
||||
api_call_metrics: ApiCallJitterMetrics,
|
||||
}
|
||||
|
||||
impl EchoCanceller3 {
|
||||
pub(crate) fn new(
|
||||
config: EchoCanceller3Config,
|
||||
multichannel_config: Option<EchoCanceller3Config>,
|
||||
sample_rate_hz: usize,
|
||||
num_render_channels: usize,
|
||||
num_capture_channels: usize,
|
||||
) -> Self {
|
||||
debug_assert!(valid_full_band_rate(sample_rate_hz));
|
||||
|
||||
let num_bands = num_bands_for_rate(sample_rate_hz);
|
||||
debug_assert!(num_bands <= MAX_NUM_BANDS);
|
||||
|
||||
let config_selector =
|
||||
ConfigSelector::new(config.clone(), multichannel_config, num_render_channels);
|
||||
let active = config_selector.active_config();
|
||||
|
||||
let multichannel_content_detector = MultiChannelContentDetector::new(
|
||||
active.multi_channel.detect_stereo_content,
|
||||
num_render_channels,
|
||||
active.multi_channel.stereo_detection_threshold,
|
||||
active
|
||||
.multi_channel
|
||||
.stereo_detection_timeout_threshold_seconds,
|
||||
active.multi_channel.stereo_detection_hysteresis_seconds,
|
||||
);
|
||||
|
||||
let block_delay_buffer = if active.delay.fixed_capture_delay_samples > 0 {
|
||||
Some(BlockDelayBuffer::new(
|
||||
num_capture_channels,
|
||||
num_bands,
|
||||
SPLIT_BAND_SIZE,
|
||||
active.delay.fixed_capture_delay_samples,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let render_writer = RenderWriter::new(active, num_bands, num_render_channels);
|
||||
|
||||
let render_transfer_queue = SwapQueue::with_prototype(
|
||||
RENDER_TRANSFER_QUEUE_SIZE_FRAMES,
|
||||
vec![vec![vec![0.0_f32; SPLIT_BAND_SIZE]; num_render_channels]; num_bands],
|
||||
);
|
||||
|
||||
let render_queue_output_frame =
|
||||
vec![vec![vec![0.0_f32; SPLIT_BAND_SIZE]; num_render_channels]; num_bands];
|
||||
|
||||
let output_framer = BlockFramer::new(num_bands, num_capture_channels);
|
||||
let capture_blocker = FrameBlocker::new(num_bands, num_capture_channels);
|
||||
|
||||
let (linear_output_framer, linear_output_block, linear_output_sub_frame_view) =
|
||||
if active.filter.export_linear_aec_output {
|
||||
(
|
||||
Some(BlockFramer::new(1, num_capture_channels)),
|
||||
Some(Block::new(1, num_capture_channels)),
|
||||
Some(vec![
|
||||
vec![
|
||||
vec![0.0_f32; SUB_FRAME_LENGTH];
|
||||
num_capture_channels
|
||||
];
|
||||
1
|
||||
]),
|
||||
)
|
||||
} else {
|
||||
(None, None, None)
|
||||
};
|
||||
|
||||
// Initial render channels is 1 (mono) until stereo content is detected.
|
||||
let num_render_channels_to_aec = 1;
|
||||
let render_blocker = FrameBlocker::new(num_bands, num_render_channels_to_aec);
|
||||
let render_block = Block::new(num_bands, num_render_channels_to_aec);
|
||||
let render_sub_frame_view =
|
||||
vec![vec![vec![0.0_f32; SUB_FRAME_LENGTH]; num_render_channels_to_aec]; num_bands];
|
||||
|
||||
let block_processor = BlockProcessor::new(
|
||||
config_selector.active_config(),
|
||||
sample_rate_hz,
|
||||
num_render_channels_to_aec,
|
||||
num_capture_channels,
|
||||
);
|
||||
|
||||
let capture_block = Block::new(num_bands, num_capture_channels);
|
||||
let capture_sub_frame_view =
|
||||
vec![vec![vec![0.0_f32; SUB_FRAME_LENGTH]; num_capture_channels]; num_bands];
|
||||
|
||||
Self {
|
||||
sample_rate_hz,
|
||||
num_bands,
|
||||
num_render_input_channels: num_render_channels,
|
||||
num_render_channels_to_aec,
|
||||
num_capture_channels,
|
||||
config_selector,
|
||||
multichannel_content_detector,
|
||||
render_writer,
|
||||
render_transfer_queue,
|
||||
render_queue_output_frame,
|
||||
render_blocker,
|
||||
render_block,
|
||||
render_sub_frame_view,
|
||||
output_framer,
|
||||
capture_blocker,
|
||||
capture_block,
|
||||
capture_sub_frame_view,
|
||||
linear_output_framer,
|
||||
linear_output_block,
|
||||
linear_output_sub_frame_view,
|
||||
block_delay_buffer,
|
||||
block_processor,
|
||||
saturated_microphone_signal: false,
|
||||
api_call_metrics: ApiCallJitterMetrics::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-initializes internal state (called when stereo content changes).
|
||||
fn initialize(&mut self) {
|
||||
self.num_render_channels_to_aec = if self
|
||||
.multichannel_content_detector
|
||||
.is_proper_multi_channel_content_detected()
|
||||
{
|
||||
self.num_render_input_channels
|
||||
} else {
|
||||
1
|
||||
};
|
||||
|
||||
self.config_selector.update(
|
||||
self.multichannel_content_detector
|
||||
.is_proper_multi_channel_content_detected(),
|
||||
);
|
||||
|
||||
self.render_block
|
||||
.set_num_channels(self.num_render_channels_to_aec);
|
||||
|
||||
self.render_blocker = FrameBlocker::new(self.num_bands, self.num_render_channels_to_aec);
|
||||
|
||||
self.block_processor = BlockProcessor::new(
|
||||
self.config_selector.active_config(),
|
||||
self.sample_rate_hz,
|
||||
self.num_render_channels_to_aec,
|
||||
self.num_capture_channels,
|
||||
);
|
||||
|
||||
self.render_sub_frame_view =
|
||||
vec![
|
||||
vec![vec![0.0_f32; SUB_FRAME_LENGTH]; self.num_render_channels_to_aec];
|
||||
self.num_bands
|
||||
];
|
||||
}
|
||||
|
||||
/// Stores an internal copy of the split-band render signal.
|
||||
pub(crate) fn analyze_render(&mut self, render: &AudioBuffer) {
|
||||
debug_assert_eq!(render.num_channels(), self.num_render_input_channels);
|
||||
self.render_writer
|
||||
.insert(render, &mut self.render_transfer_queue);
|
||||
}
|
||||
|
||||
/// Detects signal saturation in the full-band capture signal.
|
||||
pub(crate) fn analyze_capture(&mut self, capture: &AudioBuffer) {
|
||||
self.saturated_microphone_signal = false;
|
||||
for channel in 0..capture.num_channels() {
|
||||
if detect_saturation(capture.channel(channel)) {
|
||||
self.saturated_microphone_signal = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes the split-band capture signal to remove echo.
|
||||
pub(crate) fn process_capture(
|
||||
&mut self,
|
||||
capture: &mut AudioBuffer,
|
||||
linear_output: Option<&mut AudioBuffer>,
|
||||
level_change: bool,
|
||||
) {
|
||||
debug_assert_eq!(self.num_bands, capture.num_bands());
|
||||
debug_assert_eq!(SPLIT_BAND_SIZE, capture.num_frames_per_band());
|
||||
debug_assert_eq!(capture.num_channels(), self.num_capture_channels);
|
||||
|
||||
if linear_output.is_some() && self.linear_output_framer.is_none() {
|
||||
tracing::error!(
|
||||
"Trying to retrieve the linear AEC output without properly configuring AEC3."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Report capture call in the metrics.
|
||||
self.api_call_metrics.report_capture_call();
|
||||
|
||||
// Optionally delay the capture signal.
|
||||
if self
|
||||
.config_selector
|
||||
.active_config()
|
||||
.delay
|
||||
.fixed_capture_delay_samples
|
||||
> 0
|
||||
&& let Some(delay_buf) = &mut self.block_delay_buffer
|
||||
{
|
||||
delay_buf.delay_signal(capture);
|
||||
}
|
||||
|
||||
self.empty_render_queue();
|
||||
|
||||
let aec_reference_is_downmixed_stereo = self
|
||||
.multichannel_content_detector
|
||||
.is_temporary_multi_channel_content_detected();
|
||||
|
||||
// Process two sub-frames (0 and 1).
|
||||
for sub_frame_idx in 0..2 {
|
||||
self.process_capture_sub_frame(
|
||||
capture,
|
||||
linear_output.is_some(),
|
||||
level_change,
|
||||
aec_reference_is_downmixed_stereo,
|
||||
sub_frame_idx,
|
||||
);
|
||||
}
|
||||
|
||||
// Process any remaining block from the capture blocker.
|
||||
self.process_remaining_capture(
|
||||
level_change,
|
||||
aec_reference_is_downmixed_stereo,
|
||||
linear_output.is_some(),
|
||||
);
|
||||
|
||||
// Write sub-frame views back to capture AudioBuffer.
|
||||
// (The sub-frame processing already wrote through capture_sub_frame_view,
|
||||
// but we need to write the modified sub-frame data back.)
|
||||
}
|
||||
|
||||
/// Processes one capture sub-frame.
|
||||
fn process_capture_sub_frame(
|
||||
&mut self,
|
||||
capture: &mut AudioBuffer,
|
||||
has_linear_output: bool,
|
||||
level_change: bool,
|
||||
aec_reference_is_downmixed_stereo: bool,
|
||||
sub_frame_index: usize,
|
||||
) {
|
||||
// Fill capture sub-frame view from AudioBuffer.
|
||||
fill_sub_frame_from_audio_buffer(
|
||||
capture,
|
||||
sub_frame_index,
|
||||
&mut self.capture_sub_frame_view,
|
||||
);
|
||||
|
||||
// Convert sub-frame slices to the format FrameBlocker expects.
|
||||
let sub_frame_refs: Vec<Vec<&[f32]>> = self
|
||||
.capture_sub_frame_view
|
||||
.iter()
|
||||
.map(|band| band.iter().map(|ch| ch.as_slice()).collect())
|
||||
.collect();
|
||||
|
||||
self.capture_blocker
|
||||
.insert_sub_frame_and_extract_block(&sub_frame_refs, &mut self.capture_block);
|
||||
|
||||
// Process through block processor.
|
||||
let echo_path_gain_change = level_change || aec_reference_is_downmixed_stereo;
|
||||
if has_linear_output {
|
||||
self.block_processor.process_capture(
|
||||
echo_path_gain_change,
|
||||
self.saturated_microphone_signal,
|
||||
self.linear_output_block.as_mut(),
|
||||
&mut self.capture_block,
|
||||
);
|
||||
} else {
|
||||
self.block_processor.process_capture(
|
||||
echo_path_gain_change,
|
||||
self.saturated_microphone_signal,
|
||||
None,
|
||||
&mut self.capture_block,
|
||||
);
|
||||
}
|
||||
|
||||
// Extract sub-frame from output framer.
|
||||
self.output_framer.insert_block_and_extract_sub_frame(
|
||||
&self.capture_block,
|
||||
&mut self.capture_sub_frame_view,
|
||||
);
|
||||
|
||||
// Write the processed sub-frame back to the AudioBuffer.
|
||||
write_sub_frame_to_audio_buffer(&self.capture_sub_frame_view, sub_frame_index, capture);
|
||||
|
||||
// Handle linear output framer.
|
||||
if has_linear_output
|
||||
&& let (Some(lo_framer), Some(lo_block), Some(lo_view)) = (
|
||||
&mut self.linear_output_framer,
|
||||
&self.linear_output_block,
|
||||
&mut self.linear_output_sub_frame_view,
|
||||
)
|
||||
{
|
||||
lo_framer.insert_block_and_extract_sub_frame(lo_block, lo_view);
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes any remaining block in the capture blocker.
|
||||
fn process_remaining_capture(
|
||||
&mut self,
|
||||
level_change: bool,
|
||||
aec_reference_is_downmixed_stereo: bool,
|
||||
has_linear_output: bool,
|
||||
) {
|
||||
if !self.capture_blocker.is_block_available() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.capture_blocker.extract_block(&mut self.capture_block);
|
||||
|
||||
let echo_path_gain_change = level_change || aec_reference_is_downmixed_stereo;
|
||||
if has_linear_output {
|
||||
self.block_processor.process_capture(
|
||||
echo_path_gain_change,
|
||||
self.saturated_microphone_signal,
|
||||
self.linear_output_block.as_mut(),
|
||||
&mut self.capture_block,
|
||||
);
|
||||
} else {
|
||||
self.block_processor.process_capture(
|
||||
echo_path_gain_change,
|
||||
self.saturated_microphone_signal,
|
||||
None,
|
||||
&mut self.capture_block,
|
||||
);
|
||||
}
|
||||
|
||||
self.output_framer.insert_block(&self.capture_block);
|
||||
|
||||
if has_linear_output
|
||||
&& let (Some(lo_framer), Some(lo_block)) =
|
||||
(&mut self.linear_output_framer, &self.linear_output_block)
|
||||
{
|
||||
lo_framer.insert_block(lo_block);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drains all render frames from the transfer queue.
|
||||
fn empty_render_queue(&mut self) {
|
||||
while self
|
||||
.render_transfer_queue
|
||||
.remove(&mut self.render_queue_output_frame)
|
||||
{
|
||||
// Report render call in the metrics.
|
||||
self.api_call_metrics.report_render_call();
|
||||
|
||||
if self
|
||||
.multichannel_content_detector
|
||||
.update_detection(&self.render_queue_output_frame)
|
||||
{
|
||||
// Reinitialize AEC when proper stereo is detected.
|
||||
self.initialize();
|
||||
}
|
||||
|
||||
let proper_downmix_needed = self
|
||||
.multichannel_content_detector
|
||||
.is_temporary_multi_channel_content_detected();
|
||||
|
||||
// Buffer two sub-frames from the render frame.
|
||||
for sub_frame_idx in 0..2 {
|
||||
fill_sub_frame_from_render_frame(
|
||||
proper_downmix_needed,
|
||||
&mut self.render_queue_output_frame,
|
||||
sub_frame_idx,
|
||||
&mut self.render_sub_frame_view,
|
||||
);
|
||||
|
||||
let sub_frame_refs: Vec<Vec<&[f32]>> = self
|
||||
.render_sub_frame_view
|
||||
.iter()
|
||||
.map(|band| band.iter().map(|ch| ch.as_slice()).collect())
|
||||
.collect();
|
||||
|
||||
self.render_blocker
|
||||
.insert_sub_frame_and_extract_block(&sub_frame_refs, &mut self.render_block);
|
||||
self.block_processor.buffer_render(&self.render_block);
|
||||
}
|
||||
|
||||
// Buffer any remaining block.
|
||||
if self.render_blocker.is_block_available() {
|
||||
self.render_blocker.extract_block(&mut self.render_block);
|
||||
self.block_processor.buffer_render(&self.render_block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects current metrics from the echo canceller.
|
||||
pub(crate) fn get_metrics(&self) -> BlockProcessorMetricsOutput {
|
||||
self.block_processor.get_metrics()
|
||||
}
|
||||
|
||||
/// Provides an optional external estimate of the audio buffer delay.
|
||||
pub(crate) fn set_audio_buffer_delay(&mut self, delay_ms: i32) {
|
||||
self.block_processor.set_audio_buffer_delay(delay_ms);
|
||||
}
|
||||
|
||||
/// Specifies whether the capture output will be used.
|
||||
pub(crate) fn set_capture_output_usage(&mut self, capture_output_used: bool) {
|
||||
self.block_processor
|
||||
.set_capture_output_usage(capture_output_used);
|
||||
}
|
||||
|
||||
/// Returns whether echo cancellation is actively processing.
|
||||
pub(crate) fn active_processing(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns whether stereo render processing is active (for testing).
|
||||
#[cfg(test)]
|
||||
fn stereo_render_processing_active_for_testing(&self) -> bool {
|
||||
self.multichannel_content_detector
|
||||
.is_proper_multi_channel_content_detected()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn create_audio_buffer(sample_rate_hz: usize, num_channels: usize) -> AudioBuffer {
|
||||
AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construct_default_config_16khz() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let ec3 = EchoCanceller3::new(config, None, 16000, 1, 1);
|
||||
assert_eq!(ec3.num_bands, 1);
|
||||
assert_eq!(ec3.num_render_input_channels, 1);
|
||||
assert_eq!(ec3.num_capture_channels, 1);
|
||||
assert!(ec3.active_processing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construct_default_config_48khz() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let ec3 = EchoCanceller3::new(config, None, 48000, 1, 1);
|
||||
assert_eq!(ec3.num_bands, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construct_stereo() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let ec3 = EchoCanceller3::new(config, None, 48000, 2, 2);
|
||||
assert_eq!(ec3.num_render_input_channels, 2);
|
||||
assert_eq!(ec3.num_capture_channels, 2);
|
||||
// Initially mono until stereo content is detected.
|
||||
assert_eq!(ec3.num_render_channels_to_aec, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyze_and_process_mono_16khz() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let mut ec3 = EchoCanceller3::new(config, None, 16000, 1, 1);
|
||||
|
||||
let render = create_audio_buffer(16000, 1);
|
||||
let mut capture = create_audio_buffer(16000, 1);
|
||||
|
||||
// Run a few frames.
|
||||
for _ in 0..10 {
|
||||
ec3.analyze_render(&render);
|
||||
ec3.analyze_capture(&capture);
|
||||
ec3.process_capture(&mut capture, None, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyze_and_process_mono_48khz() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let mut ec3 = EchoCanceller3::new(config, None, 48000, 1, 1);
|
||||
|
||||
let render = create_audio_buffer(48000, 1);
|
||||
let mut capture = create_audio_buffer(48000, 1);
|
||||
|
||||
for _ in 0..10 {
|
||||
ec3.analyze_render(&render);
|
||||
ec3.analyze_capture(&capture);
|
||||
ec3.process_capture(&mut capture, None, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_detection() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let mut ec3 = EchoCanceller3::new(config, None, 16000, 1, 1);
|
||||
|
||||
let mut capture = create_audio_buffer(16000, 1);
|
||||
|
||||
// No saturation with normal signal.
|
||||
ec3.analyze_capture(&capture);
|
||||
assert!(!ec3.saturated_microphone_signal);
|
||||
|
||||
// Saturated signal.
|
||||
let data = capture.channel_mut(0);
|
||||
data[0] = 32700.0;
|
||||
ec3.analyze_capture(&capture);
|
||||
assert!(ec3.saturated_microphone_signal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_content_detection() {
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
config.multi_channel.detect_stereo_content = true;
|
||||
let ec3 = EchoCanceller3::new(config, None, 16000, 2, 1);
|
||||
|
||||
assert!(!ec3.stereo_render_processing_active_for_testing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_metrics_returns_valid() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let ec3 = EchoCanceller3::new(config, None, 16000, 1, 1);
|
||||
let _metrics = ec3.get_metrics();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_audio_buffer_delay() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let mut ec3 = EchoCanceller3::new(config, None, 16000, 1, 1);
|
||||
ec3.set_audio_buffer_delay(50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_capture_output_usage() {
|
||||
let config = EchoCanceller3Config::default();
|
||||
let mut ec3 = EchoCanceller3::new(config, None, 16000, 1, 1);
|
||||
ec3.set_capture_output_usage(false);
|
||||
ec3.set_capture_output_usage(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_delay_buffer_basic() {
|
||||
let mut buf = BlockDelayBuffer::new(1, 1, 160, 10);
|
||||
let mut audio = create_audio_buffer(16000, 1);
|
||||
|
||||
// Fill with known pattern.
|
||||
for i in 0..160 {
|
||||
audio.split_band_mut(0, 0)[i] = (i + 1) as f32;
|
||||
}
|
||||
|
||||
buf.delay_signal(&mut audio);
|
||||
|
||||
// First 10 samples should be zeros (the delay).
|
||||
for i in 0..10 {
|
||||
assert_eq!(
|
||||
audio.split_band(0, 0)[i],
|
||||
0.0,
|
||||
"sample {i} should be delayed"
|
||||
);
|
||||
}
|
||||
// Samples 10..160 should be the original 1..151.
|
||||
for i in 10..160 {
|
||||
assert_eq!(
|
||||
audio.split_band(0, 0)[i],
|
||||
(i - 9) as f32,
|
||||
"sample {i} mismatch"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_delay_buffer_zero_delay() {
|
||||
let mut buf = BlockDelayBuffer::new(1, 1, 160, 0);
|
||||
let mut audio = create_audio_buffer(16000, 1);
|
||||
|
||||
for i in 0..160 {
|
||||
audio.split_band_mut(0, 0)[i] = (i + 1) as f32;
|
||||
}
|
||||
|
||||
buf.delay_signal(&mut audio);
|
||||
|
||||
// No delay — signal should be unchanged.
|
||||
for i in 0..160 {
|
||||
assert_eq!(audio.split_band(0, 0)[i], (i + 1) as f32);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
//! Echo detector utilities for residual echo detection.
|
||||
|
||||
pub(crate) mod circular_buffer;
|
||||
pub(crate) mod mean_variance_estimator;
|
||||
pub(crate) mod moving_max;
|
||||
pub(crate) mod normalized_covariance_estimator;
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Fixed-size ring buffer for floating point values.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/echo_detector/circular_buffer.h/cc`.
|
||||
|
||||
/// Ring buffer containing floating point values.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CircularBuffer {
|
||||
buffer: Vec<f32>,
|
||||
next_insertion_index: usize,
|
||||
nr_elements_in_buffer: usize,
|
||||
}
|
||||
|
||||
impl CircularBuffer {
|
||||
pub(crate) fn new(size: usize) -> Self {
|
||||
Self {
|
||||
buffer: vec![0.0; size],
|
||||
next_insertion_index: 0,
|
||||
nr_elements_in_buffer: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, value: f32) {
|
||||
self.buffer[self.next_insertion_index] = value;
|
||||
self.next_insertion_index += 1;
|
||||
self.next_insertion_index %= self.buffer.len();
|
||||
self.nr_elements_in_buffer = (self.nr_elements_in_buffer + 1).min(self.buffer.len());
|
||||
}
|
||||
|
||||
pub(crate) fn pop(&mut self) -> Option<f32> {
|
||||
if self.nr_elements_in_buffer == 0 {
|
||||
return None;
|
||||
}
|
||||
let index = (self.buffer.len() + self.next_insertion_index - self.nr_elements_in_buffer)
|
||||
% self.buffer.len();
|
||||
self.nr_elements_in_buffer -= 1;
|
||||
Some(self.buffer[index])
|
||||
}
|
||||
|
||||
pub(crate) fn size(&self) -> usize {
|
||||
self.nr_elements_in_buffer
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.buffer.fill(0.0);
|
||||
self.next_insertion_index = 0;
|
||||
self.nr_elements_in_buffer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn less_than_max() {
|
||||
let mut buf = CircularBuffer::new(3);
|
||||
buf.push(1.0);
|
||||
buf.push(2.0);
|
||||
assert_eq!(Some(1.0), buf.pop());
|
||||
assert_eq!(Some(2.0), buf.pop());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill() {
|
||||
let mut buf = CircularBuffer::new(3);
|
||||
buf.push(1.0);
|
||||
buf.push(2.0);
|
||||
buf.push(3.0);
|
||||
assert_eq!(Some(1.0), buf.pop());
|
||||
assert_eq!(Some(2.0), buf.pop());
|
||||
assert_eq!(Some(3.0), buf.pop());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow() {
|
||||
let mut buf = CircularBuffer::new(3);
|
||||
buf.push(1.0);
|
||||
buf.push(2.0);
|
||||
buf.push(3.0);
|
||||
buf.push(4.0);
|
||||
// The first insert should have been forgotten.
|
||||
assert_eq!(Some(2.0), buf.pop());
|
||||
assert_eq!(Some(3.0), buf.pop());
|
||||
assert_eq!(Some(4.0), buf.pop());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_from_empty() {
|
||||
let mut buf = CircularBuffer::new(3);
|
||||
assert_eq!(None, buf.pop());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Online mean and variance estimator using exponential smoothing.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/echo_detector/mean_variance_estimator.h/cc`.
|
||||
|
||||
/// Adaptation speed parameter.
|
||||
const ALPHA: f32 = 0.001;
|
||||
|
||||
/// Iteratively estimates the mean and variance of a signal.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct MeanVarianceEstimator {
|
||||
mean: f32,
|
||||
variance: f32,
|
||||
}
|
||||
|
||||
impl MeanVarianceEstimator {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
mean: 0.0,
|
||||
variance: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(&mut self, value: f32) {
|
||||
self.mean = (1.0 - ALPHA) * self.mean + ALPHA * value;
|
||||
self.variance =
|
||||
(1.0 - ALPHA) * self.variance + ALPHA * (value - self.mean) * (value - self.mean);
|
||||
debug_assert!(self.mean.is_finite());
|
||||
debug_assert!(self.variance.is_finite());
|
||||
}
|
||||
|
||||
pub(crate) fn std_deviation(&self) -> f32 {
|
||||
debug_assert!(self.variance >= 0.0);
|
||||
self.variance.sqrt()
|
||||
}
|
||||
|
||||
pub(crate) fn mean(&self) -> f32 {
|
||||
self.mean
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.mean = 0.0;
|
||||
self.variance = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn insert_two_values() {
|
||||
let mut est = MeanVarianceEstimator::new();
|
||||
est.update(3.0);
|
||||
est.update(5.0);
|
||||
assert!(est.mean() > 0.0);
|
||||
assert!(est.std_deviation() > 0.0);
|
||||
est.clear();
|
||||
assert_eq!(est.mean(), 0.0);
|
||||
assert_eq!(est.std_deviation(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_zeroes() {
|
||||
let mut est = MeanVarianceEstimator::new();
|
||||
for _ in 0..20000 {
|
||||
est.update(0.0);
|
||||
}
|
||||
assert_eq!(est.mean(), 0.0);
|
||||
assert_eq!(est.std_deviation(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_value() {
|
||||
let mut est = MeanVarianceEstimator::new();
|
||||
for _ in 0..20000 {
|
||||
est.update(3.0);
|
||||
}
|
||||
assert!((est.mean() - 3.0).abs() < 0.01);
|
||||
assert!(est.std_deviation() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternating_value() {
|
||||
let mut est = MeanVarianceEstimator::new();
|
||||
for _ in 0..20000 {
|
||||
est.update(1.0);
|
||||
est.update(-1.0);
|
||||
}
|
||||
assert!(est.mean().abs() < 0.01);
|
||||
assert!((est.std_deviation() - 1.0).abs() < 0.01);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
//! Sliding window maximum with exponential decay.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/echo_detector/moving_max.h/cc`.
|
||||
|
||||
/// Decay factor: max decays to 1% after 460 updates past window end.
|
||||
const DECAY_FACTOR: f32 = 0.99;
|
||||
|
||||
/// Tracks the maximum value within a sliding window.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct MovingMax {
|
||||
max_value: f32,
|
||||
counter: usize,
|
||||
window_size: usize,
|
||||
}
|
||||
|
||||
impl MovingMax {
|
||||
pub(crate) fn new(window_size: usize) -> Self {
|
||||
debug_assert!(window_size > 0);
|
||||
Self {
|
||||
max_value: 0.0,
|
||||
counter: 0,
|
||||
window_size,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(&mut self, value: f32) {
|
||||
if self.counter >= self.window_size - 1 {
|
||||
self.max_value *= DECAY_FACTOR;
|
||||
} else {
|
||||
self.counter += 1;
|
||||
}
|
||||
if value > self.max_value {
|
||||
self.max_value = value;
|
||||
self.counter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn max(&self) -> f32 {
|
||||
self.max_value
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.max_value = 0.0;
|
||||
self.counter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn simple() {
|
||||
let mut mm = MovingMax::new(5);
|
||||
mm.update(1.0);
|
||||
mm.update(1.1);
|
||||
mm.update(1.9);
|
||||
mm.update(1.87);
|
||||
mm.update(1.89);
|
||||
assert_eq!(mm.max(), 1.9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window() {
|
||||
let mut mm = MovingMax::new(5);
|
||||
mm.update(1.0);
|
||||
mm.update(1.9);
|
||||
mm.update(1.7);
|
||||
mm.update(1.87);
|
||||
mm.update(1.89);
|
||||
mm.update(1.3);
|
||||
mm.update(1.2);
|
||||
assert!(mm.max() < 1.9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_test() {
|
||||
let mut mm = MovingMax::new(5);
|
||||
mm.update(1.0);
|
||||
mm.update(1.1);
|
||||
mm.update(1.9);
|
||||
mm.update(1.87);
|
||||
mm.update(1.89);
|
||||
assert_eq!(mm.max(), 1.9);
|
||||
mm.clear();
|
||||
assert_eq!(mm.max(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decay() {
|
||||
let mut mm = MovingMax::new(1);
|
||||
mm.update(1.0);
|
||||
let mut previous_value = 1.0;
|
||||
for _ in 0..500 {
|
||||
mm.update(0.0);
|
||||
assert!(mm.max() < previous_value);
|
||||
assert!(mm.max() > 0.0);
|
||||
previous_value = mm.max();
|
||||
}
|
||||
assert!(mm.max() < 0.01);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Normalized covariance estimator using exponential smoothing.
|
||||
//!
|
||||
//! Estimates the Pearson product-moment correlation coefficient between two signals.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/echo_detector/normalized_covariance_estimator.h/cc`.
|
||||
|
||||
/// Adaptation speed parameter.
|
||||
const ALPHA: f32 = 0.001;
|
||||
|
||||
/// Iteratively estimates the normalized covariance between two signals.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct NormalizedCovarianceEstimator {
|
||||
normalized_cross_correlation: f32,
|
||||
covariance: f32,
|
||||
}
|
||||
|
||||
impl NormalizedCovarianceEstimator {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
normalized_cross_correlation: 0.0,
|
||||
covariance: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(
|
||||
&mut self,
|
||||
x: f32,
|
||||
x_mean: f32,
|
||||
x_sigma: f32,
|
||||
y: f32,
|
||||
y_mean: f32,
|
||||
y_sigma: f32,
|
||||
) {
|
||||
self.covariance = (1.0 - ALPHA) * self.covariance + ALPHA * (x - x_mean) * (y - y_mean);
|
||||
self.normalized_cross_correlation = self.covariance / (x_sigma * y_sigma + 0.0001);
|
||||
debug_assert!(self.covariance.is_finite());
|
||||
debug_assert!(self.normalized_cross_correlation.is_finite());
|
||||
}
|
||||
|
||||
pub(crate) fn normalized_cross_correlation(&self) -> f32 {
|
||||
self.normalized_cross_correlation
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.covariance = 0.0;
|
||||
self.normalized_cross_correlation = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn identical_signal() {
|
||||
let mut est = NormalizedCovarianceEstimator::new();
|
||||
for _ in 0..10000 {
|
||||
est.update(1.0, 0.0, 1.0, 1.0, 0.0, 1.0);
|
||||
est.update(-1.0, 0.0, 1.0, -1.0, 0.0, 1.0);
|
||||
}
|
||||
assert!(
|
||||
(est.normalized_cross_correlation() - 1.0).abs() < 0.01,
|
||||
"expected ~1.0, got {}",
|
||||
est.normalized_cross_correlation(),
|
||||
);
|
||||
est.clear();
|
||||
assert_eq!(est.normalized_cross_correlation(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opposite_signal() {
|
||||
let mut est = NormalizedCovarianceEstimator::new();
|
||||
for _ in 0..10000 {
|
||||
est.update(1.0, 0.0, 1.0, -1.0, 0.0, 1.0);
|
||||
est.update(-1.0, 0.0, 1.0, 1.0, 0.0, 1.0);
|
||||
}
|
||||
assert!(
|
||||
(est.normalized_cross_correlation() + 1.0).abs() < 0.01,
|
||||
"expected ~-1.0, got {}",
|
||||
est.normalized_cross_correlation(),
|
||||
);
|
||||
}
|
||||
}
|
||||
+907
@@ -0,0 +1,907 @@
|
||||
//! Gain Controller 2 — orchestrates AGC2 subcomponents.
|
||||
//!
|
||||
//! Coordinates fixed gain, adaptive digital gain, input volume control,
|
||||
//! VAD, noise/speech level estimation, saturation protection, and limiting.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/gain_controller2.h/cc`.
|
||||
|
||||
use crate::audio_buffer::AudioBuffer;
|
||||
use crate::input_volume_controller::{InputVolumeController, InputVolumeControllerConfig};
|
||||
use sonora_agc2::adaptive_digital_gain_controller::{AdaptiveDigitalGainController, FrameInfo};
|
||||
use sonora_agc2::common::{
|
||||
ADJACENT_SPEECH_FRAMES_THRESHOLD, SATURATION_PROTECTOR_INITIAL_HEADROOM_DB,
|
||||
VAD_RESET_PERIOD_MS, db_to_ratio, float_s16_to_dbfs,
|
||||
};
|
||||
use sonora_agc2::gain_applier::GainApplier;
|
||||
use sonora_agc2::limiter::Limiter;
|
||||
use sonora_agc2::noise_level_estimator::NoiseLevelEstimator;
|
||||
use sonora_agc2::saturation_protector::SaturationProtector;
|
||||
use sonora_agc2::speech_level_estimator::{AdaptiveDigitalConfig, SpeechLevelEstimator};
|
||||
use sonora_agc2::vad_wrapper::VoiceActivityDetectorWrapper;
|
||||
use sonora_simd::detect_backend;
|
||||
|
||||
/// Configuration for the fixed digital controller.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct FixedDigitalConfig {
|
||||
pub gain_db: f32,
|
||||
}
|
||||
|
||||
impl Default for FixedDigitalConfig {
|
||||
fn default() -> Self {
|
||||
Self { gain_db: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for GainController2's input volume controller.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct Agc2InputVolumeControllerConfig {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// Top-level configuration for GainController2.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct Agc2Config {
|
||||
pub fixed_digital: FixedDigitalConfig,
|
||||
pub adaptive_digital: Agc2AdaptiveDigitalConfig,
|
||||
pub input_volume_controller: Agc2InputVolumeControllerConfig,
|
||||
}
|
||||
|
||||
/// Adaptive digital controller configuration (mirrors C++ API struct).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Agc2AdaptiveDigitalConfig {
|
||||
pub enabled: bool,
|
||||
pub headroom_db: f32,
|
||||
pub max_gain_db: f32,
|
||||
pub initial_gain_db: f32,
|
||||
pub max_gain_change_db_per_second: f32,
|
||||
pub max_output_noise_level_dbfs: f32,
|
||||
}
|
||||
|
||||
impl Default for Agc2AdaptiveDigitalConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
headroom_db: 5.0,
|
||||
max_gain_db: 50.0,
|
||||
initial_gain_db: 15.0,
|
||||
max_gain_change_db_per_second: 6.0,
|
||||
max_output_noise_level_dbfs: -50.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Agc2AdaptiveDigitalConfig> for AdaptiveDigitalConfig {
|
||||
fn from(c: &Agc2AdaptiveDigitalConfig) -> Self {
|
||||
Self {
|
||||
headroom_db: c.headroom_db,
|
||||
max_gain_db: c.max_gain_db,
|
||||
initial_gain_db: c.initial_gain_db,
|
||||
max_gain_change_db_per_second: c.max_gain_change_db_per_second,
|
||||
max_output_noise_level_dbfs: c.max_output_noise_level_dbfs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Peak and RMS audio levels in dBFS.
|
||||
struct AudioLevels {
|
||||
peak_dbfs: f32,
|
||||
rms_dbfs: f32,
|
||||
}
|
||||
|
||||
/// Computes the audio levels for the first channel.
|
||||
fn compute_audio_levels(audio: &AudioBuffer) -> AudioLevels {
|
||||
let channel = audio.channel(0);
|
||||
let num_samples = audio.num_frames();
|
||||
let mut peak: f32 = 0.0;
|
||||
let mut rms: f32 = 0.0;
|
||||
for &x in &channel[..num_samples] {
|
||||
peak = peak.max(x.abs());
|
||||
rms += x * x;
|
||||
}
|
||||
AudioLevels {
|
||||
peak_dbfs: float_s16_to_dbfs(peak),
|
||||
rms_dbfs: float_s16_to_dbfs((rms / num_samples as f32).sqrt()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies channel data out of an AudioBuffer for use with `&mut [&mut [f32]]` APIs.
|
||||
fn extract_channels(audio: &AudioBuffer) -> Vec<Vec<f32>> {
|
||||
(0..audio.num_channels())
|
||||
.map(|ch| audio.channel(ch).to_vec())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Writes channel data back into an AudioBuffer.
|
||||
fn write_back_channels(audio: &mut AudioBuffer, channel_data: &[Vec<f32>]) {
|
||||
let num_frames = audio.num_frames();
|
||||
for (ch, data) in channel_data.iter().enumerate() {
|
||||
audio.channel_mut(ch)[..num_frames].copy_from_slice(&data[..num_frames]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Gain Controller 2 aims to automatically adjust levels by acting on the
|
||||
/// microphone gain and/or applying digital gain.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct GainController2 {
|
||||
fixed_gain_applier: GainApplier,
|
||||
noise_level_estimator: Option<NoiseLevelEstimator>,
|
||||
vad: Option<VoiceActivityDetectorWrapper>,
|
||||
speech_level_estimator: Option<SpeechLevelEstimator>,
|
||||
input_volume_controller: Option<InputVolumeController>,
|
||||
saturation_protector: Option<SaturationProtector>,
|
||||
adaptive_digital_controller: Option<AdaptiveDigitalGainController>,
|
||||
limiter: Limiter,
|
||||
recommended_input_volume: Option<i32>,
|
||||
}
|
||||
|
||||
impl GainController2 {
|
||||
/// Creates a new GainController2.
|
||||
///
|
||||
/// If `use_internal_vad` is true, an internal voice activity detector is
|
||||
/// used for digital adaptive gain.
|
||||
pub(crate) fn new(
|
||||
config: &Agc2Config,
|
||||
input_volume_controller_config: &InputVolumeControllerConfig,
|
||||
sample_rate_hz: usize,
|
||||
num_channels: usize,
|
||||
use_internal_vad: bool,
|
||||
) -> Self {
|
||||
debug_assert!(Self::validate(config));
|
||||
let samples_per_channel = sample_rate_hz / 100;
|
||||
|
||||
let mut speech_level_estimator = None;
|
||||
let mut vad = None;
|
||||
|
||||
if config.input_volume_controller.enabled || config.adaptive_digital.enabled {
|
||||
let adaptive_config = AdaptiveDigitalConfig::from(&config.adaptive_digital);
|
||||
speech_level_estimator = Some(SpeechLevelEstimator::new(
|
||||
&adaptive_config,
|
||||
ADJACENT_SPEECH_FRAMES_THRESHOLD,
|
||||
));
|
||||
if use_internal_vad {
|
||||
let backend = detect_backend();
|
||||
vad = Some(VoiceActivityDetectorWrapper::with_reset_period(
|
||||
VAD_RESET_PERIOD_MS,
|
||||
backend,
|
||||
sample_rate_hz as i32,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut input_volume_controller = None;
|
||||
if config.input_volume_controller.enabled {
|
||||
let mut ivc = InputVolumeController::new(num_channels, input_volume_controller_config);
|
||||
ivc.initialize();
|
||||
input_volume_controller = Some(ivc);
|
||||
}
|
||||
|
||||
let mut noise_level_estimator = None;
|
||||
let mut saturation_protector = None;
|
||||
let mut adaptive_digital_controller = None;
|
||||
if config.adaptive_digital.enabled {
|
||||
noise_level_estimator = Some(NoiseLevelEstimator::default());
|
||||
saturation_protector = Some(SaturationProtector::new(
|
||||
SATURATION_PROTECTOR_INITIAL_HEADROOM_DB,
|
||||
ADJACENT_SPEECH_FRAMES_THRESHOLD,
|
||||
));
|
||||
let adaptive_config = AdaptiveDigitalConfig::from(&config.adaptive_digital);
|
||||
adaptive_digital_controller = Some(AdaptiveDigitalGainController::new(
|
||||
adaptive_config,
|
||||
ADJACENT_SPEECH_FRAMES_THRESHOLD,
|
||||
));
|
||||
}
|
||||
|
||||
Self {
|
||||
fixed_gain_applier: GainApplier::new(false, db_to_ratio(config.fixed_digital.gain_db)),
|
||||
noise_level_estimator,
|
||||
vad,
|
||||
speech_level_estimator,
|
||||
input_volume_controller,
|
||||
saturation_protector,
|
||||
adaptive_digital_controller,
|
||||
limiter: Limiter::new(samples_per_channel),
|
||||
recommended_input_volume: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the fixed digital gain.
|
||||
pub(crate) fn set_fixed_gain_db(&mut self, gain_db: f32) {
|
||||
let gain_factor = db_to_ratio(gain_db);
|
||||
if self.fixed_gain_applier.get_gain_factor() != gain_factor {
|
||||
self.limiter.reset();
|
||||
}
|
||||
self.fixed_gain_applier.set_gain_factor(gain_factor);
|
||||
}
|
||||
|
||||
/// Updates the input volume controller about whether the capture output is
|
||||
/// used or not.
|
||||
pub(crate) fn set_capture_output_used(&mut self, capture_output_used: bool) {
|
||||
if let Some(ref mut ivc) = self.input_volume_controller {
|
||||
ivc.handle_capture_output_used_change(capture_output_used);
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyzes `audio_buffer` before `process()` is called so that the
|
||||
/// analysis can be performed before digital processing operations take
|
||||
/// place (e.g., echo cancellation). The analysis consists of input
|
||||
/// clipping detection and prediction (if enabled).
|
||||
pub(crate) fn analyze(&mut self, applied_input_volume: i32, audio_buffer: &AudioBuffer) {
|
||||
self.recommended_input_volume = None;
|
||||
debug_assert!((0..=255).contains(&applied_input_volume));
|
||||
if let Some(ref mut ivc) = self.input_volume_controller {
|
||||
ivc.analyze_input_audio(applied_input_volume, audio_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the recommended input volume, applies the adaptive digital and
|
||||
/// the fixed digital gains, and runs a limiter on `audio`.
|
||||
pub(crate) fn process(&mut self, input_volume_changed: bool, audio: &mut AudioBuffer) {
|
||||
self.recommended_input_volume = None;
|
||||
|
||||
if input_volume_changed {
|
||||
if let Some(ref mut sle) = self.speech_level_estimator {
|
||||
sle.reset();
|
||||
}
|
||||
if let Some(ref mut sp) = self.saturation_protector {
|
||||
sp.reset();
|
||||
}
|
||||
}
|
||||
|
||||
// Compute speech probability.
|
||||
let speech_probability = if let Some(ref mut vad) = self.vad {
|
||||
let first_channel = audio.channel(0);
|
||||
vad.analyze(first_channel)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Compute audio levels from the first channel.
|
||||
let audio_levels = compute_audio_levels(audio);
|
||||
|
||||
// Noise level estimation.
|
||||
let noise_rms_dbfs = if let Some(ref mut nle) = self.noise_level_estimator {
|
||||
if audio.num_channels() == 1 {
|
||||
Some(nle.analyze(&[audio.channel(0)]))
|
||||
} else {
|
||||
let num_ch = audio.num_channels();
|
||||
let channels: Vec<&[f32]> = (0..num_ch).map(|ch| audio.channel(ch)).collect();
|
||||
Some(nle.analyze(&channels))
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Speech level estimation.
|
||||
let speech_level = if let Some(ref mut sle) = self.speech_level_estimator {
|
||||
sle.update(audio_levels.rms_dbfs, speech_probability);
|
||||
Some((sle.is_confident(), sle.level_dbfs()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Update the recommended input volume.
|
||||
if let (Some(ivc), Some((is_confident, rms_dbfs))) =
|
||||
(&mut self.input_volume_controller, speech_level)
|
||||
{
|
||||
let speech_level_opt = if is_confident { Some(rms_dbfs) } else { None };
|
||||
self.recommended_input_volume =
|
||||
ivc.recommend_input_volume(speech_probability, speech_level_opt);
|
||||
}
|
||||
|
||||
// Adaptive digital controller.
|
||||
if let Some(ref mut adc) = self.adaptive_digital_controller {
|
||||
let sp = self
|
||||
.saturation_protector
|
||||
.as_mut()
|
||||
.expect("saturation protector must exist when adaptive digital controller exists");
|
||||
let (is_confident, rms_dbfs) = speech_level
|
||||
.expect("speech level must exist when adaptive digital controller exists");
|
||||
sp.analyze(speech_probability, audio_levels.peak_dbfs, rms_dbfs);
|
||||
let headroom_db = sp.headroom_db();
|
||||
let limiter_envelope_dbfs = float_s16_to_dbfs(self.limiter.last_audio_level());
|
||||
let noise = noise_rms_dbfs
|
||||
.expect("noise level must exist when adaptive digital controller exists");
|
||||
|
||||
let info = FrameInfo {
|
||||
speech_probability,
|
||||
speech_level_dbfs: rms_dbfs,
|
||||
speech_level_reliable: is_confident,
|
||||
noise_rms_dbfs: noise,
|
||||
headroom_db,
|
||||
limiter_envelope_dbfs,
|
||||
};
|
||||
|
||||
// Mono capture borrows the existing channel; no sample/descriptor Vec is needed.
|
||||
if audio.num_channels() == 1 {
|
||||
adc.process(&info, &mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
let mut channel_data = extract_channels(audio);
|
||||
let mut channel_slices: Vec<&mut [f32]> =
|
||||
channel_data.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
adc.process(&info, &mut channel_slices);
|
||||
write_back_channels(audio, &channel_data);
|
||||
}
|
||||
}
|
||||
|
||||
// Fixed gain.
|
||||
if audio.num_channels() == 1 {
|
||||
self.fixed_gain_applier.apply_gain(&mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
let mut channel_data = extract_channels(audio);
|
||||
let mut channel_slices: Vec<&mut [f32]> =
|
||||
channel_data.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
self.fixed_gain_applier.apply_gain(&mut channel_slices);
|
||||
write_back_channels(audio, &channel_data);
|
||||
}
|
||||
|
||||
// Limiter.
|
||||
if audio.num_channels() == 1 {
|
||||
self.limiter.process(&mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
let mut channel_data = extract_channels(audio);
|
||||
let mut channel_slices: Vec<&mut [f32]> =
|
||||
channel_data.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
self.limiter.process(&mut channel_slices);
|
||||
write_back_channels(audio, &channel_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates the configuration.
|
||||
pub(crate) fn validate(config: &Agc2Config) -> bool {
|
||||
let fixed = &config.fixed_digital;
|
||||
let adaptive = &config.adaptive_digital;
|
||||
fixed.gain_db >= 0.0
|
||||
&& fixed.gain_db < 50.0
|
||||
&& adaptive.headroom_db >= 0.0
|
||||
&& adaptive.max_gain_db > 0.0
|
||||
&& adaptive.initial_gain_db >= 0.0
|
||||
&& adaptive.max_gain_change_db_per_second > 0.0
|
||||
&& adaptive.max_output_noise_level_dbfs <= 0.0
|
||||
}
|
||||
|
||||
/// Returns the recommended input volume, if available.
|
||||
pub(crate) fn recommended_input_volume(&self) -> Option<i32> {
|
||||
self.recommended_input_volume
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sonora_agc2::common::LIMITER_MAX_INPUT_LEVEL_DB_FS;
|
||||
|
||||
#[test]
|
||||
fn borrowed_mono_matches_identical_channels_through_upstream_fallback() {
|
||||
for adaptive in [false, true] {
|
||||
for fixed_gain_db in [0.0, 12.0] {
|
||||
let config = Agc2Config {
|
||||
fixed_digital: FixedDigitalConfig { gain_db: fixed_gain_db },
|
||||
adaptive_digital: Agc2AdaptiveDigitalConfig {
|
||||
enabled: adaptive,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let volume_config = InputVolumeControllerConfig::default();
|
||||
let mut mono = GainController2::new(&config, &volume_config, 48000, 1, true);
|
||||
let mut stereo = GainController2::new(&config, &volume_config, 48000, 2, true);
|
||||
let mut mono_audio = AudioBuffer::new(48000, 1, 48000, 1, 48000);
|
||||
let mut stereo_audio = AudioBuffer::new(48000, 2, 48000, 2, 48000);
|
||||
for frame in 0..300 {
|
||||
// Exercise silence, adaptive gain, clipping, fixed-gain changes and history.
|
||||
let amplitude = match frame % 100 {
|
||||
0..=9 => 0.0,
|
||||
10..=49 => 100.0,
|
||||
_ => 30000.0,
|
||||
};
|
||||
for sample in 0..480 {
|
||||
let phase = (frame * 480 + sample) as f32 * 0.037;
|
||||
let value = amplitude * phase.sin();
|
||||
mono_audio.channel_mut(0)[sample] = value;
|
||||
stereo_audio.channel_mut(0)[sample] = value;
|
||||
stereo_audio.channel_mut(1)[sample] = value;
|
||||
}
|
||||
if frame == 150 {
|
||||
mono.set_fixed_gain_db(6.0);
|
||||
stereo.set_fixed_gain_db(6.0);
|
||||
}
|
||||
mono.process(frame == 200, &mut mono_audio);
|
||||
stereo.process(frame == 200, &mut stereo_audio);
|
||||
for channel in 0..2 {
|
||||
assert_eq!(mono_audio.channel(0), stereo_audio.channel(channel),
|
||||
"adaptive={adaptive}, fixed={fixed_gain_db}, frame={frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets all samples in `ab` to `value`.
|
||||
fn set_audio_buffer_samples(value: f32, ab: &mut AudioBuffer) {
|
||||
for ch in 0..ab.num_channels() {
|
||||
let channel = ab.channel_mut(ch);
|
||||
for sample in channel.iter_mut() {
|
||||
*sample = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_agc2_with_constant_input(
|
||||
agc2: &mut GainController2,
|
||||
input_level: f32,
|
||||
num_frames: usize,
|
||||
sample_rate_hz: usize,
|
||||
num_channels: usize,
|
||||
applied_initial_volume: i32,
|
||||
) -> f32 {
|
||||
let num_samples = sample_rate_hz / 100;
|
||||
let mut ab = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
for _ in 0..num_frames + 1 {
|
||||
set_audio_buffer_samples(input_level, &mut ab);
|
||||
let applied_volume = agc2
|
||||
.recommended_input_volume()
|
||||
.unwrap_or(applied_initial_volume);
|
||||
agc2.analyze(applied_volume, &ab);
|
||||
agc2.process(false, &mut ab);
|
||||
}
|
||||
|
||||
ab.channel(0)[num_samples - 1]
|
||||
}
|
||||
|
||||
fn create_agc2_fixed_digital_mode(
|
||||
fixed_gain_db: f32,
|
||||
sample_rate_hz: usize,
|
||||
) -> GainController2 {
|
||||
let config = Agc2Config {
|
||||
fixed_digital: FixedDigitalConfig {
|
||||
gain_db: fixed_gain_db,
|
||||
},
|
||||
adaptive_digital: Agc2AdaptiveDigitalConfig {
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(GainController2::validate(&config));
|
||||
GainController2::new(
|
||||
&config,
|
||||
&InputVolumeControllerConfig::default(),
|
||||
sample_rate_hz,
|
||||
1,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
const TEST_INPUT_VOLUME_CONTROLLER_CONFIG: InputVolumeControllerConfig =
|
||||
InputVolumeControllerConfig {
|
||||
min_input_volume: 20,
|
||||
clipped_level_min: 20,
|
||||
clipped_level_step: 30,
|
||||
clipped_ratio_threshold: 0.4,
|
||||
clipped_wait_frames: 50,
|
||||
enable_clipping_predictor: true,
|
||||
target_range_max_dbfs: -6,
|
||||
target_range_min_dbfs: -70,
|
||||
update_input_volume_wait_frames: 100,
|
||||
speech_probability_threshold: 0.9,
|
||||
speech_ratio_threshold: 1.0,
|
||||
};
|
||||
|
||||
// --- Validation tests ---
|
||||
|
||||
#[test]
|
||||
fn check_default_config() {
|
||||
let config = Agc2Config::default();
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_fixed_digital_config() {
|
||||
let mut config = Agc2Config::default();
|
||||
// Attenuation is not allowed.
|
||||
config.fixed_digital.gain_db = -5.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
// No gain is allowed.
|
||||
config.fixed_digital.gain_db = 0.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
// Positive gain is allowed.
|
||||
config.fixed_digital.gain_db = 15.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_headroom_db() {
|
||||
let mut config = Agc2Config::default();
|
||||
config.adaptive_digital.headroom_db = -1.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.headroom_db = 0.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
config.adaptive_digital.headroom_db = 5.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_max_gain_db() {
|
||||
let mut config = Agc2Config::default();
|
||||
config.adaptive_digital.max_gain_db = -1.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.max_gain_db = 0.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.max_gain_db = 5.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_initial_gain_db() {
|
||||
let mut config = Agc2Config::default();
|
||||
config.adaptive_digital.initial_gain_db = -1.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.initial_gain_db = 0.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
config.adaptive_digital.initial_gain_db = 5.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_adaptive_digital_max_gain_change_speed_config() {
|
||||
let mut config = Agc2Config::default();
|
||||
config.adaptive_digital.max_gain_change_db_per_second = -1.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.max_gain_change_db_per_second = 0.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.max_gain_change_db_per_second = 5.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_adaptive_digital_max_output_noise_level_config() {
|
||||
let mut config = Agc2Config::default();
|
||||
config.adaptive_digital.max_output_noise_level_dbfs = 5.0;
|
||||
assert!(!GainController2::validate(&config));
|
||||
config.adaptive_digital.max_output_noise_level_dbfs = 0.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
config.adaptive_digital.max_output_noise_level_dbfs = -5.0;
|
||||
assert!(GainController2::validate(&config));
|
||||
}
|
||||
|
||||
// --- Input volume controller tests ---
|
||||
|
||||
#[test]
|
||||
fn check_recommended_input_volume_when_input_volume_controller_not_enabled() {
|
||||
let high_input_level = 32767.0_f32;
|
||||
let low_input_level = 1000.0_f32;
|
||||
let initial_input_volume = 100;
|
||||
let num_channels = 2;
|
||||
let num_frames = 5;
|
||||
let sample_rate_hz = 16000;
|
||||
|
||||
let config = Agc2Config {
|
||||
input_volume_controller: Agc2InputVolumeControllerConfig { enabled: false },
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gain_controller = GainController2::new(
|
||||
&config,
|
||||
&InputVolumeControllerConfig::default(),
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
true,
|
||||
);
|
||||
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
low_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
high_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_recommended_input_volume_when_not_enabled_and_specific_config() {
|
||||
let high_input_level = 32767.0_f32;
|
||||
let low_input_level = 1000.0_f32;
|
||||
let initial_input_volume = 100;
|
||||
let num_channels = 2;
|
||||
let num_frames = 5;
|
||||
let sample_rate_hz = 16000;
|
||||
|
||||
let config = Agc2Config {
|
||||
input_volume_controller: Agc2InputVolumeControllerConfig { enabled: false },
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gain_controller = GainController2::new(
|
||||
&config,
|
||||
&TEST_INPUT_VOLUME_CONTROLLER_CONFIG,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
true,
|
||||
);
|
||||
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
low_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
high_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_recommended_input_volume_when_input_volume_controller_enabled() {
|
||||
let high_input_level = 32767.0_f32;
|
||||
let low_input_level = 1000.0_f32;
|
||||
let initial_input_volume = 100;
|
||||
let num_channels = 2;
|
||||
let num_frames = 5;
|
||||
let sample_rate_hz = 16000;
|
||||
|
||||
let config = Agc2Config {
|
||||
input_volume_controller: Agc2InputVolumeControllerConfig { enabled: true },
|
||||
adaptive_digital: Agc2AdaptiveDigitalConfig {
|
||||
enabled: true,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gain_controller = GainController2::new(
|
||||
&config,
|
||||
&InputVolumeControllerConfig::default(),
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
true,
|
||||
);
|
||||
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
low_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_some());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
high_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_recommended_input_volume_when_enabled_and_specific_config() {
|
||||
let high_input_level = 32767.0_f32;
|
||||
let low_input_level = 1000.0_f32;
|
||||
let initial_input_volume = 100;
|
||||
let num_channels = 2;
|
||||
let num_frames = 5;
|
||||
let sample_rate_hz = 16000;
|
||||
|
||||
let config = Agc2Config {
|
||||
input_volume_controller: Agc2InputVolumeControllerConfig { enabled: true },
|
||||
adaptive_digital: Agc2AdaptiveDigitalConfig {
|
||||
enabled: true,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gain_controller = GainController2::new(
|
||||
&config,
|
||||
&TEST_INPUT_VOLUME_CONTROLLER_CONFIG,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
true,
|
||||
);
|
||||
|
||||
assert!(gain_controller.recommended_input_volume().is_none());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
low_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_some());
|
||||
|
||||
run_agc2_with_constant_input(
|
||||
&mut gain_controller,
|
||||
high_input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
initial_input_volume,
|
||||
);
|
||||
assert!(gain_controller.recommended_input_volume().is_some());
|
||||
}
|
||||
|
||||
// --- Construction test ---
|
||||
|
||||
#[test]
|
||||
fn apply_default_config() {
|
||||
let config = Agc2Config::default();
|
||||
let gain_controller = GainController2::new(
|
||||
&config,
|
||||
&InputVolumeControllerConfig::default(),
|
||||
16000,
|
||||
2,
|
||||
true,
|
||||
);
|
||||
// Just check it constructs without panicking.
|
||||
let _ = gain_controller;
|
||||
}
|
||||
|
||||
// --- Fixed digital tests ---
|
||||
|
||||
#[test]
|
||||
fn gain_should_change_on_set_gain() {
|
||||
let input_level = 1000.0_f32;
|
||||
let num_frames = 5;
|
||||
let sample_rate_hz = 8000;
|
||||
let gain_0_db = 0.0_f32;
|
||||
let gain_20_db = 20.0_f32;
|
||||
|
||||
let mut agc2_fixed = create_agc2_fixed_digital_mode(gain_0_db, sample_rate_hz);
|
||||
|
||||
// Signal level is unchanged with 0 dB gain.
|
||||
let out = run_agc2_with_constant_input(
|
||||
&mut agc2_fixed,
|
||||
input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
1,
|
||||
0,
|
||||
);
|
||||
assert!(
|
||||
(out - input_level).abs() < 0.01,
|
||||
"expected ~{input_level}, got {out}"
|
||||
);
|
||||
|
||||
// +20 dB should increase signal by a factor of 10.
|
||||
agc2_fixed.set_fixed_gain_db(gain_20_db);
|
||||
let out = run_agc2_with_constant_input(
|
||||
&mut agc2_fixed,
|
||||
input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
1,
|
||||
0,
|
||||
);
|
||||
assert!(
|
||||
(out - input_level * 10.0).abs() < 0.01,
|
||||
"expected ~{}, got {out}",
|
||||
input_level * 10.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_fixed_gain_should_be_fast_and_time_invariant() {
|
||||
let num_frames = 5;
|
||||
let input_level = 1000.0_f32;
|
||||
let sample_rate_hz = 8000;
|
||||
let gain_db_low = 0.0_f32;
|
||||
let gain_db_high = 25.0_f32;
|
||||
|
||||
let mut agc2_fixed = create_agc2_fixed_digital_mode(gain_db_low, sample_rate_hz);
|
||||
|
||||
// Start with a lower gain.
|
||||
let output_level_pre = run_agc2_with_constant_input(
|
||||
&mut agc2_fixed,
|
||||
input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
1,
|
||||
0,
|
||||
);
|
||||
|
||||
// Increase gain.
|
||||
agc2_fixed.set_fixed_gain_db(gain_db_high);
|
||||
let _ = run_agc2_with_constant_input(
|
||||
&mut agc2_fixed,
|
||||
input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
1,
|
||||
0,
|
||||
);
|
||||
|
||||
// Back to the lower gain.
|
||||
agc2_fixed.set_fixed_gain_db(gain_db_low);
|
||||
let output_level_post = run_agc2_with_constant_input(
|
||||
&mut agc2_fixed,
|
||||
input_level,
|
||||
num_frames,
|
||||
sample_rate_hz,
|
||||
1,
|
||||
0,
|
||||
);
|
||||
|
||||
assert_eq!(output_level_pre, output_level_post);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_saturation_behavior_with_limiter() {
|
||||
// LinSpace equivalent: generate evenly-spaced values.
|
||||
fn lin_space(l: f64, r: f64, num_points: usize) -> Vec<f64> {
|
||||
if num_points == 1 {
|
||||
return vec![l];
|
||||
}
|
||||
let step = (r - l) / (num_points - 1) as f64;
|
||||
(0..num_points).map(|i| l + step * i as f64).collect()
|
||||
}
|
||||
|
||||
let test_cases: Vec<(f64, f64, usize, bool)> = vec![
|
||||
// When gain < kLimiterMaxInputLevelDbFs, no saturation.
|
||||
(0.1, LIMITER_MAX_INPUT_LEVEL_DB_FS - 0.01, 8000, false),
|
||||
(0.1, LIMITER_MAX_INPUT_LEVEL_DB_FS - 0.01, 48000, false),
|
||||
// When gain > kLimiterMaxInputLevelDbFs, saturation.
|
||||
(LIMITER_MAX_INPUT_LEVEL_DB_FS + 0.01, 10.0, 8000, true),
|
||||
(LIMITER_MAX_INPUT_LEVEL_DB_FS + 0.01, 10.0, 48000, true),
|
||||
];
|
||||
|
||||
for (gain_db_min, gain_db_max, sample_rate_hz, saturation_expected) in test_cases {
|
||||
for gain_db in lin_space(gain_db_min, gain_db_max, 10) {
|
||||
let mut agc2_fixed = create_agc2_fixed_digital_mode(gain_db as f32, sample_rate_hz);
|
||||
let processed_sample =
|
||||
run_agc2_with_constant_input(&mut agc2_fixed, 32767.0, 5, sample_rate_hz, 1, 0);
|
||||
if saturation_expected {
|
||||
assert!(
|
||||
(processed_sample - 32767.0).abs() < 0.01,
|
||||
"gain_db={gain_db}, rate={sample_rate_hz}: expected saturation at 32767, got {processed_sample}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
processed_sample < 32767.0,
|
||||
"gain_db={gain_db}, rate={sample_rate_hz}: expected no saturation, got {processed_sample}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+410
@@ -0,0 +1,410 @@
|
||||
//! High-pass filter for removing DC and low-frequency noise.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/high_pass_filter.h/cc`.
|
||||
|
||||
use sonora_common_audio::cascaded_biquad_filter::{BiQuadCoefficients, CascadedBiQuadFilter};
|
||||
|
||||
use crate::audio_buffer::AudioBuffer;
|
||||
|
||||
const HIGH_PASS_FILTER_COEFFICIENTS_16KHZ: [BiQuadCoefficients; 3] = [
|
||||
BiQuadCoefficients {
|
||||
b: [
|
||||
0.8773539420715290582_f32,
|
||||
-1.754683920749088077_f32,
|
||||
0.8773539420715289472_f32,
|
||||
],
|
||||
a: [-1.881687317862849707_f32, 0.8880584644559580410_f32],
|
||||
},
|
||||
BiQuadCoefficients {
|
||||
b: [1.0, -1.999810143464515022_f32, 1.0],
|
||||
a: [-1.976035417167170793_f32, 0.9779708644868606582_f32],
|
||||
},
|
||||
BiQuadCoefficients {
|
||||
b: [1.0, -1.999669231394235469_f32, 1.0],
|
||||
a: [-1.994265767864654482_f32, 0.9954861594635392441_f32],
|
||||
},
|
||||
];
|
||||
|
||||
const HIGH_PASS_FILTER_COEFFICIENTS_32KHZ: [BiQuadCoefficients; 3] = [
|
||||
BiQuadCoefficients {
|
||||
b: [
|
||||
0.9102055685511306615_f32,
|
||||
-1.820404922871161624_f32,
|
||||
0.9102055685511306615_f32,
|
||||
],
|
||||
a: [-1.940710875829138482_f32, 0.9423512845457852061_f32],
|
||||
},
|
||||
BiQuadCoefficients {
|
||||
b: [1.0, -1.999952541587768806_f32, 1.0],
|
||||
a: [-1.988434609801665420_f32, 0.9889212529819323416_f32],
|
||||
},
|
||||
BiQuadCoefficients {
|
||||
b: [1.0, -1.999917315632020021_f32, 1.0],
|
||||
a: [-1.997434723613889629_f32, 0.9977401885079651978_f32],
|
||||
},
|
||||
];
|
||||
|
||||
const HIGH_PASS_FILTER_COEFFICIENTS_48KHZ: [BiQuadCoefficients; 3] = [
|
||||
BiQuadCoefficients {
|
||||
b: [
|
||||
0.9213790163564168_f32,
|
||||
-1.8427552370064049_f32,
|
||||
0.9213790163564168_f32,
|
||||
],
|
||||
a: [-1.9604500061078971_f32, 0.9611862979079667_f32],
|
||||
},
|
||||
BiQuadCoefficients {
|
||||
b: [1.0, -1.9999789078432082_f32, 1.0],
|
||||
a: [-1.9923834169149972_f32, 0.9926001112941157_f32],
|
||||
},
|
||||
BiQuadCoefficients {
|
||||
b: [1.0, -1.9999632520325810_f32, 1.0],
|
||||
a: [-1.9983570340145236_f32, 0.9984928491805198_f32],
|
||||
},
|
||||
];
|
||||
|
||||
fn choose_coefficients(sample_rate_hz: i32) -> &'static [BiQuadCoefficients; 3] {
|
||||
match sample_rate_hz {
|
||||
16000 => &HIGH_PASS_FILTER_COEFFICIENTS_16KHZ,
|
||||
32000 => &HIGH_PASS_FILTER_COEFFICIENTS_32KHZ,
|
||||
48000 => &HIGH_PASS_FILTER_COEFFICIENTS_48KHZ,
|
||||
_ => panic!("unsupported sample rate: {sample_rate_hz}; expected 16000, 32000, or 48000"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-channel high-pass filter using cascaded biquad sections.
|
||||
#[derive(Debug)]
|
||||
pub struct HighPassFilter {
|
||||
sample_rate_hz: i32,
|
||||
filters: Vec<CascadedBiQuadFilter>,
|
||||
}
|
||||
|
||||
impl HighPassFilter {
|
||||
pub fn new(sample_rate_hz: i32, num_channels: usize) -> Self {
|
||||
let coefficients = choose_coefficients(sample_rate_hz);
|
||||
let filters = (0..num_channels)
|
||||
.map(|_| CascadedBiQuadFilter::new(coefficients))
|
||||
.collect();
|
||||
Self {
|
||||
sample_rate_hz,
|
||||
filters,
|
||||
}
|
||||
}
|
||||
|
||||
/// Process audio through the high-pass filter using an AudioBuffer.
|
||||
pub(crate) fn process(&mut self, audio: &mut AudioBuffer, use_split_band_data: bool) {
|
||||
debug_assert_eq!(self.filters.len(), audio.num_channels());
|
||||
if use_split_band_data {
|
||||
for k in 0..audio.num_channels() {
|
||||
let data = audio.split_band_mut(k, 0);
|
||||
self.filters[k].process_in_place(data);
|
||||
}
|
||||
} else {
|
||||
for k in 0..audio.num_channels() {
|
||||
let data = audio.channel_mut(k);
|
||||
self.filters[k].process_in_place(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Process audio through the high-pass filter using raw channel vectors.
|
||||
pub fn process_channels(&mut self, audio: &mut [Vec<f32>]) {
|
||||
debug_assert_eq!(self.filters.len(), audio.len());
|
||||
for (k, channel) in audio.iter_mut().enumerate() {
|
||||
self.filters[k].process_in_place(channel);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sample_rate_hz(&self) -> i32 {
|
||||
self.sample_rate_hz
|
||||
}
|
||||
|
||||
pub(crate) fn num_channels(&self) -> usize {
|
||||
self.filters.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::stream_config::StreamConfig;
|
||||
|
||||
fn process_one_frame_as_audio_buffer(
|
||||
frame_input: &[f32],
|
||||
stream_config: &StreamConfig,
|
||||
hpf: &mut HighPassFilter,
|
||||
) -> Vec<f32> {
|
||||
let rate = stream_config.sample_rate_hz() as usize;
|
||||
let ch_count = stream_config.num_channels() as usize;
|
||||
let mut audio_buffer = AudioBuffer::new(rate, ch_count, rate, ch_count, rate);
|
||||
|
||||
// CopyVectorToAudioBuffer: deinterleave into per-channel data.
|
||||
let frames = stream_config.num_frames();
|
||||
for ch in 0..ch_count {
|
||||
let channel = audio_buffer.channel_mut(ch);
|
||||
for i in 0..frames {
|
||||
channel[i] = frame_input[i * ch_count + ch];
|
||||
}
|
||||
}
|
||||
|
||||
hpf.process(&mut audio_buffer, false);
|
||||
|
||||
// ExtractVectorFromAudioBuffer: read back per-channel data.
|
||||
let mut output = vec![0.0f32; frames * ch_count];
|
||||
for ch in 0..ch_count {
|
||||
let channel = audio_buffer.channel(ch);
|
||||
for i in 0..frames {
|
||||
output[ch * frames + i] = channel[i];
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn process_one_frame_as_vector(
|
||||
frame_input: &[f32],
|
||||
stream_config: &StreamConfig,
|
||||
hpf: &mut HighPassFilter,
|
||||
) -> Vec<f32> {
|
||||
let frames = stream_config.num_frames();
|
||||
let ch_count = stream_config.num_channels() as usize;
|
||||
|
||||
let mut process_vector: Vec<Vec<f32>> = vec![vec![0.0; frames]; ch_count];
|
||||
for k in 0..frames {
|
||||
for ch in 0..ch_count {
|
||||
process_vector[ch][k] = frame_input[k * ch_count + ch];
|
||||
}
|
||||
}
|
||||
|
||||
hpf.process_channels(&mut process_vector);
|
||||
|
||||
process_vector[0].clone()
|
||||
}
|
||||
|
||||
fn run_bitexactness_test(
|
||||
num_channels: u16,
|
||||
use_audio_buffer_interface: bool,
|
||||
input: &[f32],
|
||||
reference: &[f32],
|
||||
) {
|
||||
let stream_config = StreamConfig::new(16000, num_channels);
|
||||
let mut hpf = HighPassFilter::new(16000, num_channels as usize);
|
||||
|
||||
let frames = stream_config.num_frames();
|
||||
let nch = num_channels as usize;
|
||||
let num_frames_to_process = input.len() / (frames * nch);
|
||||
let mut output = Vec::new();
|
||||
|
||||
for frame_no in 0..num_frames_to_process {
|
||||
let start = frames * nch * frame_no;
|
||||
let end = frames * nch * (frame_no + 1);
|
||||
let frame_input = &input[start..end];
|
||||
|
||||
output = if use_audio_buffer_interface {
|
||||
process_one_frame_as_audio_buffer(frame_input, &stream_config, &mut hpf)
|
||||
} else {
|
||||
process_one_frame_as_vector(frame_input, &stream_config, &mut hpf)
|
||||
};
|
||||
}
|
||||
|
||||
let reference_frame_length = reference.len() / nch;
|
||||
let mut output_to_verify = Vec::new();
|
||||
for channel_no in 0..nch {
|
||||
let start = channel_no * frames;
|
||||
let end = start + reference_frame_length;
|
||||
output_to_verify.extend_from_slice(&output[start..end]);
|
||||
}
|
||||
|
||||
let element_error_bound = 1.0 / 32768.0;
|
||||
for (i, (o, r)) in output_to_verify.iter().zip(reference.iter()).enumerate() {
|
||||
assert!(
|
||||
(o - r).abs() <= element_error_bound,
|
||||
"mismatch at index {i}: output={o}, reference={r}, diff={}",
|
||||
(o - r).abs(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_initial() {
|
||||
#[rustfmt::skip]
|
||||
let reference_input: Vec<f32> = vec![
|
||||
0.150254, 0.512488, -0.631245, 0.240938, 0.089080, -0.365440,
|
||||
-0.121169, 0.095748, 1.000000, 0.773932, -0.377232, 0.848124,
|
||||
0.202718, -0.017621, 0.199738, -0.057279, -0.034693, 0.416303,
|
||||
0.393761, 0.396041, 0.187653, -0.337438, 0.200436, 0.455577,
|
||||
0.136624, 0.289150, 0.203131, -0.084798, 0.082124, -0.220010,
|
||||
0.248266, -0.320554, -0.298701, -0.226218, -0.822794, 0.401962,
|
||||
0.090876, -0.210968, 0.382936, -0.478291, -0.028572, -0.067474,
|
||||
0.089204, 0.087430, -0.241695, -0.008398, -0.046076, 0.175416,
|
||||
0.305518, 0.309992, -0.241352, 0.021618, -0.339291, -0.311173,
|
||||
-0.001914, 0.428301, -0.215087, 0.103784, -0.063041, 0.312250,
|
||||
-0.304344, 0.009098, 0.154406, 0.307571, 0.431537, 0.024014,
|
||||
-0.416832, -0.207440, -0.296664, 0.656846, -0.172033, 0.209054,
|
||||
-0.053772, 0.248326, -0.213741, -0.391871, -0.397490, 0.136428,
|
||||
-0.049568, -0.054788, 0.396633, 0.081485, 0.055279, 0.443690,
|
||||
-0.224812, 0.194675, 0.233369, -0.068107, 0.060270, -0.325801,
|
||||
-0.320801, 0.029308, 0.201837, 0.722528, -0.186366, 0.052351,
|
||||
-0.023053, -0.540192, -0.122671, -0.501532, 0.234847, -0.248165,
|
||||
0.027971, -0.152171, 0.084820, -0.167764, 0.136923, 0.206619,
|
||||
0.478395, -0.054249, -0.597574, -0.234627, 0.378548, -0.299619,
|
||||
0.268543, 0.034666, 0.401492, -0.547983, -0.055248, -0.337538,
|
||||
0.812657, 0.230611, 0.385360, -0.295713, -0.130957, -0.076143,
|
||||
0.306960, -0.077653, 0.196049, -0.573390, -0.098885, -0.230155,
|
||||
-0.440716, 0.141956, 0.078802, 0.009356, -0.372703, 0.315083,
|
||||
0.097859, -0.083575, 0.006397, -0.073216, -0.489105, -0.079827,
|
||||
-0.232329, -0.273644, -0.323162, -0.149105, -0.559646, 0.269458,
|
||||
0.145333, -0.005597, -0.009717, -0.223051, 0.284676, -0.037228,
|
||||
-0.199679, 0.377651, -0.062813, -0.164607,
|
||||
];
|
||||
#[rustfmt::skip]
|
||||
let reference: Vec<f32> = vec![
|
||||
0.131826, 0.430194, -0.638357, 0.213868,
|
||||
0.049683, -0.358489, -0.094094, 0.111697,
|
||||
0.891429, 0.563210, -0.539361, 0.598238,
|
||||
];
|
||||
|
||||
for use_audio_buffer_interface in [true, false] {
|
||||
run_bitexactness_test(1, use_audio_buffer_interface, &reference_input, &reference);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_converged() {
|
||||
#[rustfmt::skip]
|
||||
let reference_input: Vec<f32> = vec![
|
||||
0.150254, 0.512488, -0.631245, 0.240938, 0.089080, -0.365440,
|
||||
-0.121169, 0.095748, 1.000000, 0.773932, -0.377232, 0.848124,
|
||||
0.202718, -0.017621, 0.199738, -0.057279, -0.034693, 0.416303,
|
||||
0.393761, 0.396041, 0.187653, -0.337438, 0.200436, 0.455577,
|
||||
0.136624, 0.289150, 0.203131, -0.084798, 0.082124, -0.220010,
|
||||
0.248266, -0.320554, -0.298701, -0.226218, -0.822794, 0.401962,
|
||||
0.090876, -0.210968, 0.382936, -0.478291, -0.028572, -0.067474,
|
||||
0.089204, 0.087430, -0.241695, -0.008398, -0.046076, 0.175416,
|
||||
0.305518, 0.309992, -0.241352, 0.021618, -0.339291, -0.311173,
|
||||
-0.001914, 0.428301, -0.215087, 0.103784, -0.063041, 0.312250,
|
||||
-0.304344, 0.009098, 0.154406, 0.307571, 0.431537, 0.024014,
|
||||
-0.416832, -0.207440, -0.296664, 0.656846, -0.172033, 0.209054,
|
||||
-0.053772, 0.248326, -0.213741, -0.391871, -0.397490, 0.136428,
|
||||
-0.049568, -0.054788, 0.396633, 0.081485, 0.055279, 0.443690,
|
||||
-0.224812, 0.194675, 0.233369, -0.068107, 0.060270, -0.325801,
|
||||
-0.320801, 0.029308, 0.201837, 0.722528, -0.186366, 0.052351,
|
||||
-0.023053, -0.540192, -0.122671, -0.501532, 0.234847, -0.248165,
|
||||
0.027971, -0.152171, 0.084820, -0.167764, 0.136923, 0.206619,
|
||||
0.478395, -0.054249, -0.597574, -0.234627, 0.378548, -0.299619,
|
||||
0.268543, 0.034666, 0.401492, -0.547983, -0.055248, -0.337538,
|
||||
0.812657, 0.230611, 0.385360, -0.295713, -0.130957, -0.076143,
|
||||
0.306960, -0.077653, 0.196049, -0.573390, -0.098885, -0.230155,
|
||||
-0.440716, 0.141956, 0.078802, 0.009356, -0.372703, 0.315083,
|
||||
0.097859, -0.083575, 0.006397, -0.073216, -0.489105, -0.079827,
|
||||
-0.232329, -0.273644, -0.323162, -0.149105, -0.559646, 0.269458,
|
||||
0.145333, -0.005597, -0.009717, -0.223051, 0.284676, -0.037228,
|
||||
-0.199679, 0.377651, -0.062813, -0.164607, -0.082091, -0.236957,
|
||||
-0.313025, 0.705903, 0.462637, 0.085942, -0.351308, -0.241859,
|
||||
-0.049333, 0.221165, -0.372235, -0.651092, -0.404957, 0.093201,
|
||||
0.109366, 0.126224, -0.036409, 0.051333, -0.133063, 0.240896,
|
||||
-0.380532, 0.127160, -0.237176, -0.093586, 0.154478, 0.290379,
|
||||
-0.312329, 0.352297, 0.184480, -0.018965, -0.054555, -0.060811,
|
||||
-0.084705, 0.006440, 0.014333, 0.230847, 0.426721, 0.130481,
|
||||
-0.058605, 0.174712, 0.051204, -0.287773, 0.265265, 0.085810,
|
||||
0.037775, 0.143988, 0.073051, -0.263103, -0.045366, -0.040816,
|
||||
-0.148673, 0.470072, -0.244727, -0.135204, -0.198973, -0.328139,
|
||||
-0.053722, -0.076590, 0.427586, -0.069591, -0.297399, 0.448094,
|
||||
0.345037, -0.064170, -0.420903, -0.124253, -0.043578, 0.077149,
|
||||
-0.072983, 0.123916, 0.109517, -0.349508, -0.264912, -0.207106,
|
||||
-0.141912, -0.089586, 0.003485, -0.846518, -0.127715, 0.347208,
|
||||
-0.298095, 0.260935, 0.097899, -0.008106, 0.050987, -0.437362,
|
||||
-0.023625, 0.448230, 0.027484, 0.011562, -0.205167, -0.008611,
|
||||
0.064930, 0.119156, -0.104183, -0.066078, 0.565530, -0.631108,
|
||||
0.623029, 0.094334, 0.279472, -0.465059, -0.164888, -0.077706,
|
||||
0.118130, -0.466746, 0.131800, -0.338936, 0.018497, 0.182304,
|
||||
0.091398, 0.302547, 0.281153, -0.181899, 0.071836, -0.263911,
|
||||
-0.369380, 0.258447, 0.000014, -0.015347, 0.254619, 0.166159,
|
||||
0.097865, 0.349389, 0.259834, 0.067003, -0.192925, -0.182080,
|
||||
0.333139, -0.450434, -0.006836, -0.544615, 0.285183, 0.240811,
|
||||
0.000325, -0.019796, -0.694804, 0.162411, -0.612686, -0.648134,
|
||||
0.022338, -0.265058, 0.114993, 0.189185, 0.239697, -0.193148,
|
||||
0.125581, 0.028122, 0.230849, 0.149832, 0.250919, -0.036871,
|
||||
-0.041136, 0.281627, -0.593466, -0.141009, -0.355074, -0.106915,
|
||||
0.181276, 0.230753, -0.283631, -0.131643, 0.038292, -0.081563,
|
||||
0.084345, 0.111763, -0.259882, -0.049416, -0.595824, 0.320077,
|
||||
-0.175802, -0.336422, -0.070966, -0.399242, -0.005829, -0.156680,
|
||||
0.608591, 0.318150, -0.697767, 0.123331, -0.390716, -0.071276,
|
||||
0.045943, 0.208958, -0.076304, 0.440505, -0.134400, 0.091525,
|
||||
0.185763, 0.023806, 0.246186, 0.090323, -0.219133, -0.504520,
|
||||
0.519393, -0.168939, 0.028884, 0.157380, 0.031745, -0.252830,
|
||||
-0.130705, -0.034901, 0.413302, -0.240559, 0.219279, 0.086246,
|
||||
-0.065353, -0.295376, -0.079405, -0.024226, -0.410629, 0.053706,
|
||||
-0.229794, -0.026336, 0.093956, -0.252810, -0.080555, 0.097827,
|
||||
-0.513040, 0.289508, 0.677527, 0.268109, -0.088244, 0.119781,
|
||||
-0.289511, 0.524778, 0.262884, 0.220028, -0.244767, 0.089411,
|
||||
-0.156018, -0.087030, -0.159292, -0.286646, -0.253953, -0.058657,
|
||||
-0.474756, 0.169797, -0.032919, 0.195384, 0.075355, 0.138131,
|
||||
-0.414465, -0.285118, -0.124915, 0.030645, 0.315431, -0.081032,
|
||||
0.352546, 0.132860, 0.328112, 0.035476, -0.183550, -0.413984,
|
||||
0.043452, 0.228748, -0.081765, -0.151125, -0.086251, -0.306448,
|
||||
-0.137774, -0.050508, 0.012811, -0.017824, 0.170841, 0.030549,
|
||||
0.506935, 0.087197, 0.504274, -0.202080, 0.147146, -0.072728,
|
||||
0.167713, 0.165977, -0.610894, -0.370849, -0.402698, 0.112297,
|
||||
0.410855, -0.091330, 0.227008, 0.152454, -0.293884, 0.111074,
|
||||
-0.210121, 0.423728, -0.009101, 0.457188, -0.118785, 0.164720,
|
||||
-0.017547, -0.565046, -0.274461, 0.171169, -0.015338, -0.312635,
|
||||
-0.175044, 0.069729, -0.277504, 0.272454, -0.179049, 0.505495,
|
||||
-0.301774, 0.055664, -0.425058, -0.202222, -0.165787, 0.112155,
|
||||
0.263284, 0.083972, -0.104256, 0.227892, 0.223253, 0.033592,
|
||||
0.159638, 0.115358, -0.275811, 0.212265, -0.183658, -0.168768,
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
let reference: Vec<f32> = vec![
|
||||
-0.232532, -0.066054, 0.094511, -0.021924,
|
||||
0.128477, 0.135562, -0.210019, 0.004422,
|
||||
-0.474193, 0.400765, -0.085890, -0.211323,
|
||||
];
|
||||
|
||||
for use_audio_buffer_interface in [true, false] {
|
||||
run_bitexactness_test(1, use_audio_buffer_interface, &reference_input, &reference);
|
||||
}
|
||||
}
|
||||
|
||||
fn dc_signal_attenuation(sample_rate: f32) -> f32 {
|
||||
let num_channels = 1;
|
||||
let mut hpf = HighPassFilter::new(sample_rate as i32, num_channels);
|
||||
let len = sample_rate as usize / 10;
|
||||
let mut audio_data = vec![vec![0.0f32; len]; 1];
|
||||
|
||||
let max_dc_level = 32767.0f32;
|
||||
let mut energy_before_filtering = 0.0f32;
|
||||
let mut energy_after_filtering = 0.0f32;
|
||||
|
||||
for _ in 0..2 {
|
||||
energy_before_filtering = 0.0;
|
||||
for sample in audio_data[0].iter_mut() {
|
||||
*sample = max_dc_level;
|
||||
energy_before_filtering += *sample * *sample;
|
||||
}
|
||||
|
||||
hpf.process_channels(&mut audio_data);
|
||||
energy_after_filtering = 0.0;
|
||||
for &sample in &audio_data[0] {
|
||||
energy_after_filtering += sample * sample;
|
||||
}
|
||||
}
|
||||
|
||||
10.0 * (energy_before_filtering / energy_after_filtering).log10()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dc_signal_attenuation_16() {
|
||||
assert!(dc_signal_attenuation(16000.0) >= 47.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dc_signal_attenuation_32() {
|
||||
assert!(dc_signal_attenuation(32000.0) >= 47.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dc_signal_attenuation_48() {
|
||||
assert!(dc_signal_attenuation(48000.0) >= 47.3);
|
||||
}
|
||||
}
|
||||
+1914
File diff suppressed because it is too large.
Load diff
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
|
||||
pub(crate) mod audio_buffer;
|
||||
pub(crate) mod audio_converter;
|
||||
pub(crate) mod audio_processing;
|
||||
pub(crate) mod audio_processing_impl;
|
||||
pub(crate) mod audio_samples_scaler;
|
||||
pub(crate) mod capture_levels_adjuster;
|
||||
pub(crate) mod config_selector;
|
||||
pub(crate) mod echo_canceller3;
|
||||
pub(crate) mod echo_detector;
|
||||
pub(crate) mod gain_controller2;
|
||||
pub(crate) mod input_volume_controller;
|
||||
pub(crate) mod residual_echo_detector;
|
||||
pub(crate) mod rms_level;
|
||||
pub(crate) mod splitting_filter;
|
||||
pub(crate) mod stream_config;
|
||||
pub(crate) mod submodule_states;
|
||||
pub(crate) mod swap_queue;
|
||||
|
||||
pub mod config;
|
||||
pub mod high_pass_filter;
|
||||
pub mod stats;
|
||||
pub mod three_band_filter_bank;
|
||||
|
||||
pub use audio_processing::{AudioProcessing, AudioProcessingBuilder, Error};
|
||||
pub use config::Config;
|
||||
pub use stats::AudioProcessingStats;
|
||||
pub use stream_config::StreamConfig;
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
//! Residual echo detector using normalized covariance analysis.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/residual_echo_detector.h/cc`.
|
||||
|
||||
use crate::echo_detector::circular_buffer::CircularBuffer;
|
||||
use crate::echo_detector::mean_variance_estimator::MeanVarianceEstimator;
|
||||
use crate::echo_detector::moving_max::MovingMax;
|
||||
use crate::echo_detector::normalized_covariance_estimator::NormalizedCovarianceEstimator;
|
||||
|
||||
const LOOKBACK_FRAMES: usize = 650;
|
||||
const RENDER_BUFFER_SIZE: usize = 30;
|
||||
const ALPHA: f32 = 0.001;
|
||||
/// 10 seconds of data, updated every 10 ms.
|
||||
const AGGREGATION_BUFFER_SIZE: usize = 10 * 100;
|
||||
|
||||
fn power(input: &[f32]) -> f32 {
|
||||
if input.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let sum: f32 = input.iter().map(|x| x * x).sum();
|
||||
sum / input.len() as f32
|
||||
}
|
||||
|
||||
/// Echo detector metrics.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct EchoDetectorMetrics {
|
||||
pub(crate) echo_likelihood: Option<f32>,
|
||||
pub(crate) echo_likelihood_recent_max: Option<f32>,
|
||||
}
|
||||
|
||||
/// Residual echo detector that estimates echo likelihood from render/capture signals.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ResidualEchoDetector {
|
||||
first_process_call: bool,
|
||||
render_buffer: CircularBuffer,
|
||||
frames_since_zero_buffer_size: usize,
|
||||
render_power: Vec<f32>,
|
||||
render_power_mean: Vec<f32>,
|
||||
render_power_std_dev: Vec<f32>,
|
||||
covariances: Vec<NormalizedCovarianceEstimator>,
|
||||
next_insertion_index: usize,
|
||||
render_statistics: MeanVarianceEstimator,
|
||||
capture_statistics: MeanVarianceEstimator,
|
||||
echo_likelihood: f32,
|
||||
reliability: f32,
|
||||
recent_likelihood_max: MovingMax,
|
||||
log_counter: i32,
|
||||
}
|
||||
|
||||
impl ResidualEchoDetector {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
first_process_call: true,
|
||||
render_buffer: CircularBuffer::new(RENDER_BUFFER_SIZE),
|
||||
frames_since_zero_buffer_size: 0,
|
||||
render_power: vec![0.0; LOOKBACK_FRAMES],
|
||||
render_power_mean: vec![0.0; LOOKBACK_FRAMES],
|
||||
render_power_std_dev: vec![0.0; LOOKBACK_FRAMES],
|
||||
covariances: (0..LOOKBACK_FRAMES)
|
||||
.map(|_| NormalizedCovarianceEstimator::new())
|
||||
.collect(),
|
||||
next_insertion_index: 0,
|
||||
render_statistics: MeanVarianceEstimator::new(),
|
||||
capture_statistics: MeanVarianceEstimator::new(),
|
||||
echo_likelihood: 0.0,
|
||||
reliability: 0.0,
|
||||
recent_likelihood_max: MovingMax::new(AGGREGATION_BUFFER_SIZE),
|
||||
log_counter: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze render (far-end) audio. Should be called while holding the render lock.
|
||||
pub(crate) fn analyze_render_audio(&mut self, render_audio: &[f32]) {
|
||||
if self.render_buffer.size() == 0 {
|
||||
self.frames_since_zero_buffer_size = 0;
|
||||
} else if self.frames_since_zero_buffer_size >= RENDER_BUFFER_SIZE {
|
||||
self.render_buffer.pop();
|
||||
self.frames_since_zero_buffer_size = 0;
|
||||
}
|
||||
self.frames_since_zero_buffer_size += 1;
|
||||
let pwr = power(render_audio);
|
||||
self.render_buffer.push(pwr);
|
||||
}
|
||||
|
||||
/// Analyze capture (near-end) audio. Should be called while holding the capture lock.
|
||||
pub(crate) fn analyze_capture_audio(&mut self, capture_audio: &[f32]) {
|
||||
if self.first_process_call {
|
||||
self.render_buffer.clear();
|
||||
self.first_process_call = false;
|
||||
}
|
||||
|
||||
let Some(buffered_render_power) = self.render_buffer.pop() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Update render statistics and store in circular buffers.
|
||||
self.render_statistics.update(buffered_render_power);
|
||||
debug_assert!(self.next_insertion_index < LOOKBACK_FRAMES);
|
||||
self.render_power[self.next_insertion_index] = buffered_render_power;
|
||||
self.render_power_mean[self.next_insertion_index] = self.render_statistics.mean();
|
||||
self.render_power_std_dev[self.next_insertion_index] =
|
||||
self.render_statistics.std_deviation();
|
||||
|
||||
// Get capture power and update capture statistics.
|
||||
let capture_power = power(capture_audio);
|
||||
self.capture_statistics.update(capture_power);
|
||||
let capture_mean = self.capture_statistics.mean();
|
||||
let capture_std_deviation = self.capture_statistics.std_deviation();
|
||||
|
||||
// Update covariance values and determine echo likelihood.
|
||||
self.echo_likelihood = 0.0;
|
||||
let mut read_index = self.next_insertion_index;
|
||||
|
||||
for delay in 0..self.covariances.len() {
|
||||
debug_assert!(read_index < self.render_power.len());
|
||||
self.covariances[delay].update(
|
||||
capture_power,
|
||||
capture_mean,
|
||||
capture_std_deviation,
|
||||
self.render_power[read_index],
|
||||
self.render_power_mean[read_index],
|
||||
self.render_power_std_dev[read_index],
|
||||
);
|
||||
read_index = if read_index > 0 {
|
||||
read_index - 1
|
||||
} else {
|
||||
LOOKBACK_FRAMES - 1
|
||||
};
|
||||
|
||||
if self.covariances[delay].normalized_cross_correlation() > self.echo_likelihood {
|
||||
self.echo_likelihood = self.covariances[delay].normalized_cross_correlation();
|
||||
}
|
||||
}
|
||||
|
||||
if self.echo_likelihood > 1.1 && self.log_counter < 5 {
|
||||
tracing::error!(
|
||||
echo_likelihood = self.echo_likelihood,
|
||||
reliability = self.reliability,
|
||||
"echo detector internal state: echo likelihood > 1.1"
|
||||
);
|
||||
self.log_counter += 1;
|
||||
}
|
||||
debug_assert!(self.echo_likelihood < 1.1);
|
||||
|
||||
self.reliability = (1.0 - ALPHA) * self.reliability + ALPHA;
|
||||
self.echo_likelihood *= self.reliability;
|
||||
self.echo_likelihood = self.echo_likelihood.min(1.0);
|
||||
|
||||
self.recent_likelihood_max.update(self.echo_likelihood);
|
||||
|
||||
self.next_insertion_index = if self.next_insertion_index < (LOOKBACK_FRAMES - 1) {
|
||||
self.next_insertion_index + 1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
}
|
||||
|
||||
/// Initialize/reset the detector.
|
||||
pub(crate) fn initialize(&mut self) {
|
||||
self.render_buffer.clear();
|
||||
self.render_power.fill(0.0);
|
||||
self.render_power_mean.fill(0.0);
|
||||
self.render_power_std_dev.fill(0.0);
|
||||
self.render_statistics.clear();
|
||||
self.capture_statistics.clear();
|
||||
self.recent_likelihood_max.clear();
|
||||
for cov in &mut self.covariances {
|
||||
cov.clear();
|
||||
}
|
||||
self.echo_likelihood = 0.0;
|
||||
self.next_insertion_index = 0;
|
||||
self.reliability = 0.0;
|
||||
}
|
||||
|
||||
/// Get current echo detection metrics.
|
||||
pub(crate) fn get_metrics(&self) -> EchoDetectorMetrics {
|
||||
EchoDetectorMetrics {
|
||||
echo_likelihood: Some(self.echo_likelihood),
|
||||
echo_likelihood_recent_max: Some(self.recent_likelihood_max.max()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set reliability directly (for testing only).
|
||||
#[cfg(test)]
|
||||
fn set_reliability_for_test(&mut self, value: f32) {
|
||||
self.reliability = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn echo() {
|
||||
let mut echo_detector = ResidualEchoDetector::new();
|
||||
echo_detector.set_reliability_for_test(1.0);
|
||||
let ones = vec![1.0f32; 160];
|
||||
let zeros = vec![0.0f32; 160];
|
||||
|
||||
for i in 0..1000 {
|
||||
if i % 20 == 0 {
|
||||
echo_detector.analyze_render_audio(&ones);
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
} else if i % 20 == 10 {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
echo_detector.analyze_capture_audio(&ones);
|
||||
} else {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
}
|
||||
}
|
||||
|
||||
let metrics = echo_detector.get_metrics();
|
||||
assert!(metrics.echo_likelihood.is_some());
|
||||
let likelihood = metrics.echo_likelihood.unwrap();
|
||||
assert!(
|
||||
(likelihood - 1.0).abs() < 0.01,
|
||||
"expected near 1.0, got {likelihood}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_echo() {
|
||||
let mut echo_detector = ResidualEchoDetector::new();
|
||||
echo_detector.set_reliability_for_test(1.0);
|
||||
let ones = vec![1.0f32; 160];
|
||||
let zeros = vec![0.0f32; 160];
|
||||
|
||||
for i in 0..1000 {
|
||||
if i % 20 == 0 {
|
||||
echo_detector.analyze_render_audio(&ones);
|
||||
} else {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
}
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
}
|
||||
|
||||
let metrics = echo_detector.get_metrics();
|
||||
assert!(metrics.echo_likelihood.is_some());
|
||||
let likelihood = metrics.echo_likelihood.unwrap();
|
||||
assert!(
|
||||
likelihood.abs() < 0.01,
|
||||
"expected near 0.0, got {likelihood}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo_with_render_clock_drift() {
|
||||
let mut echo_detector = ResidualEchoDetector::new();
|
||||
echo_detector.set_reliability_for_test(1.0);
|
||||
let ones = vec![1.0f32; 160];
|
||||
let zeros = vec![0.0f32; 160];
|
||||
|
||||
for i in 0..1000 {
|
||||
if i % 20 == 0 {
|
||||
echo_detector.analyze_render_audio(&ones);
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
} else if i % 20 == 10 {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
echo_detector.analyze_capture_audio(&ones);
|
||||
} else {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
}
|
||||
if i % 100 == 0 {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
}
|
||||
}
|
||||
|
||||
let metrics = echo_detector.get_metrics();
|
||||
assert!(metrics.echo_likelihood.is_some());
|
||||
let likelihood = metrics.echo_likelihood.unwrap();
|
||||
assert!(likelihood > 0.75, "expected > 0.75, got {likelihood}",);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo_with_capture_clock_drift() {
|
||||
let mut echo_detector = ResidualEchoDetector::new();
|
||||
echo_detector.set_reliability_for_test(1.0);
|
||||
let ones = vec![1.0f32; 160];
|
||||
let zeros = vec![0.0f32; 160];
|
||||
|
||||
for i in 0..1000 {
|
||||
if i % 20 == 0 {
|
||||
echo_detector.analyze_render_audio(&ones);
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
} else if i % 20 == 10 {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
echo_detector.analyze_capture_audio(&ones);
|
||||
} else {
|
||||
echo_detector.analyze_render_audio(&zeros);
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
}
|
||||
if i % 100 == 0 {
|
||||
echo_detector.analyze_capture_audio(&zeros);
|
||||
}
|
||||
}
|
||||
|
||||
let metrics = echo_detector.get_metrics();
|
||||
assert!(metrics.echo_likelihood.is_some());
|
||||
let likelihood = metrics.echo_likelihood.unwrap();
|
||||
assert!(
|
||||
(likelihood - 1.0).abs() < 0.01,
|
||||
"expected near 1.0, got {likelihood}",
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+321
@@ -0,0 +1,321 @@
|
||||
//! RMS level computation following RFC 6465.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/rms_level.h/cc`.
|
||||
|
||||
// Constants and computation functions used by test-only methods
|
||||
// (average, average_and_peak). Production code only uses
|
||||
// analyze_float + reset.
|
||||
#[cfg(test)]
|
||||
const MAX_SQUARED_LEVEL: f32 = 32768.0 * 32768.0;
|
||||
#[cfg(test)]
|
||||
const MIN_LEVEL: f32 = 1.995_262_3e-13;
|
||||
#[cfg(test)]
|
||||
const MIN_LEVEL_DB: i32 = 127;
|
||||
#[cfg(test)]
|
||||
const INAUDIBLE_BUT_NOT_MUTED: i32 = 126;
|
||||
|
||||
#[cfg(test)]
|
||||
fn compute_rms(mean_square: f32) -> i32 {
|
||||
if mean_square <= MIN_LEVEL * MAX_SQUARED_LEVEL {
|
||||
return MIN_LEVEL_DB;
|
||||
}
|
||||
let mean_square_norm = mean_square / MAX_SQUARED_LEVEL;
|
||||
debug_assert!(mean_square_norm > MIN_LEVEL);
|
||||
let rms = 10.0 * mean_square_norm.log10();
|
||||
debug_assert!(rms <= 0.0);
|
||||
(-rms + 0.5) as i32
|
||||
}
|
||||
|
||||
/// Average and peak RMS levels.
|
||||
#[cfg(test)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Levels {
|
||||
pub(crate) average: i32,
|
||||
pub(crate) peak: i32,
|
||||
}
|
||||
|
||||
/// Computes RMS level in dBFS following RFC 6465.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RmsLevel {
|
||||
sum_square: f32,
|
||||
sample_count: usize,
|
||||
max_sum_square: f32,
|
||||
block_size: Option<usize>,
|
||||
}
|
||||
|
||||
impl RmsLevel {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
sum_square: 0.0,
|
||||
sample_count: 0,
|
||||
max_sum_square: 0.0,
|
||||
block_size: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.sum_square = 0.0;
|
||||
self.sample_count = 0;
|
||||
self.max_sum_square = 0.0;
|
||||
self.block_size = None;
|
||||
}
|
||||
|
||||
/// Analyze a block of i16 samples.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn analyze_i16(&mut self, data: &[i16]) {
|
||||
if data.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.check_block_size(data.len());
|
||||
|
||||
let sum_square: f32 = data.iter().map(|&s| (s as f32) * (s as f32)).sum();
|
||||
debug_assert!(sum_square >= 0.0);
|
||||
self.sum_square += sum_square;
|
||||
self.sample_count += data.len();
|
||||
self.max_sum_square = self.max_sum_square.max(sum_square);
|
||||
}
|
||||
|
||||
/// Analyze a block of float samples (FloatS16 range).
|
||||
pub(crate) fn analyze_float(&mut self, data: &[f32]) {
|
||||
if data.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.check_block_size(data.len());
|
||||
|
||||
let mut sum_square = 0.0f32;
|
||||
for &sample in data {
|
||||
let tmp = sample.clamp(-32768.0, 32767.0) as i16;
|
||||
sum_square += (tmp as f32) * (tmp as f32);
|
||||
}
|
||||
debug_assert!(sum_square >= 0.0);
|
||||
self.sum_square += sum_square;
|
||||
self.sample_count += data.len();
|
||||
self.max_sum_square = self.max_sum_square.max(sum_square);
|
||||
}
|
||||
|
||||
/// Record muted samples (all zeros).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn analyze_muted(&mut self, length: usize) {
|
||||
self.check_block_size(length);
|
||||
self.sample_count += length;
|
||||
}
|
||||
|
||||
/// Compute average RMS and reset.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn average(&mut self) -> i32 {
|
||||
let have_samples = self.sample_count != 0;
|
||||
let mut rms = if have_samples {
|
||||
compute_rms(self.sum_square / self.sample_count as f32)
|
||||
} else {
|
||||
MIN_LEVEL_DB
|
||||
};
|
||||
|
||||
if have_samples && rms == MIN_LEVEL_DB && self.sum_square != 0.0 {
|
||||
rms = INAUDIBLE_BUT_NOT_MUTED;
|
||||
}
|
||||
|
||||
self.reset();
|
||||
rms
|
||||
}
|
||||
|
||||
/// Compute average and peak RMS levels and reset.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn average_and_peak(&mut self) -> Levels {
|
||||
let levels = if self.sample_count == 0 {
|
||||
Levels {
|
||||
average: MIN_LEVEL_DB,
|
||||
peak: MIN_LEVEL_DB,
|
||||
}
|
||||
} else {
|
||||
let block_size = self
|
||||
.block_size
|
||||
.expect("block_size should be set when sample_count > 0");
|
||||
Levels {
|
||||
average: compute_rms(self.sum_square / self.sample_count as f32),
|
||||
peak: compute_rms(self.max_sum_square / block_size as f32),
|
||||
}
|
||||
};
|
||||
self.reset();
|
||||
levels
|
||||
}
|
||||
|
||||
fn check_block_size(&mut self, block_size: usize) {
|
||||
if self.block_size != Some(block_size) {
|
||||
self.reset();
|
||||
self.block_size = Some(block_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SAMPLE_RATE_HZ: usize = 48000;
|
||||
const BLOCK_SIZE_SAMPLES: usize = SAMPLE_RATE_HZ / 100;
|
||||
|
||||
fn run_test_i16(input: &[i16]) -> RmsLevel {
|
||||
let mut level = RmsLevel::new();
|
||||
let mut n = 0;
|
||||
while n + BLOCK_SIZE_SAMPLES <= input.len() {
|
||||
level.analyze_i16(&input[n..n + BLOCK_SIZE_SAMPLES]);
|
||||
n += BLOCK_SIZE_SAMPLES;
|
||||
}
|
||||
level
|
||||
}
|
||||
|
||||
fn run_test_float(input: &[f32]) -> RmsLevel {
|
||||
let mut level = RmsLevel::new();
|
||||
let mut n = 0;
|
||||
while n + BLOCK_SIZE_SAMPLES <= input.len() {
|
||||
level.analyze_float(&input[n..n + BLOCK_SIZE_SAMPLES]);
|
||||
n += BLOCK_SIZE_SAMPLES;
|
||||
}
|
||||
level
|
||||
}
|
||||
|
||||
fn create_i16_sinusoid(frequency_hz: i32, amplitude: i32, num_samples: usize) -> Vec<i16> {
|
||||
use std::f64::consts::PI;
|
||||
|
||||
(0..num_samples)
|
||||
.map(|n| {
|
||||
let val = amplitude as f64
|
||||
* (2.0 * PI * n as f64 * frequency_hz as f64 / SAMPLE_RATE_HZ as f64).sin();
|
||||
val.clamp(i16::MIN as f64, i16::MAX as f64) as i16
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn create_float_sinusoid(frequency_hz: i32, amplitude: i32, num_samples: usize) -> Vec<f32> {
|
||||
let x16 = create_i16_sinusoid(frequency_hz, amplitude, num_samples);
|
||||
x16.iter().map(|&s| s as f32).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_identity_between_float_and_fix() {
|
||||
let x_f = create_float_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let x_i = create_float_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level_f = run_test_float(&x_f);
|
||||
let mut level_i = run_test_float(&x_i);
|
||||
let avg_i = level_i.average();
|
||||
let avg_f = level_f.average();
|
||||
assert_eq!(3, avg_i);
|
||||
assert_eq!(avg_f, avg_i);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_1000hz_full_scale() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
assert_eq!(3, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_1000hz_full_scale_average_and_peak() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
let stats = level.average_and_peak();
|
||||
assert_eq!(3, stats.average);
|
||||
assert_eq!(3, stats.peak);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_1000hz_half_scale() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32 / 2, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
assert_eq!(9, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_zeros() {
|
||||
let x = vec![0i16; SAMPLE_RATE_HZ];
|
||||
let mut level = run_test_i16(&x);
|
||||
assert_eq!(127, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_zeros_average_and_peak() {
|
||||
let x = vec![0i16; SAMPLE_RATE_HZ];
|
||||
let mut level = run_test_i16(&x);
|
||||
let stats = level.average_and_peak();
|
||||
assert_eq!(127, stats.average);
|
||||
assert_eq!(127, stats.peak);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_samples() {
|
||||
let mut level = RmsLevel::new();
|
||||
assert_eq!(127, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_samples_average_and_peak() {
|
||||
let mut level = RmsLevel::new();
|
||||
let stats = level.average_and_peak();
|
||||
assert_eq!(127, stats.average);
|
||||
assert_eq!(127, stats.peak);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poll_twice() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
level.average();
|
||||
assert_eq!(127, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_test() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
level.reset();
|
||||
assert_eq!(127, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_muted() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
let blocks_per_second = SAMPLE_RATE_HZ / BLOCK_SIZE_SAMPLES;
|
||||
for _ in 0..blocks_per_second {
|
||||
level.analyze_muted(BLOCK_SIZE_SAMPLES);
|
||||
}
|
||||
assert_eq!(6, level.average());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_digital_silence_is_127() {
|
||||
let mut test_buffer = vec![0i16; SAMPLE_RATE_HZ];
|
||||
let mut level = run_test_i16(&test_buffer);
|
||||
assert_eq!(127, level.average());
|
||||
|
||||
test_buffer[0] = 1;
|
||||
level = run_test_i16(&test_buffer);
|
||||
assert!(level.average() < 127);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_half_scale_and_insert_full_scale() {
|
||||
let half_scale = create_i16_sinusoid(1000, i16::MAX as i32 / 2, SAMPLE_RATE_HZ);
|
||||
let full_scale = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ / 100);
|
||||
let mut x = half_scale.clone();
|
||||
x.extend_from_slice(&full_scale);
|
||||
x.extend_from_slice(&half_scale);
|
||||
assert_eq!(2 * SAMPLE_RATE_HZ + SAMPLE_RATE_HZ / 100, x.len());
|
||||
let mut level = run_test_i16(&x);
|
||||
let stats = level.average_and_peak();
|
||||
assert_eq!(9, stats.average);
|
||||
assert_eq!(3, stats.peak);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_on_block_size_change() {
|
||||
let x = create_i16_sinusoid(1000, i16::MAX as i32, SAMPLE_RATE_HZ);
|
||||
let mut level = run_test_i16(&x);
|
||||
let y = create_i16_sinusoid(1000, i16::MAX as i32 / 2, BLOCK_SIZE_SAMPLES * 2);
|
||||
level.analyze_i16(&y);
|
||||
let stats = level.average_and_peak();
|
||||
assert_eq!(9, stats.average);
|
||||
assert_eq!(9, stats.peak);
|
||||
}
|
||||
}
|
||||
+658
@@ -0,0 +1,658 @@
|
||||
//! Band-splitting filter for 2-band (32 kHz) and 3-band (48 kHz) operation.
|
||||
//!
|
||||
//! Splits a fullband audio frame into sub-band frames using QMF filter banks:
|
||||
//! - **2-band** (32 kHz → 2 × 160 samples): allpass-based QMF from SPL library
|
||||
//! - **3-band** (48 kHz → 3 × 160 samples): FIR filter bank with DCT modulation
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/splitting_filter.h/cc` and
|
||||
//! `common_audio/signal_processing/splitting_filter.c`.
|
||||
|
||||
use sonora_common_audio::channel_buffer::ChannelBuffer;
|
||||
|
||||
use crate::three_band_filter_bank::ThreeBandFilterBank;
|
||||
|
||||
const SAMPLES_PER_BAND: usize = 160;
|
||||
const TWO_BAND_FILTER_SAMPLES_PER_FRAME: usize = 320;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2-band QMF filter (ported from common_audio/signal_processing/splitting_filter.c)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ALL_PASS_FILTER_1: [f32; 3] = [0.097_930_91, 0.564_300_54, 0.873_733_5];
|
||||
const ALL_PASS_FILTER_2: [f32; 3] = [0.325_515_75, 0.748_626_7, 0.961_456_3];
|
||||
|
||||
/// State size for one allpass QMF filter chain (3 cascaded first-order sections,
|
||||
/// each needing 2 state values = 6 total).
|
||||
const QMF_STATE_SIZE: usize = 6;
|
||||
|
||||
/// Three cascaded first-order allpass sections.
|
||||
///
|
||||
/// Each section implements:
|
||||
/// y[n] = x[n-1] + a * (x[n] - y[n-1])
|
||||
///
|
||||
/// The three sections alternate between two scratch buffers to avoid allocation.
|
||||
fn allpass_qmf(
|
||||
in_data: &mut [f32; SAMPLES_PER_BAND],
|
||||
out_data: &mut [f32; SAMPLES_PER_BAND],
|
||||
coefficients: &[f32; 3],
|
||||
state: &mut [f32; QMF_STATE_SIZE],
|
||||
) {
|
||||
let data_length = SAMPLES_PER_BAND;
|
||||
|
||||
// First cascade: in_data → out_data
|
||||
let diff = in_data[0] - state[1];
|
||||
out_data[0] = state[0] + coefficients[0] * diff;
|
||||
for k in 1..data_length {
|
||||
let diff = in_data[k] - out_data[k - 1];
|
||||
out_data[k] = in_data[k - 1] + coefficients[0] * diff;
|
||||
}
|
||||
state[0] = in_data[data_length - 1];
|
||||
state[1] = out_data[data_length - 1];
|
||||
|
||||
// Second cascade: out_data → in_data
|
||||
let diff = out_data[0] - state[3];
|
||||
in_data[0] = state[2] + coefficients[1] * diff;
|
||||
for k in 1..data_length {
|
||||
let diff = out_data[k] - in_data[k - 1];
|
||||
in_data[k] = out_data[k - 1] + coefficients[1] * diff;
|
||||
}
|
||||
state[2] = out_data[data_length - 1];
|
||||
state[3] = in_data[data_length - 1];
|
||||
|
||||
// Third cascade: in_data → out_data
|
||||
let diff = in_data[0] - state[5];
|
||||
out_data[0] = state[4] + coefficients[2] * diff;
|
||||
for k in 1..data_length {
|
||||
let diff = in_data[k] - out_data[k - 1];
|
||||
out_data[k] = in_data[k - 1] + coefficients[2] * diff;
|
||||
}
|
||||
state[4] = in_data[data_length - 1];
|
||||
state[5] = out_data[data_length - 1];
|
||||
}
|
||||
|
||||
/// Split a fullband signal into low-band and high-band using QMF analysis.
|
||||
fn analysis_qmf(
|
||||
in_data: &[f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME],
|
||||
low_band: &mut [f32; SAMPLES_PER_BAND],
|
||||
high_band: &mut [f32; SAMPLES_PER_BAND],
|
||||
filter_state1: &mut [f32; QMF_STATE_SIZE],
|
||||
filter_state2: &mut [f32; QMF_STATE_SIZE],
|
||||
) {
|
||||
// Split even and odd samples (stack arrays, matching C++).
|
||||
let mut half_in1 = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut half_in2 = [0.0f32; SAMPLES_PER_BAND];
|
||||
for i in 0..SAMPLES_PER_BAND {
|
||||
half_in2[i] = in_data[2 * i];
|
||||
half_in1[i] = in_data[2 * i + 1];
|
||||
}
|
||||
|
||||
// Allpass filter even and odd samples independently.
|
||||
let mut filter1 = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut filter2 = [0.0f32; SAMPLES_PER_BAND];
|
||||
allpass_qmf(
|
||||
&mut half_in1,
|
||||
&mut filter1,
|
||||
&ALL_PASS_FILTER_1,
|
||||
filter_state1,
|
||||
);
|
||||
allpass_qmf(
|
||||
&mut half_in2,
|
||||
&mut filter2,
|
||||
&ALL_PASS_FILTER_2,
|
||||
filter_state2,
|
||||
);
|
||||
|
||||
// Sum and difference to get low and high bands.
|
||||
for i in 0..SAMPLES_PER_BAND {
|
||||
low_band[i] = (filter1[i] + filter2[i]) * 0.5;
|
||||
high_band[i] = (filter1[i] - filter2[i]) * 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge low-band and high-band into a fullband signal using QMF synthesis.
|
||||
fn synthesis_qmf(
|
||||
low_band: &[f32; SAMPLES_PER_BAND],
|
||||
high_band: &[f32; SAMPLES_PER_BAND],
|
||||
out_data: &mut [f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME],
|
||||
filter_state1: &mut [f32; QMF_STATE_SIZE],
|
||||
filter_state2: &mut [f32; QMF_STATE_SIZE],
|
||||
) {
|
||||
// Sum and difference channels (stack arrays, matching C++).
|
||||
let mut half_in1 = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut half_in2 = [0.0f32; SAMPLES_PER_BAND];
|
||||
for i in 0..SAMPLES_PER_BAND {
|
||||
half_in1[i] = low_band[i] + high_band[i];
|
||||
half_in2[i] = low_band[i] - high_band[i];
|
||||
}
|
||||
|
||||
// Allpass filter.
|
||||
let mut filter1 = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut filter2 = [0.0f32; SAMPLES_PER_BAND];
|
||||
allpass_qmf(
|
||||
&mut half_in1,
|
||||
&mut filter1,
|
||||
&ALL_PASS_FILTER_2,
|
||||
filter_state1,
|
||||
);
|
||||
allpass_qmf(
|
||||
&mut half_in2,
|
||||
&mut filter2,
|
||||
&ALL_PASS_FILTER_1,
|
||||
filter_state2,
|
||||
);
|
||||
|
||||
// Interleave with saturation (matching C++ int16 range clamp).
|
||||
for i in 0..SAMPLES_PER_BAND {
|
||||
out_data[2 * i] = filter2[i].clamp(-32768.0, 32767.0);
|
||||
out_data[2 * i + 1] = filter1[i].clamp(-32768.0, 32767.0);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TwoBandsStates
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TwoBandsStates {
|
||||
analysis_state1: [f32; QMF_STATE_SIZE],
|
||||
analysis_state2: [f32; QMF_STATE_SIZE],
|
||||
synthesis_state1: [f32; QMF_STATE_SIZE],
|
||||
synthesis_state2: [f32; QMF_STATE_SIZE],
|
||||
}
|
||||
|
||||
impl TwoBandsStates {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
analysis_state1: [0.0; QMF_STATE_SIZE],
|
||||
analysis_state2: [0.0; QMF_STATE_SIZE],
|
||||
synthesis_state1: [0.0; QMF_STATE_SIZE],
|
||||
synthesis_state2: [0.0; QMF_STATE_SIZE],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SplittingFilter
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug)]
|
||||
enum FilterState {
|
||||
TwoBand(Vec<TwoBandsStates>),
|
||||
ThreeBand(Vec<ThreeBandFilterBank>),
|
||||
}
|
||||
|
||||
/// Band-splitting filter supporting 2-band and 3-band operation.
|
||||
///
|
||||
/// For each block, call [`analysis`] to split into bands, then [`synthesis`]
|
||||
/// to merge them back.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SplittingFilter {
|
||||
num_bands: usize,
|
||||
state: FilterState,
|
||||
}
|
||||
|
||||
impl SplittingFilter {
|
||||
/// Create a new splitting filter.
|
||||
///
|
||||
/// - `num_channels`: number of audio channels
|
||||
/// - `num_bands`: 2 (for 32 kHz) or 3 (for 48 kHz)
|
||||
pub(crate) fn new(num_channels: usize, num_bands: usize) -> Self {
|
||||
assert!(num_bands == 2 || num_bands == 3, "num_bands must be 2 or 3");
|
||||
let state = match num_bands {
|
||||
2 => FilterState::TwoBand((0..num_channels).map(|_| TwoBandsStates::new()).collect()),
|
||||
3 => FilterState::ThreeBand(
|
||||
(0..num_channels)
|
||||
.map(|_| ThreeBandFilterBank::new())
|
||||
.collect(),
|
||||
),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
Self { num_bands, state }
|
||||
}
|
||||
|
||||
/// Split fullband data into sub-bands.
|
||||
pub(crate) fn analysis(&mut self, data: &ChannelBuffer<f32>, bands: &mut ChannelBuffer<f32>) {
|
||||
debug_assert_eq!(self.num_bands, bands.num_bands());
|
||||
debug_assert_eq!(data.num_channels(), bands.num_channels());
|
||||
debug_assert_eq!(
|
||||
data.num_frames(),
|
||||
bands.num_frames_per_band() * bands.num_bands()
|
||||
);
|
||||
match &mut self.state {
|
||||
FilterState::TwoBand(states) => {
|
||||
Self::two_bands_analysis(states, data, bands);
|
||||
}
|
||||
FilterState::ThreeBand(banks) => {
|
||||
Self::three_bands_analysis(banks, data, bands);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge sub-bands back into fullband data.
|
||||
pub(crate) fn synthesis(&mut self, bands: &ChannelBuffer<f32>, data: &mut ChannelBuffer<f32>) {
|
||||
debug_assert_eq!(self.num_bands, bands.num_bands());
|
||||
debug_assert_eq!(data.num_channels(), bands.num_channels());
|
||||
debug_assert_eq!(
|
||||
data.num_frames(),
|
||||
bands.num_frames_per_band() * bands.num_bands()
|
||||
);
|
||||
match &mut self.state {
|
||||
FilterState::TwoBand(states) => {
|
||||
Self::two_bands_synthesis(states, bands, data);
|
||||
}
|
||||
FilterState::ThreeBand(banks) => {
|
||||
Self::three_bands_synthesis(banks, bands, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn two_bands_analysis(
|
||||
states: &mut [TwoBandsStates],
|
||||
data: &ChannelBuffer<f32>,
|
||||
bands: &mut ChannelBuffer<f32>,
|
||||
) {
|
||||
debug_assert_eq!(states.len(), data.num_channels());
|
||||
debug_assert_eq!(data.num_frames(), TWO_BAND_FILTER_SAMPLES_PER_FRAME);
|
||||
|
||||
for (i, state) in states.iter_mut().enumerate() {
|
||||
let mut low_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut high_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
|
||||
// C++ uses channels(0)[i] with num_frames() length, which reads
|
||||
// the full channel data across all bands (320 samples).
|
||||
let in_data: &[f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME] =
|
||||
data.bands(i).try_into().unwrap();
|
||||
analysis_qmf(
|
||||
in_data,
|
||||
&mut low_band,
|
||||
&mut high_band,
|
||||
&mut state.analysis_state1,
|
||||
&mut state.analysis_state2,
|
||||
);
|
||||
|
||||
bands.channel_mut(0, i).copy_from_slice(&low_band);
|
||||
bands.channel_mut(1, i).copy_from_slice(&high_band);
|
||||
}
|
||||
}
|
||||
|
||||
fn two_bands_synthesis(
|
||||
states: &mut [TwoBandsStates],
|
||||
bands: &ChannelBuffer<f32>,
|
||||
data: &mut ChannelBuffer<f32>,
|
||||
) {
|
||||
debug_assert!(data.num_channels() <= states.len());
|
||||
debug_assert_eq!(data.num_frames(), TWO_BAND_FILTER_SAMPLES_PER_FRAME);
|
||||
|
||||
for (i, state) in states.iter_mut().enumerate().take(data.num_channels()) {
|
||||
let mut low_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut high_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
low_band.copy_from_slice(bands.channel(0, i));
|
||||
high_band.copy_from_slice(bands.channel(1, i));
|
||||
|
||||
// C++ writes to channels(0)[i] with full num_frames() length.
|
||||
let out_data: &mut [f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME] =
|
||||
data.bands_mut(i).try_into().unwrap();
|
||||
synthesis_qmf(
|
||||
&low_band,
|
||||
&high_band,
|
||||
out_data,
|
||||
&mut state.synthesis_state1,
|
||||
&mut state.synthesis_state2,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn three_bands_analysis(
|
||||
banks: &mut [ThreeBandFilterBank],
|
||||
data: &ChannelBuffer<f32>,
|
||||
bands: &mut ChannelBuffer<f32>,
|
||||
) {
|
||||
use crate::three_band_filter_bank::{FULL_BAND_SIZE, NUM_BANDS, SPLIT_BAND_SIZE};
|
||||
debug_assert_eq!(banks.len(), data.num_channels());
|
||||
debug_assert_eq!(data.num_frames(), FULL_BAND_SIZE);
|
||||
debug_assert_eq!(bands.num_frames(), FULL_BAND_SIZE);
|
||||
debug_assert_eq!(bands.num_bands(), NUM_BANDS);
|
||||
debug_assert_eq!(bands.num_frames_per_band(), SPLIT_BAND_SIZE);
|
||||
|
||||
for (i, bank) in banks.iter_mut().enumerate() {
|
||||
// C++ uses channels_view()[i] which gives the full 480 samples.
|
||||
let input: &[f32; FULL_BAND_SIZE] = data.bands(i).try_into().unwrap();
|
||||
let mut output = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
bank.analysis(input, &mut output);
|
||||
for (band, out) in output.iter().enumerate() {
|
||||
bands.channel_mut(band, i).copy_from_slice(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn three_bands_synthesis(
|
||||
banks: &mut [ThreeBandFilterBank],
|
||||
bands: &ChannelBuffer<f32>,
|
||||
data: &mut ChannelBuffer<f32>,
|
||||
) {
|
||||
use crate::three_band_filter_bank::{FULL_BAND_SIZE, NUM_BANDS, SPLIT_BAND_SIZE};
|
||||
debug_assert!(data.num_channels() <= banks.len());
|
||||
debug_assert_eq!(data.num_frames(), FULL_BAND_SIZE);
|
||||
debug_assert_eq!(bands.num_frames(), FULL_BAND_SIZE);
|
||||
debug_assert_eq!(bands.num_bands(), NUM_BANDS);
|
||||
debug_assert_eq!(bands.num_frames_per_band(), SPLIT_BAND_SIZE);
|
||||
|
||||
for (i, bank) in banks.iter_mut().enumerate().take(data.num_channels()) {
|
||||
let mut input = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
for (band, inp) in input.iter_mut().enumerate() {
|
||||
inp.copy_from_slice(bands.channel(band, i));
|
||||
}
|
||||
let output: &mut [f32; FULL_BAND_SIZE] = data.bands_mut(i).try_into().unwrap();
|
||||
bank.synthesis(&input, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::f32::consts::PI;
|
||||
|
||||
use super::*;
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// QMF filter unit tests
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qmf_analysis_splits_signal() {
|
||||
let mut state1 = [0.0f32; QMF_STATE_SIZE];
|
||||
let mut state2 = [0.0f32; QMF_STATE_SIZE];
|
||||
|
||||
// Generate a low-frequency sine (500 Hz at 32 kHz = well within low band).
|
||||
let mut input = [0.0f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME];
|
||||
for (i, sample) in input.iter_mut().enumerate() {
|
||||
*sample = (2.0 * PI * 500.0 * i as f32 / 32000.0).sin();
|
||||
}
|
||||
|
||||
let mut low_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut high_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
|
||||
analysis_qmf(
|
||||
&input,
|
||||
&mut low_band,
|
||||
&mut high_band,
|
||||
&mut state1,
|
||||
&mut state2,
|
||||
);
|
||||
|
||||
let low_energy: f32 = low_band.iter().map(|x| x * x).sum();
|
||||
let high_energy: f32 = high_band.iter().map(|x| x * x).sum();
|
||||
|
||||
// Low-frequency signal should appear mostly in low band.
|
||||
assert!(
|
||||
low_energy > high_energy * 10.0,
|
||||
"low_energy={low_energy}, high_energy={high_energy}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qmf_synthesis_reconstructs() {
|
||||
let mut a_state1 = [0.0f32; QMF_STATE_SIZE];
|
||||
let mut a_state2 = [0.0f32; QMF_STATE_SIZE];
|
||||
let mut s_state1 = [0.0f32; QMF_STATE_SIZE];
|
||||
let mut s_state2 = [0.0f32; QMF_STATE_SIZE];
|
||||
|
||||
// Process multiple frames to let filter settle.
|
||||
let num_frames = 10;
|
||||
let mut last_input = [0.0f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME];
|
||||
let mut last_output = [0.0f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME];
|
||||
|
||||
for frame in 0..num_frames {
|
||||
let mut input = [0.0f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME];
|
||||
for (i, sample) in input.iter_mut().enumerate() {
|
||||
let t = (frame * TWO_BAND_FILTER_SAMPLES_PER_FRAME + i) as f32 / 32000.0;
|
||||
*sample = (2.0 * PI * 1000.0 * t).sin() * 1000.0;
|
||||
}
|
||||
|
||||
let mut low_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
let mut high_band = [0.0f32; SAMPLES_PER_BAND];
|
||||
analysis_qmf(
|
||||
&input,
|
||||
&mut low_band,
|
||||
&mut high_band,
|
||||
&mut a_state1,
|
||||
&mut a_state2,
|
||||
);
|
||||
|
||||
let mut output = [0.0f32; TWO_BAND_FILTER_SAMPLES_PER_FRAME];
|
||||
synthesis_qmf(
|
||||
&low_band,
|
||||
&high_band,
|
||||
&mut output,
|
||||
&mut s_state1,
|
||||
&mut s_state2,
|
||||
);
|
||||
|
||||
last_input = input;
|
||||
last_output = output;
|
||||
}
|
||||
|
||||
// After settling, output should have significant energy relative to input.
|
||||
let input_energy: f32 = last_input.iter().map(|x| x * x).sum();
|
||||
let output_energy: f32 = last_output.iter().map(|x| x * x).sum();
|
||||
assert!(
|
||||
output_energy > input_energy * 0.5,
|
||||
"roundtrip should preserve energy: input={input_energy}, output={output_energy}",
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// SplittingFilter — 3-band test (matches C++ upstream test)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn splits_into_three_bands_and_reconstructs() {
|
||||
let channels = 1;
|
||||
let sample_rate_hz = 48000;
|
||||
let num_bands = 3;
|
||||
let frequencies_hz = [1000, 12000, 18000];
|
||||
let amplitude = 8192.0f32;
|
||||
let chunks = 8;
|
||||
let samples_per_48khz_channel = 480;
|
||||
let samples_per_16khz_channel = 160;
|
||||
|
||||
let mut splitting_filter = SplittingFilter::new(channels, num_bands);
|
||||
let mut in_data = ChannelBuffer::<f32>::new(samples_per_48khz_channel, channels, num_bands);
|
||||
let mut bands = ChannelBuffer::<f32>::new(samples_per_48khz_channel, channels, num_bands);
|
||||
let mut out_data =
|
||||
ChannelBuffer::<f32>::new(samples_per_48khz_channel, channels, num_bands);
|
||||
|
||||
for i in 0..chunks {
|
||||
// Input signal generation.
|
||||
let mut is_present = [false; 3];
|
||||
// Zero the input channel (C++ uses channels()[0] = full channel).
|
||||
for s in in_data.bands_mut(0).iter_mut() {
|
||||
*s = 0.0;
|
||||
}
|
||||
for (j, &freq) in frequencies_hz.iter().enumerate() {
|
||||
is_present[j] = (i & (1 << j)) != 0;
|
||||
let amp = if is_present[j] { amplitude } else { 0.0 };
|
||||
let mut addition = vec![0.0f32; samples_per_48khz_channel];
|
||||
for (k, a) in addition.iter_mut().enumerate() {
|
||||
*a = amp
|
||||
* (2.0 * PI * freq as f32 * (i * samples_per_48khz_channel + k) as f32
|
||||
/ sample_rate_hz as f32)
|
||||
.sin();
|
||||
}
|
||||
let ch = in_data.bands_mut(0);
|
||||
for (c, a) in ch.iter_mut().zip(addition.iter()) {
|
||||
*c += a;
|
||||
}
|
||||
}
|
||||
|
||||
// Three-band splitting filter.
|
||||
splitting_filter.analysis(&in_data, &mut bands);
|
||||
|
||||
// Energy calculation.
|
||||
for (j, &present) in is_present.iter().enumerate().take(num_bands) {
|
||||
let mut energy = 0.0f32;
|
||||
let band_data = bands.channel(j, 0);
|
||||
for s in &band_data[..samples_per_16khz_channel] {
|
||||
energy += s * s;
|
||||
}
|
||||
energy /= samples_per_16khz_channel as f32;
|
||||
if present {
|
||||
assert!(
|
||||
energy > amplitude * amplitude / 4.0,
|
||||
"chunk {i}, band {j}: expected present, energy={energy}",
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
energy < amplitude * amplitude / 4.0,
|
||||
"chunk {i}, band {j}: expected absent, energy={energy}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Three-band merge.
|
||||
splitting_filter.synthesis(&bands, &mut out_data);
|
||||
|
||||
// Delay and cross correlation estimation.
|
||||
let mut xcorr = 0.0f32;
|
||||
let in_ch = in_data.bands(0);
|
||||
let out_ch = out_data.bands(0);
|
||||
for delay in 0..samples_per_48khz_channel {
|
||||
let mut tmpcorr = 0.0f32;
|
||||
for j in delay..samples_per_48khz_channel {
|
||||
tmpcorr += in_ch[j - delay] * out_ch[j];
|
||||
}
|
||||
tmpcorr /= samples_per_48khz_channel as f32;
|
||||
if tmpcorr > xcorr {
|
||||
xcorr = tmpcorr;
|
||||
}
|
||||
}
|
||||
|
||||
// High cross correlation check.
|
||||
let any_present = is_present.iter().any(|&p| p);
|
||||
if any_present {
|
||||
assert!(
|
||||
xcorr > amplitude * amplitude / 4.0,
|
||||
"chunk {i}: cross-correlation too low: {xcorr}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// SplittingFilter — 2-band test
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn two_band_analysis_and_synthesis() {
|
||||
let channels = 1;
|
||||
let num_bands = 2;
|
||||
let num_frames = 320;
|
||||
let chunks = 10;
|
||||
let amplitude = 4096.0f32;
|
||||
|
||||
let mut splitting_filter = SplittingFilter::new(channels, num_bands);
|
||||
|
||||
for chunk in 0..chunks {
|
||||
let mut in_data = ChannelBuffer::<f32>::new(num_frames, channels, num_bands);
|
||||
let mut bands = ChannelBuffer::<f32>::new(num_frames, channels, num_bands);
|
||||
let mut out_data = ChannelBuffer::<f32>::new(num_frames, channels, num_bands);
|
||||
|
||||
// Generate a low-frequency sine (500 Hz at 32 kHz).
|
||||
let ch = in_data.bands_mut(0);
|
||||
for (k, sample) in ch.iter_mut().enumerate().take(num_frames) {
|
||||
let t = (chunk * num_frames + k) as f32 / 32000.0;
|
||||
*sample = amplitude * (2.0 * PI * 500.0 * t).sin();
|
||||
}
|
||||
|
||||
splitting_filter.analysis(&in_data, &mut bands);
|
||||
|
||||
// Low-frequency signal should be mostly in band 0.
|
||||
let low_energy: f32 = bands.channel(0, 0).iter().map(|x| x * x).sum();
|
||||
let high_energy: f32 = bands.channel(1, 0).iter().map(|x| x * x).sum();
|
||||
if chunk >= 2 {
|
||||
assert!(
|
||||
low_energy > high_energy * 5.0,
|
||||
"chunk {chunk}: low={low_energy}, high={high_energy}",
|
||||
);
|
||||
}
|
||||
|
||||
splitting_filter.synthesis(&bands, &mut out_data);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_band_zero_input() {
|
||||
let mut filter = SplittingFilter::new(1, 2);
|
||||
let in_data = ChannelBuffer::<f32>::new(320, 1, 2);
|
||||
let mut bands = ChannelBuffer::<f32>::new(320, 1, 2);
|
||||
|
||||
filter.analysis(&in_data, &mut bands);
|
||||
|
||||
for &s in bands.data() {
|
||||
assert_eq!(s, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_band_zero_input() {
|
||||
let mut filter = SplittingFilter::new(1, 3);
|
||||
let in_data = ChannelBuffer::<f32>::new(480, 1, 3);
|
||||
let mut bands = ChannelBuffer::<f32>::new(480, 1, 3);
|
||||
|
||||
filter.analysis(&in_data, &mut bands);
|
||||
|
||||
for &s in bands.data() {
|
||||
assert_eq!(s, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_channel_two_band() {
|
||||
let channels = 4;
|
||||
let mut filter = SplittingFilter::new(channels, 2);
|
||||
let mut in_data = ChannelBuffer::<f32>::new(320, channels, 2);
|
||||
let mut bands = ChannelBuffer::<f32>::new(320, channels, 2);
|
||||
|
||||
// Put different signals in each channel.
|
||||
for ch in 0..channels {
|
||||
let data = in_data.bands_mut(ch);
|
||||
for (k, d) in data.iter_mut().enumerate().take(320) {
|
||||
*d = (ch as f32 + 1.0) * (k as f32 / 320.0);
|
||||
}
|
||||
}
|
||||
|
||||
filter.analysis(&in_data, &mut bands);
|
||||
|
||||
// Each channel should have non-zero output.
|
||||
for ch in 0..channels {
|
||||
let energy: f32 = bands.channel(0, ch).iter().map(|x| x * x).sum();
|
||||
assert!(energy > 0.0, "channel {ch} should have non-zero output");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_channel_three_band() {
|
||||
let channels = 2;
|
||||
let mut filter = SplittingFilter::new(channels, 3);
|
||||
let mut in_data = ChannelBuffer::<f32>::new(480, channels, 3);
|
||||
let mut bands = ChannelBuffer::<f32>::new(480, channels, 3);
|
||||
|
||||
// Put different signals in each channel.
|
||||
for ch in 0..channels {
|
||||
let data = in_data.bands_mut(ch);
|
||||
for (k, d) in data.iter_mut().enumerate().take(480) {
|
||||
*d = (ch as f32 + 1.0) * (2.0 * PI * 1000.0 * k as f32 / 48000.0).sin();
|
||||
}
|
||||
}
|
||||
|
||||
filter.analysis(&in_data, &mut bands);
|
||||
|
||||
for ch in 0..channels {
|
||||
let energy: f32 = bands.channel(0, ch).iter().map(|x| x * x).sum();
|
||||
assert!(
|
||||
energy > 0.0,
|
||||
"channel {ch} band 0 should have non-zero output"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
//! Audio processing statistics.
|
||||
//!
|
||||
//! Ported from `AudioProcessingStats` in
|
||||
//! `api/audio/audio_processing_statistics.h`.
|
||||
|
||||
/// Statistics from the audio processing pipeline.
|
||||
///
|
||||
/// All fields are `Option` — `None` indicates the statistic is unavailable
|
||||
/// (e.g. because the relevant component is disabled).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct AudioProcessingStats {
|
||||
/// Echo Return Loss in dB: `ERL = 10 log10(P_far / P_echo)`.
|
||||
pub echo_return_loss: Option<f64>,
|
||||
/// Echo Return Loss Enhancement in dB: `ERLE = 10 log10(P_echo / P_out)`.
|
||||
pub echo_return_loss_enhancement: Option<f64>,
|
||||
/// Fraction of time that the AEC linear filter is divergent, in a 1-second
|
||||
/// non-overlapping aggregation window.
|
||||
pub divergent_filter_fraction: Option<f64>,
|
||||
/// Median delay estimate in milliseconds.
|
||||
///
|
||||
/// The delay metrics are aggregated until the first call to
|
||||
/// [`AudioProcessing::statistics()`](crate::AudioProcessing::statistics)
|
||||
/// and afterwards aggregated and updated every second.
|
||||
pub delay_median_ms: Option<i32>,
|
||||
/// Standard deviation of the delay estimate in milliseconds.
|
||||
///
|
||||
/// Uses the same aggregation window as [`delay_median_ms`](Self::delay_median_ms).
|
||||
pub delay_standard_deviation_ms: Option<i32>,
|
||||
/// Residual echo detector likelihood in `[0.0, 1.0]`.
|
||||
pub residual_echo_likelihood: Option<f64>,
|
||||
/// Maximum residual echo likelihood from the last time period.
|
||||
pub residual_echo_likelihood_recent_max: Option<f64>,
|
||||
/// Instantaneous delay estimate from the AEC in milliseconds.
|
||||
///
|
||||
/// This is the value at the time of the call to
|
||||
/// [`AudioProcessing::statistics()`](crate::AudioProcessing::statistics),
|
||||
/// not an aggregated value.
|
||||
pub delay_ms: Option<i32>,
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
//! Stream configuration for audio processing.
|
||||
//!
|
||||
//! Ported from `api/audio/audio_processing.h` (StreamConfig class).
|
||||
|
||||
/// Configuration describing an audio stream's properties.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StreamConfig {
|
||||
sample_rate_hz: u32,
|
||||
num_channels: u16,
|
||||
}
|
||||
|
||||
impl StreamConfig {
|
||||
/// Create a new stream configuration.
|
||||
pub const fn new(sample_rate_hz: u32, num_channels: u16) -> Self {
|
||||
Self {
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampling rate in Hz.
|
||||
#[inline]
|
||||
pub fn sample_rate_hz(&self) -> u32 {
|
||||
self.sample_rate_hz
|
||||
}
|
||||
|
||||
/// The number of channels.
|
||||
#[inline]
|
||||
pub fn num_channels(&self) -> u16 {
|
||||
self.num_channels
|
||||
}
|
||||
|
||||
/// The number of frames per 10ms chunk.
|
||||
#[inline]
|
||||
pub fn num_frames(&self) -> usize {
|
||||
self.sample_rate_hz as usize / 100
|
||||
}
|
||||
|
||||
/// Total number of samples (channels × frames).
|
||||
#[inline]
|
||||
pub fn num_samples(&self) -> usize {
|
||||
self.num_channels as usize * self.num_frames()
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
//! Submodule state tracking for the audio processing pipeline.
|
||||
//!
|
||||
//! Ported from `AudioProcessingImpl::SubmoduleStates` in
|
||||
//! `modules/audio_processing/audio_processing_impl.h/cc`.
|
||||
//!
|
||||
//! Tracks which submodules are active and detects state changes that
|
||||
//! require reinitialization.
|
||||
|
||||
/// Tracks the enabled/disabled state of each audio processing submodule.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SubmoduleStates {
|
||||
high_pass_filter_enabled: bool,
|
||||
noise_suppressor_enabled: bool,
|
||||
gain_controller2_enabled: bool,
|
||||
gain_adjustment_enabled: bool,
|
||||
echo_controller_enabled: bool,
|
||||
first_update: bool,
|
||||
}
|
||||
|
||||
impl SubmoduleStates {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
high_pass_filter_enabled: false,
|
||||
noise_suppressor_enabled: false,
|
||||
gain_controller2_enabled: false,
|
||||
gain_adjustment_enabled: false,
|
||||
echo_controller_enabled: false,
|
||||
first_update: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the submodule state and returns `true` if it has changed.
|
||||
pub(crate) fn update(
|
||||
&mut self,
|
||||
high_pass_filter_enabled: bool,
|
||||
noise_suppressor_enabled: bool,
|
||||
gain_controller2_enabled: bool,
|
||||
gain_adjustment_enabled: bool,
|
||||
echo_controller_enabled: bool,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
changed |= high_pass_filter_enabled != self.high_pass_filter_enabled;
|
||||
changed |= noise_suppressor_enabled != self.noise_suppressor_enabled;
|
||||
changed |= gain_controller2_enabled != self.gain_controller2_enabled;
|
||||
changed |= gain_adjustment_enabled != self.gain_adjustment_enabled;
|
||||
changed |= echo_controller_enabled != self.echo_controller_enabled;
|
||||
|
||||
if changed {
|
||||
self.high_pass_filter_enabled = high_pass_filter_enabled;
|
||||
self.noise_suppressor_enabled = noise_suppressor_enabled;
|
||||
self.gain_controller2_enabled = gain_controller2_enabled;
|
||||
self.gain_adjustment_enabled = gain_adjustment_enabled;
|
||||
self.echo_controller_enabled = echo_controller_enabled;
|
||||
}
|
||||
|
||||
changed |= self.first_update;
|
||||
self.first_update = false;
|
||||
changed
|
||||
}
|
||||
|
||||
/// Returns whether any capture multi-band processing submodules are active.
|
||||
pub(crate) fn capture_multi_band_sub_modules_active(&self) -> bool {
|
||||
self.capture_multi_band_processing_present()
|
||||
}
|
||||
|
||||
/// Returns whether capture multi-band processing is present.
|
||||
pub(crate) fn capture_multi_band_processing_present(&self) -> bool {
|
||||
self.capture_multi_band_processing_active(true)
|
||||
}
|
||||
|
||||
/// Returns whether capture multi-band processing is active.
|
||||
pub(crate) fn capture_multi_band_processing_active(&self, ec_processing_active: bool) -> bool {
|
||||
self.high_pass_filter_enabled
|
||||
|| self.noise_suppressor_enabled
|
||||
|| (self.echo_controller_enabled && ec_processing_active)
|
||||
}
|
||||
|
||||
/// Returns whether capture full-band processing is active.
|
||||
pub(crate) fn capture_full_band_processing_active(&self) -> bool {
|
||||
self.gain_controller2_enabled || self.gain_adjustment_enabled
|
||||
}
|
||||
|
||||
/// Returns whether render multi-band submodules are active.
|
||||
pub(crate) fn render_multi_band_sub_modules_active(&self) -> bool {
|
||||
self.echo_controller_enabled
|
||||
}
|
||||
|
||||
/// Returns whether render output was modified by processing.
|
||||
/// Always false: the Rust port does not include render pre-processors.
|
||||
pub(crate) fn render_output_modified(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Returns whether high-pass filtering is required.
|
||||
pub(crate) fn high_pass_filtering_required(&self) -> bool {
|
||||
self.high_pass_filter_enabled || self.noise_suppressor_enabled
|
||||
}
|
||||
|
||||
/// Returns whether the echo controller is enabled.
|
||||
pub(crate) fn echo_controller_enabled(&self) -> bool {
|
||||
self.echo_controller_enabled
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn first_update_always_returns_changed() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
assert!(states.update(false, false, false, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_update_no_change() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
states.update(false, false, false, false, false);
|
||||
assert!(!states.update(false, false, false, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_module_returns_changed() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
states.update(false, false, false, false, false);
|
||||
assert!(states.update(true, false, false, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_multi_band_with_hpf() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
states.update(true, false, false, false, false);
|
||||
assert!(states.capture_multi_band_processing_active(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_multi_band_with_echo_controller_inactive() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
states.update(false, false, false, false, true);
|
||||
assert!(!states.capture_multi_band_processing_active(false));
|
||||
assert!(states.capture_multi_band_processing_active(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_pass_filtering_required() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
states.update(false, true, false, false, false);
|
||||
assert!(states.high_pass_filtering_required());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_multi_band_with_echo_controller() {
|
||||
let mut states = SubmoduleStates::new();
|
||||
states.update(false, false, false, false, true);
|
||||
assert!(states.render_multi_band_sub_modules_active());
|
||||
}
|
||||
}
|
||||
Vendored
+263
@@ -0,0 +1,263 @@
|
||||
//! Single-threaded swap queue.
|
||||
//!
|
||||
//! A fixed-size queue where elements are moved via `std::mem::swap` rather
|
||||
//! than copy, avoiding allocations in the hot path.
|
||||
//!
|
||||
//! Ported from `rtc_base/swap_queue.h`.
|
||||
|
||||
use std::mem;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// A fixed-size, single-threaded swap queue.
|
||||
///
|
||||
/// Elements are moved via swap rather than copy. All methods take `&mut self`,
|
||||
/// so concurrent access is prevented at compile time.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SwapQueue<T> {
|
||||
queue: Vec<T>,
|
||||
next_write_index: usize,
|
||||
next_read_index: usize,
|
||||
num_elements: AtomicUsize,
|
||||
}
|
||||
|
||||
impl<T: Default> SwapQueue<T> {
|
||||
/// Creates a queue of the given size filled with default-constructed Ts.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(size: usize) -> Self {
|
||||
let mut queue = Vec::with_capacity(size);
|
||||
for _ in 0..size {
|
||||
queue.push(T::default());
|
||||
}
|
||||
Self {
|
||||
queue,
|
||||
next_write_index: 0,
|
||||
next_read_index: 0,
|
||||
num_elements: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SwapQueue<T> {
|
||||
/// Creates a queue of the given size filled with copies of `prototype`.
|
||||
pub(crate) fn with_prototype(size: usize, prototype: T) -> Self
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
Self {
|
||||
queue: vec![prototype; size],
|
||||
next_write_index: 0,
|
||||
next_read_index: 0,
|
||||
num_elements: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the queue to have zero content while maintaining the queue size.
|
||||
/// Only safe to call from the consumer side.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
let old = self.num_elements.swap(0, Ordering::Relaxed);
|
||||
self.next_read_index += old;
|
||||
if self.next_read_index >= self.queue.len() {
|
||||
self.next_read_index -= self.queue.len();
|
||||
}
|
||||
debug_assert!(self.next_read_index < self.queue.len());
|
||||
}
|
||||
|
||||
/// Inserts a "full" T at the back of the queue by swapping `*input` with
|
||||
/// an "empty" T from the queue.
|
||||
///
|
||||
/// Returns `true` if the item was inserted, `false` if the queue was full.
|
||||
pub(crate) fn insert(&mut self, input: &mut T) -> bool {
|
||||
if self.num_elements.load(Ordering::Acquire) == self.queue.len() {
|
||||
return false;
|
||||
}
|
||||
|
||||
mem::swap(input, &mut self.queue[self.next_write_index]);
|
||||
|
||||
self.num_elements.fetch_add(1, Ordering::Release);
|
||||
|
||||
self.next_write_index += 1;
|
||||
if self.next_write_index == self.queue.len() {
|
||||
self.next_write_index = 0;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes the frontmost "full" T from the queue by swapping it with
|
||||
/// the "empty" T in `*output`.
|
||||
///
|
||||
/// Returns `true` if an item was removed, `false` if the queue was empty.
|
||||
pub(crate) fn remove(&mut self, output: &mut T) -> bool {
|
||||
if self.num_elements.load(Ordering::Acquire) == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
mem::swap(output, &mut self.queue[self.next_read_index]);
|
||||
|
||||
self.num_elements.fetch_sub(1, Ordering::Release);
|
||||
|
||||
self.next_read_index += 1;
|
||||
if self.next_read_index == self.queue.len() {
|
||||
self.next_read_index = 0;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns the current number of elements in the queue.
|
||||
///
|
||||
/// Since elements may be concurrently added, the caller must treat this
|
||||
/// as a lower bound, not an exact count. May only be called by the
|
||||
/// consumer.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn size_at_least(&self) -> usize {
|
||||
self.num_elements.load(Ordering::Acquire)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn basic_insert_remove() {
|
||||
let mut queue = SwapQueue::<i32>::new(3);
|
||||
let mut val = 42;
|
||||
assert!(queue.insert(&mut val));
|
||||
assert_eq!(val, 0); // swapped with default
|
||||
|
||||
let mut out = 0;
|
||||
assert!(queue.remove(&mut out));
|
||||
assert_eq!(out, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_queue_rejects_insert() {
|
||||
let mut queue = SwapQueue::<i32>::new(2);
|
||||
let mut a = 1;
|
||||
let mut b = 2;
|
||||
let mut c = 3;
|
||||
assert!(queue.insert(&mut a));
|
||||
assert!(queue.insert(&mut b));
|
||||
assert!(!queue.insert(&mut c)); // full
|
||||
assert_eq!(c, 3); // unchanged
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_queue_rejects_remove() {
|
||||
let mut queue = SwapQueue::<i32>::new(2);
|
||||
let mut out = 0;
|
||||
assert!(!queue.remove(&mut out));
|
||||
assert_eq!(out, 0); // unchanged
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fifo_ordering() {
|
||||
let mut queue = SwapQueue::<i32>::new(4);
|
||||
let mut vals = [10, 20, 30];
|
||||
for v in &mut vals {
|
||||
queue.insert(v);
|
||||
}
|
||||
|
||||
let mut out = 0;
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(out, 10);
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(out, 20);
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(out, 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraparound() {
|
||||
let mut queue = SwapQueue::<i32>::new(2);
|
||||
let mut val = 1;
|
||||
queue.insert(&mut val);
|
||||
val = 2;
|
||||
queue.insert(&mut val);
|
||||
|
||||
let mut out = 0;
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(out, 1);
|
||||
|
||||
// Insert again — wraps around.
|
||||
val = 3;
|
||||
queue.insert(&mut val);
|
||||
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(out, 2);
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(out, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_empties_queue() {
|
||||
let mut queue = SwapQueue::<i32>::new(3);
|
||||
let mut val = 1;
|
||||
queue.insert(&mut val);
|
||||
val = 2;
|
||||
queue.insert(&mut val);
|
||||
|
||||
assert_eq!(queue.size_at_least(), 2);
|
||||
queue.clear();
|
||||
assert_eq!(queue.size_at_least(), 0);
|
||||
|
||||
let mut out = 0;
|
||||
assert!(!queue.remove(&mut out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_at_least() {
|
||||
let mut queue = SwapQueue::<i32>::new(3);
|
||||
assert_eq!(queue.size_at_least(), 0);
|
||||
|
||||
let mut val = 1;
|
||||
queue.insert(&mut val);
|
||||
assert_eq!(queue.size_at_least(), 1);
|
||||
|
||||
val = 2;
|
||||
queue.insert(&mut val);
|
||||
assert_eq!(queue.size_at_least(), 2);
|
||||
|
||||
let mut out = 0;
|
||||
queue.remove(&mut out);
|
||||
assert_eq!(queue.size_at_least(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_prototype() {
|
||||
let mut queue = SwapQueue::with_prototype(2, vec![0i32; 10]);
|
||||
let mut input = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
assert!(queue.insert(&mut input));
|
||||
// Swapped with prototype — should get a vec of length 10 with zeros.
|
||||
assert_eq!(input.len(), 10);
|
||||
assert!(input.iter().all(|&x| x == 0));
|
||||
|
||||
let mut output = vec![0i32; 10];
|
||||
assert!(queue.remove(&mut output));
|
||||
assert_eq!(output, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_setting_style_usage() {
|
||||
// Simulates how AudioProcessingImpl uses SwapQueue with RuntimeSettings.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct Setting {
|
||||
kind: u8,
|
||||
value: f32,
|
||||
}
|
||||
|
||||
let mut queue = SwapQueue::new(10);
|
||||
let mut s = Setting {
|
||||
kind: 1,
|
||||
value: 3.125,
|
||||
};
|
||||
assert!(queue.insert(&mut s));
|
||||
assert_eq!(s.kind, 0); // swapped with default
|
||||
|
||||
let mut out = Setting::default();
|
||||
assert!(queue.remove(&mut out));
|
||||
assert_eq!(out.kind, 1);
|
||||
assert!((out.value - 3.125).abs() < 0.001);
|
||||
}
|
||||
}
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
//! 3-band FIR filter bank with DCT modulation.
|
||||
//!
|
||||
//! Splits a 480-sample (48 kHz, 10 ms) frame into three 160-sample sub-bands
|
||||
//! (0–8 kHz, 8–16 kHz, 16–24 kHz) and can merge them back.
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/three_band_filter_bank.h/cc`.
|
||||
|
||||
const SQRT_3: f32 = 1.732_050_8;
|
||||
|
||||
const SPARSITY: usize = 4;
|
||||
const STRIDE_LOG2: usize = 2;
|
||||
const STRIDE: usize = 1 << STRIDE_LOG2;
|
||||
const NUM_ZERO_FILTERS: usize = 2;
|
||||
const FILTER_SIZE: usize = 4;
|
||||
const MEMORY_SIZE: usize = FILTER_SIZE * STRIDE - 1; // 15
|
||||
|
||||
/// Number of frequency bands.
|
||||
pub const NUM_BANDS: usize = 3;
|
||||
/// Full-band frame size (480 samples = 48 kHz × 10 ms).
|
||||
pub const FULL_BAND_SIZE: usize = 480;
|
||||
/// Split-band frame size (160 samples per band).
|
||||
pub const SPLIT_BAND_SIZE: usize = FULL_BAND_SIZE / NUM_BANDS;
|
||||
|
||||
const NUM_NON_ZERO_FILTERS: usize = SPARSITY * NUM_BANDS - NUM_ZERO_FILTERS; // 10
|
||||
const SUB_SAMPLING: usize = NUM_BANDS;
|
||||
const ZERO_FILTER_INDEX_1: usize = 3;
|
||||
const ZERO_FILTER_INDEX_2: usize = 9;
|
||||
|
||||
#[rustfmt::skip]
|
||||
const FILTER_COEFFS: [[f32; FILTER_SIZE]; NUM_NON_ZERO_FILTERS] = [
|
||||
[-0.00047749, -0.00496888, 0.16547118, 0.00425496],
|
||||
[-0.00173287, -0.01585778, 0.14989004, 0.00994113],
|
||||
[-0.00304815, -0.02536082, 0.12154542, 0.01157993],
|
||||
[-0.00346946, -0.02587886, 0.04760441, 0.00607594],
|
||||
[-0.00154717, -0.01136076, 0.01387458, 0.00186353],
|
||||
[ 0.00186353, 0.01387458,-0.01136076, -0.00154717],
|
||||
[ 0.00607594, 0.04760441,-0.02587886, -0.00346946],
|
||||
[ 0.00983212, 0.08543175,-0.02982767, -0.00383509],
|
||||
[ 0.00994113, 0.14989004,-0.01585778, -0.00173287],
|
||||
[ 0.00425496, 0.16547118,-0.00496888, -0.00047749],
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const DCT_MODULATION: [[f32; NUM_BANDS]; NUM_NON_ZERO_FILTERS] = [
|
||||
[ 2.0, 2.0, 2.0],
|
||||
[ SQRT_3, 0.0, -SQRT_3],
|
||||
[ 1.0, -2.0, 1.0],
|
||||
[-1.0, 2.0, -1.0],
|
||||
[-SQRT_3, 0.0, SQRT_3],
|
||||
[-2.0, -2.0, -2.0],
|
||||
[-SQRT_3, 0.0, SQRT_3],
|
||||
[-1.0, 2.0, -1.0],
|
||||
[ 1.0, -2.0, 1.0],
|
||||
[ SQRT_3, 0.0, -SQRT_3],
|
||||
];
|
||||
|
||||
/// Polyphase filter core: filters `input` through `filter` with shift `in_shift`,
|
||||
/// using and updating `state`.
|
||||
///
|
||||
/// Direct port of C++ `FilterCore` in `three_band_filter_bank.cc`.
|
||||
fn filter_core(
|
||||
filter: &[f32; FILTER_SIZE],
|
||||
input: &[f32; SPLIT_BAND_SIZE],
|
||||
in_shift: usize,
|
||||
output: &mut [f32; SPLIT_BAND_SIZE],
|
||||
state: &mut [f32; MEMORY_SIZE],
|
||||
) {
|
||||
debug_assert!(in_shift < STRIDE);
|
||||
|
||||
// Zero-initialize output (matches C++ std::fill).
|
||||
output.fill(0.0);
|
||||
|
||||
let f0 = filter[0];
|
||||
let f1 = filter[1];
|
||||
let f2 = filter[2];
|
||||
let f3 = filter[3];
|
||||
|
||||
// Part 1: samples that depend entirely on state (0..in_shift, at most 3 iterations).
|
||||
#[allow(clippy::needless_range_loop, reason = "index used in arithmetic")]
|
||||
for k in 0..in_shift {
|
||||
let j = MEMORY_SIZE + k - in_shift;
|
||||
output[k] = f0.mul_add(
|
||||
state[j],
|
||||
f1.mul_add(
|
||||
state[j - STRIDE],
|
||||
f2.mul_add(state[j - 2 * STRIDE], f3 * state[j - 3 * STRIDE]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Part 2: transition samples (partially from input, partially from state).
|
||||
// Matches C++ loop structure with loop_limit = min(kFilterSize, 1 + (shift >> kStrideLog2)).
|
||||
#[allow(clippy::needless_range_loop, reason = "index used in arithmetic")]
|
||||
for k in in_shift..(FILTER_SIZE * STRIDE) {
|
||||
let shift = k - in_shift;
|
||||
let loop_limit = (1 + (shift >> STRIDE_LOG2)).min(FILTER_SIZE);
|
||||
|
||||
// Taps sourced from input.
|
||||
for i in 0..loop_limit {
|
||||
output[k] += input[shift - i * STRIDE] * filter[i];
|
||||
}
|
||||
|
||||
// Taps sourced from state.
|
||||
let j_base = MEMORY_SIZE + shift - loop_limit * STRIDE;
|
||||
for i in loop_limit..FILTER_SIZE {
|
||||
output[k] += state[j_base - (i - loop_limit) * STRIDE] * filter[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Part 3: samples fully within input (hottest path — 144 of 160 iterations).
|
||||
// All 4 taps read from input at fixed offsets.
|
||||
#[allow(clippy::needless_range_loop, reason = "index used in arithmetic")]
|
||||
for k in (FILTER_SIZE * STRIDE)..SPLIT_BAND_SIZE {
|
||||
let base = k - in_shift;
|
||||
output[k] = f0.mul_add(
|
||||
input[base],
|
||||
f1.mul_add(
|
||||
input[base - STRIDE],
|
||||
f2.mul_add(input[base - 2 * STRIDE], f3 * input[base - 3 * STRIDE]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Update state from end of input.
|
||||
state.copy_from_slice(&input[SPLIT_BAND_SIZE - MEMORY_SIZE..]);
|
||||
}
|
||||
|
||||
/// 3-band QMF filter bank for analysis and synthesis.
|
||||
#[derive(Debug)]
|
||||
pub struct ThreeBandFilterBank {
|
||||
state_analysis: [[f32; MEMORY_SIZE]; NUM_NON_ZERO_FILTERS],
|
||||
state_synthesis: [[f32; MEMORY_SIZE]; NUM_NON_ZERO_FILTERS],
|
||||
}
|
||||
|
||||
impl Default for ThreeBandFilterBank {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreeBandFilterBank {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state_analysis: [[0.0; MEMORY_SIZE]; NUM_NON_ZERO_FILTERS],
|
||||
state_synthesis: [[0.0; MEMORY_SIZE]; NUM_NON_ZERO_FILTERS],
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a 480-sample fullband frame into 3 × 160-sample sub-bands.
|
||||
pub fn analysis(
|
||||
&mut self,
|
||||
input: &[f32; FULL_BAND_SIZE],
|
||||
output: &mut [[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
) {
|
||||
// Initialize output to zero.
|
||||
for band in output.iter_mut() {
|
||||
band.fill(0.0);
|
||||
}
|
||||
|
||||
for downsampling_index in 0..SUB_SAMPLING {
|
||||
// Downsample: pick every SUB_SAMPLING-th sample with offset.
|
||||
let mut in_subsampled = [0.0f32; SPLIT_BAND_SIZE];
|
||||
for k in 0..SPLIT_BAND_SIZE {
|
||||
in_subsampled[k] =
|
||||
input[(SUB_SAMPLING - 1) - downsampling_index + SUB_SAMPLING * k];
|
||||
}
|
||||
|
||||
for in_shift in 0..STRIDE {
|
||||
// Choose filter, skip zero filters.
|
||||
let index = downsampling_index + in_shift * SUB_SAMPLING;
|
||||
if index == ZERO_FILTER_INDEX_1 || index == ZERO_FILTER_INDEX_2 {
|
||||
continue;
|
||||
}
|
||||
let filter_index = if index < ZERO_FILTER_INDEX_1 {
|
||||
index
|
||||
} else if index < ZERO_FILTER_INDEX_2 {
|
||||
index - 1
|
||||
} else {
|
||||
index - 2
|
||||
};
|
||||
|
||||
let filter = &FILTER_COEFFS[filter_index];
|
||||
let dct_mod = &DCT_MODULATION[filter_index];
|
||||
|
||||
// Filter.
|
||||
let mut out_subsampled = [0.0f32; SPLIT_BAND_SIZE];
|
||||
filter_core(
|
||||
filter,
|
||||
&in_subsampled,
|
||||
in_shift,
|
||||
&mut out_subsampled,
|
||||
&mut self.state_analysis[filter_index],
|
||||
);
|
||||
|
||||
// Band-modulate and accumulate.
|
||||
for band in 0..NUM_BANDS {
|
||||
let mod_val = dct_mod[band];
|
||||
for n in 0..SPLIT_BAND_SIZE {
|
||||
output[band][n] += mod_val * out_subsampled[n];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges 3 × 160-sample sub-bands into a 480-sample fullband frame.
|
||||
pub fn synthesis(
|
||||
&mut self,
|
||||
input: &[[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
output: &mut [f32; FULL_BAND_SIZE],
|
||||
) {
|
||||
output.fill(0.0);
|
||||
|
||||
for upsampling_index in 0..SUB_SAMPLING {
|
||||
for in_shift in 0..STRIDE {
|
||||
// Choose filter, skip zero filters.
|
||||
let index = upsampling_index + in_shift * SUB_SAMPLING;
|
||||
if index == ZERO_FILTER_INDEX_1 || index == ZERO_FILTER_INDEX_2 {
|
||||
continue;
|
||||
}
|
||||
let filter_index = if index < ZERO_FILTER_INDEX_1 {
|
||||
index
|
||||
} else if index < ZERO_FILTER_INDEX_2 {
|
||||
index - 1
|
||||
} else {
|
||||
index - 2
|
||||
};
|
||||
|
||||
let filter = &FILTER_COEFFS[filter_index];
|
||||
let dct_mod = &DCT_MODULATION[filter_index];
|
||||
|
||||
// Prepare filter input by modulating the banded input.
|
||||
let mut in_subsampled = [0.0f32; SPLIT_BAND_SIZE];
|
||||
for band in 0..NUM_BANDS {
|
||||
let mod_val = dct_mod[band];
|
||||
for n in 0..SPLIT_BAND_SIZE {
|
||||
in_subsampled[n] += mod_val * input[band][n];
|
||||
}
|
||||
}
|
||||
|
||||
// Filter.
|
||||
let mut out_subsampled = [0.0f32; SPLIT_BAND_SIZE];
|
||||
filter_core(
|
||||
filter,
|
||||
&in_subsampled,
|
||||
in_shift,
|
||||
&mut out_subsampled,
|
||||
&mut self.state_synthesis[filter_index],
|
||||
);
|
||||
|
||||
// Upsample.
|
||||
let upsampling_scaling = SUB_SAMPLING as f32;
|
||||
for k in 0..SPLIT_BAND_SIZE {
|
||||
output[upsampling_index + SUB_SAMPLING * k] +=
|
||||
upsampling_scaling * out_subsampled[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn analysis_produces_output() {
|
||||
let mut fb = ThreeBandFilterBank::new();
|
||||
// Impulse input.
|
||||
let mut input = [0.0f32; FULL_BAND_SIZE];
|
||||
input[0] = 1.0;
|
||||
let mut output = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
fb.analysis(&input, &mut output);
|
||||
|
||||
// At least one band should have non-zero output.
|
||||
let total_energy: f32 = output.iter().flat_map(|b| b.iter()).map(|x| x * x).sum();
|
||||
assert!(
|
||||
total_energy > 0.0,
|
||||
"output should be non-zero for impulse input"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthesis_produces_output() {
|
||||
let mut fb = ThreeBandFilterBank::new();
|
||||
// Put a signal in band 0.
|
||||
let mut input = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
input[0][0] = 1.0;
|
||||
let mut output = [0.0f32; FULL_BAND_SIZE];
|
||||
fb.synthesis(&input, &mut output);
|
||||
|
||||
let total_energy: f32 = output.iter().map(|x| x * x).sum();
|
||||
assert!(total_energy > 0.0, "output should be non-zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_synthesis_roundtrip() {
|
||||
use std::f32::consts::PI;
|
||||
|
||||
let mut fb_analysis = ThreeBandFilterBank::new();
|
||||
let mut fb_synthesis = ThreeBandFilterBank::new();
|
||||
|
||||
// Create a signal and process multiple frames to let filter settle.
|
||||
let num_frames = 20;
|
||||
let mut last_input = [0.0f32; FULL_BAND_SIZE];
|
||||
let mut last_output = [0.0f32; FULL_BAND_SIZE];
|
||||
|
||||
for frame in 0..num_frames {
|
||||
let mut input = [0.0f32; FULL_BAND_SIZE];
|
||||
// Sine wave at ~1 kHz (well within band 0).
|
||||
for (i, sample) in input.iter_mut().enumerate() {
|
||||
let t = (frame * FULL_BAND_SIZE + i) as f32 / 48000.0;
|
||||
*sample = (2.0 * PI * 1000.0 * t).sin();
|
||||
}
|
||||
|
||||
let mut bands = [[0.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
fb_analysis.analysis(&input, &mut bands);
|
||||
|
||||
let mut output = [0.0f32; FULL_BAND_SIZE];
|
||||
fb_synthesis.synthesis(&bands, &mut output);
|
||||
|
||||
last_input = input;
|
||||
last_output = output;
|
||||
}
|
||||
|
||||
// After many frames, the output should approximate the input
|
||||
// (with a fixed delay of 24 samples and ~9.5 dB SNR).
|
||||
// Just check that the output has significant energy.
|
||||
let input_energy: f32 = last_input.iter().map(|x| x * x).sum();
|
||||
let output_energy: f32 = last_output.iter().map(|x| x * x).sum();
|
||||
assert!(
|
||||
output_energy > input_energy * 0.05,
|
||||
"roundtrip should preserve most energy: input={input_energy}, output={output_energy}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_input_produces_zero_output() {
|
||||
let mut fb = ThreeBandFilterBank::new();
|
||||
let input = [0.0f32; FULL_BAND_SIZE];
|
||||
let mut output = [[1.0f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
fb.analysis(&input, &mut output);
|
||||
|
||||
for band in &output {
|
||||
for &s in band {
|
||||
assert_eq!(s, 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user