tsc-audio: echo cancellation, noise suppression, gain control, VAD, client volume, device hotplug

- process: Processor on sonora (pure Rust WebRTC APM: AEC3, NS, AGC2,
  high-pass) with serde ProcessingSettings; far end fed from what is played
- vad: level gate with hangover, optional RNN speech probability
- mixer: Mixer wraps the vendored AudioHandler with per-client volume/mute
- settings: AudioSettings bundles transmit mode, processing, VAD, devices
- device: stable device ids, default flags, loss detection through the
  error callback, Managed reopen/fallback policy
- tests: synthetic echo >= 10 dB, noise suppression keeps tone bursts,
  per-client gain, one-hour drift simulation at +-200 ppm
- dev profile optimises the sonora crates (real-time in debug builds)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 19:48:23 +00:00
1 parent 81ecb53100
commit b3737c00a6
12 files changed
+1716 -26

No files matched your search

+7
View File
@@ -19,10 +19,17 @@ hound = "3.5.1"
opus2 = "0.4"
rtrb = { version = "0.4.0", optional = true }
rubato = "5.0.0"
serde = { version = "1.0.228", features = ["derive"] }
sonora = "0.2"
sonora-agc2 = "0.2"
sonora-simd = "0.2"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
+456 -20
View File
@@ -2,42 +2,140 @@
//!
//! The device callbacks only move samples through lock-free ring buffers; all
//! processing happens on the caller's side.
//!
//! Devices are identified by cpal's stable device id (`host:device`, e.g.
//! `alsa:hw:1,0`), which survives restarts and replugging. A stream notices
//! when its device goes away through cpal's error callback
//! ([`Capture::is_lost`]); [`Managed`] reopens it, on the default device when
//! the selected one is gone, and moves back when it returns.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{ErrorKind, SampleFormat};
use rtrb::{Consumer, Producer, RingBuffer};
use tracing::warn;
use tracing::{debug, warn};
use crate::{Error, Result};
/// A device as shown in settings.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeviceInfo {
/// Stable id to store in settings (`AudioSettings::input_device`).
pub id: String,
/// Human-readable name.
pub name: String,
pub input: bool,
pub output: bool,
/// The system's default input device.
pub default_input: bool,
/// The system's default output device.
pub default_output: bool,
}
fn device_error(e: impl std::fmt::Display) -> Error {
Error::Device(e.to_string())
}
fn device_name(device: &cpal::Device) -> String {
device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| device.to_string())
}
fn device_id(device: &cpal::Device) -> Option<String> {
device.id().ok().map(|id| id.to_string())
}
/// All devices of the default host.
pub fn list_devices() -> Result<Vec<DeviceInfo>> {
let host = cpal::default_host();
let default_input = host.default_input_device().and_then(|d| device_id(&d));
let default_output = host.default_output_device().and_then(|d| device_id(&d));
let devices = host.devices().map_err(device_error)?;
Ok(devices
.map(|d| DeviceInfo {
name: d.description().map(|d| d.name().to_string()).unwrap_or_default(),
input: d.supports_input(),
output: d.supports_output(),
.filter_map(|d| {
let id = device_id(&d)?;
Some(DeviceInfo {
name: device_name(&d),
input: d.supports_input(),
output: d.supports_output(),
default_input: default_input.as_deref() == Some(id.as_str()),
default_output: default_output.as_deref() == Some(id.as_str()),
id,
})
})
.collect())
}
/// Devices that can record.
pub fn input_devices() -> Result<Vec<DeviceInfo>> {
Ok(list_devices()?.into_iter().filter(|d| d.input).collect())
}
/// Devices that can play.
pub fn output_devices() -> Result<Vec<DeviceInfo>> {
Ok(list_devices()?.into_iter().filter(|d| d.output).collect())
}
/// The device with this id, or the default one for `None`.
fn find_device(id: Option<&str>, input: bool) -> Result<cpal::Device> {
let host = cpal::default_host();
let kind = if input { "input" } else { "output" };
let Some(id) = id else {
let device = if input { host.default_input_device() } else { host.default_output_device() };
return device.ok_or_else(|| Error::Device(format!("no {kind} device")));
};
let parsed = id.parse().map_err(device_error)?;
host.device_by_id(&parsed).ok_or_else(|| Error::Device(format!("{kind} device {id} not found")))
}
/// Whether a device with this id is present.
pub fn device_exists(id: &str) -> bool {
id.parse().ok().and_then(|id| cpal::default_host().device_by_id(&id)).is_some()
}
/// Errors after which a stream will not recover by itself.
fn is_fatal(kind: ErrorKind) -> bool {
!matches!(kind, ErrorKind::DeviceChanged | ErrorKind::Xrun | ErrorKind::RealtimeDenied)
}
/// The error callback: log, and flag the stream lost on fatal errors.
fn error_callback(what: &'static str, lost: Arc<AtomicBool>) -> impl FnMut(cpal::Error) + Send {
move |error| {
if is_fatal(error.kind()) {
warn!(%error, "{what} stream lost");
lost.store(true, Ordering::Relaxed);
} else {
debug!(%error, "{what} stream");
}
}
}
/// The default config, but with f32 samples if the device offers them at the
/// same rate (streams here are f32 only).
fn f32_config(
default: cpal::SupportedStreamConfig,
supported: impl Iterator<Item = cpal::SupportedStreamConfigRange>,
) -> cpal::StreamConfig {
if default.sample_format() == SampleFormat::F32 {
return default.config();
}
let rate = default.sample_rate();
supported
.filter(|r| r.sample_format() == SampleFormat::F32)
.find_map(|r| r.try_with_sample_rate(rate))
.map(|c| c.config())
.unwrap_or_else(|| default.config())
}
/// Running capture stream. Samples are interleaved at the device's rate.
pub struct Capture {
_stream: cpal::Stream,
consumer: Consumer<f32>,
lost: Arc<AtomicBool>,
id: Option<String>,
name: String,
pub channels: usize,
pub rate: u32,
}
@@ -45,14 +143,21 @@ pub struct Capture {
impl Capture {
/// Open the default input device, buffering up to `buffer_ms` of audio.
pub fn open_default(buffer_ms: u32) -> Result<Self> {
let device = cpal::default_host()
.default_input_device()
.ok_or_else(|| Error::Device("no input device".into()))?;
let config = device.default_input_config().map_err(device_error)?.config();
Self::open(None, buffer_ms)
}
/// Open the input device with this id (see [`DeviceInfo::id`]), or the
/// default one for `None`.
pub fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
let device = find_device(id, true)?;
let default = device.default_input_config().map_err(device_error)?;
let supported = device.supported_input_configs().map_err(device_error)?;
let config = f32_config(default, supported);
let channels = config.channels as usize;
let rate = config.sample_rate;
let (mut producer, consumer) =
RingBuffer::new((rate * buffer_ms / 1000) as usize * channels);
let lost = Arc::new(AtomicBool::new(false));
let stream = device
.build_input_stream(
config,
@@ -62,12 +167,20 @@ impl Capture {
chunk.fill_from_iter(data[..n].iter().copied());
}
},
|error| warn!(%error, "capture stream error"),
error_callback("capture", lost.clone()),
None,
)
.map_err(device_error)?;
stream.play().map_err(device_error)?;
Ok(Self { _stream: stream, consumer, channels, rate })
Ok(Self {
_stream: stream,
consumer,
lost,
id: device_id(&device),
name: device_name(&device),
channels,
rate,
})
}
/// Move everything captured so far into `out`.
@@ -77,26 +190,45 @@ impl Capture {
out.extend(chunk);
}
}
/// The device went away or the stream broke; reopen it.
pub fn is_lost(&self) -> bool {
self.lost.load(Ordering::Relaxed)
}
pub fn name(&self) -> &str {
&self.name
}
}
/// Running playback stream. Write interleaved samples at the device's rate.
pub struct Playback {
_stream: cpal::Stream,
producer: Producer<f32>,
lost: Arc<AtomicBool>,
id: Option<String>,
name: String,
capacity: usize,
pub channels: usize,
pub rate: u32,
}
impl Playback {
pub fn open_default(buffer_ms: u32) -> Result<Self> {
let device = cpal::default_host()
.default_output_device()
.ok_or_else(|| Error::Device("no output device".into()))?;
let config = device.default_output_config().map_err(device_error)?.config();
Self::open(None, buffer_ms)
}
/// Open the output device with this id, or the default one for `None`.
pub fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
let device = find_device(id, false)?;
let default = device.default_output_config().map_err(device_error)?;
let supported = device.supported_output_configs().map_err(device_error)?;
let config = f32_config(default, supported);
let channels = config.channels as usize;
let rate = config.sample_rate;
let (producer, mut consumer) =
RingBuffer::<f32>::new((rate * buffer_ms / 1000) as usize * channels);
let capacity = (rate * buffer_ms / 1000) as usize * channels;
let (producer, mut consumer) = RingBuffer::<f32>::new(capacity);
let lost = Arc::new(AtomicBool::new(false));
let stream = device
.build_output_stream(
config,
@@ -110,12 +242,21 @@ impl Playback {
// Underrun: play silence.
data[n..].fill(0.0);
},
|error| warn!(%error, "playback stream error"),
error_callback("playback", lost.clone()),
None,
)
.map_err(device_error)?;
stream.play().map_err(device_error)?;
Ok(Self { _stream: stream, producer, channels, rate })
Ok(Self {
_stream: stream,
producer,
lost,
id: device_id(&device),
name: device_name(&device),
capacity,
channels,
rate,
})
}
/// Queue samples; returns how many fit into the buffer.
@@ -131,4 +272,299 @@ impl Playback {
pub fn free(&self) -> usize {
self.producer.slots()
}
/// Samples (all channels) queued and not yet handed to the device.
pub fn queued(&self) -> usize {
self.capacity - self.producer.slots()
}
/// Queued audio in milliseconds.
pub fn queued_ms(&self) -> u32 {
(self.queued() / self.channels.max(1)) as u32 * 1000 / self.rate.max(1)
}
/// The device went away or the stream broke; reopen it.
pub fn is_lost(&self) -> bool {
self.lost.load(Ordering::Relaxed)
}
pub fn name(&self) -> &str {
&self.name
}
}
/// What [`Managed`] needs from a stream; implemented by [`Capture`] and
/// [`Playback`].
pub trait DeviceStream: Sized {
fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self>;
fn is_lost(&self) -> bool;
/// Id of the device actually opened.
fn device_id(&self) -> Option<&str>;
fn name(&self) -> &str;
fn device_exists(id: &str) -> bool;
}
impl DeviceStream for Capture {
fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
Capture::open(id, buffer_ms)
}
fn is_lost(&self) -> bool {
Capture::is_lost(self)
}
fn device_id(&self) -> Option<&str> {
self.id.as_deref()
}
fn name(&self) -> &str {
&self.name
}
fn device_exists(id: &str) -> bool {
device_exists(id)
}
}
impl DeviceStream for Playback {
fn open(id: Option<&str>, buffer_ms: u32) -> Result<Self> {
Playback::open(id, buffer_ms)
}
fn is_lost(&self) -> bool {
Playback::is_lost(self)
}
fn device_id(&self) -> Option<&str> {
self.id.as_deref()
}
fn name(&self) -> &str {
&self.name
}
fn device_exists(id: &str) -> bool {
device_exists(id)
}
}
/// What happened to a [`Managed`] stream, for the user.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviceEvent {
/// Opened a device. `fallback` is set when it is the default device
/// because the selected one is missing.
Opened { name: String, fallback: bool },
/// The open device went away.
Lost { name: String },
/// No device could be opened; retrying in the background. Reported once
/// until a device opens again.
Unavailable(String),
}
/// Retry opening a device this often while none is open.
pub const RETRY_INTERVAL: Duration = Duration::from_secs(2);
/// While on the default device instead of the selected one, look for the
/// selected one this often.
pub const RETURN_INTERVAL: Duration = Duration::from_secs(5);
/// Keeps a stream open across device loss and selection changes. Call
/// [`poll`](Self::poll) regularly from the audio loop.
pub struct Managed<S> {
stream: Option<S>,
wanted: Option<String>,
buffer_ms: u32,
retry_at: Instant,
return_at: Instant,
failing: bool,
}
impl<S: DeviceStream> Managed<S> {
/// Nothing is opened until the first [`poll`](Self::poll).
pub fn new(wanted: Option<String>, buffer_ms: u32) -> Self {
let now = Instant::now();
Self { stream: None, wanted, buffer_ms, retry_at: now, return_at: now, failing: false }
}
/// Select another device (`None`: the default); reopens on the next poll.
pub fn select(&mut self, wanted: Option<String>) {
if wanted != self.wanted {
self.wanted = wanted;
self.stream = None;
self.retry_at = Instant::now();
}
}
pub fn wanted(&self) -> Option<&str> {
self.wanted.as_deref()
}
pub fn stream(&mut self) -> Option<&mut S> {
self.stream.as_mut()
}
/// Whether the stream was replaced since the caller last saw it matters
/// for resamplers; callers compare [`DeviceEvent::Opened`].
pub fn poll(&mut self) -> Option<DeviceEvent> {
self.poll_at(Instant::now())
}
fn poll_at(&mut self, now: Instant) -> Option<DeviceEvent> {
if let Some(stream) = &self.stream {
if stream.is_lost() {
let name = stream.name().to_string();
self.stream = None;
self.retry_at = now;
return Some(DeviceEvent::Lost { name });
}
// On the default device although another one is selected: move
// back once it is present again.
let on_fallback = self.wanted.is_some() && stream.device_id() != self.wanted.as_deref();
if !on_fallback || now < self.return_at {
return None;
}
self.return_at = now + RETURN_INTERVAL;
match self.wanted.as_deref() {
Some(id) if S::device_exists(id) => self.stream = None,
_ => return None,
}
}
if now < self.retry_at {
return None;
}
let wanted = self.wanted.clone();
let opened = match S::open(wanted.as_deref(), self.buffer_ms) {
Ok(s) => Ok((s, false)),
Err(e) if wanted.is_some() => {
S::open(None, self.buffer_ms).map(|s| (s, true)).map_err(|default_error| {
Error::Device(format!("{e}; default device: {default_error}"))
})
}
Err(e) => Err(e),
};
match opened {
Ok((stream, fallback)) => {
let name = stream.name().to_string();
self.stream = Some(stream);
self.failing = false;
self.return_at = now + RETURN_INTERVAL;
Some(DeviceEvent::Opened { name, fallback })
}
Err(e) => {
self.retry_at = now + RETRY_INTERVAL;
let first = !self.failing;
self.failing = true;
first.then(|| DeviceEvent::Unavailable(e.to_string()))
}
}
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::collections::HashSet;
use super::*;
thread_local! {
/// Plugged-in fake devices; "default" is the system default.
static PLUGGED: RefCell<HashSet<String>> = RefCell::new(HashSet::new());
}
fn plug(id: &str, on: bool) {
PLUGGED.with(|p| {
let mut p = p.borrow_mut();
if on { p.insert(id.into()) } else { p.remove(id) }
});
}
fn plugged(id: &str) -> bool {
PLUGGED.with(|p| p.borrow().contains(id))
}
struct Fake {
id: String,
}
impl DeviceStream for Fake {
fn open(id: Option<&str>, _: u32) -> Result<Self> {
let id = id.unwrap_or("default");
if plugged(id) {
Ok(Fake { id: id.into() })
} else {
Err(Error::Device(format!("{id} not found")))
}
}
fn is_lost(&self) -> bool {
!plugged(&self.id)
}
fn device_id(&self) -> Option<&str> {
Some(&self.id)
}
fn name(&self) -> &str {
&self.id
}
fn device_exists(id: &str) -> bool {
plugged(id)
}
}
fn opened(name: &str, fallback: bool) -> Option<DeviceEvent> {
Some(DeviceEvent::Opened { name: name.into(), fallback })
}
#[test]
fn fatal_errors() {
assert!(is_fatal(ErrorKind::DeviceNotAvailable));
assert!(is_fatal(ErrorKind::StreamInvalidated));
assert!(!is_fatal(ErrorKind::Xrun));
assert!(!is_fatal(ErrorKind::DeviceChanged));
}
/// Headset selected, unplugged mid-call, plugged back in.
#[test]
fn reopens_and_falls_back() {
plug("default", true);
plug("headset", true);
let mut m = Managed::<Fake>::new(Some("headset".into()), 100);
let t0 = Instant::now();
assert_eq!(m.poll_at(t0), opened("headset", false));
assert_eq!(m.poll_at(t0), None);
plug("headset", false);
assert_eq!(m.poll_at(t0), Some(DeviceEvent::Lost { name: "headset".into() }));
assert_eq!(m.poll_at(t0), opened("default", true));
assert_eq!(m.stream().unwrap().id, "default");
// Back only after the return interval.
plug("headset", true);
assert_eq!(m.poll_at(t0 + Duration::from_secs(1)), None);
assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("headset", false));
// Selecting the default device switches right away.
m.select(None);
assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("default", false));
}
/// Nothing plugged in: one report, retries every interval, recovers.
#[test]
fn retries_when_unavailable() {
plug("default", false);
let mut m = Managed::<Fake>::new(None, 100);
let t0 = Instant::now();
assert!(matches!(m.poll_at(t0), Some(DeviceEvent::Unavailable(_))));
assert!(m.stream().is_none());
plug("default", true);
// Not before the retry interval, and no repeated report.
assert_eq!(m.poll_at(t0 + Duration::from_millis(500)), None);
assert_eq!(m.poll_at(t0 + RETRY_INTERVAL), opened("default", false));
plug("default", false);
assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Lost { .. })));
assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Unavailable(_))));
assert_eq!(m.poll_at(t0 + RETRY_INTERVAL * 2), None);
}
/// Opening real devices needs hardware; just make sure enumeration does
/// not fail or panic without any.
#[test]
fn enumeration_without_hardware() {
if let Ok(devices) = list_devices() {
for d in devices {
assert!(!d.id.is_empty());
}
}
assert!(!device_exists("no-such-host:nothing"));
}
}
+15 -6
View File
@@ -5,14 +5,22 @@
//! - [`framer`]: slice an arbitrary sample stream into codec frames
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
//! - [`wav`]: WAV file input/output
//! - [`Mixer`]: per-client jitter buffer, decoder and mixer (from the vendored
//! `tsclientlib::audio::AudioHandler`)
//! - `device` (feature `device`): capture and playback through cpal
//! - [`process`]: echo cancellation, noise suppression and gain control
//! - [`vad`]: voice activity detection
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
//! vendored `tsclientlib::audio::AudioHandler`)
//! - [`settings`]: all user audio settings in one serde struct
//! - `device` (feature `device`): capture and playback through cpal, device
//! lists and loss detection
pub mod encode;
pub mod framer;
pub mod mixer;
pub mod pcm;
pub mod process;
pub mod resample;
pub mod settings;
pub mod vad;
pub mod wav;
#[cfg(feature = "device")]
@@ -20,10 +28,11 @@ pub mod device;
pub use encode::{VoiceCodec, VoiceEncoder};
pub use framer::Framer;
pub use mixer::Mixer;
pub use process::{ProcessingSettings, Processor};
pub use settings::AudioSettings;
pub use tsclientlib::audio::AudioHandler;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
pub type Mixer = AudioHandler<tsclientlib::ClientId>;
pub use vad::{Vad, VadSettings};
#[derive(Debug, thiserror::Error)]
pub enum Error {
+219
View File
@@ -0,0 +1,219 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! sender it keeps a queue of Opus packets and adapts its length:
//!
//! - a new talker starts after a pre-buffer derived from the queue lengths of
//! the other talkers (none for the first one);
//! - a queue that underruns plays Opus packet-loss concealment for the
//! missing packet (one inserted frame) and drops the talker after three
//! frames in a row without data, so a slow sender never lets latency grow;
//! - when the smallest queue length over the last 255 decoded packets exceeds
//! its spread (a fast sender, or a jitter spike that passed), every 100th
//! sample of the decoded frame is dropped (1 % faster playback) until the
//! surplus is gone; above 0.5 s the queue is truncated outright.
//!
//! So sender clock drift is absorbed by occasional 1 % speed-ups (fast
//! sender) or concealment frames (slow sender) and latency stays bounded; the
//! `drift` integration test simulates an hour at ±200 ppm to check that.
use std::collections::{HashMap, HashSet};
use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
/// Loudest per-client volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
/// Output is interleaved stereo at 48 kHz.
#[derive(Default)]
pub struct Mixer {
handler: AudioHandler<ClientId>,
volumes: HashMap<ClientId, f32>,
muted: HashSet<ClientId>,
}
impl Mixer {
pub fn new() -> Self {
Self::default()
}
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
/// just started talking. Late, duplicate and malformed packets are
/// errors; on UDP they are expected and can be ignored.
pub fn handle_packet(
&mut self,
id: ClientId,
packet: InAudioBuf,
) -> Result<Option<ClientId>, QueueError> {
self.handler.handle_packet(id, packet)
}
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
/// (not cleared first), each scaled by its volume. Returns the clients
/// that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
for (id, queue) in self.handler.get_mut_queues() {
queue.volume = if self.muted.contains(id) {
0.0
} else {
self.volumes.get(id).copied().unwrap_or(1.0)
};
}
// Muted talkers are still decoded so their queues stay in sync.
self.handler.fill_buffer(buf)
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the client stops and starts talking again.
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
if volume == 1.0 {
self.volumes.remove(&id);
} else {
self.volumes.insert(id, volume);
}
}
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
self.set_volume(id, 10f32.powf(db / 20.0));
}
pub fn volume(&self, id: ClientId) -> f32 {
self.volumes.get(&id).copied().unwrap_or(1.0)
}
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
if muted {
self.muted.insert(id);
} else {
self.muted.remove(&id);
}
}
pub fn is_muted(&self, id: ClientId) -> bool {
self.muted.contains(&id)
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
self.volumes.remove(&id);
self.muted.remove(&id);
self.handler.get_mut_queues().remove(&id);
}
/// Clients with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
self.handler.get_queues().keys().copied()
}
/// Drop all queues; volumes and mutes are kept.
pub fn reset(&mut self) {
self.handler.reset();
}
/// The underlying jitter buffer.
pub fn handler(&self) -> &AudioHandler<ClientId> {
&self.handler
}
}
impl std::fmt::Debug for Mixer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Mixer")
.field("talkers", &self.handler.get_queues().len())
.field("volumes", &self.volumes)
.field("muted", &self.muted)
.finish()
}
}
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
use super::*;
use crate::VoiceEncoder;
use crate::encode::VoiceCodec;
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
}
/// Two clients send tones at the same level; after setting volumes the
/// mix carries each at its own gain, and a muted one not at all.
#[test]
fn volume_per_client() {
let (a, b) = (ClientId(3), ClientId(4));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 2.0, 0.2);
let tone_b = pcm::sine(1300.0, 2.0, 0.2);
let mut mixer = Mixer::new();
mixer.set_volume(a, 0.25);
mixer.set_volume_db(b, 6.0);
assert!((mixer.volume(b) - 1.995).abs() < 0.01);
let mut out = Vec::new();
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
for (i, (fa, fb)) in frames.enumerate() {
let id = i as u16;
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
if i == 0 {
assert_eq!(started.unwrap(), Some(a));
}
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
assert_eq!(mixer.talkers().count(), 2);
let tail = &out[out.len() / 2..];
let power = |f| pcm::goertzel_power(tail, f, SAMPLE_RATE);
// Amplitude ratio 0.25 / 2 = 1/8, power ratio 1/64 (-18 dB).
let ratio_db = 10.0 * (power(500.0) / power(1300.0)).log10();
assert!((ratio_db + 18.0).abs() < 1.5, "ratio {ratio_db} dB");
// Mute b: only a remains.
mixer.set_muted(b, true);
let mut out = Vec::new();
for i in 0..20u16 {
let id = 100 + i;
let fa = &tone_a[..FRAME_SAMPLES];
let fb = &tone_b[..FRAME_SAMPLES];
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
let tail = &out[out.len() / 2..];
assert!(pcm::goertzel_power(tail, 1300.0, SAMPLE_RATE) < 1e-6);
assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4);
}
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
let id = ClientId(9);
mixer.set_volume(id, 100.0);
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
mixer.set_volume(id, -1.0);
assert_eq!(mixer.volume(id), 0.0);
mixer.set_volume(id, f32::NAN);
assert_eq!(mixer.volume(id), 1.0);
mixer.set_volume(id, 0.5);
mixer.set_muted(id, true);
assert!(mixer.is_muted(id));
mixer.forget(id);
assert!(!mixer.is_muted(id));
assert_eq!(mixer.volume(id), 1.0);
}
}
+25
View File
@@ -13,6 +13,20 @@ pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec<f32> {
(0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect()
}
/// Deterministic white noise, uniform in `[-amplitude, amplitude]`, for tests
/// and calibration.
pub fn white_noise(n: usize, amplitude: f32, seed: u64) -> Vec<f32> {
// PCG-style LCG; the top 24 bits are uniform enough.
let mut state = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(0..n)
.map(|_| {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let x = (state >> 40) as f32 / (1u64 << 24) as f32;
amplitude * (2.0 * x - 1.0)
})
.collect()
}
/// Average interleaved channels into mono.
pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec<f32> {
if channels <= 1 {
@@ -93,6 +107,17 @@ mod tests {
assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0);
}
#[test]
fn noise_is_white_and_deterministic() {
let n = white_noise(48_000, 0.5, 1);
assert_eq!(n, white_noise(48_000, 0.5, 1));
assert_ne!(n, white_noise(48_000, 0.5, 2));
assert!(n.iter().all(|s| s.abs() <= 0.5));
// Uniform in ±a has energy a²/3.
assert!((energy(&n) - 0.25 / 3.0).abs() < 0.005);
assert!(tone_ratio(&n, 1000.0, SAMPLE_RATE) < 0.01);
}
#[test]
fn channel_conversion() {
assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]);
+363
View File
@@ -0,0 +1,363 @@
//! Microphone processing: echo cancellation, noise suppression and automatic
//! gain control.
//!
//! Backed by [sonora](https://crates.io/crates/sonora) (BSD-3-Clause), a pure
//! Rust port of the WebRTC audio processing module (AEC3, NS, AGC2): no C++
//! toolchain or system library needed, so it builds the same on Linux,
//! Windows and Android.
//!
//! The [`Processor`] runs on 10 ms mono frames at 48 kHz. The far end, i.e.
//! exactly what goes to the speakers (the mixer output after per-client volume
//! and output mute), is fed through [`Processor::render`]; the microphone
//! through [`Processor::capture`]. Both accept any length and frame internally.
use serde::{Deserialize, Serialize};
use sonora::config::{
AdaptiveDigital, CaptureLevelAdjustment, EchoCanceller, GainController2, HighPassFilter,
MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline,
};
use sonora::{AudioProcessing, Config, StreamConfig};
use crate::Framer;
use crate::pcm::SAMPLE_RATE;
/// Samples in one 10 ms processing frame (mono, 48 kHz).
pub const PROCESS_FRAME: usize = SAMPLE_RATE as usize / 100;
/// How hard noise suppression works.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NoiseLevel {
/// About 6 dB.
Low,
/// About 12 dB.
#[default]
Moderate,
/// About 18 dB.
High,
/// About 21 dB.
VeryHigh,
}
impl From<NoiseLevel> for NoiseSuppressionLevel {
fn from(level: NoiseLevel) -> Self {
match level {
NoiseLevel::Low => Self::Low,
NoiseLevel::Moderate => Self::Moderate,
NoiseLevel::High => Self::High,
NoiseLevel::VeryHigh => Self::VeryHigh,
}
}
}
/// User settings for microphone processing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ProcessingSettings {
/// Remove what the speakers play from the microphone signal.
pub echo_cancellation: bool,
/// Remove steady background noise (fans, hum, hiss).
pub noise_suppression: bool,
pub noise_level: NoiseLevel,
/// Bring speech to a steady level (adaptive digital gain and limiter).
pub auto_gain: bool,
/// Manual microphone gain in dB, applied before everything else.
/// Clamped to ±[`MAX_INPUT_GAIN_DB`].
pub input_gain_db: f32,
/// Remove rumble below ~80 Hz. Always on while echo cancellation is.
pub high_pass: bool,
}
/// Limit of [`ProcessingSettings::input_gain_db`].
pub const MAX_INPUT_GAIN_DB: f32 = 30.0;
impl Default for ProcessingSettings {
fn default() -> Self {
Self {
echo_cancellation: true,
noise_suppression: true,
noise_level: NoiseLevel::Moderate,
auto_gain: true,
input_gain_db: 0.0,
high_pass: true,
}
}
}
impl ProcessingSettings {
/// Everything off: the processor passes audio through untouched.
pub fn off() -> Self {
Self {
echo_cancellation: false,
noise_suppression: false,
noise_level: NoiseLevel::Moderate,
auto_gain: false,
input_gain_db: 0.0,
high_pass: false,
}
}
fn input_gain(&self) -> f32 {
let db = if self.input_gain_db.is_finite() { self.input_gain_db } else { 0.0 };
10f32.powf(db.clamp(-MAX_INPUT_GAIN_DB, MAX_INPUT_GAIN_DB) / 20.0)
}
fn is_passthrough(&self) -> bool {
!self.echo_cancellation
&& !self.noise_suppression
&& !self.auto_gain
&& !self.high_pass
&& self.input_gain() == 1.0
}
fn to_config(&self) -> Config {
let gain = self.input_gain();
Config {
pipeline: Pipeline {
// Full band: voice is Opus at 48 kHz.
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
..Default::default()
},
capture_level_adjustment: (gain != 1.0)
.then(|| CaptureLevelAdjustment { pre_gain_factor: gain, ..Default::default() }),
high_pass_filter: self.high_pass.then(HighPassFilter::default),
echo_canceller: self.echo_cancellation.then(EchoCanceller::default),
noise_suppression: self
.noise_suppression
.then(|| NoiseSuppression { level: self.noise_level.into(), ..Default::default() }),
gain_controller2: self.auto_gain.then(|| GainController2 {
adaptive_digital: Some(AdaptiveDigital::default()),
..Default::default()
}),
..Default::default()
}
}
}
/// Echo canceller statistics, for diagnostics.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ProcessingStats {
/// Echo return loss enhancement in dB: how much echo the canceller removes.
pub erle_db: Option<f64>,
/// Render-to-capture delay the canceller estimated.
pub delay_ms: Option<i32>,
}
/// Microphone processing pipeline stage. See the [module docs](self).
pub struct Processor {
apm: AudioProcessing,
settings: ProcessingSettings,
passthrough: bool,
delay_ms: u32,
render_framer: Framer,
capture_framer: Framer,
frame: Vec<f32>,
}
impl Processor {
pub fn new(settings: &ProcessingSettings) -> Self {
let stream = StreamConfig::new(SAMPLE_RATE, 1);
let apm = AudioProcessing::builder()
.config(settings.to_config())
.capture_config(stream)
.render_config(stream)
.build();
Self {
apm,
settings: settings.clone(),
passthrough: settings.is_passthrough(),
delay_ms: 0,
render_framer: Framer::new(PROCESS_FRAME),
capture_framer: Framer::new(PROCESS_FRAME),
frame: vec![0.0; PROCESS_FRAME],
}
}
pub fn settings(&self) -> &ProcessingSettings {
&self.settings
}
/// Change settings. Only reconfigures when something changed, since that
/// resets the adaptive filters.
pub fn apply(&mut self, settings: &ProcessingSettings) {
if *settings == self.settings {
return;
}
self.apm.apply_config(settings.to_config());
self.settings = settings.clone();
self.passthrough = settings.is_passthrough();
}
/// Hint for the echo canceller: time from handing a frame to
/// [`render`](Self::render) until it is heard, plus time from the
/// microphone picking a sample up until it reaches
/// [`capture`](Self::capture). The canceller estimates the rest itself.
pub fn set_delay_ms(&mut self, delay_ms: u32) {
if delay_ms != self.delay_ms {
self.delay_ms = delay_ms;
// Values above 500 ms are clamped, which is fine for a hint.
let _ = self.apm.set_stream_delay_ms(delay_ms.min(500) as i32);
}
}
/// Feed far-end audio: mono 48 kHz, exactly as played.
pub fn render(&mut self, samples: &[f32]) {
if !self.settings.echo_cancellation {
return;
}
let Self { apm, render_framer, frame, .. } = self;
render_framer.push(samples, |f| {
// Render output is not used: no render-side processing is enabled.
let _ = apm.process_render_f32(&[f], &mut [frame.as_mut_slice()]);
});
}
/// Process microphone audio (mono 48 kHz), appending the result to `out`.
/// Output comes in whole 10 ms frames, so up to 10 ms stay buffered.
pub fn capture(&mut self, samples: &[f32], out: &mut Vec<f32>) {
if self.passthrough && self.capture_framer.buffered() == 0 {
out.extend_from_slice(samples);
return;
}
let Self { apm, capture_framer, frame, passthrough, .. } = self;
capture_framer.push(samples, |f| {
if *passthrough {
out.extend_from_slice(f);
} else if apm.process_capture_f32(&[f], &mut [frame.as_mut_slice()]).is_ok() {
out.extend_from_slice(frame);
} else {
out.extend_from_slice(f);
}
});
}
pub fn stats(&self) -> ProcessingStats {
let stats = self.apm.statistics();
ProcessingStats { erle_db: stats.echo_return_loss_enhancement, delay_ms: stats.delay_ms }
}
}
impl std::fmt::Debug for Processor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Processor").field("settings", &self.settings).finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use std::f32::consts::TAU;
use super::*;
use crate::pcm::{self, energy, white_noise as noise};
fn db(ratio: f32) -> f32 {
10.0 * ratio.max(1e-20).log10()
}
#[test]
fn passthrough_when_off() {
let mut p = Processor::new(&ProcessingSettings::off());
let input = pcm::sine(440.0, 0.05, 0.3);
let mut out = Vec::new();
p.capture(&input[..100], &mut out);
p.capture(&input[100..], &mut out);
assert_eq!(out, input);
}
#[test]
fn input_gain_is_clamped() {
let s = ProcessingSettings { input_gain_db: 1000.0, ..ProcessingSettings::off() };
assert!((s.input_gain() - 10f32.powf(1.5)).abs() < 1e-3);
let s = ProcessingSettings { input_gain_db: f32::NAN, ..ProcessingSettings::off() };
assert_eq!(s.input_gain(), 1.0);
let s = ProcessingSettings { input_gain_db: 6.0, ..ProcessingSettings::off() };
assert!(!s.is_passthrough());
}
#[test]
fn settings_serde_defaults() {
let s: ProcessingSettings = serde_json::from_str(r#"{"noise_level":"very_high"}"#).unwrap();
assert_eq!(s.noise_level, NoiseLevel::VeryHigh);
assert!(s.echo_cancellation);
}
/// The far end leaks into the microphone 40 ms later at -6 dB; after the
/// canceller converged the echo must be at least 10 dB quieter.
#[test]
fn cancels_synthetic_echo() {
let settings = ProcessingSettings {
echo_cancellation: true,
high_pass: true,
..ProcessingSettings::off()
};
let mut p = Processor::new(&settings);
p.set_delay_ms(40);
let seconds = 6;
let delay = 40 * PROCESS_FRAME / 10;
// Speech-like far end: noise with a syllable-rate envelope.
let far: Vec<f32> = noise(SAMPLE_RATE as usize * seconds, 0.4, 1)
.into_iter()
.enumerate()
.map(|(i, s)| s * (0.6 + 0.4 * (i as f32 * 4.0 / SAMPLE_RATE as f32 * TAU).sin()))
.collect();
let mut near = vec![0.0; delay];
near.extend(far.iter().map(|s| s * 0.5));
near.truncate(far.len());
let mut out = Vec::new();
for (f, n) in far.chunks(PROCESS_FRAME).zip(near.chunks(PROCESS_FRAME)) {
p.render(f);
p.capture(n, &mut out);
}
assert_eq!(out.len(), near.len());
let tail = SAMPLE_RATE as usize * 2;
let before = energy(&near[near.len() - tail..]);
let after = energy(&out[out.len() - tail..]);
let attenuation = db(before / after);
assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB");
}
/// White noise gets quieter while a tone on top of it survives. The tone
/// comes in 200 ms bursts like syllables: a steady tone is stationary and
/// a noise suppressor rightly learns it as noise.
#[test]
fn suppresses_noise_keeps_tone() {
let settings = ProcessingSettings {
noise_suppression: true,
noise_level: NoiseLevel::High,
..ProcessingSettings::off()
};
let seconds = 4;
let n = SAMPLE_RATE as usize * seconds;
let hiss = noise(n, 0.05, 7);
let mut p = Processor::new(&settings);
let mut out = Vec::new();
p.capture(&hiss, &mut out);
let tail = SAMPLE_RATE as usize;
let reduction = db(energy(&hiss[n - tail..]) / energy(&out[n - tail..]));
assert!(reduction >= 10.0, "noise reduced by {reduction:.1} dB");
let ms = |ms: usize| ms * SAMPLE_RATE as usize / 1000;
let tone: Vec<f32> = pcm::sine(600.0, seconds as f32, 0.3)
.into_iter()
.enumerate()
.map(|(i, s)| if i % ms(400) < ms(200) { s } else { 0.0 })
.collect();
let mixed: Vec<f32> = tone.iter().zip(&hiss).map(|(a, b)| a + b).collect();
let mut p = Processor::new(&settings);
let mut out = Vec::new();
p.capture(&mixed, &mut out);
// The last two seconds, away from the burst edges.
for start in (n - ms(2000)..n).step_by(ms(400)) {
let on = start + ms(40)..start + ms(160);
let tone_in = pcm::goertzel_power(&tone[on.clone()], 600.0, SAMPLE_RATE);
let tone_out = pcm::goertzel_power(&out[on], 600.0, SAMPLE_RATE);
let loss = db(tone_in / tone_out);
assert!(loss.abs() < 3.0, "tone changed by {loss:.1} dB");
let off = start + ms(240)..start + ms(360);
let reduction = db(energy(&hiss[off.clone()]) / energy(&out[off]));
assert!(reduction >= 6.0, "noise between bursts reduced by {reduction:.1} dB");
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//! All user audio settings in one serde struct, e.g. for
//! `tsc_store::Store::set_setting("audio", &settings)`. Missing fields take
//! their defaults, so stored settings survive new options.
use serde::{Deserialize, Serialize};
use crate::process::ProcessingSettings;
use crate::vad::VadSettings;
/// When the microphone is sent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransmitMode {
/// While the push-to-talk key or button is held.
#[default]
PushToTalk,
/// While the voice activity detector hears speech.
VoiceActivation,
/// Always (unless muted).
Continuous,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AudioSettings {
pub transmit: TransmitMode,
pub processing: ProcessingSettings,
pub vad: VadSettings,
/// Microphone by device id (`device::DeviceInfo::id`); `None` follows
/// the system default.
pub input_device: Option<String>,
/// Speakers by device id; `None` follows the system default.
pub output_device: Option<String>,
/// Output volume for everyone, linear (1 = unchanged), applied before
/// the echo canceller sees the signal.
pub output_volume: f32,
/// Audio kept queued for the speakers. Lower is snappier, higher
/// survives scheduling hiccups.
pub playback_buffer_ms: u32,
}
impl Default for AudioSettings {
fn default() -> Self {
Self {
transmit: TransmitMode::PushToTalk,
processing: ProcessingSettings::default(),
vad: VadSettings::default(),
input_device: None,
output_device: None,
output_volume: 1.0,
playback_buffer_ms: 60,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_roundtrip_and_defaults() {
let mut s = AudioSettings {
transmit: TransmitMode::VoiceActivation,
input_device: Some("alsa:hw:1,0".into()),
..Default::default()
};
s.processing.echo_cancellation = false;
s.vad.threshold_db = -35.0;
let json = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<AudioSettings>(&json).unwrap(), s);
// Older or partial settings fill in defaults.
let partial: AudioSettings =
serde_json::from_str(r#"{"transmit":"continuous","vad":{"hangover_ms":100}}"#).unwrap();
assert_eq!(partial.transmit, TransmitMode::Continuous);
assert_eq!(partial.vad.hangover_ms, 100);
assert_eq!(partial.vad.threshold_db, VadSettings::default().threshold_db);
assert_eq!(partial.processing, ProcessingSettings::default());
}
}
+250
View File
@@ -0,0 +1,250 @@
//! Voice activity detection for voice-activated transmission.
//!
//! A level gate with hangover, optionally combined with the RNN speech
//! detector of WebRTC's AGC2 (through sonora), which ignores noise such as
//! typing, fans or breathing that is loud enough to pass the level gate.
//! Works on 10 ms mono frames at 48 kHz, after [`Processor`](crate::process::Processor).
use serde::{Deserialize, Serialize};
use sonora_agc2::vad_wrapper::VoiceActivityDetectorWrapper;
use crate::pcm::SAMPLE_RATE;
use crate::process::PROCESS_FRAME;
/// What opens the gate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VadMode {
/// The level is above the threshold.
#[default]
Level,
/// The level is above the threshold and the frame sounds like speech.
Speech,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct VadSettings {
pub mode: VadMode,
/// Level in dBFS (RMS of a 10 ms frame; a full-scale sine is -3 dBFS)
/// that opens the gate.
pub threshold_db: f32,
/// Keep transmitting this long after the last active frame, so word
/// endings and short pauses are not cut.
pub hangover_ms: u32,
/// Speech probability (0 to 1) needed in [`VadMode::Speech`].
pub speech_probability: f32,
}
impl Default for VadSettings {
fn default() -> Self {
// Speech after automatic gain control sits around -20 dBFS and the
// controller keeps noise below -50 dBFS.
Self {
mode: VadMode::Level,
threshold_db: -40.0,
hangover_ms: 300,
speech_probability: 0.6,
}
}
}
/// Level of silence, so the meter has a floor.
pub const SILENCE_DB: f32 = -100.0;
/// RMS level in dBFS.
pub fn level_db(samples: &[f32]) -> f32 {
let e = crate::pcm::energy(samples);
if e > 0.0 { (10.0 * e.log10()).max(SILENCE_DB) } else { SILENCE_DB }
}
/// Voice activity detector. See the [module docs](self).
pub struct Vad {
settings: VadSettings,
rnn: Option<VoiceActivityDetectorWrapper>,
scaled: Vec<f32>,
hang_remaining_ms: u32,
level_db: f32,
probability: f32,
}
impl Vad {
pub fn new(settings: &VadSettings) -> Self {
let mut vad = Self {
settings: settings.clone(),
rnn: None,
scaled: vec![0.0; PROCESS_FRAME],
hang_remaining_ms: 0,
level_db: SILENCE_DB,
probability: 0.0,
};
vad.apply(settings);
vad
}
pub fn settings(&self) -> &VadSettings {
&self.settings
}
pub fn apply(&mut self, settings: &VadSettings) {
if settings.mode == VadMode::Speech && self.rnn.is_none() {
self.rnn = Some(VoiceActivityDetectorWrapper::new(
sonora_simd::detect_backend(),
SAMPLE_RATE as i32,
));
} else if settings.mode != VadMode::Speech {
self.rnn = None;
self.probability = 0.0;
}
self.settings = settings.clone();
}
/// Analyse mono 48 kHz audio, a whole number of 10 ms frames (a
/// trailing partial frame is ignored). Returns whether to transmit.
pub fn process(&mut self, samples: &[f32]) -> bool {
for frame in samples.chunks_exact(PROCESS_FRAME) {
self.level_db = level_db(frame);
let mut active = self.level_db >= self.settings.threshold_db;
if let Some(rnn) = &mut self.rnn {
// The detector works on 16-bit scale floats.
for (dst, src) in self.scaled.iter_mut().zip(frame) {
*dst = src * 32768.0;
}
self.probability = rnn.analyze(&self.scaled);
active &= self.probability >= self.settings.speech_probability;
}
if active {
// Plus this frame itself.
self.hang_remaining_ms = self.settings.hangover_ms + 10;
} else {
self.hang_remaining_ms = self.hang_remaining_ms.saturating_sub(10);
}
}
self.is_active()
}
/// Whether the gate is open after the last frame.
pub fn is_active(&self) -> bool {
self.hang_remaining_ms > 0
}
/// Level of the last frame in dBFS, for a microphone meter.
pub fn level_db(&self) -> f32 {
self.level_db
}
/// Speech probability of the last frame, 0 unless in [`VadMode::Speech`].
pub fn speech_probability(&self) -> f32 {
self.probability
}
/// Close the gate immediately (e.g. when switching to push-to-talk).
pub fn reset(&mut self) {
self.hang_remaining_ms = 0;
}
}
impl std::fmt::Debug for Vad {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vad")
.field("settings", &self.settings)
.field("level_db", &self.level_db)
.field("active", &self.is_active())
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pcm::{self, white_noise as noise};
/// A voiced sound: a 120 Hz pulse train through three vowel formants,
/// scaled to `amplitude` peak.
pub(crate) fn vowel(seconds: f32, amplitude: f32) -> Vec<f32> {
let n = (seconds * SAMPLE_RATE as f32) as usize;
let pulses: Vec<f32> =
(0..n).map(|i| if i % (SAMPLE_RATE as usize / 120) == 0 { 1.0 } else { 0.0 }).collect();
let resonate = |freq: f32, bandwidth: f32| -> Vec<f32> {
let r = (-std::f32::consts::PI * bandwidth / SAMPLE_RATE as f32).exp();
let c = 2.0 * r * (std::f32::consts::TAU * freq / SAMPLE_RATE as f32).cos();
let (mut y1, mut y2) = (0.0f32, 0.0f32);
pulses
.iter()
.map(|&x| {
let y = x * (1.0 - r) + c * y1 - r * r * y2;
(y2, y1) = (y1, y);
y
})
.collect()
};
let (f1, f2, f3) = (resonate(700.0, 80.0), resonate(1200.0, 90.0), resonate(2600.0, 120.0));
let mix: Vec<f32> = (0..n).map(|i| f1[i] + 0.6 * f2[i] + 0.3 * f3[i]).collect();
let peak = mix.iter().fold(0.0f32, |m, s| m.max(s.abs()));
mix.iter().map(|s| s / peak * amplitude).collect()
}
fn active_fraction(vad: &mut Vad, signal: &[f32]) -> f32 {
let frames: Vec<bool> =
signal.chunks_exact(PROCESS_FRAME).map(|f| vad.process(f)).collect();
frames.iter().filter(|&&a| a).count() as f32 / frames.len() as f32
}
#[test]
fn level() {
assert_eq!(level_db(&[0.0; 480]), SILENCE_DB);
assert!((level_db(&pcm::sine(1000.0, 0.01, 1.0)) + 3.01).abs() < 0.1);
assert!((level_db(&[0.1; 480]) + 20.0).abs() < 0.01);
}
#[test]
fn gate_and_hangover() {
let settings = VadSettings { hangover_ms: 50, ..Default::default() };
let mut vad = Vad::new(&settings);
let loud = pcm::sine(300.0, 0.01, 0.1);
let quiet = vec![0.001; PROCESS_FRAME];
assert!(!vad.process(&quiet));
assert!(vad.process(&loud));
// 50 ms of hangover after the last loud frame, then closed.
for _ in 0..5 {
assert!(vad.process(&quiet));
}
assert!(!vad.process(&quiet));
// A 20 ms frame is analysed as two 10 ms frames.
assert!(vad.process(&[loud.clone(), loud].concat()));
vad.reset();
assert!(!vad.is_active());
}
#[test]
fn threshold_is_respected() {
let mut vad =
Vad::new(&VadSettings { threshold_db: -30.0, hangover_ms: 0, ..Default::default() });
// -33 dBFS stays closed, -23 dBFS opens.
assert!(!vad.process(&pcm::sine(300.0, 0.01, 0.0316)));
assert!(vad.process(&pcm::sine(300.0, 0.01, 0.1)));
}
/// In speech mode, noise loud enough for the level gate stays out, a
/// voiced sound gets through.
#[test]
fn speech_mode_rejects_noise() {
let settings = VadSettings { mode: VadMode::Speech, hangover_ms: 0, ..Default::default() };
let hiss = noise(SAMPLE_RATE as usize * 2, 0.05, 3);
assert!(level_db(&hiss) > settings.threshold_db);
let mut level_only = Vad::new(&VadSettings { mode: VadMode::Level, ..settings.clone() });
assert!(active_fraction(&mut level_only, &hiss) > 0.99);
let mut vad = Vad::new(&settings);
let noise_active = active_fraction(&mut vad, &hiss);
assert!(noise_active < 0.1, "noise active {noise_active}");
let mut vad = Vad::new(&settings);
let voice_active = active_fraction(&mut vad, &vowel(2.0, 0.3));
assert!(voice_active > 0.8, "voice active {voice_active}");
assert!(vad.speech_probability() > 0.5);
// Switching back to level mode drops the detector.
vad.apply(&VadSettings::default());
assert_eq!(vad.speech_probability(), 0.0);
}
}
+129
View File
@@ -0,0 +1,129 @@
//! A one-hour call with a sender whose clock runs ±200 ppm off ours: the
//! jitter buffer must keep the latency bounded instead of drifting by the
//! 720 ms the clocks disagree over an hour.
//!
//! The sender transmits continuously (the worst case: talk spurts would reset
//! the queue) over a network with 20–60 ms of jitter, reordering and 0.5 %
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
//! the latency is the time from generating a marker to it leaving the mixer.
use tsc_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use tsc_audio::{Mixer, VoiceCodec, VoiceEncoder};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
/// The receiver pulls 10 ms at a time, like a playback loop.
const PULL: usize = SAMPLE_RATE as usize / 100;
const MARKER_EVERY: u64 = 1500;
struct Rng(u64);
impl Rng {
fn next(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 11) as f64 / (1u64 << 53) as f64
}
}
/// Returns the latency of each marker in ms, in order.
fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
// A quiet frame (-65 dBFS noise) and a loud marker, encoded once.
let quiet = white_noise(FRAME_SAMPLES, 0.001, 1);
for _ in 0..5 {
encoder.encode_to_bytes(&quiet).unwrap();
}
let quiet = encoder.encode_to_bytes(&quiet).unwrap().to_vec();
let marker = encoder.encode_to_bytes(&sine(1000.0, 0.02, 0.5)).unwrap().to_vec();
let mut rng = Rng(ppm.to_bits());
let mut mixer = Mixer::new();
let client = ClientId(5);
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
// Sender frame n is made at n * 20 ms of the sender's clock.
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
// (arrival time, packet id), kept sorted by arrival.
let mut in_flight: Vec<(f64, u64)> = Vec::new();
let mut next_frame = 0u64;
let mut markers_sent = Vec::new();
let mut latencies = Vec::new();
let mut out = vec![0.0f32; PULL * 2];
let mut now = 0u64;
while now < total {
// Everything the sender produced up to now goes on the wire.
while frame_time(next_frame) <= now as f64 {
let is_marker = next_frame % MARKER_EVERY == MARKER_EVERY / 2;
if is_marker {
markers_sent.push(frame_time(next_frame));
}
// Markers are never lost, so each one can be matched.
if is_marker || rng.next() >= 0.005 {
let jitter = (0.02 + 0.04 * rng.next()) * SAMPLE_RATE as f64;
in_flight.push((frame_time(next_frame) + jitter, next_frame));
}
next_frame += 1;
}
in_flight.sort_by(|a, b| a.0.total_cmp(&b.0));
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
for (_, n) in in_flight.drain(..arrived) {
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
let packet = OutAudio::new(&AudioData::S2C {
id: n as u16,
codec: CodecType::OpusVoice,
from: 5,
data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
// Late packets are dropped by the jitter buffer, as on a real network.
let _ = mixer.handle_packet(client, packet);
}
out.fill(0.0);
mixer.fill_buffer(&mut out);
let left: Vec<f32> = out.iter().step_by(2).copied().collect();
if energy(&left) > 1e-3 {
// The latest marker made before now; they are 30 s apart.
let sent = markers_sent.iter().rev().find(|&&t| t <= now as f64).copied();
if let Some(sent) = sent {
let latency = (now as f64 - sent) * 1000.0 / SAMPLE_RATE as f64;
// One detection per marker (it spans two 10 ms pulls).
if latencies.len() < markers_sent.len() && latency < 5000.0 {
let index = markers_sent.iter().position(|&t| t == sent).unwrap();
if index == latencies.len() {
latencies.push(latency);
}
}
}
}
now += PULL as u64;
}
assert_eq!(latencies.len(), markers_sent.len(), "every marker must come out (ppm {ppm})");
latencies
}
fn check(ppm: f64) {
let latencies = simulate(ppm, 1.0);
assert_eq!(latencies.len(), 120);
let max = latencies.iter().copied().fold(0.0, f64::max);
let min = latencies.iter().copied().fold(f64::MAX, f64::min);
let first: f64 = latencies[..20].iter().sum::<f64>() / 20.0;
let last: f64 = latencies[latencies.len() - 20..].iter().sum::<f64>() / 20.0;
println!(
"{ppm:+} ppm: latency min {min:.0} ms, max {max:.0} ms, first 10 min avg {first:.0} ms, last 10 min avg {last:.0} ms"
);
// The network alone adds 20-60 ms; unchecked drift would add 720 ms.
assert!(min >= 20.0, "latency {min} ms is below the network delay");
assert!(max < 250.0, "latency grew to {max} ms");
assert!((last - first).abs() < 60.0, "latency drifted from {first} ms to {last} ms");
}
#[test]
fn fast_sender_one_hour() {
check(200.0);
}
#[test]
fn slow_sender_one_hour() {
check(-200.0);
}