use crate::{RenderFn, SinkConfig};
use crossbeam_queue::ArrayQueue;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
pub const MAX_SPEAKERS: usize = 32;
pub const ACTIVE_LEVEL: f32 = 0.005_6;
pub fn db_to_gain(db: f32) -> f32 {
10f32.powf(db / 20.0)
}
#[derive(Clone, Debug)]
pub struct MicSwitch {
muted: Arc<AtomicBool>,
push_to_talk: Arc<AtomicBool>,
pressed: Arc<AtomicBool>,
forced: Arc<AtomicBool>,
}
impl Default for MicSwitch {
fn default() -> Self {
MicSwitch::new()
}
}
impl MicSwitch {
pub fn new() -> Self {
MicSwitch { muted: Arc::new(AtomicBool::new(true)), push_to_talk: Arc::default(), pressed: Arc::default(), forced: Arc::default() }
}
pub fn set_muted(&self, muted: bool) {
self.muted.store(muted, Ordering::Release);
}
pub fn muted(&self) -> bool {
self.muted.load(Ordering::Acquire)
}
pub fn set_push_to_talk(&self, on: bool) {
self.push_to_talk.store(on, Ordering::Release);
}
pub fn push_to_talk(&self) -> bool {
self.push_to_talk.load(Ordering::Acquire)
}
pub fn set_pressed(&self, pressed: bool) {
self.pressed.store(pressed, Ordering::Release);
}
pub fn set_forced_mute(&self, forced: bool) {
self.forced.store(forced, Ordering::Release);
}
pub fn forced_mute(&self) -> bool {
self.forced.load(Ordering::Acquire)
}
pub fn live(&self) -> bool {
!self.muted() && !self.forced_mute() && (!self.push_to_talk() || self.pressed.load(Ordering::Acquire))
}
}
#[derive(Clone, Debug)]
pub struct MicGate {
threshold: f32,
hold_frames: u64,
quiet_frames: u64,
}
impl MicGate {
pub fn new(threshold_db: f32, hold_frames: u64) -> Self {
MicGate { threshold: db_to_gain(threshold_db), hold_frames, quiet_frames: u64::MAX / 2 }
}
pub fn process(&mut self, block: &mut [f32], channels: u16) -> bool {
let frames = (block.len() / usize::from(channels.max(1))) as u64;
let peak = block.iter().fold(0f32, |m, s| m.max(s.abs()));
if peak >= self.threshold {
self.quiet_frames = 0;
} else {
self.quiet_frames = self.quiet_frames.saturating_add(frames);
}
let open = self.quiet_frames <= self.hold_frames;
if !open {
block.fill(0.0);
}
open
}
}
struct Speaker {
id: String,
queue: ArrayQueue<f32>,
gain: AtomicU32,
muted: AtomicBool,
gone: AtomicBool,
primed: AtomicBool,
level: AtomicU32,
underruns: AtomicU64,
dropped: AtomicU64,
played: AtomicU64,
}
#[derive(Clone)]
pub struct SpeakerInput(Arc<Speaker>);
impl SpeakerInput {
pub fn push(&self, samples: &[f32]) {
for &s in samples {
if self.0.queue.force_push(s).is_some() {
self.0.dropped.fetch_add(1, Ordering::Relaxed);
}
}
}
pub fn queued(&self) -> usize {
self.0.queue.len()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpeakerStats {
pub id: String,
pub level: f32,
pub underruns: u64,
pub dropped: u64,
pub played: u64,
pub queued: usize,
}
pub struct TalkbackControl {
adds: Arc<ArrayQueue<Arc<Speaker>>>,
speakers: Mutex<Vec<Arc<Speaker>>>,
all_muted: Arc<AtomicBool>,
active: Arc<AtomicBool>,
queue_frames: usize,
}
pub struct TalkbackAudio {
adds: Arc<ArrayQueue<Arc<Speaker>>>,
list: Vec<Arc<Speaker>>,
channels: usize,
jitter: usize,
all_muted: Arc<AtomicBool>,
active: Arc<AtomicBool>,
}
pub fn talkback_bus(config: SinkConfig, jitter_frames: usize) -> (TalkbackControl, TalkbackAudio) {
let adds = Arc::new(ArrayQueue::new(MAX_SPEAKERS));
let all_muted = Arc::new(AtomicBool::new(false));
let active = Arc::new(AtomicBool::new(false));
let queue_frames = (config.sample_rate as usize).max(jitter_frames * 4);
(
TalkbackControl { adds: adds.clone(), speakers: Mutex::new(Vec::new()), all_muted: all_muted.clone(), active: active.clone(), queue_frames },
TalkbackAudio {
adds,
list: Vec::with_capacity(MAX_SPEAKERS),
channels: usize::from(config.channels.max(1)),
jitter: jitter_frames,
all_muted,
active,
},
)
}
impl TalkbackControl {
fn find(&self, id: &str) -> Option<Arc<Speaker>> {
self.speakers.lock().ok()?.iter().find(|s| s.id == id).cloned()
}
pub fn add(&self, id: &str) -> Option<SpeakerInput> {
if let Some(s) = self.find(id) {
return Some(SpeakerInput(s));
}
let mut list = self.speakers.lock().ok()?;
list.retain(|s| !s.gone.load(Ordering::Acquire));
if list.len() >= MAX_SPEAKERS {
return None;
}
let s = Arc::new(Speaker {
id: id.to_string(),
queue: ArrayQueue::new(self.queue_frames),
gain: AtomicU32::new(1f32.to_bits()),
muted: AtomicBool::new(false),
gone: AtomicBool::new(false),
primed: AtomicBool::new(false),
level: AtomicU32::new(0),
underruns: AtomicU64::new(0),
dropped: AtomicU64::new(0),
played: AtomicU64::new(0),
});
self.adds.push(s.clone()).ok()?;
list.push(s.clone());
Some(SpeakerInput(s))
}
pub fn remove(&self, id: &str) {
if let Ok(mut list) = self.speakers.lock() {
for s in list.iter().filter(|s| s.id == id) {
s.gone.store(true, Ordering::Release);
}
list.retain(|s| s.id != id);
}
}
pub fn set_gain(&self, id: &str, gain: f32) {
if let Some(s) = self.find(id) {
s.gain.store(gain.clamp(0.0, 4.0).to_bits(), Ordering::Relaxed);
}
}
pub fn set_muted(&self, id: &str, muted: bool) {
if let Some(s) = self.find(id) {
s.muted.store(muted, Ordering::Relaxed);
}
}
pub fn set_all_muted(&self, muted: bool) {
self.all_muted.store(muted, Ordering::Relaxed);
}
pub fn active(&self) -> bool {
self.active.load(Ordering::Relaxed)
}
pub fn stats(&self) -> Vec<SpeakerStats> {
let Ok(list) = self.speakers.lock() else { return vec![] };
list.iter()
.map(|s| SpeakerStats {
id: s.id.clone(),
level: f32::from_bits(s.level.load(Ordering::Relaxed)),
underruns: s.underruns.load(Ordering::Relaxed),
dropped: s.dropped.load(Ordering::Relaxed),
played: s.played.load(Ordering::Relaxed),
queued: s.queue.len(),
})
.collect()
}
}
impl TalkbackAudio {
pub fn render(&mut self, out: &mut [f32]) {
while let Some(s) = self.adds.pop() {
if self.list.len() < self.list.capacity() {
self.list.push(s);
}
}
self.list.retain(|s| !s.gone.load(Ordering::Acquire));
out.fill(0.0);
let frames = out.len() / self.channels;
let all_muted = self.all_muted.load(Ordering::Relaxed);
let mut active = false;
for s in &self.list {
if !s.primed.load(Ordering::Relaxed) {
if s.queue.len() < self.jitter.max(1) {
s.level.store(0, Ordering::Relaxed);
continue;
}
s.primed.store(true, Ordering::Relaxed);
}
let gain = if all_muted || s.muted.load(Ordering::Relaxed) { 0.0 } else { f32::from_bits(s.gain.load(Ordering::Relaxed)) };
let mut peak = 0f32;
let mut played = 0u64;
for f in 0..frames {
let Some(x) = s.queue.pop() else {
s.primed.store(false, Ordering::Relaxed);
s.underruns.fetch_add(1, Ordering::Relaxed);
break;
};
played += 1;
let v = x * gain;
peak = peak.max(v.abs());
for c in 0..self.channels {
out[f * self.channels + c] += v;
}
}
s.played.fetch_add(played, Ordering::Relaxed);
s.level.store(peak.to_bits(), Ordering::Relaxed);
active |= peak >= ACTIVE_LEVEL;
}
self.active.store(active, Ordering::Relaxed);
}
pub fn into_render(mut self) -> RenderFn {
Box::new(move |out: &mut [f32]| self.render(out))
}
}
#[derive(Clone, Debug)]
pub struct Ducker {
target: f32,
gain: f32,
attack: f32,
release: f32,
}
impl Ducker {
pub fn new(duck_db: f32, attack_ms: f32, release_ms: f32, sample_rate: u32) -> Self {
let per_frame = |ms: f32| if ms <= 0.0 { 1.0 } else { 1.0 - (-1.0 / (ms / 1000.0 * sample_rate as f32)).exp() };
Ducker { target: db_to_gain(-duck_db.abs()), gain: 1.0, attack: per_frame(attack_ms), release: per_frame(release_ms) }
}
pub fn set_depth(&mut self, duck_db: f32) {
self.target = db_to_gain(-duck_db.abs());
}
pub fn next(&mut self, active: bool, frames: usize) -> f32 {
let (goal, k) = if active { (self.target, self.attack) } else { (1.0, self.release) };
let keep = (1.0 - k).powi(frames as i32);
self.gain = goal + (self.gain - goal) * keep;
self.gain
}
pub fn gain(&self) -> f32 {
self.gain
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_mic_starts_muted_and_push_to_talk_and_a_forced_mute_hold() {
let m = MicSwitch::new();
assert!(m.muted() && !m.live(), "muted on start");
m.set_muted(false);
assert!(m.live(), "open mic once unmuted");
m.set_push_to_talk(true);
assert!(!m.live());
m.set_pressed(true);
assert!(m.live());
m.set_forced_mute(true);
assert!(!m.live(), "the host's mute wins");
m.set_forced_mute(false);
m.set_push_to_talk(false);
assert!(m.live());
}
#[test]
fn the_gate_silences_quiet_blocks_after_the_hold() {
let mut g = MicGate::new(-40.0, 960);
let mut loud = vec![0.2f32; 480];
assert!(g.process(&mut loud, 1));
assert_eq!(loud[0], 0.2);
let mut quiet = vec![0.001f32; 480];
assert!(g.process(&mut quiet, 1), "held open");
assert!(g.process(&mut quiet, 1), "still within the hold");
let mut quiet2 = vec![0.001f32; 480];
assert!(!g.process(&mut quiet2, 1));
assert!(quiet2.iter().all(|s| *s == 0.0), "closed: silence");
}
#[test]
fn the_bus_mixes_speakers_with_volume_mute_and_a_jitter_buffer() {
let (c, mut a) = talkback_bus(SinkConfig::new(48_000, 2), 256);
let x = c.add("x").unwrap();
let y = c.add("y").unwrap();
let mut out = vec![0f32; 2 * 128];
x.push(&[0.25; 200]);
a.render(&mut out);
assert!(out.iter().all(|s| *s == 0.0), "x waits for its jitter buffer");
x.push(&[0.25; 200]);
y.push(&[0.5; 400]);
c.set_gain("y", 0.5);
a.render(&mut out);
assert!((out[0] - 0.5).abs() < 1e-6 && (out[1] - 0.5).abs() < 1e-6, "both, upmixed to two channels: {}", out[0]);
assert!(c.active());
c.set_muted("x", true);
a.render(&mut out);
assert!((out[0] - 0.25).abs() < 1e-6, "x muted for me");
c.set_all_muted(true);
a.render(&mut out);
assert!(out.iter().all(|s| *s == 0.0) && !c.active(), "all muted");
a.render(&mut out);
let st = c.stats();
assert_eq!(st.len(), 2);
assert!(st.iter().find(|s| s.id == "x").unwrap().underruns >= 1, "x ran dry");
c.remove("x");
assert_eq!(c.stats().len(), 1);
assert!(c.add("y").is_some(), "the same speaker again");
}
#[test]
fn the_ducker_drops_the_music_while_someone_talks_and_comes_back() {
let mut d = Ducker::new(6.0, 10.0, 200.0, 48_000);
for _ in 0..10 {
d.next(true, 480);
}
assert!((d.gain() - db_to_gain(-6.0)).abs() < 0.01, "{}", d.gain());
for _ in 0..200 {
d.next(false, 480);
}
assert!((d.gain() - 1.0).abs() < 0.01);
let mut off = Ducker::new(0.0, 10.0, 200.0, 48_000);
assert_eq!(off.next(true, 4800), 1.0, "0 dB is off");
}
}