resonant-stream 0.4.0

Streaming DSP pipeline with pull-based processing and in-place chunks
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
extern crate alloc;

use alloc::boxed::Box;
use alloc::vec::Vec;

use crate::chunk::Chunk;
use crate::error::StreamError;
use crate::node::DspNode;

/// A chain of [`DspNode`]s that processes audio sequentially.
///
/// `Pipeline` owns its nodes and feeds each chunk through them in order.
/// It validates sample rate and channel count on every call to
/// [`process`](Pipeline::process) if configured to do so.
///
/// # Building
///
/// ```
/// use resonant_stream::{Pipeline, Chunk};
///
/// let pipeline = Pipeline::builder()
///     .sample_rate(44100)
///     .channels(2)
///     .build();
///
/// assert_eq!(pipeline.len(), 0);
/// ```
pub struct Pipeline {
    nodes: Vec<Box<dyn DspNode>>,
    sample_rate: Option<u32>,
    channels: Option<u16>,
}

impl Pipeline {
    /// Returns a new [`PipelineBuilder`].
    #[must_use]
    pub fn builder() -> PipelineBuilder {
        PipelineBuilder {
            nodes: Vec::new(),
            sample_rate: None,
            channels: None,
        }
    }

    /// Feeds a chunk through every node in sequence, returning the final output.
    ///
    /// If `sample_rate` or `channels` were set at build time, the input chunk is
    /// validated before processing begins.
    ///
    /// # Errors
    ///
    /// Returns [`StreamError::SampleRateMismatch`] or [`StreamError::ChannelMismatch`]
    /// if the chunk does not match the configured format, or any error returned by
    /// a node's `process` method.
    ///
    /// # Examples
    ///
    /// ```
    /// use resonant_stream::{Pipeline, Chunk, DspNode, StreamError};
    ///
    /// struct Double;
    /// impl DspNode for Double {
    ///     fn process(&mut self, mut input: Chunk) -> Result<Chunk, StreamError> {
    ///         for s in input.data_mut() { *s *= 2.0; }
    ///         Ok(input)
    ///     }
    ///     fn reset(&mut self) {}
    /// }
    ///
    /// let mut pipeline = Pipeline::builder()
    ///     .node(Double)
    ///     .node(Double)
    ///     .build();
    ///
    /// let chunk = Chunk::new(vec![1.0, 0.5], 44100, 1);
    /// let out = pipeline.process(chunk).unwrap();
    /// assert_eq!(out.data(), &[4.0, 2.0]);
    /// ```
    pub fn process(&mut self, chunk: Chunk) -> Result<Chunk, StreamError> {
        if let Some(expected) = self.sample_rate {
            let got = chunk.sample_rate();
            if got != expected {
                return Err(StreamError::SampleRateMismatch { expected, got });
            }
        }
        if let Some(expected) = self.channels {
            let got = chunk.channels();
            if got != expected {
                return Err(StreamError::ChannelMismatch { expected, got });
            }
        }

        let mut current = chunk;
        for node in &mut self.nodes {
            current = node.process(current)?;
        }
        Ok(current)
    }

    /// Resets all nodes in the pipeline, clearing internal state.
    pub fn reset(&mut self) {
        for node in &mut self.nodes {
            node.reset();
        }
    }

    /// The number of nodes in the pipeline.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Returns `true` if the pipeline has no nodes.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// The expected sample rate, if configured.
    #[inline]
    #[must_use]
    pub fn sample_rate(&self) -> Option<u32> {
        self.sample_rate
    }

    /// The expected channel count, if configured.
    #[inline]
    #[must_use]
    pub fn channels(&self) -> Option<u16> {
        self.channels
    }

    /// Appends a node to the end of the pipeline.
    pub fn push(&mut self, node: impl DspNode + 'static) {
        self.nodes.push(Box::new(node));
    }

    /// Creates a single-node pipeline from any graph expression.
    ///
    /// This is the bridge between the operator-overloaded graph DSL and the
    /// imperative `Pipeline` type.  Any [`NodeGraph`] value — including nested
    /// [`Serial`], [`Parallel`], and [`Stack`] combinators — can be wrapped
    /// into a `Pipeline` for use with the builder API or format validation.
    ///
    /// # Examples
    ///
    /// ```
    /// use resonant_stream::{Chunk, DspNode, Pipeline, StreamError};
    /// use resonant_stream::graph::GraphExt;
    ///
    /// struct Scale(f32);
    /// impl DspNode for Scale {
    ///     fn process(&mut self, mut input: Chunk) -> Result<Chunk, StreamError> {
    ///         for s in input.data_mut() { *s *= self.0; }
    ///         Ok(input)
    ///     }
    ///     fn reset(&mut self) {}
    /// }
    ///
    /// let graph = Scale(2.0).serial(Scale(3.0));
    /// let mut pipeline = Pipeline::from_graph(graph);
    ///
    /// let chunk = Chunk::new(vec![1.0], 44100, 1);
    /// let out = pipeline.process(chunk).unwrap();
    /// assert_eq!(out.data(), &[6.0]);
    /// ```
    pub fn from_graph(graph: impl crate::graph::NodeGraph) -> Self {
        let mut p = Self::builder().build();
        p.push(graph);
        p
    }
}

/// Builder for constructing a [`Pipeline`].
///
/// # Examples
///
/// ```
/// use resonant_stream::{Pipeline, Chunk, DspNode, StreamError};
///
/// struct Noop;
/// impl DspNode for Noop {
///     fn process(&mut self, input: Chunk) -> Result<Chunk, StreamError> { Ok(input) }
///     fn reset(&mut self) {}
/// }
///
/// let pipeline = Pipeline::builder()
///     .sample_rate(48000)
///     .channels(1)
///     .node(Noop)
///     .node(Noop)
///     .build();
///
/// assert_eq!(pipeline.len(), 2);
/// assert_eq!(pipeline.sample_rate(), Some(48000));
/// assert_eq!(pipeline.channels(), Some(1));
/// ```
pub struct PipelineBuilder {
    nodes: Vec<Box<dyn DspNode>>,
    sample_rate: Option<u32>,
    channels: Option<u16>,
}

impl PipelineBuilder {
    /// Sets the expected sample rate for format validation.
    #[must_use]
    pub fn sample_rate(mut self, rate: u32) -> Self {
        self.sample_rate = Some(rate);
        self
    }

    /// Sets the expected channel count for format validation.
    #[must_use]
    pub fn channels(mut self, channels: u16) -> Self {
        self.channels = Some(channels);
        self
    }

    /// Appends a processing node to the pipeline.
    #[must_use]
    pub fn node(mut self, node: impl DspNode + 'static) -> Self {
        self.nodes.push(Box::new(node));
        self
    }

    /// Consumes the builder and returns the configured [`Pipeline`].
    #[must_use]
    pub fn build(self) -> Pipeline {
        Pipeline {
            nodes: self.nodes,
            sample_rate: self.sample_rate,
            channels: self.channels,
        }
    }
}

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

    struct Scale(f32);
    impl DspNode for Scale {
        fn process(&mut self, mut input: Chunk) -> Result<Chunk, StreamError> {
            for s in input.data_mut() {
                *s *= self.0;
            }
            Ok(input)
        }
        fn reset(&mut self) {}
    }

    struct Fail;
    impl DspNode for Fail {
        fn process(&mut self, _: Chunk) -> Result<Chunk, StreamError> {
            Err(StreamError::ProcessingError("boom".into()))
        }
        fn reset(&mut self) {}
    }

    #[test]
    fn empty_pipeline_passthrough() {
        let mut p = Pipeline::builder().build();
        let chunk = Chunk::new(vec![1.0, 2.0], 44100, 1);
        let out = p.process(chunk);
        assert!(out.is_ok());
        assert_eq!(out.ok().map(|c| c.into_data()), Some(vec![1.0, 2.0]));
    }

    #[test]
    fn single_node() {
        let mut p = Pipeline::builder().node(Scale(0.5)).build();
        let chunk = Chunk::new(vec![2.0, 4.0], 44100, 1);
        let out = p.process(chunk);
        assert_eq!(out.ok().map(|c| c.into_data()), Some(vec![1.0, 2.0]));
    }

    #[test]
    fn chained_nodes() {
        let mut p = Pipeline::builder()
            .node(Scale(2.0))
            .node(Scale(3.0))
            .build();
        let chunk = Chunk::new(vec![1.0], 44100, 1);
        let out = p.process(chunk);
        assert_eq!(out.ok().map(|c| c.into_data()), Some(vec![6.0]));
    }

    #[test]
    fn sample_rate_validation_pass() {
        let mut p = Pipeline::builder().sample_rate(44100).build();
        let chunk = Chunk::new(vec![1.0], 44100, 1);
        assert!(p.process(chunk).is_ok());
    }

    #[test]
    fn sample_rate_validation_fail() {
        let mut p = Pipeline::builder().sample_rate(44100).build();
        let chunk = Chunk::new(vec![1.0], 48000, 1);
        let err = p.process(chunk).err();
        assert_eq!(
            err,
            Some(StreamError::SampleRateMismatch {
                expected: 44100,
                got: 48000,
            })
        );
    }

    #[test]
    fn channel_validation_pass() {
        let mut p = Pipeline::builder().channels(2).build();
        let chunk = Chunk::new(vec![1.0, 2.0], 44100, 2);
        assert!(p.process(chunk).is_ok());
    }

    #[test]
    fn channel_validation_fail() {
        let mut p = Pipeline::builder().channels(2).build();
        let chunk = Chunk::new(vec![1.0], 44100, 1);
        let err = p.process(chunk).err();
        assert_eq!(
            err,
            Some(StreamError::ChannelMismatch {
                expected: 2,
                got: 1,
            })
        );
    }

    #[test]
    fn node_error_propagates() {
        let mut p = Pipeline::builder()
            .node(Scale(2.0))
            .node(Fail)
            .node(Scale(3.0))
            .build();
        let chunk = Chunk::new(vec![1.0], 44100, 1);
        let err = p.process(chunk).err();
        assert_eq!(err, Some(StreamError::ProcessingError("boom".into())));
    }

    #[test]
    fn reset_all_nodes() {
        let mut p = Pipeline::builder()
            .node(Scale(1.0))
            .node(Scale(2.0))
            .build();
        p.reset(); // should not panic
    }

    #[test]
    fn len_and_is_empty() {
        let p = Pipeline::builder().build();
        assert!(p.is_empty());
        assert_eq!(p.len(), 0);

        let p = Pipeline::builder().node(Scale(1.0)).build();
        assert!(!p.is_empty());
        assert_eq!(p.len(), 1);
    }

    #[test]
    fn push_after_build() {
        let mut p = Pipeline::builder().build();
        assert!(p.is_empty());
        p.push(Scale(2.0));
        assert_eq!(p.len(), 1);

        let chunk = Chunk::new(vec![3.0], 44100, 1);
        let out = p.process(chunk);
        assert_eq!(out.ok().map(|c| c.into_data()), Some(vec![6.0]));
    }

    #[test]
    fn accessors() {
        let p = Pipeline::builder().sample_rate(48000).channels(2).build();
        assert_eq!(p.sample_rate(), Some(48000));
        assert_eq!(p.channels(), Some(2));
    }

    #[test]
    fn no_validation_when_unconfigured() {
        let mut p = Pipeline::builder().build();
        let chunk = Chunk::new(vec![1.0], 96000, 6);
        assert!(p.process(chunk).is_ok());
    }

    #[test]
    fn both_validations_rate_fails_first() {
        let mut p = Pipeline::builder().sample_rate(44100).channels(2).build();
        let chunk = Chunk::new(vec![1.0], 48000, 1);
        // Sample rate is checked first
        let err = p.process(chunk).err();
        assert_eq!(
            err,
            Some(StreamError::SampleRateMismatch {
                expected: 44100,
                got: 48000,
            })
        );
    }
}