Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

5.1 KB
Raw Blame
//! Automatic gain control for the microphone, like Discord's (on in its Voice Isolation
//! profile, off in Studio).
//!
//! A quiet microphone is raised toward a steady speech level before noise suppression,
//! which otherwise mistakes soft speech for noise and turns it down further. The gain only
//! adapts while you speak (a frame well above the background), never attenuates, and a
//! limiter keeps peaks under -1 dBFS. Between words the gain holds, so room noise is not
//! pumped up in the pauses.
use crate::Frame;

/// The speech level (20 ms RMS, dBFS) the gain aims for: a typical Discord voice.
const TARGET_DB: f32 = -20.0;
/// The most a quiet microphone is raised.
const MAX_GAIN_DB: f32 = 30.0;
/// Gain changes per 20 ms frame of speech: up 10 dB/s, down 30 dB/s; the first second
/// of speech in a call converges at 50 dB/s.
const RISE_DB: f32 = 0.2;
const FALL_DB: f32 = 0.6;
const START_DB: f32 = 1.0;
const START_FRAMES: u32 = 50;
/// A frame counts as speech this far above the background, and never below this level.
const SPEECH_ABOVE_FLOOR_DB: f32 = 10.0;
const QUIETEST_SPEECH_DB: f32 = -65.0;
/// How fast the background estimate rises again after it dropped (5 dB/s).
const FLOOR_RISE_DB: f32 = 0.1;
/// Limiter ceiling: -1 dBFS.
const PEAK: f32 = 0.891;

pub(crate) struct Agc {
    gain_db: f32,
    /// The linear gain the last frame ended on, so gain changes ramp instead of stepping.
    applied: f32,
    speech_db: Option<f32>,
    floor_db: f32,
    speech_frames: u32,
}

impl Default for Agc {
    fn default() -> Self {
        Self {
            gain_db: 0.0,
            applied: 1.0,
            speech_db: None,
            floor_db: -60.0,
            speech_frames: 0,
        }
    }
}

impl Agc {
    /// Raises `frame` in place; returns the gain it ended on, in dB.
    pub fn apply(&mut self, frame: &mut Frame) -> f32 {
        let level = crate::activity::level_db(frame);
        self.floor_db = level.min(self.floor_db + FLOOR_RISE_DB);
        if level > QUIETEST_SPEECH_DB && level > self.floor_db + SPEECH_ABOVE_FLOOR_DB {
            let speech = self.speech_db.map_or(level, |speech| speech + (level - speech) * 0.05);
            self.speech_db = Some(speech);
            let step = if self.speech_frames < START_FRAMES { START_DB } else { RISE_DB };
            self.speech_frames = self.speech_frames.saturating_add(1);
            let wanted = (TARGET_DB - speech).clamp(0.0, MAX_GAIN_DB);
            self.gain_db += (wanted - self.gain_db).clamp(-FALL_DB.max(step), step);
        }
        let peak = frame
            .iter()
            .filter(|sample| sample.is_finite())
            .fold(0.0f32, |peak, sample| peak.max(sample.abs()));
        let ceiling = if peak > 0.0 { PEAK / peak } else { f32::MAX };
        let end = 10f32.powf(self.gain_db / 20.0).min(ceiling);
        let start = self.applied.min(ceiling);
        if start != 1.0 || end != 1.0 {
            let step = (end - start) / frame.len() as f32;
            for (index, sample) in frame.iter_mut().enumerate() {
                *sample = (*sample * (start + step * index as f32)).clamp(-1.0, 1.0);
            }
        }
        self.applied = end;
        20.0 * end.log10()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A 200 Hz tone with `level_db` RMS.
    fn tone(level_db: f32, offset: usize) -> Frame {
        let amplitude = 10f32.powf(level_db / 20.0) * std::f32::consts::SQRT_2;
        std::array::from_fn(|i| {
            amplitude * (2.0 * std::f32::consts::PI * 200.0 * (offset + i) as f32 / 48_000.0).sin()
        })
    }

    #[test]
    fn quiet_speech_is_raised_to_the_target() {
        let mut agc = Agc::default();
        let mut gain = 0.0;
        // Three seconds of speech at -40 dBFS over a -70 dBFS room.
        for n in 0..150 {
            let mut frame = if n % 10 == 9 { tone(-70.0, n * 960) } else { tone(-40.0, n * 960) };
            gain = agc.apply(&mut frame);
        }
        assert!((gain - 20.0).abs() < 1.0, "raised by about 20 dB: {gain}");
        let mut frame = tone(-40.0, 0);
        agc.apply(&mut frame);
        let level = crate::activity::level_db(&frame);
        assert!((level - TARGET_DB).abs() < 1.5, "speech near the target: {level}");
    }

    #[test]
    fn background_alone_is_not_raised() {
        let mut agc = Agc::default();
        let mut gain = 0.0;
        for n in 0..500 {
            gain = agc.apply(&mut tone(-62.0, n * 960));
        }
        assert!(gain < 1.0, "steady room noise is not speech: {gain}");
    }

    #[test]
    fn loud_speech_is_untouched_and_peaks_are_limited() {
        let mut agc = Agc::default();
        for n in 0..100 {
            let mut frame = tone(-12.0, n * 960);
            let before = frame;
            assert_eq!(agc.apply(&mut frame), 0.0);
            assert_eq!(frame, before);
        }
        // A raised quiet voice followed by a shout: the shout stays under the ceiling.
        let mut agc = Agc::default();
        for n in 0..150 {
            agc.apply(&mut tone(-40.0, n * 960));
        }
        let mut shout = tone(-6.0, 0);
        agc.apply(&mut shout);
        assert!(shout.iter().all(|sample| sample.abs() <= PEAK + 1e-4));
    }
}