Skip to main content

sew_noise/
lib.rs

1//! `sew-noise`: microphone noise removal, a thin API over [`nnnoiseless`] (Joe Neeman's
2//! pure-Rust port of RNNoise, by Jean-Marc Valin and Mozilla; BSD-3-Clause, pinned exactly).
3//!
4//! - [`Stage`]: the native capture stage. One [`FRAME`] (480 samples, 10 ms) block of 48 kHz
5//!   mono `f32` in place, a fixed latency of one block, a [`Mode`] that any thread can change
6//!   at any block without a click, and per-block timing counters ([`StageStats`]).
7//! - [`Denoiser`]: one frame at a time, [`FRAME`] samples of 48 kHz mono `f32` in the range
8//!   `[-1, 1]`, in and out. The output lags the input by one frame ([`Denoiser::LATENCY`],
9//!   10 ms), RNNoise's overlap-add.
10//! - [`StreamDenoiser`]: any block size at any rate (8–192 kHz). It buffers to frames,
11//!   resamples linearly to and from 48 kHz when the rate differs, and keeps a fixed latency
12//!   ([`StreamDenoiser::latency_samples`]). This is what a Web Audio worklet calls.
13//!
14//! No allocation after construction, no C, no unsafe. Non-finite input samples are read as
15//! silence (one NaN would otherwise poison the RNN state for good) and the output is always
16//! finite.
17//!
18//! RNNoise's model is compiled in from `nnnoiseless`; without feature `dfn3` nothing is
19//! loaded at run time.
20//!
21//! Cargo features:
22//! - `capture-stage`: the `capture_stage` module, the capture-hook trait an audio pipeline
23//!   calls a [`Stage`] through.
24//! - `dfn3`: [`Mode::Strong`], DeepFilterNet3's low-latency model (by Hendrik Schröter and
25//!   the DeepFilterNet authors; MIT OR Apache-2.0), run by inference code in this crate. Its
26//!   weights are not in the crate: an app ships them beside itself and loads them with
27//!   `dfn3::Dfn3Model::load`, which checks their pinned sha256 first (RustCrypto's `sha2`).
28//!   The feature adds `sha2` (and `realfft`, which `nnnoiseless` already brings), and no C, no
29//!   unsafe code and no neural-network runtime.
30
31#[cfg(feature = "capture-stage")]
32pub mod capture_stage;
33#[cfg(feature = "dfn3")]
34pub mod dfn3;
35#[cfg(feature = "probe")]
36pub mod probe;
37mod resample;
38mod stage;
39mod standard;
40mod stream;
41mod strong;
42mod thread_clock;
43
44pub use resample::Linear;
45#[cfg(feature = "dfn3")]
46pub use stage::Dfn3Layer;
47pub use stage::{
48    DEFAULT_GRACE, Mode, ModeUnavailable, Stage, StageControl, StageStats, warm_up_thread,
49};
50pub use stream::StreamDenoiser;
51pub use strong::{StepDownReason, StrongState};
52
53use nnnoiseless::DenoiseState;
54
55/// RNNoise's only rate.
56pub const SAMPLE_RATE: u32 = 48_000;
57/// Samples per frame (10 ms at 48 kHz).
58pub const FRAME: usize = DenoiseState::FRAME_SIZE;
59/// The lowest context rate [`StreamDenoiser`] takes.
60pub const MIN_RATE: u32 = 8_000;
61/// The highest context rate [`StreamDenoiser`] takes.
62pub const MAX_RATE: u32 = 192_000;
63
64/// RNNoise works on `f32` holding 16-bit PCM values.
65const SCALE: f32 = 32_768.0;
66
67/// A refused call. Nothing is processed when one is returned.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum Error {
71    /// A frame call's input or output is not [`FRAME`] samples.
72    FrameLength {
73        /// The input's length.
74        input: usize,
75        /// The output's length.
76        output: usize,
77    },
78    /// A stream call's input and output differ in length, or exceed the block size given at
79    /// construction.
80    BlockLength {
81        /// The input's length.
82        input: usize,
83        /// The output's length.
84        output: usize,
85        /// The largest block the stream takes.
86        max: usize,
87    },
88    /// The context rate is outside [`MIN_RATE`]..=[`MAX_RATE`].
89    SampleRate(u32),
90    /// The largest block is 0 or above 16384 samples.
91    MaxBlock(usize),
92}
93
94impl std::fmt::Display for Error {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        match self {
97            Self::FrameLength { input, output } => write!(
98                f,
99                "a frame is {FRAME} samples in and out (got {input} in, {output} out)"
100            ),
101            Self::BlockLength { input, output, max } => write!(
102                f,
103                "a block is the same length in and out, at most {max} samples (got {input} in, {output} out)"
104            ),
105            Self::SampleRate(r) => write!(
106                f,
107                "the sample rate must be {MIN_RATE}..={MAX_RATE} Hz (got {r})"
108            ),
109            Self::MaxBlock(n) => write!(f, "the largest block must be 1..=16384 samples (got {n})"),
110        }
111    }
112}
113
114impl std::error::Error for Error {}
115
116/// README.md's examples, compiled and run as doc tests.
117#[cfg(doctest)]
118#[doc = include_str!("../README.md")]
119struct ReadmeExamples;
120
121/// One RNNoise state: 480-sample frames of 48 kHz mono `f32` in `[-1, 1]`.
122pub struct Denoiser {
123    state: Box<DenoiseState<'static>>,
124    scaled_in: [f32; FRAME],
125    scaled_out: [f32; FRAME],
126}
127
128impl std::fmt::Debug for Denoiser {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.debug_struct("Denoiser").finish_non_exhaustive()
131    }
132}
133
134impl Default for Denoiser {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140impl Denoiser {
141    /// The output lags the input by this many samples (one frame).
142    pub const LATENCY: usize = FRAME;
143
144    /// A fresh state with RNNoise's built-in model (compiled in; nothing is loaded).
145    ///
146    /// It warms the calling thread up first ([`warm_up_thread`]): nnnoiseless makes (and
147    /// allocates) its FFT plans on first use, cached per thread, so the first real frame must
148    /// not be the one that allocates (on wasm32 an allocation may grow the memory, which
149    /// detaches a worklet's views on it). The warm-up runs a frame through a throwaway state,
150    /// never through this one: a frame through the live state changes its history.
151    pub fn new() -> Self {
152        warm_up_thread();
153        Self {
154            state: DenoiseState::new(),
155            scaled_in: [0.0; FRAME],
156            scaled_out: [0.0; FRAME],
157        }
158    }
159
160    /// Denoises one frame and returns RNNoise's voice probability for it (0 to 1).
161    pub fn process_frame(&mut self, input: &[f32], output: &mut [f32]) -> Result<f32, Error> {
162        if input.len() != FRAME || output.len() != FRAME {
163            return Err(Error::FrameLength {
164                input: input.len(),
165                output: output.len(),
166            });
167        }
168        for (s, &x) in self.scaled_in.iter_mut().zip(input) {
169            *s = if x.is_finite() {
170                x.clamp(-1.0, 1.0) * SCALE
171            } else {
172                0.0
173            };
174        }
175        let vad = self
176            .state
177            .process_frame(&mut self.scaled_out[..], &self.scaled_in[..]);
178        for (y, &s) in output.iter_mut().zip(&self.scaled_out) {
179            let v = s / SCALE;
180            *y = if v.is_finite() {
181                v.clamp(-1.0, 1.0)
182            } else {
183                0.0
184            };
185        }
186        Ok(if vad.is_finite() {
187            vad.clamp(0.0, 1.0)
188        } else {
189            0.0
190        })
191    }
192
193    /// Forgets all history (as if new).
194    pub fn reset(&mut self) {
195        *self = Self::new();
196    }
197}
198
199#[cfg(test)]
200pub(crate) mod test_signals {
201    //! The unit tests' "is it suppressing" signal is fan noise (low-passed brown noise plus a
202    //! 100 Hz hum with harmonics), which the model takes down by tens of dB; white noise it
203    //! takes down by only a few dB, so a white-noise floor cannot tell a working filter from
204    //! a bypassed one.
205
206    /// `n` samples of fan noise at 48 kHz with RMS `amp`, deterministic in `seed`.
207    pub(crate) fn fan(seed: u64, n: usize, amp: f32) -> Vec<f32> {
208        let mut s = seed | 1;
209        let (mut brown, mut lp) = (0.0f32, 0.0f32);
210        let mut v: Vec<f32> = (0..n)
211            .map(|i| {
212                s ^= s << 13;
213                s ^= s >> 7;
214                s ^= s << 17;
215                let w = (s >> 40) as f32 / (1u64 << 23) as f32 - 1.0;
216                brown = (brown + w * 0.02) * 0.998;
217                lp += 0.05 * (brown - lp);
218                let t = i as f32 / 48_000.0;
219                let hum: f32 = [(100.0, 1.0), (200.0, 0.5), (300.0, 0.3), (1_250.0, 0.15)]
220                    .iter()
221                    .map(|(f, a)| a * (2.0 * std::f32::consts::PI * f * t).sin())
222                    .sum();
223                lp * 8.0 + hum * 0.05
224            })
225            .collect();
226        let rms = (v.iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / n.max(1) as f64).sqrt();
227        for x in &mut v {
228            *x = (f64::from(*x) / rms) as f32 * amp;
229        }
230        v
231    }
232}
233
234#[cfg(test)]
235#[allow(clippy::unwrap_used, clippy::expect_used)]
236mod tests {
237    use super::*;
238
239    fn noise(seed: &mut u64, n: usize, amp: f32) -> Vec<f32> {
240        (0..n)
241            .map(|_| {
242                *seed ^= *seed << 13;
243                *seed ^= *seed >> 7;
244                *seed ^= *seed << 17;
245                ((*seed >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp
246            })
247            .collect()
248    }
249
250    fn rms(x: &[f32]) -> f32 {
251        (x.iter().map(|v| v * v).sum::<f32>() / x.len().max(1) as f32).sqrt()
252    }
253
254    #[test]
255    fn frame_is_480_at_48k() {
256        assert_eq!(FRAME, 480);
257        assert_eq!(SAMPLE_RATE as usize / 100, FRAME);
258    }
259
260    #[test]
261    fn wrong_lengths_are_refused() {
262        let mut d = Denoiser::new();
263        let mut out = [0.0; FRAME];
264        assert_eq!(
265            d.process_frame(&[0.0; 479], &mut out),
266            Err(Error::FrameLength {
267                input: 479,
268                output: 480
269            })
270        );
271        let mut short = [0.0; 10];
272        assert!(d.process_frame(&[0.0; FRAME], &mut short).is_err());
273        assert!(
274            Error::FrameLength {
275                input: 1,
276                output: 2
277            }
278            .to_string()
279            .contains("480")
280        );
281    }
282
283    #[test]
284    fn silence_stays_silent() {
285        let mut d = Denoiser::new();
286        let mut out = [1.0; FRAME];
287        for _ in 0..20 {
288            let vad = d.process_frame(&[0.0; FRAME], &mut out).unwrap();
289            assert!((0.0..=1.0).contains(&vad));
290            assert!(
291                out.iter().all(|v| v.abs() < 1e-6),
292                "silence in, silence out"
293            );
294        }
295    }
296
297    /// Output over input power (dB) of `x` through a fresh denoiser, after 50 frames of warm-up.
298    fn reduction_db(x: &[f32]) -> f32 {
299        let mut d = Denoiser::new();
300        let mut out = [0.0; FRAME];
301        let (mut pin, mut pout) = (0.0f32, 0.0f32);
302        for (i, f) in x.as_chunks::<FRAME>().0.iter().enumerate() {
303            d.process_frame(f, &mut out).unwrap();
304            if i >= 50 {
305                pin += rms(f).powi(2);
306                pout += rms(&out).powi(2);
307            }
308        }
309        10.0 * (pout / pin).log10()
310    }
311
312    /// Fan noise down by at least 40 dB (a bypass gives 0 dB and fails), white
313    /// noise never made louder.
314    #[test]
315    fn fan_noise_is_suppressed_and_white_noise_never_louder() {
316        let fan = reduction_db(&test_signals::fan(0x5eed, 300 * FRAME, 0.05));
317        assert!(
318            fan <= -40.0,
319            "fan noise down by at least 40 dB (got {fan:.1} dB)"
320        );
321        let mut seed = 0x5eed_u64;
322        let white = reduction_db(&noise(&mut seed, 300 * FRAME, 0.05));
323        assert!(
324            white <= 0.0,
325            "white noise never made louder (got {white:+.1} dB)"
326        );
327    }
328
329    #[test]
330    fn non_finite_input_does_not_poison_the_state() {
331        let mut d = Denoiser::new();
332        let mut out = [0.0; FRAME];
333        let mut bad = [0.1f32; FRAME];
334        bad[3] = f32::NAN;
335        bad[7] = f32::INFINITY;
336        bad[9] = f32::NEG_INFINITY;
337        bad[11] = 7.0;
338        d.process_frame(&bad, &mut out).unwrap();
339        assert!(out.iter().all(|v| v.is_finite() && v.abs() <= 1.0));
340        let mut seed = 9;
341        for _ in 0..50 {
342            let x = noise(&mut seed, FRAME, 0.2);
343            d.process_frame(&x, &mut out).unwrap();
344            assert!(out.iter().all(|v| v.is_finite() && v.abs() <= 1.0));
345        }
346        // After a reset the state is as new: silence gives silence at once.
347        d.reset();
348        d.process_frame(&[0.0; FRAME], &mut out).unwrap();
349        assert!(out.iter().all(|v| v.abs() < 1e-6));
350    }
351
352    #[test]
353    fn output_lags_by_one_frame() {
354        // A loud tone burst in frame 10: its energy comes out in frame 11, not frame 10.
355        let mut d = Denoiser::new();
356        let mut out = [0.0; FRAME];
357        let mut energy = Vec::new();
358        for i in 0..14 {
359            let x: Vec<f32> = (0..FRAME)
360                .map(|n| {
361                    if i == 10 {
362                        (n as f32 * 0.05).sin() * 0.5
363                    } else {
364                        0.0
365                    }
366                })
367                .collect();
368            d.process_frame(&x, &mut out).unwrap();
369            energy.push(rms(&out));
370        }
371        // The spectral gains spread a little of the burst into its own frame: raw nnnoiseless
372        // 0.3.2, 0.4.0 and 0.5.2 all put about 0.0016 rms there against 0.35 in the next frame
373        // (-47 dB), so the bound is relative: at least 40 dB under the next frame.
374        assert!(
375            energy[10] < energy[11] / 100.0,
376            "nothing much comes out in the burst's own frame: {energy:?}"
377        );
378        assert!(
379            energy[11] > energy[10] * 10.0 && energy[11] > 1e-3,
380            "{energy:?}"
381        );
382    }
383}