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.
//! Audio preferences shared by every call (Settings → Voice & Video): which microphone and
//! speakers, their volumes, echo cancellation and "Voice Isolation" noise suppression, plus
//! the device list and the settings page's mic test.
//!
//! The preferences are process-wide: a running call picks a change up within one audio
//! worker turn (5 ms). Volumes and processing apply to the next 20 ms frame; a new
//! microphone reopens only the microphone, a new speaker reopens both directions.
use crate::Frame;
use cpal::traits::{DeviceTrait, HostTrait};
use std::sync::{
Mutex,
atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
};
/// The microphone, speaker, volume and processing choices of Voice & Video.
#[derive(Clone, Debug, PartialEq)]
pub struct AudioSettings {
/// Microphone ([`AudioDevice::id`]); `None` follows the system default. A chosen device
/// that is unplugged falls back to the default until it returns.
pub input_device: Option<String>,
/// Speakers ([`AudioDevice::id`]); `None` follows the system default.
pub output_device: Option<String>,
/// Microphone gain, `0.0..=1.0` (Discord's Microphone Volume).
pub input_volume: f32,
/// Playback gain, `0.0..=2.0` (Discord's Speaker Volume).
pub output_volume: f32,
/// RNNoise noise suppression on the microphone ("Voice Isolation"); off is "Studio":
/// the microphone as it is.
pub voice_isolation: bool,
/// Echo cancellation (WebRTC's AEC3): what the speakers play is taken back out of the
/// microphone, so the others don't hear themselves.
pub echo_cancellation: bool,
/// Automatic gain control: a quiet microphone raised toward a steady speech level.
pub automatic_gain_control: bool,
/// Play your own microphone (after processing, before the send gate) on the speakers
/// while a call captures it: off while muted or deafened.
pub listen_to_mic: bool,
/// Input sensitivity: the microphone level (dBFS, `-80.0..=0.0`) above which you are sent
/// and shown as speaking. Quieter sound, such as headphone bleed, is dropped.
pub input_sensitivity_db: f32,
}
impl Default for AudioSettings {
fn default() -> Self {
Self {
input_device: None,
output_device: None,
input_volume: 1.0,
output_volume: 1.0,
voice_isolation: false,
echo_cancellation: false,
automatic_gain_control: false,
listen_to_mic: false,
input_sensitivity_db: f32::from(crate::audio::SEND_THRESHOLD_DB),
}
}
}
static SENSITIVITY: std::sync::atomic::AtomicI16 =
std::sync::atomic::AtomicI16::new(crate::audio::SEND_THRESHOLD_DB);
static LISTEN: AtomicBool = AtomicBool::new(false);
static DEVICES: Mutex<(Option<String>, Option<String>)> = Mutex::new((None, None));
/// Bumped when a chosen device changes, so the worker only reopens on real changes.
static DEVICE_REVISION: AtomicU64 = AtomicU64::new(0);
static INPUT_GAIN: AtomicU32 = AtomicU32::new(1.0f32.to_bits());
static OUTPUT_GAIN: AtomicU32 = AtomicU32::new(1.0f32.to_bits());
static ISOLATION: AtomicBool = AtomicBool::new(false);
static ECHO_CANCELLATION: AtomicBool = AtomicBool::new(false);
static GAIN_CONTROL: AtomicBool = AtomicBool::new(false);
fn devices() -> std::sync::MutexGuard<'static, (Option<String>, Option<String>)> {
DEVICES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Apply audio preferences to running and future calls (and a running mic test).
/// Out-of-range or non-finite volumes are clamped (non-finite ones become 100%).
pub fn set_audio_settings(settings: &AudioSettings) {
let gain = |value: f32, max: f32| {
if value.is_finite() {
value.clamp(0.0, max)
} else {
1.0
}
};
INPUT_GAIN.store(gain(settings.input_volume, 1.0).to_bits(), Ordering::Release);
OUTPUT_GAIN.store(gain(settings.output_volume, 2.0).to_bits(), Ordering::Release);
ISOLATION.store(settings.voice_isolation, Ordering::Release);
ECHO_CANCELLATION.store(settings.echo_cancellation, Ordering::Release);
GAIN_CONTROL.store(settings.automatic_gain_control, Ordering::Release);
LISTEN.store(settings.listen_to_mic, Ordering::Release);
let sensitivity = if settings.input_sensitivity_db.is_finite() {
settings.input_sensitivity_db.clamp(-80.0, 0.0).round() as i16
} else {
crate::audio::SEND_THRESHOLD_DB
};
SENSITIVITY.store(sensitivity, Ordering::Release);
let mut chosen = devices();
let wanted = (settings.input_device.clone(), settings.output_device.clone());
if *chosen != wanted {
*chosen = wanted;
DEVICE_REVISION.fetch_add(1, Ordering::AcqRel);
}
}
/// The preferences currently in effect.
pub fn audio_settings() -> AudioSettings {
let (input_device, output_device) = devices().clone();
AudioSettings {
input_device,
output_device,
input_volume: input_gain(),
output_volume: output_gain(),
voice_isolation: ISOLATION.load(Ordering::Acquire),
echo_cancellation: ECHO_CANCELLATION.load(Ordering::Acquire),
automatic_gain_control: GAIN_CONTROL.load(Ordering::Acquire),
listen_to_mic: listen_to_mic(),
input_sensitivity_db: f32::from(send_threshold_db()),
}
}
/// "Video Hardware Acceleration" (on unless turned off).
static VIDEO_HARDWARE: AtomicBool = AtomicBool::new(true);
/// "Video Hardware Acceleration": H.264 encoded and decoded on the GPU. Off, video runs on
/// the CPU instead: a watched 1080p stream then takes about 80 MB less memory (the GPU
/// driver's video device) and about three times the decoding time. Applies to the next
/// stream or camera started or watched.
pub fn set_video_hardware_acceleration(on: bool) {
VIDEO_HARDWARE.store(on, Ordering::Release);
}
pub(crate) fn video_hardware_acceleration() -> bool {
VIDEO_HARDWARE.load(Ordering::Acquire)
}
/// Push to Talk: 0 = off (voice activity), 1 = on and the key is up, 2 = held.
static PUSH_TO_TALK: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Input mode: `None` sends while you speak (voice activity); `Some(held)` is Push to
/// Talk, sending everything while the key is held and nothing otherwise. The mic test
/// keeps using the input sensitivity.
pub fn set_push_to_talk(mode: Option<bool>) {
let value = match mode {
None => 0,
Some(false) => 1,
Some(true) => 2,
};
PUSH_TO_TALK.store(value, Ordering::Release);
}
/// The call's send threshold: the input sensitivity, or with Push to Talk a level
/// nothing reaches (key up) or everything does (key held).
pub(crate) fn call_threshold_db() -> i16 {
match PUSH_TO_TALK.load(Ordering::Acquire) {
1 => i16::MAX,
2 => i16::MIN,
_ => send_threshold_db(),
}
}
/// The send gate's and the speaking indicator's threshold, in dBFS.
pub(crate) fn send_threshold_db() -> i16 {
SENSITIVITY.load(Ordering::Acquire)
}
pub(crate) fn listen_to_mic() -> bool {
LISTEN.load(Ordering::Acquire)
}
pub(crate) fn input_gain() -> f32 {
f32::from_bits(INPUT_GAIN.load(Ordering::Acquire))
}
pub(crate) fn output_gain() -> f32 {
f32::from_bits(OUTPUT_GAIN.load(Ordering::Acquire))
}
pub(crate) fn device_revision() -> u64 {
DEVICE_REVISION.load(Ordering::Acquire)
}
/// (microphone, speakers) chosen; `None` is the system default.
pub(crate) fn wanted_devices() -> (Option<String>, Option<String>) {
devices().clone()
}
/// Scale a frame in place (skipped at unity gain).
pub(crate) fn scale(frame: &mut Frame, gain: f32) {
if gain != 1.0 {
for sample in frame.iter_mut() {
*sample *= gain;
}
}
}
/// Microphone processing before the send gate: echo cancellation (`echo.rs`, about 9 ms of
/// added latency), automatic gain control, "Voice Isolation" (RNNoise at 48 kHz, two 10 ms
/// hops per 20 ms frame, about 10 ms of added latency) and the microphone volume. Each stage
/// only exists while it is on.
#[derive(Default)]
pub(crate) struct Processing {
echo: Option<Box<crate::echo::Canceller>>,
agc: Option<crate::agc::Agc>,
denoiser: Option<Box<nnnoiseless::DenoiseState<'static>>>,
}
impl Processing {
/// 20 ms the speakers played: the echo canceller's reference (ignored while it is off).
pub fn played(&mut self, frame: &Frame) {
if ECHO_CANCELLATION.load(Ordering::Acquire) {
self.echo.get_or_insert_default().played(frame);
}
}
/// New devices: a new echo path and delay for the canceller to learn from scratch.
pub fn reset_echo(&mut self) {
self.echo = None;
}
/// Processes `frame` in place; returns the automatic gain it was raised by (dB), which
/// the send gate discounts so the input sensitivity keeps meaning the microphone's level.
pub fn apply(&mut self, frame: &mut Frame) -> f32 {
// First, as in WebRTC: the gain control and denoiser would change the echo path the
// canceller learns.
if ECHO_CANCELLATION.load(Ordering::Acquire) {
self.echo.get_or_insert_default().capture(frame);
} else {
self.echo = None;
}
// Before noise suppression, which handles soft speech badly.
let raised = if GAIN_CONTROL.load(Ordering::Acquire) {
self.agc.get_or_insert_default().apply(frame)
} else {
self.agc = None;
0.0
};
if ISOLATION.load(Ordering::Acquire) {
const HOP: usize = nnnoiseless::DenoiseState::FRAME_SIZE;
let denoiser = self
.denoiser
.get_or_insert_with(nnnoiseless::DenoiseState::new);
// RNNoise works on 16-bit-scaled samples.
let mut input = [0.0f32; HOP];
let mut output = [0.0f32; HOP];
for hop in frame.chunks_exact_mut(HOP) {
for (scaled, sample) in input.iter_mut().zip(hop.iter()) {
*scaled = sample * 32_768.0;
}
denoiser.process_frame(&mut output, &input);
for (sample, denoised) in hop.iter_mut().zip(output.iter()) {
*sample = if denoised.is_finite() {
(denoised / 32_768.0).clamp(-1.0, 1.0)
} else {
0.0
};
}
}
} else {
self.denoiser = None;
}
scale(frame, input_gain());
raised
}
}
/// One microphone or speaker device.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioDevice {
/// Stable identifier to store in [`AudioSettings`] (survives restarts and replugging).
pub id: String,
/// The name Windows shows, e.g. "Microphone (fifine Microphone)".
pub name: String,
}
/// The system's audio devices.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AudioDevices {
pub inputs: Vec<AudioDevice>,
pub outputs: Vec<AudioDevice>,
/// Names of the current system default microphone and speakers.
pub default_input: Option<String>,
pub default_output: Option<String>,
}
/// List the active microphones and speakers. Blocking (a few to tens of milliseconds of
/// system calls): call it off the UI thread.
pub fn audio_devices() -> AudioDevices {
let host = cpal::default_host();
let name = |device: &cpal::Device| device.description().ok().map(|d| d.name().to_string());
let mut out = AudioDevices {
default_input: host.default_input_device().as_ref().and_then(name),
default_output: host.default_output_device().as_ref().and_then(name),
..AudioDevices::default()
};
let Ok(all) = host.devices() else {
return out;
};
for device in all.take(128) {
let (Ok(id), Some(name)) = (device.id(), name(&device)) else {
continue;
};
let entry = AudioDevice {
id: id.to_string(),
name,
};
if device.supports_input() {
out.inputs.push(entry.clone());
}
if device.supports_output() {
out.outputs.push(entry);
}
}
out
}
/// Voice & Video's "Mic Test": the chosen microphone with the call's processing and send
/// gate, played back on the chosen speakers so you hear what others would. Runs until
/// dropped, or stops by itself once [`MicTest::level_db`] has not been read for two seconds
/// (the settings page closed).
pub struct MicTest {
audio: crate::audio::Audio,
failure: std::sync::Arc<std::sync::OnceLock<&'static str>>,
}
impl MicTest {
pub fn start() -> MicTest {
let failure: std::sync::Arc<std::sync::OnceLock<&'static str>> = Default::default();
let failed = failure.clone();
let audio = crate::audio::Audio::start_test(move |error| {
let _ = failed.set(error);
});
MicTest { audio, failure }
}
/// Microphone level after processing, in dBFS (-100 when silent or not open yet).
pub fn level_db(&self) -> f32 {
self.audio.test_level()
}
/// Still capturing (false after a failure or the idle stop).
pub fn is_running(&self) -> bool {
self.failure.get().is_none() && self.audio.running()
}
/// Why the test cannot hear anything, if it cannot.
pub fn error(&self) -> Option<&'static str> {
self.failure.get().copied().or_else(|| {
self.audio
.microphone_missing()
.then_some("No microphone is available")
})
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The preferences are process-wide; these tests change them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
#[test]
fn preferences_round_trip_and_clamp() {
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let before = device_revision();
set_audio_settings(&AudioSettings {
input_device: Some("wasapi:mic".into()),
output_device: None,
input_volume: 3.0,
output_volume: f32::NAN,
voice_isolation: true,
echo_cancellation: true,
automatic_gain_control: true,
listen_to_mic: true,
input_sensitivity_db: -200.0,
});
let now = audio_settings();
assert!(now.listen_to_mic && now.echo_cancellation);
assert_eq!(now.input_sensitivity_db, -80.0);
assert_eq!(now.input_device.as_deref(), Some("wasapi:mic"));
assert_eq!((now.input_volume, now.output_volume), (1.0, 1.0));
assert!(now.voice_isolation && now.automatic_gain_control);
assert!(device_revision() > before);
// Changing only volumes keeps the device revision (no device reopen).
let revision = device_revision();
set_audio_settings(&AudioSettings {
output_volume: 1.5,
..now.clone()
});
assert_eq!(device_revision(), revision);
assert_eq!(output_gain(), 1.5);
set_audio_settings(&AudioSettings::default());
}
#[test]
fn processing_scales_and_denoises_finitely() {
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut processing = Processing::default();
INPUT_GAIN.store(0.5f32.to_bits(), Ordering::Release);
let mut frame = [0.4f32; 960];
processing.apply(&mut frame);
assert!(frame.iter().all(|s| (*s - 0.2).abs() < 1e-6));
ISOLATION.store(true, Ordering::Release);
let mut noisy: Frame = std::array::from_fn(|i| ((i * 7919) % 200) as f32 / 1000.0 - 0.1);
for _ in 0..10 {
processing.apply(&mut noisy);
}
assert!(noisy.iter().all(|s| s.is_finite() && s.abs() <= 1.0));
assert!(processing.denoiser.is_some());
ISOLATION.store(false, Ordering::Release);
processing.apply(&mut noisy);
assert!(processing.denoiser.is_none(), "Studio frees the denoiser");
INPUT_GAIN.store(1.0f32.to_bits(), Ordering::Release);
}
#[test]
fn echo_is_cancelled_first_and_freed_when_off() {
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (far, echo) = crate::echo::test_call(3, 60);
let frame = |samples: &[f32], k: usize| -> Frame { samples[k * 960..(k + 1) * 960].try_into().unwrap() };
let mut processing = Processing::default();
// Off: nothing is kept for the speakers' audio, and the echo goes through.
processing.played(&frame(&far, 0));
assert!(processing.echo.is_none());
ECHO_CANCELLATION.store(true, Ordering::Release);
let (mut heard, mut cleaned) = (0.0f64, 0.0f64);
for k in 0..far.len() / 960 {
processing.played(&frame(&far, k));
let mut mic = frame(&echo, k);
processing.apply(&mut mic);
if k >= 100 {
heard += frame(&echo, k).iter().map(|s| f64::from(*s).powi(2)).sum::<f64>();
cleaned += mic.iter().map(|s| f64::from(*s).powi(2)).sum::<f64>();
}
}
assert!(10.0 * (heard / cleaned).log10() > 25.0, "the echo should be gone after two seconds");
// A new device starts the canceller over; turning it off frees it.
processing.reset_echo();
assert!(processing.echo.is_none());
processing.played(&frame(&far, 0));
assert!(processing.echo.is_some());
ECHO_CANCELLATION.store(false, Ordering::Release);
let mut mic = frame(&echo, 0);
processing.apply(&mut mic);
assert!(processing.echo.is_none());
assert_eq!(mic, frame(&echo, 0), "off leaves the microphone as it is");
}
/// This machine's device list as RustCord sees it:
/// `cargo test -p voice --lib -- --ignored --nocapture list_devices`.
#[test]
#[ignore]
fn list_devices() {
let start = std::time::Instant::now();
let devices = audio_devices();
println!("listed in {:?}", start.elapsed());
println!("default input: {:?}", devices.default_input);
println!("default output: {:?}", devices.default_output);
for (kind, list) in [("input", &devices.inputs), ("output", &devices.outputs)] {
for device in list {
println!("{kind}: {} [{}]", device.name, device.id);
}
}
}
/// CPU cost of Voice Isolation: `cargo test -p voice --release -- --ignored --nocapture rnnoise_cost`.
#[test]
#[ignore]
fn rnnoise_cost() {
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
ISOLATION.store(true, Ordering::Release);
let mut processing = Processing::default();
// A tone over noise, fresh each frame (silence would take RNNoise's shortcut).
let input: Frame = std::array::from_fn(|i| (i as f32 * 0.05).sin() * 0.2 + ((i * 7919) % 200) as f32 / 4000.0);
let frames = 500; // 10 s of audio
let start = std::time::Instant::now();
for _ in 0..frames {
let mut frame = input;
processing.apply(&mut frame);
}
let per_frame = start.elapsed() / frames;
ISOLATION.store(false, Ordering::Release);
println!("RNNoise: {per_frame:?} per 20 ms frame = {:.2}% of one core", per_frame.as_secs_f64() / 0.02 * 100.0);
}
/// CPU cost of Echo Cancellation (the played audio and the microphone, while the far end
/// talks): `cargo test -p voice --release -- --ignored --nocapture echo_cancellation_cost`.
#[test]
#[ignore]
fn echo_cancellation_cost() {
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
ECHO_CANCELLATION.store(true, Ordering::Release);
let mut processing = Processing::default();
let (far, echo) = crate::echo::test_call(10, 80);
let frames: Vec<(Frame, Frame)> = (0..far.len() / 960)
.map(|k| {
let range = k * 960..(k + 1) * 960;
(far[range.clone()].try_into().unwrap(), echo[range].try_into().unwrap())
})
.collect();
let start = std::time::Instant::now();
for (played, heard) in &frames {
processing.played(played);
let mut frame = *heard;
processing.apply(&mut frame);
}
let per_frame = start.elapsed() / frames.len() as u32;
ECHO_CANCELLATION.store(false, Ordering::Release);
println!("Echo cancellation: {per_frame:?} per 20 ms frame = {:.2}% of one core", per_frame.as_secs_f64() / 0.02 * 100.0);
}
}