geng_rodio/
dynamic_mixer.rs

1//! Mixer that plays multiple sounds at the same time.
2
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::Duration;
6
7use crate::source::{Source, UniformSourceIterator};
8use crate::Sample;
9
10/// Builds a new mixer.
11///
12/// You can choose the characteristics of the output thanks to this constructor. All the sounds
13/// added to the mixer will be converted to these values.
14///
15/// After creating a mixer, you can add new sounds with the controller.
16pub fn mixer<S>(
17    channels: u16,
18    sample_rate: u32,
19) -> (Arc<DynamicMixerController<S>>, DynamicMixer<S>)
20where
21    S: Sample + Send + 'static,
22{
23    let input = Arc::new(DynamicMixerController {
24        has_pending: AtomicBool::new(false),
25        pending_sources: Mutex::new(Vec::new()),
26        channels,
27        sample_rate,
28    });
29
30    let output = DynamicMixer {
31        current_sources: Vec::with_capacity(16),
32        input: input.clone(),
33        sample_count: 0,
34        still_pending: vec![],
35        still_current: vec![],
36    };
37
38    (input, output)
39}
40
41/// The input of the mixer.
42pub struct DynamicMixerController<S> {
43    has_pending: AtomicBool,
44    pending_sources: Mutex<Vec<Box<dyn Source<Item = S> + Send>>>,
45    channels: u16,
46    sample_rate: u32,
47}
48
49impl<S> DynamicMixerController<S>
50where
51    S: Sample + Send + 'static,
52{
53    /// Adds a new source to mix to the existing ones.
54    #[inline]
55    pub fn add<T>(&self, source: T)
56    where
57        T: Source<Item = S> + Send + 'static,
58    {
59        let uniform_source = UniformSourceIterator::new(source, self.channels, self.sample_rate);
60        self.pending_sources
61            .lock()
62            .unwrap()
63            .push(Box::new(uniform_source) as Box<_>);
64        self.has_pending.store(true, Ordering::SeqCst); // TODO: can we relax this ordering?
65    }
66}
67
68/// The output of the mixer. Implements `Source`.
69pub struct DynamicMixer<S> {
70    // The current iterator that produces samples.
71    current_sources: Vec<Box<dyn Source<Item = S> + Send>>,
72
73    // The pending sounds.
74    input: Arc<DynamicMixerController<S>>,
75
76    // The number of samples produced so far.
77    sample_count: usize,
78
79    // A temporary vec used in start_pending_sources.
80    still_pending: Vec<Box<dyn Source<Item = S> + Send>>,
81
82    // A temporary vec used in sum_current_sources.
83    still_current: Vec<Box<dyn Source<Item = S> + Send>>,
84}
85
86impl<S> Source for DynamicMixer<S>
87where
88    S: Sample + Send + 'static,
89{
90    #[inline]
91    fn current_frame_len(&self) -> Option<usize> {
92        None
93    }
94
95    #[inline]
96    fn channels(&self) -> u16 {
97        self.input.channels
98    }
99
100    #[inline]
101    fn sample_rate(&self) -> u32 {
102        self.input.sample_rate
103    }
104
105    #[inline]
106    fn total_duration(&self) -> Option<Duration> {
107        None
108    }
109}
110
111impl<S> Iterator for DynamicMixer<S>
112where
113    S: Sample + Send + 'static,
114{
115    type Item = S;
116
117    #[inline]
118    fn next(&mut self) -> Option<S> {
119        if self.input.has_pending.load(Ordering::SeqCst) {
120            self.start_pending_sources();
121        }
122
123        self.sample_count += 1;
124
125        let sum = self.sum_current_sources();
126
127        if self.current_sources.is_empty() {
128            None
129        } else {
130            Some(sum)
131        }
132    }
133
134    #[inline]
135    fn size_hint(&self) -> (usize, Option<usize>) {
136        (0, None)
137    }
138}
139
140impl<S> DynamicMixer<S>
141where
142    S: Sample + Send + 'static,
143{
144    // Samples from the #next() function are interlaced for each of the channels.
145    // We need to ensure we start playing sources so that their samples are
146    // in-step with the modulo of the samples produced so far. Otherwise, the
147    // sound will play on the wrong channels, e.g. left / right will be reversed.
148    fn start_pending_sources(&mut self) {
149        let mut pending = self.input.pending_sources.lock().unwrap(); // TODO: relax ordering?
150
151        for source in pending.drain(..) {
152            let in_step = self.sample_count % source.channels() as usize == 0;
153
154            if in_step {
155                self.current_sources.push(source);
156            } else {
157                self.still_pending.push(source);
158            }
159        }
160        std::mem::swap(&mut self.still_pending, &mut pending);
161
162        let has_pending = !pending.is_empty();
163        self.input.has_pending.store(has_pending, Ordering::SeqCst); // TODO: relax ordering?
164    }
165
166    fn sum_current_sources(&mut self) -> S {
167        let mut sum = S::zero_value();
168
169        for mut source in self.current_sources.drain(..) {
170            if let Some(value) = source.next() {
171                sum = sum.saturating_add(value);
172                self.still_current.push(source);
173            }
174        }
175        std::mem::swap(&mut self.still_current, &mut self.current_sources);
176
177        sum
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use crate::buffer::SamplesBuffer;
184    use crate::dynamic_mixer;
185    use crate::source::Source;
186
187    #[test]
188    fn basic() {
189        let (tx, mut rx) = dynamic_mixer::mixer(1, 48000);
190
191        tx.add(SamplesBuffer::new(1, 48000, vec![10i16, -10, 10, -10]));
192        tx.add(SamplesBuffer::new(1, 48000, vec![5i16, 5, 5, 5]));
193
194        assert_eq!(rx.channels(), 1);
195        assert_eq!(rx.sample_rate(), 48000);
196        assert_eq!(rx.next(), Some(15));
197        assert_eq!(rx.next(), Some(-5));
198        assert_eq!(rx.next(), Some(15));
199        assert_eq!(rx.next(), Some(-5));
200        assert_eq!(rx.next(), None);
201    }
202
203    #[test]
204    fn channels_conv() {
205        let (tx, mut rx) = dynamic_mixer::mixer(2, 48000);
206
207        tx.add(SamplesBuffer::new(1, 48000, vec![10i16, -10, 10, -10]));
208        tx.add(SamplesBuffer::new(1, 48000, vec![5i16, 5, 5, 5]));
209
210        assert_eq!(rx.channels(), 2);
211        assert_eq!(rx.sample_rate(), 48000);
212        assert_eq!(rx.next(), Some(15));
213        assert_eq!(rx.next(), Some(15));
214        assert_eq!(rx.next(), Some(-5));
215        assert_eq!(rx.next(), Some(-5));
216        assert_eq!(rx.next(), Some(15));
217        assert_eq!(rx.next(), Some(15));
218        assert_eq!(rx.next(), Some(-5));
219        assert_eq!(rx.next(), Some(-5));
220        assert_eq!(rx.next(), None);
221    }
222
223    #[test]
224    fn rate_conv() {
225        let (tx, mut rx) = dynamic_mixer::mixer(1, 96000);
226
227        tx.add(SamplesBuffer::new(1, 48000, vec![10i16, -10, 10, -10]));
228        tx.add(SamplesBuffer::new(1, 48000, vec![5i16, 5, 5, 5]));
229
230        assert_eq!(rx.channels(), 1);
231        assert_eq!(rx.sample_rate(), 96000);
232        assert_eq!(rx.next(), Some(15));
233        assert_eq!(rx.next(), Some(5));
234        assert_eq!(rx.next(), Some(-5));
235        assert_eq!(rx.next(), Some(5));
236        assert_eq!(rx.next(), Some(15));
237        assert_eq!(rx.next(), Some(5));
238        assert_eq!(rx.next(), Some(-5));
239        assert_eq!(rx.next(), None);
240    }
241
242    #[test]
243    fn start_afterwards() {
244        let (tx, mut rx) = dynamic_mixer::mixer(1, 48000);
245
246        tx.add(SamplesBuffer::new(1, 48000, vec![10i16, -10, 10, -10]));
247
248        assert_eq!(rx.next(), Some(10));
249        assert_eq!(rx.next(), Some(-10));
250
251        tx.add(SamplesBuffer::new(1, 48000, vec![5i16, 5, 6, 6, 7, 7, 7]));
252
253        assert_eq!(rx.next(), Some(15));
254        assert_eq!(rx.next(), Some(-5));
255
256        assert_eq!(rx.next(), Some(6));
257        assert_eq!(rx.next(), Some(6));
258
259        tx.add(SamplesBuffer::new(1, 48000, vec![2i16]));
260
261        assert_eq!(rx.next(), Some(9));
262        assert_eq!(rx.next(), Some(7));
263        assert_eq!(rx.next(), Some(7));
264
265        assert_eq!(rx.next(), None);
266    }
267}