Skip to main content

weirdnet_audio_engine/
manual.rs

1use crate::sink::validate;
2use crate::{AudioSink, RenderFn, SinkConfig, SinkError, SinkHandle, SinkStats};
3use std::sync::{Arc, Mutex};
4
5struct Running {
6    config: SinkConfig,
7    render: RenderFn,
8}
9
10/// A sink with no device. [`ManualSink::render_block`] plays the part of the device's callback, so a test decides exactly when and how much
11/// audio is pulled. It accepts any valid config.
12#[derive(Clone)]
13pub struct ManualSink {
14    running: Arc<Mutex<Option<Running>>>,
15    stats: SinkStats,
16    default: SinkConfig,
17}
18
19impl Default for ManualSink {
20    fn default() -> Self {
21        ManualSink::new()
22    }
23}
24
25struct Stop(Arc<Mutex<Option<Running>>>);
26
27impl Drop for Stop {
28    fn drop(&mut self) {
29        if let Ok(mut r) = self.0.lock() {
30            *r = None;
31        }
32    }
33}
34
35impl ManualSink {
36    /// A manual sink that reports 48 kHz stereo as its default.
37    pub fn new() -> Self {
38        ManualSink { running: Arc::default(), stats: SinkStats::new(), default: SinkConfig::new(48_000, 2) }
39    }
40
41    pub fn is_running(&self) -> bool {
42        self.running.lock().is_ok_and(|r| r.is_some())
43    }
44
45    pub fn stats(&self) -> &SinkStats {
46        &self.stats
47    }
48
49    /// Calls the render function once for `frames` frames and returns the interleaved samples (`None` if the sink is not running).
50    /// The buffer is filled with a sentinel first, so a render function that forgets to write shows up in a test.
51    pub fn render_block(&self, frames: usize) -> Option<Vec<f32>> {
52        let mut guard = self.running.lock().ok()?;
53        let running = guard.as_mut()?;
54        let mut buffer = vec![f32::NAN; frames * usize::from(running.config.channels)];
55        (running.render)(&mut buffer);
56        self.stats.record_callback();
57        Some(buffer)
58    }
59
60    /// Pulls `frames` frames in blocks of `block` frames (the last one shorter) and returns them joined, like a device would.
61    pub fn render_blocks(&self, frames: usize, block: usize) -> Option<Vec<f32>> {
62        let block = block.max(1);
63        let mut out = Vec::new();
64        let mut left = frames;
65        while left > 0 {
66            let n = left.min(block);
67            out.extend(self.render_block(n)?);
68            left -= n;
69        }
70        Some(out)
71    }
72}
73
74impl AudioSink for ManualSink {
75    fn default_config(&self) -> Result<SinkConfig, SinkError> {
76        Ok(self.default)
77    }
78
79    fn start(&mut self, config: SinkConfig, render: RenderFn) -> Result<SinkHandle, SinkError> {
80        validate(config)?;
81        let mut running = self.running.lock().map_err(|_| SinkError::Backend("poisoned".into()))?;
82        if running.is_some() {
83            return Err(SinkError::AlreadyStarted);
84        }
85        *running = Some(Running { config, render });
86        Ok(SinkHandle::new(config, "manual sink (no device)", self.stats.clone(), Box::new(Stop(self.running.clone()))))
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    fn silence_fill(v: f32) -> RenderFn {
95        Box::new(move |out: &mut [f32]| out.fill(v))
96    }
97
98    #[test]
99    fn renders_what_the_function_writes_and_counts_calls() {
100        let mut sink = ManualSink::new();
101        assert!(sink.render_block(4).is_none(), "not running yet");
102        let handle = sink.start(SinkConfig::new(44_100, 2), silence_fill(0.5)).unwrap();
103        assert_eq!(handle.config(), SinkConfig::new(44_100, 2));
104        let block = sink.render_block(3).unwrap();
105        assert_eq!(block, vec![0.5; 6]);
106        assert_eq!(sink.stats().callbacks(), 1);
107        assert_eq!(sink.render_blocks(10, 4).unwrap().len(), 20);
108        assert_eq!(sink.stats().callbacks(), 4, "10 frames in blocks of 4 is 3 more calls");
109    }
110
111    #[test]
112    fn the_buffer_is_pre_filled_with_a_sentinel_so_a_silent_bug_is_visible() {
113        let mut sink = ManualSink::new();
114        let _h = sink.start(SinkConfig::new(48_000, 1), Box::new(|_out: &mut [f32]| {})).unwrap();
115        assert!(sink.render_block(2).unwrap().iter().all(|s| s.is_nan()));
116    }
117
118    #[test]
119    fn dropping_the_handle_stops_it_and_allows_a_restart() {
120        let mut sink = ManualSink::new();
121        let h = sink.start(SinkConfig::new(48_000, 2), silence_fill(0.1)).unwrap();
122        assert!(sink.is_running());
123        assert_eq!(sink.start(SinkConfig::new(48_000, 2), silence_fill(0.2)).unwrap_err(), SinkError::AlreadyStarted);
124        drop(h);
125        assert!(!sink.is_running());
126        assert!(sink.render_block(1).is_none());
127        let _h2 = sink.start(SinkConfig::new(48_000, 2), silence_fill(0.2)).unwrap();
128        assert_eq!(sink.render_block(1).unwrap(), vec![0.2, 0.2]);
129    }
130
131    #[test]
132    fn invalid_configs_are_rejected_and_do_not_start() {
133        let mut sink = ManualSink::new();
134        for c in [SinkConfig::new(0, 2), SinkConfig::new(48_000, 0), SinkConfig::new(48_000, 2).with_buffer_frames(0)] {
135            assert!(matches!(sink.start(c, silence_fill(0.0)), Err(SinkError::InvalidConfig(_))), "{c:?}");
136        }
137        assert!(!sink.is_running());
138    }
139
140    #[test]
141    fn zero_frames_is_fine_and_the_default_is_reported() {
142        let mut sink = ManualSink::new();
143        assert_eq!(sink.default_config().unwrap(), SinkConfig::new(48_000, 2));
144        let _h = sink.start(SinkConfig::new(48_000, 2), silence_fill(0.0)).unwrap();
145        assert_eq!(sink.render_block(0).unwrap(), Vec::<f32>::new());
146        assert_eq!(sink.render_blocks(0, 4).unwrap(), Vec::<f32>::new());
147    }
148
149    #[test]
150    fn errors_have_readable_messages() {
151        let e = SinkError::UnsupportedConfig { requested: SinkConfig::new(96_000, 6), supported: Some(SinkConfig::new(48_000, 2)) };
152        let text = e.to_string();
153        assert!(text.contains("96000") && text.contains("48000"), "{text}");
154        assert_eq!(SinkError::NoDevice.to_string(), "no audio output device");
155    }
156}