Skip to main content

weirdnet_audio_engine/
talkback.rs

1//! Talkback: voices between people, kept apart from the music.
2//!
3//! * [`MicSwitch`]: the person's own mic switch, shared between a UI and the capture thread. It **starts muted**; push to talk is an
4//!   option. [`MicSwitch::live`] says whether the mic is sending.
5//! * [`MicGate`]: a level gate with hold, so an open mic sends silence (zeros) between words.
6//! * [`talkback_bus`]: the talkback bus, a mixer of speakers (mono, each with a small jitter buffer, a volume and a mute, and a mute
7//!   for everyone) that a device plays. It is a separate bus: nothing here touches a music bus.
8//! * [`Ducker`]: the gain a music bus applies while someone talks (smoothed, a few dB by default, off at 0 dB).
9//!
10//! The bus's render function follows the engine's rule: no lock, no block, no allocation. Speakers are added through a bounded lock-free
11//! queue into a list with fixed capacity ([`MAX_SPEAKERS`]); a speaker's samples arrive through its own bounded queue.
12
13use crate::{RenderFn, SinkConfig};
14use crossbeam_queue::ArrayQueue;
15use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
16use std::sync::{Arc, Mutex};
17
18/// The most speakers one bus mixes.
19pub const MAX_SPEAKERS: usize = 32;
20/// A speaker counts as talking above this peak level (−45 dBFS).
21pub const ACTIVE_LEVEL: f32 = 0.005_6;
22
23/// dB to a linear gain.
24pub fn db_to_gain(db: f32) -> f32 {
25    10f32.powf(db / 20.0)
26}
27
28/// The person's own mic switch. It starts muted: unmuting is a deliberate first step.
29#[derive(Clone, Debug)]
30pub struct MicSwitch {
31    muted: Arc<AtomicBool>,
32    push_to_talk: Arc<AtomicBool>,
33    pressed: Arc<AtomicBool>,
34    forced: Arc<AtomicBool>,
35}
36
37impl Default for MicSwitch {
38    fn default() -> Self {
39        MicSwitch::new()
40    }
41}
42
43impl MicSwitch {
44    /// A switch, muted.
45    pub fn new() -> Self {
46        MicSwitch { muted: Arc::new(AtomicBool::new(true)), push_to_talk: Arc::default(), pressed: Arc::default(), forced: Arc::default() }
47    }
48
49    /// Mute or unmute your mic.
50    pub fn set_muted(&self, muted: bool) {
51        self.muted.store(muted, Ordering::Release);
52    }
53
54    /// Whether you muted your mic.
55    pub fn muted(&self) -> bool {
56        self.muted.load(Ordering::Acquire)
57    }
58
59    /// Push to talk on or off. With it on, the mic sends only while the talk key is held.
60    pub fn set_push_to_talk(&self, on: bool) {
61        self.push_to_talk.store(on, Ordering::Release);
62    }
63
64    /// Whether push to talk is on.
65    pub fn push_to_talk(&self) -> bool {
66        self.push_to_talk.load(Ordering::Acquire)
67    }
68
69    /// The talk key is held (push to talk).
70    pub fn set_pressed(&self, pressed: bool) {
71        self.pressed.store(pressed, Ordering::Release);
72    }
73
74    /// Muted from outside (the host, a policy, a kick): wins over the person's own switch until lifted.
75    pub fn set_forced_mute(&self, forced: bool) {
76        self.forced.store(forced, Ordering::Release);
77    }
78
79    /// Whether a mute from outside holds.
80    pub fn forced_mute(&self) -> bool {
81        self.forced.load(Ordering::Acquire)
82    }
83
84    /// Whether the mic is sending now.
85    pub fn live(&self) -> bool {
86        !self.muted() && !self.forced_mute() && (!self.push_to_talk() || self.pressed.load(Ordering::Acquire))
87    }
88}
89
90/// A level gate with hold: below the threshold for longer than the hold, the block is silenced.
91#[derive(Clone, Debug)]
92pub struct MicGate {
93    threshold: f32,
94    hold_frames: u64,
95    quiet_frames: u64,
96}
97
98impl MicGate {
99    /// A gate at `threshold_db` (dBFS peak) that stays open `hold_frames` after the last loud block.
100    pub fn new(threshold_db: f32, hold_frames: u64) -> Self {
101        MicGate { threshold: db_to_gain(threshold_db), hold_frames, quiet_frames: u64::MAX / 2 }
102    }
103
104    /// Gate one block of interleaved samples (`channels` per frame) in place. Returns whether it was open.
105    pub fn process(&mut self, block: &mut [f32], channels: u16) -> bool {
106        let frames = (block.len() / usize::from(channels.max(1))) as u64;
107        let peak = block.iter().fold(0f32, |m, s| m.max(s.abs()));
108        if peak >= self.threshold {
109            self.quiet_frames = 0;
110        } else {
111            self.quiet_frames = self.quiet_frames.saturating_add(frames);
112        }
113        let open = self.quiet_frames <= self.hold_frames;
114        if !open {
115            block.fill(0.0);
116        }
117        open
118    }
119}
120
121struct Speaker {
122    id: String,
123    queue: ArrayQueue<f32>,
124    gain: AtomicU32,
125    muted: AtomicBool,
126    gone: AtomicBool,
127    primed: AtomicBool,
128    level: AtomicU32,
129    underruns: AtomicU64,
130    dropped: AtomicU64,
131    played: AtomicU64,
132}
133
134/// Where a speaker's samples go in (from the network thread): mono, at the bus's rate.
135#[derive(Clone)]
136pub struct SpeakerInput(Arc<Speaker>);
137
138impl SpeakerInput {
139    /// Queue mono samples. When the queue is full the oldest go (talkback stays current rather than late).
140    pub fn push(&self, samples: &[f32]) {
141        for &s in samples {
142            if self.0.queue.force_push(s).is_some() {
143                self.0.dropped.fetch_add(1, Ordering::Relaxed);
144            }
145        }
146    }
147
148    /// Samples waiting to be played.
149    pub fn queued(&self) -> usize {
150        self.0.queue.len()
151    }
152}
153
154/// What the bus reports about one speaker.
155#[derive(Clone, Debug, PartialEq)]
156pub struct SpeakerStats {
157    /// The speaker.
158    pub id: String,
159    /// Peak level of the last block played (linear).
160    pub level: f32,
161    /// Times the queue ran dry while playing.
162    pub underruns: u64,
163    /// Samples dropped because the queue was full.
164    pub dropped: u64,
165    /// Samples played.
166    pub played: u64,
167    /// Samples waiting.
168    pub queued: usize,
169}
170
171/// The control side of a talkback bus.
172pub struct TalkbackControl {
173    adds: Arc<ArrayQueue<Arc<Speaker>>>,
174    speakers: Mutex<Vec<Arc<Speaker>>>,
175    all_muted: Arc<AtomicBool>,
176    active: Arc<AtomicBool>,
177    queue_frames: usize,
178}
179
180/// The audio side: make it the render function of a sink with [`TalkbackAudio::into_render`].
181pub struct TalkbackAudio {
182    adds: Arc<ArrayQueue<Arc<Speaker>>>,
183    list: Vec<Arc<Speaker>>,
184    channels: usize,
185    jitter: usize,
186    all_muted: Arc<AtomicBool>,
187    active: Arc<AtomicBool>,
188}
189
190/// A talkback bus for a device with `config`, holding `jitter_frames` of each speaker before it starts playing (again after running dry).
191pub fn talkback_bus(config: SinkConfig, jitter_frames: usize) -> (TalkbackControl, TalkbackAudio) {
192    let adds = Arc::new(ArrayQueue::new(MAX_SPEAKERS));
193    let all_muted = Arc::new(AtomicBool::new(false));
194    let active = Arc::new(AtomicBool::new(false));
195    let queue_frames = (config.sample_rate as usize).max(jitter_frames * 4);
196    (
197        TalkbackControl { adds: adds.clone(), speakers: Mutex::new(Vec::new()), all_muted: all_muted.clone(), active: active.clone(), queue_frames },
198        TalkbackAudio {
199            adds,
200            list: Vec::with_capacity(MAX_SPEAKERS),
201            channels: usize::from(config.channels.max(1)),
202            jitter: jitter_frames,
203            all_muted,
204            active,
205        },
206    )
207}
208
209impl TalkbackControl {
210    fn find(&self, id: &str) -> Option<Arc<Speaker>> {
211        self.speakers.lock().ok()?.iter().find(|s| s.id == id).cloned()
212    }
213
214    /// Add a speaker (or return the one with this id). `None` when the bus is full.
215    pub fn add(&self, id: &str) -> Option<SpeakerInput> {
216        if let Some(s) = self.find(id) {
217            return Some(SpeakerInput(s));
218        }
219        let mut list = self.speakers.lock().ok()?;
220        list.retain(|s| !s.gone.load(Ordering::Acquire));
221        if list.len() >= MAX_SPEAKERS {
222            return None;
223        }
224        let s = Arc::new(Speaker {
225            id: id.to_string(),
226            queue: ArrayQueue::new(self.queue_frames),
227            gain: AtomicU32::new(1f32.to_bits()),
228            muted: AtomicBool::new(false),
229            gone: AtomicBool::new(false),
230            primed: AtomicBool::new(false),
231            level: AtomicU32::new(0),
232            underruns: AtomicU64::new(0),
233            dropped: AtomicU64::new(0),
234            played: AtomicU64::new(0),
235        });
236        self.adds.push(s.clone()).ok()?;
237        list.push(s.clone());
238        Some(SpeakerInput(s))
239    }
240
241    /// Remove a speaker (the audio side lets go of it at its next block).
242    pub fn remove(&self, id: &str) {
243        if let Ok(mut list) = self.speakers.lock() {
244            for s in list.iter().filter(|s| s.id == id) {
245                s.gone.store(true, Ordering::Release);
246            }
247            list.retain(|s| s.id != id);
248        }
249    }
250
251    /// A speaker's volume (linear, 0 to 4).
252    pub fn set_gain(&self, id: &str, gain: f32) {
253        if let Some(s) = self.find(id) {
254            s.gain.store(gain.clamp(0.0, 4.0).to_bits(), Ordering::Relaxed);
255        }
256    }
257
258    /// Mute or unmute one speaker for yourself.
259    pub fn set_muted(&self, id: &str, muted: bool) {
260        if let Some(s) = self.find(id) {
261            s.muted.store(muted, Ordering::Relaxed);
262        }
263    }
264
265    /// Mute all talkback for yourself. The music is never touched.
266    pub fn set_all_muted(&self, muted: bool) {
267        self.all_muted.store(muted, Ordering::Relaxed);
268    }
269
270    /// Whether someone is audible now (for ducking).
271    pub fn active(&self) -> bool {
272        self.active.load(Ordering::Relaxed)
273    }
274
275    /// Each speaker's numbers.
276    pub fn stats(&self) -> Vec<SpeakerStats> {
277        let Ok(list) = self.speakers.lock() else { return vec![] };
278        list.iter()
279            .map(|s| SpeakerStats {
280                id: s.id.clone(),
281                level: f32::from_bits(s.level.load(Ordering::Relaxed)),
282                underruns: s.underruns.load(Ordering::Relaxed),
283                dropped: s.dropped.load(Ordering::Relaxed),
284                played: s.played.load(Ordering::Relaxed),
285                queued: s.queue.len(),
286            })
287            .collect()
288    }
289}
290
291impl TalkbackAudio {
292    /// Mix one block of interleaved output.
293    pub fn render(&mut self, out: &mut [f32]) {
294        while let Some(s) = self.adds.pop() {
295            if self.list.len() < self.list.capacity() {
296                self.list.push(s);
297            }
298        }
299        self.list.retain(|s| !s.gone.load(Ordering::Acquire));
300        out.fill(0.0);
301        let frames = out.len() / self.channels;
302        let all_muted = self.all_muted.load(Ordering::Relaxed);
303        let mut active = false;
304        for s in &self.list {
305            if !s.primed.load(Ordering::Relaxed) {
306                if s.queue.len() < self.jitter.max(1) {
307                    s.level.store(0, Ordering::Relaxed);
308                    continue;
309                }
310                s.primed.store(true, Ordering::Relaxed);
311            }
312            let gain = if all_muted || s.muted.load(Ordering::Relaxed) { 0.0 } else { f32::from_bits(s.gain.load(Ordering::Relaxed)) };
313            let mut peak = 0f32;
314            let mut played = 0u64;
315            for f in 0..frames {
316                let Some(x) = s.queue.pop() else {
317                    s.primed.store(false, Ordering::Relaxed);
318                    s.underruns.fetch_add(1, Ordering::Relaxed);
319                    break;
320                };
321                played += 1;
322                let v = x * gain;
323                peak = peak.max(v.abs());
324                for c in 0..self.channels {
325                    out[f * self.channels + c] += v;
326                }
327            }
328            s.played.fetch_add(played, Ordering::Relaxed);
329            s.level.store(peak.to_bits(), Ordering::Relaxed);
330            active |= peak >= ACTIVE_LEVEL;
331        }
332        self.active.store(active, Ordering::Relaxed);
333    }
334
335    /// The render function for a sink.
336    pub fn into_render(mut self) -> RenderFn {
337        Box::new(move |out: &mut [f32]| self.render(out))
338    }
339}
340
341/// The gain a music bus applies while someone talks: down by `duck_db` within the attack, back within the release.
342#[derive(Clone, Debug)]
343pub struct Ducker {
344    target: f32,
345    gain: f32,
346    attack: f32,
347    release: f32,
348}
349
350impl Ducker {
351    /// Ducking by `duck_db` (0 is off), with attack and release times in ms, for blocks at `sample_rate`.
352    pub fn new(duck_db: f32, attack_ms: f32, release_ms: f32, sample_rate: u32) -> Self {
353        let per_frame = |ms: f32| if ms <= 0.0 { 1.0 } else { 1.0 - (-1.0 / (ms / 1000.0 * sample_rate as f32)).exp() };
354        Ducker { target: db_to_gain(-duck_db.abs()), gain: 1.0, attack: per_frame(attack_ms), release: per_frame(release_ms) }
355    }
356
357    /// Change the depth (0 dB is off).
358    pub fn set_depth(&mut self, duck_db: f32) {
359        self.target = db_to_gain(-duck_db.abs());
360    }
361
362    /// Advance by `frames` with talkback `active` or not; returns the gain for the music now.
363    pub fn next(&mut self, active: bool, frames: usize) -> f32 {
364        let (goal, k) = if active { (self.target, self.attack) } else { (1.0, self.release) };
365        let keep = (1.0 - k).powi(frames as i32);
366        self.gain = goal + (self.gain - goal) * keep;
367        self.gain
368    }
369
370    /// The gain now.
371    pub fn gain(&self) -> f32 {
372        self.gain
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    #[test]
381    fn the_mic_starts_muted_and_push_to_talk_and_a_forced_mute_hold() {
382        let m = MicSwitch::new();
383        assert!(m.muted() && !m.live(), "muted on start");
384        m.set_muted(false);
385        assert!(m.live(), "open mic once unmuted");
386        m.set_push_to_talk(true);
387        assert!(!m.live());
388        m.set_pressed(true);
389        assert!(m.live());
390        m.set_forced_mute(true);
391        assert!(!m.live(), "the host's mute wins");
392        m.set_forced_mute(false);
393        m.set_push_to_talk(false);
394        assert!(m.live());
395    }
396
397    #[test]
398    fn the_gate_silences_quiet_blocks_after_the_hold() {
399        let mut g = MicGate::new(-40.0, 960);
400        let mut loud = vec![0.2f32; 480];
401        assert!(g.process(&mut loud, 1));
402        assert_eq!(loud[0], 0.2);
403        let mut quiet = vec![0.001f32; 480];
404        assert!(g.process(&mut quiet, 1), "held open");
405        assert!(g.process(&mut quiet, 1), "still within the hold");
406        let mut quiet2 = vec![0.001f32; 480];
407        assert!(!g.process(&mut quiet2, 1));
408        assert!(quiet2.iter().all(|s| *s == 0.0), "closed: silence");
409    }
410
411    #[test]
412    fn the_bus_mixes_speakers_with_volume_mute_and_a_jitter_buffer() {
413        let (c, mut a) = talkback_bus(SinkConfig::new(48_000, 2), 256);
414        let x = c.add("x").unwrap();
415        let y = c.add("y").unwrap();
416        let mut out = vec![0f32; 2 * 128];
417        x.push(&[0.25; 200]);
418        a.render(&mut out);
419        assert!(out.iter().all(|s| *s == 0.0), "x waits for its jitter buffer");
420        x.push(&[0.25; 200]);
421        y.push(&[0.5; 400]);
422        c.set_gain("y", 0.5);
423        a.render(&mut out);
424        assert!((out[0] - 0.5).abs() < 1e-6 && (out[1] - 0.5).abs() < 1e-6, "both, upmixed to two channels: {}", out[0]);
425        assert!(c.active());
426        c.set_muted("x", true);
427        a.render(&mut out);
428        assert!((out[0] - 0.25).abs() < 1e-6, "x muted for me");
429        c.set_all_muted(true);
430        a.render(&mut out);
431        assert!(out.iter().all(|s| *s == 0.0) && !c.active(), "all muted");
432        a.render(&mut out);
433        let st = c.stats();
434        assert_eq!(st.len(), 2);
435        assert!(st.iter().find(|s| s.id == "x").unwrap().underruns >= 1, "x ran dry");
436        c.remove("x");
437        assert_eq!(c.stats().len(), 1);
438        assert!(c.add("y").is_some(), "the same speaker again");
439    }
440
441    #[test]
442    fn the_ducker_drops_the_music_while_someone_talks_and_comes_back() {
443        let mut d = Ducker::new(6.0, 10.0, 200.0, 48_000);
444        for _ in 0..10 {
445            d.next(true, 480);
446        }
447        assert!((d.gain() - db_to_gain(-6.0)).abs() < 0.01, "{}", d.gain());
448        for _ in 0..200 {
449            d.next(false, 480);
450        }
451        assert!((d.gain() - 1.0).abs() < 0.01);
452        let mut off = Ducker::new(0.0, 10.0, 200.0, 48_000);
453        assert_eq!(off.next(true, 4800), 1.0, "0 dB is off");
454    }
455}