oddio/
signal.rs

1use crate::{flatten_stereo, Sample};
2
3/// An audio signal
4///
5/// This interface is intended for use only from the code actually generating an audio signal for
6/// output. For example, in a real-time application, `Signal`s will typically be owned by the
7/// real-time audio thread and not directly accessible from elsewhere. Access to an active signal
8/// for other purposes (e.g. to adjust parameters) is generally through a control handle returned by
9/// its constructor.
10///
11/// To ensure glitch-free audio, none of these methods should perform any operation that may
12/// wait. This includes locks, memory allocation or freeing, and even unbounded compare-and-swap
13/// loops.
14pub trait Signal {
15    /// Type of frames yielded by `sample`, e.g. `[Sample; 2]` for stereo
16    type Frame;
17
18    /// Sample frames separated by `interval` seconds each
19    fn sample(&mut self, interval: f32, out: &mut [Self::Frame]);
20
21    /// Whether future calls to `sample` with a nonnegative `interval` will only produce zeroes
22    ///
23    /// Commonly used to determine when a `Signal` can be discarded.
24    #[inline]
25    fn is_finished(&self) -> bool {
26        false
27    }
28}
29
30impl<T: Signal + ?Sized> Signal for alloc::boxed::Box<T> {
31    type Frame = T::Frame;
32
33    fn sample(&mut self, interval: f32, out: &mut [T::Frame]) {
34        (**self).sample(interval, out);
35    }
36
37    #[inline]
38    fn is_finished(&self) -> bool {
39        (**self).is_finished()
40    }
41}
42
43/// Audio signals which support seeking
44///
45/// Should only be implemented for signals which are defined deterministically in terms of absolute
46/// sample time. Nondeterministic or stateful behavior may produce audible glitches in downstream
47/// code.
48pub trait Seek: Signal {
49    /// Shift the starting point of the next `sample` call by `seconds`
50    fn seek(&mut self, seconds: f32);
51}
52
53impl<T: Seek + ?Sized> Seek for alloc::boxed::Box<T> {
54    #[inline]
55    fn seek(&mut self, seconds: f32) {
56        (**self).seek(seconds);
57    }
58}
59
60/// Adapts a mono signal to output stereo by duplicating its output
61pub struct MonoToStereo<T: ?Sized>(T);
62
63impl<T> MonoToStereo<T> {
64    /// Adapt `signal` from mono to stereo
65    pub fn new(signal: T) -> Self {
66        Self(signal)
67    }
68}
69
70impl<T: Signal<Frame = Sample>> Signal for MonoToStereo<T> {
71    type Frame = [Sample; 2];
72
73    fn sample(&mut self, interval: f32, out: &mut [[Sample; 2]]) {
74        let n = out.len();
75        let buf = flatten_stereo(out);
76        self.0.sample(interval, &mut buf[..n]);
77        for i in (0..buf.len()).rev() {
78            buf[i] = buf[i / 2];
79        }
80    }
81
82    fn is_finished(&self) -> bool {
83        self.0.is_finished()
84    }
85}
86
87impl<T: Seek + Signal<Frame = Sample>> Seek for MonoToStereo<T> {
88    fn seek(&mut self, seconds: f32) {
89        self.0.seek(seconds)
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    struct CountingSignal(u32);
98
99    impl Signal for CountingSignal {
100        type Frame = Sample;
101        fn sample(&mut self, _: f32, out: &mut [Sample]) {
102            for x in out {
103                let i = self.0;
104                *x = i as f32;
105                self.0 = i + 1;
106            }
107        }
108    }
109
110    #[test]
111    fn mono_to_stereo() {
112        let mut signal = MonoToStereo::new(CountingSignal(0));
113        let mut buf = [[0.0; 2]; 4];
114        signal.sample(1.0, (&mut buf[..]).into());
115        assert_eq!(buf, [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]);
116    }
117}