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
use crate::{flatten_stereo, Sample};

/// An audio signal
///
/// This interface is intended for use only from the code actually generating an audio signal for
/// output. For example, in a real-time application, `Signal`s will typically be owned by the
/// real-time audio thread and not directly accessible from elsewhere. Access to an active signal
/// for other purposes (e.g. to adjust parameters) is generally through a control handle returned by
/// its constructor.
///
/// To ensure glitch-free audio, none of these methods should perform any operation that may
/// wait. This includes locks, memory allocation or freeing, and even unbounded compare-and-swap
/// loops.
pub trait Signal {
    /// Type of frames yielded by `sample`, e.g. `[Sample; 2]` for stereo
    type Frame;

    /// Sample frames separated by `interval` seconds each
    fn sample(&mut self, interval: f32, out: &mut [Self::Frame]);

    /// Whether future calls to `sample` with a nonnegative `interval` will only produce zeroes
    ///
    /// Commonly used to determine when a `Signal` can be discarded.
    #[inline]
    fn is_finished(&self) -> bool {
        false
    }
}

impl<T: Signal + ?Sized> Signal for alloc::boxed::Box<T> {
    type Frame = T::Frame;

    fn sample(&mut self, interval: f32, out: &mut [T::Frame]) {
        (**self).sample(interval, out);
    }

    #[inline]
    fn is_finished(&self) -> bool {
        (**self).is_finished()
    }
}

/// Audio signals which support seeking
///
/// Should only be implemented for signals which are defined deterministically in terms of absolute
/// sample time. Nondeterministic or stateful behavior may produce audible glitches in downstream
/// code.
pub trait Seek: Signal {
    /// Shift the starting point of the next `sample` call by `seconds`
    fn seek(&mut self, seconds: f32);
}

impl<T: Seek + ?Sized> Seek for alloc::boxed::Box<T> {
    #[inline]
    fn seek(&mut self, seconds: f32) {
        (**self).seek(seconds);
    }
}

/// Adapts a mono signal to output stereo by duplicating its output
pub struct MonoToStereo<T: ?Sized>(T);

impl<T> MonoToStereo<T> {
    /// Adapt `signal` from mono to stereo
    pub fn new(signal: T) -> Self {
        Self(signal)
    }
}

impl<T: Signal<Frame = Sample>> Signal for MonoToStereo<T> {
    type Frame = [Sample; 2];

    fn sample(&mut self, interval: f32, out: &mut [[Sample; 2]]) {
        let n = out.len();
        let buf = flatten_stereo(out);
        self.0.sample(interval, &mut buf[..n]);
        for i in (0..buf.len()).rev() {
            buf[i] = buf[i / 2];
        }
    }

    fn is_finished(&self) -> bool {
        self.0.is_finished()
    }
}

impl<T: Seek + Signal<Frame = Sample>> Seek for MonoToStereo<T> {
    fn seek(&mut self, seconds: f32) {
        self.0.seek(seconds)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct CountingSignal(u32);

    impl Signal for CountingSignal {
        type Frame = Sample;
        fn sample(&mut self, _: f32, out: &mut [Sample]) {
            for x in out {
                let i = self.0;
                *x = i as f32;
                self.0 = i + 1;
            }
        }
    }

    #[test]
    fn mono_to_stereo() {
        let mut signal = MonoToStereo::new(CountingSignal(0));
        let mut buf = [[0.0; 2]; 4];
        signal.sample(1.0, (&mut buf[..]).into());
        assert_eq!(buf, [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]);
    }
}