Skip to main content

qualia_audio/features/vad/
noise_estimate.rs

1//! Adaptive noise-floor estimation by minimum statistics.
2//!
3//! The quietest recent frames are, with high probability, noise-only. Tracking
4//! the *minimum* short-term energy over a trailing window therefore yields a
5//! robust estimate of the noise level that follows slow drifts (fans, hiss,
6//! room tone) without ever being pulled up by transient speech or tones.
7//!
8//! The raw minimum systematically *under*-estimates the mean noise power (it is
9//! an extreme-order statistic), so it is multiplied by a fixed bias-compensation
10//! factor to recover an estimate of the floor an activity gate should clear.
11//!
12//! Zero-heap: a single pass over a caller-supplied energy slice. Stateless, so
13//! callers stream by keeping their own small ring of recent per-frame energies
14//! (see [`crate::features::vad::segment_voiced`]).
15
16/// Bias compensation for the minimum-of-window estimator.
17///
18/// The trailing minimum lies below the mean noise energy; scaling it up by this
19/// factor (≈ +3.5 dB) approximates the level a voice-activity gate must exceed
20/// to avoid firing on the noise itself. Empirical minimum-statistics work uses
21/// window-length-dependent factors in roughly this range; a fixed conservative
22/// value keeps the estimator honest (it never claims the floor is *below* the
23/// observed quiet frames) and dependency-free.
24pub const NOISE_BIAS: f32 = 1.5;
25
26/// Estimate the noise floor as the bias-compensated minimum energy over the
27/// trailing `window` entries of `energies` (per-frame RMS or power values).
28///
29/// - `energies`: recent per-frame energy statistics, oldest→newest. Only the
30///   last `window` entries are considered; if fewer are present, all are used.
31/// - `window`: number of trailing frames the minimum is taken over. A larger
32///   window is more robust to sustained speech but slower to track rising noise.
33///
34/// Returns the estimated floor `min(recent) * NOISE_BIAS`, clamped to be
35/// non-negative. Returns `0.0` for an empty slice (no evidence yet — the caller
36/// should treat a zero floor as "unknown", which downstream gates guard with a
37/// tiny epsilon rather than declaring everything voiced).
38///
39/// Non-finite inputs (`NaN`/`±inf`) are ignored so a single bad sample cannot
40/// poison the estimate.
41pub fn noise_floor_min_stat(energies: &[f32], window: usize) -> f32 {
42    if energies.is_empty() {
43        return 0.0;
44    }
45    let w = window.max(1);
46    let start = energies.len().saturating_sub(w);
47    let mut min_e = f32::INFINITY;
48    let mut seen = false;
49    for &e in &energies[start..] {
50        if e.is_finite() && e >= 0.0 && e < min_e {
51            min_e = e;
52            seen = true;
53        }
54    }
55    if !seen {
56        return 0.0;
57    }
58    (min_e * NOISE_BIAS).max(0.0)
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn empty_is_zero() {
67        assert_eq!(noise_floor_min_stat(&[], 8), 0.0);
68    }
69
70    #[test]
71    fn tracks_minimum_scaled_by_bias() {
72        let energies = [0.5f32, 0.4, 0.01, 0.6, 0.3];
73        let floor = noise_floor_min_stat(&energies, 8);
74        assert!((floor - 0.01 * NOISE_BIAS).abs() < 1e-6, "floor={floor}");
75        // The floor is inflated above the raw minimum (bias compensation).
76        assert!(floor > 0.01, "floor should exceed raw min, got {floor}");
77    }
78
79    #[test]
80    fn window_limits_to_trailing_frames() {
81        // Quiet frame is old and outside the window → ignored; min is the recent 0.2.
82        let energies = [0.01f32, 0.5, 0.4, 0.3, 0.2];
83        let floor = noise_floor_min_stat(&energies, 3);
84        assert!((floor - 0.2 * NOISE_BIAS).abs() < 1e-6, "floor={floor}");
85    }
86
87    #[test]
88    fn window_larger_than_len_uses_all() {
89        let energies = [0.05f32, 0.5, 0.4];
90        let floor = noise_floor_min_stat(&energies, 64);
91        assert!((floor - 0.05 * NOISE_BIAS).abs() < 1e-6, "floor={floor}");
92    }
93
94    #[test]
95    fn ignores_non_finite() {
96        let energies = [f32::NAN, 0.3, f32::INFINITY, 0.02];
97        let floor = noise_floor_min_stat(&energies, 8);
98        assert!((floor - 0.02 * NOISE_BIAS).abs() < 1e-6, "floor={floor}");
99    }
100
101    #[test]
102    fn all_non_finite_is_zero() {
103        let energies = [f32::NAN, f32::INFINITY];
104        assert_eq!(noise_floor_min_stat(&energies, 8), 0.0);
105    }
106}