Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
// RustCord addition (not from Serein); MIT OR Apache-2.0 like the rest of the crate.
//! "Echo Cancellation": what the speakers play is taken back out of the microphone, so the
//! others in the call don't hear themselves. This is WebRTC's AEC3, the canceller behind
//! Discord's own setting, through sonora, a pure-Rust port of WebRTC's audio processing.
//!
//! The reference is what the speaker callback actually played (the call, Go Live audio and
//! "Listen to Microphone", after the speaker volume), 20 ms at a time (`audio.rs`). The
//! worker hands over each turn's played frames before that turn's microphone frames, the
//! order the devices produced them in. AEC3 finds the delay between the two streams itself
//! (device buffers, Bluetooth: up to about 450 ms) and follows it when it changes.
//!
//! It works on 10 ms at 48 kHz, split into three bands as WebRTC does on desktop, and adds
//! about 9 ms to the microphone path.
use crate::Frame;
use sonora::config::{EchoCanceller, MaxProcessingRate, Pipeline};
use sonora::{AudioProcessing, Config, StreamConfig};
/// 10 ms at 48 kHz: the canceller's frame.
const HOP: usize = 480;
pub(crate) struct Canceller {
apm: AudioProcessing,
/// The 10 ms being processed: sonora reads and writes separate buffers.
scratch: [f32; HOP],
}
impl Default for Canceller {
fn default() -> Self {
let config = Config {
pipeline: Pipeline {
// The call's own rate: no resampling inside (32 kHz cost more).
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
multi_channel_render: false,
multi_channel_capture: false,
..Pipeline::default()
},
// Includes the high-pass filter on the microphone that AEC3 expects.
echo_canceller: Some(EchoCanceller::default()),
..Config::default()
};
let mono = StreamConfig::new(48_000, 1);
Self {
apm: AudioProcessing::builder()
.config(config)
.capture_config(mono)
.render_config(mono)
.build(),
scratch: [0.0; HOP],
}
}
}
impl Canceller {
/// 20 ms the speakers played.
pub fn played(&mut self, frame: &Frame) {
for hop in frame.chunks_exact(HOP) {
// Nothing changes the played audio, so its copy is discarded. (Only an invalid
// stream format fails, and this one is fixed.)
let _ = self.apm.process_render_f32(&[hop], &mut [&mut self.scratch]);
}
}
/// 20 ms of microphone, with the echo taken out in place.
pub fn capture(&mut self, frame: &mut Frame) {
for hop in frame.chunks_exact_mut(HOP) {
self.scratch.copy_from_slice(hop);
let _ = self.apm.process_capture_f32(&[&self.scratch], &mut [hop]);
}
}
}
/// A test call: `seconds` of something like speech from the far end (noise through a 500 Hz
/// resonance, in syllable-rate bursts) and its echo `delay_ms` later, through a speaker,
/// room and microphone path with two reflections.
#[cfg(test)]
pub(crate) fn test_call(seconds: usize, delay_ms: usize) -> (Vec<f32>, Vec<f32>) {
let total = 48_000 * seconds;
let mut seed = 0x1234_5678_9abc_def1u64;
let mut noise = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0
};
let (radius, angle) = (0.98f32, 2.0 * std::f32::consts::PI * 500.0 / 48_000.0);
let (mut y1, mut y2) = (0.0f32, 0.0f32);
let far: Vec<f32> = (0..total)
.map(|n| {
let y = noise() + 2.0 * radius * angle.cos() * y1 - radius * radius * y2;
(y2, y1) = (y1, y);
let syllables = 0.5 + 0.5 * (n as f32 * 2.0 * std::f32::consts::PI * 4.0 / 48_000.0).sin();
y * 0.02 * syllables * syllables
})
.collect();
let delay = 48 * delay_ms;
let at = |n: usize, back: usize| n.checked_sub(back).map_or(0.0, |i| far[i]);
let echo = (0..total)
.map(|n| 0.1 * (at(n, delay) + 0.4 * at(n, delay + 48 * 7) + 0.1 * at(n, delay + 48 * 23)))
.collect();
(far, echo)
}
#[cfg(test)]
mod tests {
use super::*;
fn frame(samples: &[f32], k: usize) -> Frame {
samples[k * 960..(k + 1) * 960].try_into().unwrap()
}
fn energy_db(samples: &[f32]) -> f64 {
let energy: f64 = samples.iter().map(|s| f64::from(*s).powi(2)).sum();
10.0 * (energy / samples.len() as f64).max(1e-20).log10()
}
#[test]
fn removes_the_echo_and_keeps_your_voice() {
// Four seconds of the far end talking, then one of you talking alone (a 1 kHz tone).
let (far, echo) = test_call(5, 80);
let voice = |n: usize| 0.05 * (2.0 * std::f32::consts::PI * 1_000.0 * n as f32 / 48_000.0).sin();
let mic: Vec<f32> = (0..far.len()).map(|n| if n < 4 * 48_000 { echo[n] } else { voice(n) }).collect();
let mut canceller = Canceller::default();
let mut out = Vec::with_capacity(mic.len());
for k in 0..far.len() / 960 {
let played = if k < 200 { frame(&far, k) } else { [0.0; 960] };
canceller.played(&played);
let mut heard = frame(&mic, k);
canceller.capture(&mut heard);
out.extend_from_slice(&heard);
}
let second = 3 * 48_000..4 * 48_000;
let removed = energy_db(&mic[second.clone()]) - energy_db(&out[second]);
assert!(removed > 25.0, "the echo is only {removed:.1} dB quieter");
let alone = 4 * 48_000 + 4_800..5 * 48_000;
let kept = energy_db(&out[alone.clone()]) - energy_db(&mic[alone]);
assert!(kept.abs() < 1.0, "your voice changed by {kept:.1} dB");
}
#[test]
fn finds_a_long_echo_delay() {
// A Bluetooth headset: the echo comes back 300 ms later.
let (far, echo) = test_call(4, 300);
let mut canceller = Canceller::default();
let mut out = Vec::with_capacity(echo.len());
for k in 0..far.len() / 960 {
canceller.played(&frame(&far, k));
let mut heard = frame(&echo, k);
canceller.capture(&mut heard);
out.extend_from_slice(&heard);
}
let second = 3 * 48_000..4 * 48_000;
let removed = energy_db(&echo[second.clone()]) - energy_db(&out[second]);
assert!(removed > 25.0, "the echo is only {removed:.1} dB quieter");
}
}