voelin-audio: dim everyone else while a priority speaker talks

The server sends virtualserver_priority_speaker_dimm_modificator (-18 dB
by default) but nothing read it. ServerDetails carries it now, the
session tells the audio thread the priority speakers when they or the
value change, and the mixer dims every other queue (watched streams too)
while an unmuted priority speaker has one, fading sample by sample over
5 frames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
This commit is contained in:
Claude committed 2026-10-06 18:59:23 +00:00
1 parent 8b605b5b45
commit 92f4416934
8 files changed
+364 -20

No files matched your search

+224 -8
View File
@@ -1,5 +1,6 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client.
//! volume and mute per client, and everyone else dimmed while a priority
//! speaker talks.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! sender it keeps a queue of Opus packets and adapts its length:
@@ -24,16 +25,44 @@ use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
use crate::pcm::FRAME_SAMPLES;
/// Loudest per-client volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Most a priority speaker dims the others (dB).
const MAX_DIMM_DB: f32 = -60.0;
/// The dimming for a priority speaker fades in and out over this many
/// samples (5 frames, 100 ms) instead of jumping.
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
/// 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>,
/// While one of them talks, everyone else is dimmed.
priority: HashSet<ClientId>,
/// Linear gain of the others while a priority speaker talks (1: none).
dimm: f32,
/// How far the dimming has faded in (0..=1).
fade: f32,
/// The others' mix while the dimming fades (reused).
others: Vec<f32>,
}
impl Default for Mixer {
fn default() -> Self {
Self {
handler: AudioHandler::new(),
volumes: HashMap::new(),
muted: HashSet::new(),
priority: HashSet::new(),
dimm: 1.0,
fade: 0.0,
others: Vec::new(),
}
}
}
impl Mixer {
@@ -53,18 +82,63 @@ impl Mixer {
}
/// 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.
/// (not cleared first), each scaled by its volume, and dimmed while a
/// priority speaker talks. 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) {
let queues = self.handler.get_mut_queues();
// A priority speaker with a queue (talking or buffering) dims all
// other queues, streams too, unless we muted it.
let dim = queues.keys().any(|id| self.priority.contains(id) && !self.muted.contains(id));
let frames = buf.len() / 2;
let step = frames as f32 / DIMM_RAMP_SAMPLES as f32;
let from = self.fade;
self.fade = if dim { (from + step).min(1.0) } else { (from - step).max(0.0) };
let to = self.fade;
let dimm = self.dimm;
let gain = |fade: f32| 1.0 + (dimm - 1.0) * fade;
let fading = from != to;
// While fading, the others are mixed into a buffer of their own and
// ramped sample by sample; the priority speakers go straight to `buf`.
let mut priority = Vec::new();
for (id, queue) in queues {
// Muted talkers are still decoded so their queues stay in sync.
let volume = if self.muted.contains(id) {
0.0
} else {
self.volumes.get(id).copied().unwrap_or(1.0)
};
queue.volume = if self.priority.contains(id) {
if fading {
priority.push((*id, volume));
0.0
} else {
volume
}
} else if fading {
volume
} else {
volume * gain(to)
};
}
// Muted talkers are still decoded so their queues stay in sync.
self.handler.fill_buffer(buf)
if !fading {
return self.handler.fill_buffer(buf);
}
self.others.clear();
self.others.resize(buf.len(), 0.0);
let stopped = self.handler.fill_buffer_with_proc(&mut self.others, |id, samples| {
if let Some(&(_, volume)) = priority.iter().find(|(p, _)| p == id) {
for (out, s) in buf.iter_mut().zip(samples) {
*out += s * volume;
}
}
});
// From the last frame's gain to this one's.
for (i, (out, s)) in buf.chunks_exact_mut(2).zip(self.others.chunks_exact(2)).enumerate() {
let g = gain(from + (to - from) * (i + 1) as f32 / frames as f32);
out[0] += s[0] * g;
out[1] += s[1] * g;
}
stopped
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
@@ -99,6 +173,16 @@ impl Mixer {
self.muted.contains(&id)
}
/// The priority speakers, and how much everyone else is dimmed while
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
/// the caller sends a new set when the clients change.
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
self.priority = clients.into_iter().collect();
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
self.dimm = 10f32.powf(db / 20.0);
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
@@ -129,6 +213,8 @@ impl std::fmt::Debug for Mixer {
.field("talkers", &self.handler.get_queues().len())
.field("volumes", &self.volumes)
.field("muted", &self.muted)
.field("priority", &self.priority)
.field("dimm", &self.dimm)
.finish()
}
}
@@ -199,6 +285,136 @@ mod tests {
assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4);
}
/// A priority speaker dims the other talker by the server's -18 dB, fading
/// in and out, but not itself, and not while we muted it.
#[test]
fn priority_speaker_dims_others() {
let (a, p) = (ClientId(3), ClientId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 4.0, 0.2);
let tone_p = pcm::sine(1300.0, 4.0, 0.2);
let frame = |tone: &[f32], i: u16| {
let at = i as usize * FRAME_SAMPLES;
tone[at..at + FRAME_SAMPLES].to_vec()
};
let mut mixer = Mixer::new();
mixer.set_priority([p], -18.0);
let (mut id_a, mut id_p) = (0u16, 0u16);
// `frames` frames with a talking and p too if `with_p`; returns the
// second half of the mix.
let mut play = |mixer: &mut Mixer, frames: u16, with_p: bool| {
let mut out = Vec::new();
for _ in 0..frames {
let fa = frame(&tone_a, id_a);
mixer
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
.unwrap();
id_a += 1;
if with_p {
let fp = frame(&tone_p, id_p);
let data = enc_p.encode_to_bytes(&fp).unwrap();
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
id_p += 1;
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
out.split_off(out.len() / 2)
};
let power = |out: &[f32], f| pcm::goertzel_power(out, f, SAMPLE_RATE);
let db = |level: f32, full: f32| 10.0 * (level / full).log10();
let alone = play(&mut mixer, 30, false);
let full = power(&alone, 500.0);
assert!(full > 1e-4);
// The dimming fades in over 5 frames: 1/5 of the way after the first.
play(&mut mixer, 1, true);
assert!((mixer.fade - 0.2).abs() < 1e-6, "fade {}", mixer.fade);
let both = play(&mut mixer, 50, true);
let dimmed = db(power(&both, 500.0), full);
assert!((dimmed + 18.0).abs() < 1.0, "dimmed by {dimmed} dB");
let own = db(power(&both, 1300.0), full);
assert!(own.abs() < 1.0, "priority speaker at {own} dB");
// p stops: its queue ends after three lost frames, and a is back.
let after = play(&mut mixer, 40, false);
assert_eq!(mixer.talkers().collect::<Vec<_>>(), vec![a]);
assert_eq!(mixer.fade, 0.0);
let back = db(power(&after, 500.0), full);
assert!(back.abs() < 1.0, "after the priority speaker: {back} dB");
// A priority speaker we muted dims nobody.
mixer.set_muted(p, true);
let muted = play(&mut mixer, 40, true);
assert_eq!(mixer.talkers().count(), 2);
let level = db(power(&muted, 500.0), full);
assert!(level.abs() < 1.0, "muted priority speaker: {level} dB");
assert!(power(&muted, 1300.0) < 1e-6);
}
/// The dimming fades in and out sample by sample, not in a step per
/// frame: the other talker's level (per period of its tone) never jumps.
#[test]
fn priority_dimming_ramps_per_sample() {
let (a, p) = (ClientId(3), ClientId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone = pcm::sine(500.0, 2.0, 0.2);
let mut mixer = Mixer::new();
mixer.set_priority([p], -18.0);
// p is not heard (volume 0) but dims, so the mix is a's tone alone.
mixer.set_volume(p, 0.0);
let mut out = Vec::new();
// p talks from frame 30 to 59.
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let id = i as u16;
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
let data = enc_p.encode_to_bytes(frame).unwrap();
mixer.handle_packet(p, packet(5, j as u16, data)).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.fade, 0.0);
// The level per period of the 500 Hz tone (96 samples, 10 a frame).
let level: Vec<f32> = out.chunks_exact(96).map(|c| pcm::energy(c).sqrt()).collect();
let full = level[200..300].iter().sum::<f32>() / 100.0;
let mean = |range: std::ops::Range<usize>| {
level[range.clone()].iter().sum::<f32>() / range.len() as f32 / full
};
let jump = level[200..].windows(2).map(|w| (w[1] - w[0]).abs() / full).fold(0.0, f32::max);
assert!(jump < 0.05, "the level jumps by {jump} of full");
// Fully dimmed after 5 frames, and back after p's queue ended.
let dimmed = mean(350..600);
assert!((dimmed - 0.126).abs() < 0.02, "dimmed to {dimmed}");
let back = mean(800..1000);
assert!((back - 1.0).abs() < 0.05, "back to {back}");
}
#[test]
fn priority_dimm_bounds() {
let mut mixer = Mixer::new();
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], -18.0);
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
mixer.set_priority([ClientId(1)], 6.0);
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
assert!((mixer.dimm - 0.001).abs() < 1e-6);
mixer.set_priority([ClientId(1)], f32::NAN);
assert_eq!(mixer.dimm, 1.0);
// Forgetting a client keeps the set: the caller replaces it.
mixer.forget(ClientId(1));
assert!(mixer.priority.contains(&ClientId(1)));
mixer.set_priority([], -18.0);
assert!(mixer.priority.is_empty());
}
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
+48 -1
View File
@@ -42,6 +42,12 @@ pub(crate) enum AudioIn {
},
/// The client left; client ids are reused, so forget its volume.
ClientLeft(ClientId),
/// The priority speakers: while one talks, everyone else (streams too)
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
PrioritySpeakers {
clients: Vec<ClientId>,
dimm_db: f32,
},
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
/// on the 48 kHz clock.
StreamAudio {
@@ -208,6 +214,9 @@ impl Pipeline {
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
AudioIn::ClientLeft(client) => self.mixer.forget(client),
AudioIn::PrioritySpeakers { clients, dimm_db } => {
self.mixer.set_priority(clients, dimm_db);
}
AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data),
AudioIn::StreamVolume { stream, volume } => {
if let Some(s) = self.streams.get(&stream) {
@@ -547,7 +556,7 @@ mod devices {
#[cfg(test)]
mod tests {
use voelin_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::pcm::{SAMPLE_RATE, energy, goertzel_power, sine, white_noise};
use voelin_audio::{ProcessingSettings, VadSettings};
use super::*;
@@ -668,6 +677,44 @@ mod tests {
assert!(!p.mixer.is_muted(ClientId(3)));
}
/// While a priority speaker talks, another talker and a watched stream
/// are dimmed by the server's setting.
#[test]
fn priority_speaker() {
let mut p = pipeline(TransmitMode::PushToTalk);
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let tone = sine(700.0, 2.0, 0.3);
let stream = pcm::from_mono(&sine(1100.0, 2.0, 0.3), 2);
let other = sine(1700.0, 1.0, 0.3);
let mut out = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
p.handle(incoming(1, i as u16, voice.encode_to_bytes(frame).unwrap()));
let frame = &stream[i * FRAME_SAMPLES * 2..(i + 1) * FRAME_SAMPLES * 2];
let data: Arc<[u8]> = music.encode_to_bytes(frame).unwrap().into();
let time = i as u64 * OPUS_FRAME;
p.handle(AudioIn::StreamAudio { stream: "s".into(), time, data });
// The priority speaker talks during the second second.
if let Some(j) = i.checked_sub(50) {
let frame = &other[j * FRAME_SAMPLES..(j + 1) * FRAME_SAMPLES];
p.handle(incoming(2, j as u16, priority.encode_to_bytes(frame).unwrap()));
}
out.extend(p.playback_frame());
}
// The second half of each second.
let half = SAMPLE_RATE as usize / 2;
let level = |second: usize, freq: f32| {
let from = second * 2 * half + half;
goertzel_power(&out[from..from + half], freq, SAMPLE_RATE)
};
for freq in [700.0, 1100.0] {
let ratio_db = 10.0 * (level(1, freq) / level(0, freq)).log10();
assert!((ratio_db + 12.0).abs() < 1.0, "{freq} Hz dimmed by {ratio_db} dB");
}
}
/// End to end: a remote talker is played, the speakers leak into the
/// microphone 30 ms later, and the echo canceller (fed with what was
/// played) removes it from what we would send.
+3
View File
@@ -60,6 +60,8 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
platform: server.platform.clone(),
version: server.version.clone(),
max_clients: server.max_clients,
// `as` saturates (and turns NaN into 0); the mixer clamps it.
priority_speaker_dimm_db: server.priority_speaker_dimm_modificator.round() as i32,
default_server_group: Some(server.default_server_group.0),
default_channel_group: Some(server.default_channel_group.0),
}
@@ -265,5 +267,6 @@ mod tests {
assert_eq!(p.server.banner_gfx_interval_s, 60);
assert_eq!(p.server.banner_mode, BannerMode::KeepAspect);
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
assert_eq!(p.server.priority_speaker_dimm_db, -18);
}
}
+59
View File
@@ -234,6 +234,9 @@ struct Session {
banner_reload: Option<(String, u64, tokio::task::AbortHandle)>,
/// Contact volume and mute applied per client.
contact_audio: HashMap<u16, (f32, bool)>,
/// Priority speakers and the server's dimming (dB) as told to the
/// audio thread.
priority_audio: (BTreeSet<u16>, i32),
/// Friends' client ids, as last told to the streams.
stream_friends: BTreeSet<u16>,
/// The server's details and groups as last reported.
@@ -266,6 +269,7 @@ impl Session {
image_retries: HashMap::new(),
banner_reload: None,
contact_audio: HashMap::new(),
priority_audio: Default::default(),
stream_friends: BTreeSet::new(),
details: None,
groups: None,
@@ -824,6 +828,7 @@ impl Session {
self.icons.clear();
self.pictures.clear();
self.contact_audio.clear();
self.priority_audio = Default::default();
self.stream_friends.clear();
self.details = None;
self.groups = None;
@@ -1139,6 +1144,19 @@ impl Session {
}
}
/// Tell the audio thread who the priority speakers are and how much they
/// dim the others, when that changed (voice presence).
fn apply_priority(&mut self, p: &Presence) {
let Some(a) = &self.audio else { return };
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
let wanted = (clients, p.server.priority_speaker_dimm_db);
if wanted != self.priority_audio {
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
self.priority_audio = wanted;
}
}
/// Report the server's details and groups when they changed.
fn report_details(&mut self, p: &Presence) {
if self.details.as_deref() != Some(&p.server) {
@@ -1649,6 +1667,7 @@ impl Session {
self.report_details(&p);
self.fetch_images(&p);
self.apply_contacts(&p);
self.apply_priority(&p);
self.voice_presence = Some(*p);
self.publish_presence();
}
@@ -2273,4 +2292,44 @@ mod banner_tests {
tokio::task::yield_now().await;
assert!(timer.is_finished());
}
/// The priority speakers and the server's dimming reach the audio thread
/// once, and again when either changes.
#[tokio::test]
async fn priority_speakers_reach_the_audio_thread_when_changed() {
let (mut session, _) = session("priority");
let (audio, rx) = AudioHandle::channel();
session.audio = Some(audio);
let mut presence = Presence::default();
presence.server.priority_speaker_dimm_db = -18;
for (id, priority_speaker) in [(2, false), (5, true)] {
let client = voelin_model::ClientInfo { id, priority_speaker, ..Default::default() };
presence.clients.insert(id, client);
}
let sent = || -> Vec<(Vec<u16>, f32)> {
rx.try_iter()
.filter_map(|msg| match msg {
AudioIn::PrioritySpeakers { clients, dimm_db } => {
Some((clients.iter().map(|c| c.0).collect(), dimm_db))
}
_ => None,
})
.collect()
};
session.apply_priority(&presence);
assert_eq!(sent(), [(vec![5], -18.0)]);
session.apply_priority(&presence);
assert!(sent().is_empty());
presence.server.priority_speaker_dimm_db = -30;
session.apply_priority(&presence);
assert_eq!(sent(), [(vec![5], -30.0)]);
presence.clients.get_mut(&5).unwrap().priority_speaker = false;
session.apply_priority(&presence);
assert_eq!(sent(), [(vec![], -30.0)]);
// A new connection has a new audio thread: told again.
session.forget_images();
session.apply_priority(&presence);
assert_eq!(sent(), [(vec![], -30.0)]);
session.stop_all();
}
}
+5
View File
@@ -184,6 +184,11 @@ pub struct ServerDetails {
pub version: String,
#[serde(default)]
pub max_clients: u16,
/// How much everyone else is dimmed while a priority speaker talks
/// (dB, e.g. -18; `virtualserver_priority_speaker_dimm_modificator`,
/// rounded).
#[serde(default)]
pub priority_speaker_dimm_db: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_server_group: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]