1use crate::{RenderFn, SinkConfig};
14use crossbeam_queue::ArrayQueue;
15use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
16use std::sync::{Arc, Mutex};
17
18pub const MAX_SPEAKERS: usize = 32;
20pub const ACTIVE_LEVEL: f32 = 0.005_6;
22
23pub fn db_to_gain(db: f32) -> f32 {
25 10f32.powf(db / 20.0)
26}
27
28#[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 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 pub fn set_muted(&self, muted: bool) {
51 self.muted.store(muted, Ordering::Release);
52 }
53
54 pub fn muted(&self) -> bool {
56 self.muted.load(Ordering::Acquire)
57 }
58
59 pub fn set_push_to_talk(&self, on: bool) {
61 self.push_to_talk.store(on, Ordering::Release);
62 }
63
64 pub fn push_to_talk(&self) -> bool {
66 self.push_to_talk.load(Ordering::Acquire)
67 }
68
69 pub fn set_pressed(&self, pressed: bool) {
71 self.pressed.store(pressed, Ordering::Release);
72 }
73
74 pub fn set_forced_mute(&self, forced: bool) {
76 self.forced.store(forced, Ordering::Release);
77 }
78
79 pub fn forced_mute(&self) -> bool {
81 self.forced.load(Ordering::Acquire)
82 }
83
84 pub fn live(&self) -> bool {
86 !self.muted() && !self.forced_mute() && (!self.push_to_talk() || self.pressed.load(Ordering::Acquire))
87 }
88}
89
90#[derive(Clone, Debug)]
92pub struct MicGate {
93 threshold: f32,
94 hold_frames: u64,
95 quiet_frames: u64,
96}
97
98impl MicGate {
99 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 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#[derive(Clone)]
136pub struct SpeakerInput(Arc<Speaker>);
137
138impl SpeakerInput {
139 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 pub fn queued(&self) -> usize {
150 self.0.queue.len()
151 }
152}
153
154#[derive(Clone, Debug, PartialEq)]
156pub struct SpeakerStats {
157 pub id: String,
159 pub level: f32,
161 pub underruns: u64,
163 pub dropped: u64,
165 pub played: u64,
167 pub queued: usize,
169}
170
171pub 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
180pub 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
190pub 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 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 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 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 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 pub fn set_all_muted(&self, muted: bool) {
267 self.all_muted.store(muted, Ordering::Relaxed);
268 }
269
270 pub fn active(&self) -> bool {
272 self.active.load(Ordering::Relaxed)
273 }
274
275 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 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 pub fn into_render(mut self) -> RenderFn {
337 Box::new(move |out: &mut [f32]| self.render(out))
338 }
339}
340
341#[derive(Clone, Debug)]
343pub struct Ducker {
344 target: f32,
345 gain: f32,
346 attack: f32,
347 release: f32,
348}
349
350impl Ducker {
351 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 pub fn set_depth(&mut self, duck_db: f32) {
359 self.target = db_to_gain(-duck_db.abs());
360 }
361
362 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 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}