Skip to content

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

12.6 KB
Raw Blame
//! Microphone conditioning on the capture callback, before 20 ms framing: the device's
//! channels down to mono, then band-limited resampling to 48 kHz for devices that run at
//! another rate (Bluetooth headsets at 16 kHz, interfaces at 44.1 or 96 kHz).
//!
//! Everything is allocated up front; the per-sample work allocates nothing.

/// The most channels a capture device may have (`audio::checked` refuses more).
const MAX_CHANNELS: usize = 8;

/// Mono from the device's channels: the average of the channels that carry the voice.
///
/// A channel 30 dB below the loudest, or in opposite phase to it, is left out. Audio
/// interfaces put the microphone on one input of a stereo pair, and averaging in the unused
/// input halves the voice and adds that input's noise; an inverted channel (some mic
/// arrays and virtual devices) would cancel the voice instead.
pub(crate) struct Downmix {
    channels: usize,
    weights: [f32; MAX_CHANNELS],
    /// The channel that was loudest in the last decided window, that phase is judged against.
    reference: usize,
    energy: [f32; MAX_CHANNELS],
    correlation: [f32; MAX_CHANNELS],
    frames: u32,
    window: u32,
}
impl Downmix {
    pub fn new(channels: usize, rate: u32) -> Self {
        let channels = channels.clamp(1, MAX_CHANNELS);
        let mut weights = [0.0; MAX_CHANNELS];
        weights[..channels].fill(1.0 / channels as f32);
        Self {
            channels,
            weights,
            reference: 0,
            energy: [0.0; MAX_CHANNELS],
            correlation: [0.0; MAX_CHANNELS],
            frames: 0,
            // Decide every 100 ms.
            window: (rate / 10).max(1),
        }
    }
    /// One device frame (one sample per channel) to a mono sample.
    pub fn mix(&mut self, frame: &[f32]) -> f32 {
        if self.channels == 1 {
            return frame[0];
        }
        let reference = frame[self.reference];
        let mut mono = 0.0;
        for (channel, &value) in frame.iter().enumerate().take(self.channels) {
            mono += value * self.weights[channel];
            self.energy[channel] += value * value;
            self.correlation[channel] += value * reference;
        }
        self.frames += 1;
        if self.frames >= self.window {
            self.decide();
        }
        mono
    }
    fn decide(&mut self) {
        let channels = self.channels;
        let (loudest, peak) = self.energy[..channels]
            .iter()
            .copied()
            .enumerate()
            .fold((0, 0.0f32), |best, (channel, energy)| if energy > best.1 { (channel, energy) } else { best });
        // Below about -80 dBFS nothing can be told apart: keep the current choice.
        if peak.is_finite() && peak > self.frames as f32 * 1e-8 {
            let reference = self.energy[self.reference];
            let mut used = [false; MAX_CHANNELS];
            for channel in 0..channels {
                let energy = self.energy[channel];
                let loud = energy >= peak * 1e-3;
                let opposed = reference > 0.0
                    && self.correlation[channel] < -0.5 * (energy * reference).sqrt();
                used[channel] = channel == loudest || (loud && !opposed);
            }
            // Phase is judged against the reference, so an opposed loudest channel keeps
            // the reference's side instead.
            if used[self.reference] && self.correlation[loudest] < -0.5 * (peak * reference).sqrt() {
                used[loudest] = false;
            }
            let count = used[..channels].iter().filter(|used| **used).count().max(1);
            for channel in 0..channels {
                self.weights[channel] = if used[channel] { 1.0 / count as f32 } else { 0.0 };
            }
            if used[loudest] {
                self.reference = loudest;
            }
        }
        self.energy = [0.0; MAX_CHANNELS];
        self.correlation = [0.0; MAX_CHANNELS];
        self.frames = 0;
    }
}

/// Zero crossings of the low-pass filter on each side of an output sample, counted at the
/// lower of the two rates. 32 gives a stopband near -60 dB with the Kaiser window below.
const ZEROS: usize = 32;
/// At most this many precomputed filter phases. Common rates need fewer (44.1 kHz: 160,
/// 16 kHz: 3, 96 kHz: 1); an odd rate snaps to the nearest of 1024 phases (error < -60 dB).
const MAX_PHASES: usize = 1024;
/// Pass band edge as a fraction of the lower rate's Nyquist frequency.
const CUTOFF: f64 = 0.9;
/// Kaiser window shape for about 60 dB of attenuation.
const KAISER_BETA: f64 = 5.65;

/// Band-limited (windowed-sinc, polyphase) conversion from the device rate to 48 kHz.
///
/// Linear interpolation, which this replaces, mirrors a 16 kHz headset's voice into
/// metallic images up to 13 dB below it and folds a 96 kHz device's ultrasonic noise into
/// the voice band.
pub(crate) struct Resampler {
    /// One normalised filter of `taps` coefficients per output phase, back to back.
    filters: Box<[f32]>,
    taps: usize,
    phases: usize,
    /// The last `taps` input samples, written twice so one window is always contiguous.
    history: Box<[f32]>,
    write: usize,
    primed: bool,
    /// Where the next output falls between the two centre inputs: `position / denominator`
    /// input samples, advancing `step / denominator` per output (exact, no drift).
    position: u64,
    step: u64,
    denominator: u64,
}
impl Resampler {
    /// `None` at 48 kHz, where samples pass through untouched.
    pub fn new(rate: u32) -> Option<Self> {
        if rate == 48_000 || rate == 0 {
            return None;
        }
        let gcd = |mut a: u64, mut b: u64| {
            while b != 0 {
                (a, b) = (b, a % b);
            }
            a
        };
        let divisor = gcd(u64::from(rate), 48_000);
        let (step, denominator) = (u64::from(rate) / divisor, 48_000 / divisor);
        let phases = (denominator as usize).min(MAX_PHASES);
        // Zero crossings per input sample, and the inputs each side the kernel reaches.
        let scale = (48_000.0 / f64::from(rate)).min(1.0);
        let half = (ZEROS as f64 / scale).ceil() as usize;
        let taps = 2 * half;
        let bessel = |x: f64| {
            // I0 by its power series; converges quickly for the arguments used here.
            let (mut sum, mut term, mut k) = (1.0f64, 1.0f64, 1.0f64);
            while term > 1e-12 * sum {
                term *= (x / (2.0 * k)).powi(2);
                sum += term;
                k += 1.0;
            }
            sum
        };
        let kernel = |z: f64| {
            if z >= ZEROS as f64 {
                return 0.0;
            }
            let u = std::f64::consts::PI * CUTOFF * z;
            let sinc = if u == 0.0 { 1.0 } else { u.sin() / u };
            let edge = z / ZEROS as f64;
            sinc * bessel(KAISER_BETA * (1.0 - edge * edge).sqrt()) / bessel(KAISER_BETA)
        };
        let mut filters = Vec::with_capacity(phases * taps);
        let mut filter = vec![0.0f64; taps];
        for phase in 0..phases {
            let centre = (half - 1) as f64 + phase as f64 / phases as f64;
            for (tap, h) in filter.iter_mut().enumerate() {
                *h = kernel((tap as f64 - centre).abs() * scale);
            }
            // Unity gain at every phase.
            let sum: f64 = filter.iter().sum();
            filters.extend(filter.iter().map(|h| (h / sum) as f32));
        }
        Some(Self {
            filters: filters.into_boxed_slice(),
            taps,
            phases,
            history: vec![0.0; 2 * taps].into_boxed_slice(),
            write: 0,
            primed: false,
            position: 0,
            step,
            denominator,
        })
    }
    pub fn reset(&mut self) {
        self.primed = false;
        self.write = 0;
        self.position = 0;
    }
    /// Take one input sample and hand every 48 kHz sample now due to `emit`.
    /// Output trails input by half the filter (0.7 ms at 44.1 kHz).
    pub fn process(&mut self, sample: f32, mut emit: impl FnMut(f32)) {
        let taps = self.taps;
        if self.primed {
            self.history[self.write] = sample;
            self.history[self.write + taps] = sample;
            self.write = (self.write + 1) % taps;
        } else {
            // Start from a steady signal instead of a step up from silence.
            self.history.fill(sample);
            self.primed = true;
        }
        let window = &self.history[self.write..self.write + taps];
        while self.position < self.denominator {
            let phase = (self.position * self.phases as u64 / self.denominator) as usize;
            let filter = &self.filters[phase * taps..(phase + 1) * taps];
            emit(window.iter().zip(filter).map(|(x, h)| x * h).sum());
            self.position += self.step;
        }
        self.position -= self.denominator;
    }
}

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

    /// Resample a tone of `frequency` Hz from `rate` and measure it and everything else.
    fn tone_through(rate: u32, frequency: f64) -> (f64, f64) {
        let mut resampler = Resampler::new(rate).unwrap();
        let mut output = Vec::new();
        for n in 0..rate as usize / 2 {
            let x = (2.0 * std::f64::consts::PI * frequency * n as f64 / f64::from(rate)).sin() as f32 * 0.5;
            resampler.process(x, |y| output.push(y));
        }
        // Skip the start; fit the expected tone at 48 kHz and see what is left over.
        let output = &output[4800..];
        let (mut sin, mut cos) = (0.0, 0.0);
        for (n, &y) in output.iter().enumerate() {
            let w = 2.0 * std::f64::consts::PI * frequency * n as f64 / 48_000.0;
            sin += f64::from(y) * w.sin();
            cos += f64::from(y) * w.cos();
        }
        let len = output.len() as f64;
        let (a, b) = (2.0 * sin / len, 2.0 * cos / len);
        let amplitude = (a * a + b * b).sqrt();
        let residual: f64 = output
            .iter()
            .enumerate()
            .map(|(n, &y)| {
                let w = 2.0 * std::f64::consts::PI * frequency * n as f64 / 48_000.0;
                (f64::from(y) - a * w.sin() - b * w.cos()).powi(2)
            })
            .sum::<f64>()
            / len;
        (amplitude, residual.sqrt())
    }

    #[test]
    fn resampling_keeps_the_voice_band_and_rejects_images() {
        for rate in [16_000, 44_100, 96_000] {
            for frequency in [300.0, 1_000.0, 3_000.0, 6_000.0] {
                let (amplitude, residual) = tone_through(rate, frequency);
                assert!((amplitude - 0.5).abs() < 0.005, "{rate} Hz, {frequency} Hz tone: {amplitude}");
                // Images and aliases at least 50 dB below the tone.
                assert!(residual < 0.5 * 10f64.powf(-50.0 / 20.0), "{rate} Hz, {frequency} Hz: {residual}");
            }
        }
        assert!(Resampler::new(48_000).is_none());
    }

    /// CPU cost per rate: `cargo test -p voice --release -- --ignored --nocapture resampling_cost`.
    #[test]
    #[ignore]
    fn resampling_cost() {
        for rate in [16_000, 44_100, 96_000, 192_000] {
            let mut resampler = Resampler::new(rate).unwrap();
            let start = std::time::Instant::now();
            let mut count = 0usize;
            for n in 0..rate * 10 {
                resampler.process((n as f32 * 0.01).sin(), |_| count += 1);
            }
            let elapsed = start.elapsed() / 10;
            println!("{rate} Hz: {elapsed:?} per second of audio = {:.2}% of one core", elapsed.as_secs_f64() * 100.0);
            assert!((479_000..=480_001).contains(&count), "{rate} Hz: {count}");
        }
    }

    #[test]
    fn downmix_leaves_out_silent_and_inverted_channels() {
        let voice = |n: usize| (n as f32 * 0.05).sin() * 0.3;
        // A stereo interface with the microphone on input 1 only.
        let mut mix = Downmix::new(2, 48_000);
        let mut last = 0.0;
        for n in 0..9_600 {
            last = mix.mix(&[voice(n), 0.000_01]);
        }
        assert!((last - voice(9_599)).abs() < 1e-4, "the live input at full level");
        // Two live channels are averaged, as before.
        let mut mix = Downmix::new(2, 48_000);
        for n in 0..9_600 {
            last = mix.mix(&[voice(n), voice(n) * 0.5]);
        }
        assert!((last - voice(9_599) * 0.75).abs() < 1e-4);
        // An inverted second channel would cancel the voice.
        let mut mix = Downmix::new(2, 48_000);
        for n in 0..9_600 {
            last = mix.mix(&[voice(n), -voice(n)]);
        }
        assert!((last - voice(9_599)).abs() < 1e-4);
        // Silence decides nothing.
        let mut mix = Downmix::new(2, 48_000);
        for _ in 0..9_600 {
            mix.mix(&[0.0, 0.0]);
        }
        assert_eq!(mix.mix(&[1.0, 1.0]), 1.0);
    }
}