weirdnet-audio-engine 0.4.0

Audio engine pieces for Weirdnet: the AudioSink trait, a manual sink for tests, a cpal device sink (feature `cpal`) and a waveform player.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Talkback: voices between people, kept apart from the music.
//!
//! * [`MicSwitch`]: the person's own mic switch, shared between a UI and the capture thread. It **starts muted**; push to talk is an
//!   option. [`MicSwitch::live`] says whether the mic is sending.
//! * [`MicGate`]: a level gate with hold, so an open mic sends silence (zeros) between words.
//! * [`talkback_bus`]: the talkback bus, a mixer of speakers (mono, each with a small jitter buffer, a volume and a mute, and a mute
//!   for everyone) that a device plays. It is a separate bus: nothing here touches a music bus.
//! * [`Ducker`]: the gain a music bus applies while someone talks (smoothed, a few dB by default, off at 0 dB).
//!
//! The bus's render function follows the engine's rule: no lock, no block, no allocation. Speakers are added through a bounded lock-free
//! queue into a list with fixed capacity ([`MAX_SPEAKERS`]); a speaker's samples arrive through its own bounded queue.

use crate::{RenderFn, SinkConfig};
use crossbeam_queue::ArrayQueue;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

/// The most speakers one bus mixes.
pub const MAX_SPEAKERS: usize = 32;
/// A speaker counts as talking above this peak level (−45 dBFS).
pub const ACTIVE_LEVEL: f32 = 0.005_6;

/// dB to a linear gain.
pub fn db_to_gain(db: f32) -> f32 {
    10f32.powf(db / 20.0)
}

/// The person's own mic switch. It starts muted: unmuting is a deliberate first step.
#[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 {
    /// A switch, muted.
    pub fn new() -> Self {
        MicSwitch { muted: Arc::new(AtomicBool::new(true)), push_to_talk: Arc::default(), pressed: Arc::default(), forced: Arc::default() }
    }

    /// Mute or unmute your mic.
    pub fn set_muted(&self, muted: bool) {
        self.muted.store(muted, Ordering::Release);
    }

    /// Whether you muted your mic.
    pub fn muted(&self) -> bool {
        self.muted.load(Ordering::Acquire)
    }

    /// Push to talk on or off. With it on, the mic sends only while the talk key is held.
    pub fn set_push_to_talk(&self, on: bool) {
        self.push_to_talk.store(on, Ordering::Release);
    }

    /// Whether push to talk is on.
    pub fn push_to_talk(&self) -> bool {
        self.push_to_talk.load(Ordering::Acquire)
    }

    /// The talk key is held (push to talk).
    pub fn set_pressed(&self, pressed: bool) {
        self.pressed.store(pressed, Ordering::Release);
    }

    /// Muted from outside (the host, a policy, a kick): wins over the person's own switch until lifted.
    pub fn set_forced_mute(&self, forced: bool) {
        self.forced.store(forced, Ordering::Release);
    }

    /// Whether a mute from outside holds.
    pub fn forced_mute(&self) -> bool {
        self.forced.load(Ordering::Acquire)
    }

    /// Whether the mic is sending now.
    pub fn live(&self) -> bool {
        !self.muted() && !self.forced_mute() && (!self.push_to_talk() || self.pressed.load(Ordering::Acquire))
    }
}

/// A level gate with hold: below the threshold for longer than the hold, the block is silenced.
#[derive(Clone, Debug)]
pub struct MicGate {
    threshold: f32,
    hold_frames: u64,
    quiet_frames: u64,
}

impl MicGate {
    /// A gate at `threshold_db` (dBFS peak) that stays open `hold_frames` after the last loud block.
    pub fn new(threshold_db: f32, hold_frames: u64) -> Self {
        MicGate { threshold: db_to_gain(threshold_db), hold_frames, quiet_frames: u64::MAX / 2 }
    }

    /// Gate one block of interleaved samples (`channels` per frame) in place. Returns whether it was open.
    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,
}

/// Where a speaker's samples go in (from the network thread): mono, at the bus's rate.
#[derive(Clone)]
pub struct SpeakerInput(Arc<Speaker>);

impl SpeakerInput {
    /// Queue mono samples. When the queue is full the oldest go (talkback stays current rather than late).
    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);
            }
        }
    }

    /// Samples waiting to be played.
    pub fn queued(&self) -> usize {
        self.0.queue.len()
    }
}

/// What the bus reports about one speaker.
#[derive(Clone, Debug, PartialEq)]
pub struct SpeakerStats {
    /// The speaker.
    pub id: String,
    /// Peak level of the last block played (linear).
    pub level: f32,
    /// Times the queue ran dry while playing.
    pub underruns: u64,
    /// Samples dropped because the queue was full.
    pub dropped: u64,
    /// Samples played.
    pub played: u64,
    /// Samples waiting.
    pub queued: usize,
}

/// The control side of a talkback bus.
pub struct TalkbackControl {
    adds: Arc<ArrayQueue<Arc<Speaker>>>,
    speakers: Mutex<Vec<Arc<Speaker>>>,
    all_muted: Arc<AtomicBool>,
    active: Arc<AtomicBool>,
    queue_frames: usize,
}

/// The audio side: make it the render function of a sink with [`TalkbackAudio::into_render`].
pub struct TalkbackAudio {
    adds: Arc<ArrayQueue<Arc<Speaker>>>,
    list: Vec<Arc<Speaker>>,
    channels: usize,
    jitter: usize,
    all_muted: Arc<AtomicBool>,
    active: Arc<AtomicBool>,
}

/// A talkback bus for a device with `config`, holding `jitter_frames` of each speaker before it starts playing (again after running dry).
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()
    }

    /// Add a speaker (or return the one with this id). `None` when the bus is full.
    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))
    }

    /// Remove a speaker (the audio side lets go of it at its next block).
    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);
        }
    }

    /// A speaker's volume (linear, 0 to 4).
    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);
        }
    }

    /// Mute or unmute one speaker for yourself.
    pub fn set_muted(&self, id: &str, muted: bool) {
        if let Some(s) = self.find(id) {
            s.muted.store(muted, Ordering::Relaxed);
        }
    }

    /// Mute all talkback for yourself. The music is never touched.
    pub fn set_all_muted(&self, muted: bool) {
        self.all_muted.store(muted, Ordering::Relaxed);
    }

    /// Whether someone is audible now (for ducking).
    pub fn active(&self) -> bool {
        self.active.load(Ordering::Relaxed)
    }

    /// Each speaker's numbers.
    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 {
    /// Mix one block of interleaved output.
    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);
    }

    /// The render function for a sink.
    pub fn into_render(mut self) -> RenderFn {
        Box::new(move |out: &mut [f32]| self.render(out))
    }
}

/// The gain a music bus applies while someone talks: down by `duck_db` within the attack, back within the release.
#[derive(Clone, Debug)]
pub struct Ducker {
    target: f32,
    gain: f32,
    attack: f32,
    release: f32,
}

impl Ducker {
    /// Ducking by `duck_db` (0 is off), with attack and release times in ms, for blocks at `sample_rate`.
    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) }
    }

    /// Change the depth (0 dB is off).
    pub fn set_depth(&mut self, duck_db: f32) {
        self.target = db_to_gain(-duck_db.abs());
    }

    /// Advance by `frames` with talkback `active` or not; returns the gain for the music now.
    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
    }

    /// The gain now.
    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");
    }
}