fundsp 0.23.0

Audio processing and synthesis library.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Feedback components.

use super::audionode::*;
use super::audiounit::*;
use super::buffer::*;
use super::math::*;
use super::signal::*;
use super::*;
use core::marker::PhantomData;
extern crate alloc;
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;

/// Diffusive Hadamard feedback matrix. The number of channels must be a power of two.
#[derive(Default, Clone)]
pub struct FrameHadamard<N: Size<f32>> {
    _marker: PhantomData<N>,
}

impl<N: Size<f32>> FrameHadamard<N> {
    pub fn new() -> FrameHadamard<N> {
        assert!(N::USIZE.is_power_of_two());
        FrameHadamard::default()
    }
}

impl<N: Size<f32>> FrameUnop<N> for FrameHadamard<N> {
    fn unop(&self, _x: F32x) -> F32x {
        // Not implemented.
        panic!()
    }
    #[inline]
    fn frame(&self, x: &Frame<f32, N>) -> Frame<f32, N> {
        let mut output = x.clone();
        let mut h = 1;
        while h < N::USIZE {
            let mut i = 0;
            while i < N::USIZE {
                for j in i..i + h {
                    let x = output[j];
                    let y = output[j + h];
                    output[j] = x + y;
                    output[j + h] = x - y;
                    // Note. This unsafe version is not any faster.
                    //let x = unsafe { *output.get_unchecked(j) };
                    //let y = unsafe { *output.get_unchecked(j + h) };
                    //unsafe { *output.get_unchecked_mut(j) = x + y };
                    //unsafe { *output.get_unchecked_mut(j + h) = x - y };
                }
                i += h * 2;
            }
            h *= 2;
        }
        output * Frame::splat((1.0 / sqrt(N::I32 as f64)) as f32)
    }
    // Not implemented.
    // TODO: Hadamard is a special op because of interchannel dependencies.
    fn route(&self, _: Signal) -> Signal {
        panic!()
    }
    fn assign(&self, _size: usize, _x: &mut [f32]) {
        panic!()
    }
}

/// Mix back output of contained node to its input.
/// The contained node must have an equal number of inputs and outputs.
#[derive(Clone)]
pub struct Feedback<N, X, U>
where
    N: Size<f32>,
    X: AudioNode<Inputs = N, Outputs = N>,
    X::Inputs: Size<f32>,
    X::Outputs: Size<f32>,
    U: FrameUnop<X::Outputs>,
{
    x: X,
    // Current feedback value.
    value: Frame<f32, N>,
    // Feedback operator.
    #[allow(dead_code)]
    feedback: U,
}

impl<N, X, U> Feedback<N, X, U>
where
    N: Size<f32>,
    X: AudioNode<Inputs = N, Outputs = N>,
    X::Inputs: Size<f32>,
    X::Outputs: Size<f32>,
    U: FrameUnop<X::Outputs>,
{
    pub fn new(x: X, feedback: U) -> Self {
        let mut node = Feedback {
            x,
            value: Frame::default(),
            feedback,
        };
        let hash = node.ping(true, AttoHash::new(Self::ID));
        node.ping(false, hash);
        node
    }
}

impl<N, X, U> AudioNode for Feedback<N, X, U>
where
    N: Size<f32>,
    X: AudioNode<Inputs = N, Outputs = N>,
    X::Inputs: Size<f32>,
    X::Outputs: Size<f32>,
    U: FrameUnop<X::Outputs>,
{
    const ID: u64 = 11;
    type Inputs = N;
    type Outputs = N;

    fn reset(&mut self) {
        self.x.reset();
        self.value = Frame::default();
    }

    fn set_sample_rate(&mut self, sample_rate: f64) {
        self.x.set_sample_rate(sample_rate);
    }

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        super::denormal::prevent_denormals();
        let output = self.x.tick(&(input + self.value.clone()));
        self.value = self.feedback.frame(&output);
        output
    }

    fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) {
        super::denormal::prevent_denormals();
        for i in 0..size {
            let input_frame =
                Frame::generate(|channel| input.at_f32(channel, i) + self.value[channel]);
            let output_frame = self.x.tick(&input_frame);
            self.value = self.feedback.frame(&output_frame);
            for channel in 0..self.outputs() {
                output.set_f32(channel, i, output_frame[channel]);
            }
        }
    }

    fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame {
        Routing::Arbitrary(0.0).route(input, self.outputs())
    }

    fn ping(&mut self, probe: bool, hash: AttoHash) -> AttoHash {
        self.x.ping(probe, hash.hash(Self::ID))
    }

    fn allocate(&mut self) {
        self.x.allocate();
    }
}

/// Mix back output of contained node `X` to its input, with extra feedback processing `Y`.
/// The contained nodes must have an equal number of inputs and outputs.
#[derive(Clone)]
pub struct Feedback2<N, X, Y, U>
where
    N: Size<f32>,
    X: AudioNode<Inputs = N, Outputs = N>,
    X::Inputs: Size<f32>,
    X::Outputs: Size<f32>,
    Y: AudioNode<Inputs = N, Outputs = N>,
    Y::Inputs: Size<f32>,
    Y::Outputs: Size<f32>,
    U: FrameUnop<X::Outputs>,
{
    x: X,
    /// Feedback processing.
    y: Y,
    /// Current feedback value.
    value: Frame<f32, N>,
    /// Feedback operator.
    #[allow(dead_code)]
    feedback: U,
}

impl<N, X, Y, U> Feedback2<N, X, Y, U>
where
    N: Size<f32>,
    X: AudioNode<Inputs = N, Outputs = N>,
    X::Inputs: Size<f32>,
    X::Outputs: Size<f32>,
    Y: AudioNode<Inputs = N, Outputs = N>,
    Y::Inputs: Size<f32>,
    Y::Outputs: Size<f32>,
    U: FrameUnop<X::Outputs>,
{
    /// Create new (single sample) feedback node.
    /// It mixes back output of contained node `X` to its input, with extra feedback processing `Y`.
    /// The feedforward path does not include `Y`.
    /// The contained nodes must have an equal number of inputs and outputs.
    pub fn new(x: X, y: Y, feedback: U) -> Self {
        let mut node = Feedback2 {
            x,
            y,
            value: Frame::default(),
            feedback,
        };
        let hash = node.ping(true, AttoHash::new(Self::ID));
        node.ping(false, hash);
        node
    }
}

impl<N, X, Y, U> AudioNode for Feedback2<N, X, Y, U>
where
    N: Size<f32>,
    X: AudioNode<Inputs = N, Outputs = N>,
    X::Inputs: Size<f32>,
    X::Outputs: Size<f32>,
    Y: AudioNode<Inputs = N, Outputs = N>,
    Y::Inputs: Size<f32>,
    Y::Outputs: Size<f32>,
    U: FrameUnop<X::Outputs>,
{
    const ID: u64 = 66;
    type Inputs = N;
    type Outputs = N;

    fn reset(&mut self) {
        self.x.reset();
        self.y.reset();
        self.value = Frame::default();
    }

    fn set_sample_rate(&mut self, sample_rate: f64) {
        self.x.set_sample_rate(sample_rate);
        self.y.set_sample_rate(sample_rate);
    }

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        super::denormal::prevent_denormals();
        let output = self.x.tick(&(input + self.value.clone()));
        self.value = self.feedback.frame(&self.y.tick(&output));
        output
    }

    fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) {
        super::denormal::prevent_denormals();
        for i in 0..size {
            let input_frame =
                Frame::generate(|channel| input.at_f32(channel, i) + self.value[channel]);
            let output_frame = self.x.tick(&input_frame);
            self.value = self.feedback.frame(&self.y.tick(&output_frame));
            for channel in 0..self.outputs() {
                output.set_f32(channel, i, output_frame[channel]);
            }
        }
    }

    fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame {
        Routing::Arbitrary(0.0).route(input, self.outputs())
    }

    fn ping(&mut self, probe: bool, hash: AttoHash) -> AttoHash {
        self.y.ping(probe, self.x.ping(probe, hash.hash(Self::ID)))
    }

    fn allocate(&mut self) {
        self.x.allocate();
    }
}

/// Feedback unit with integrated delay.
#[derive(Clone)]
pub struct FeedbackUnit {
    /// Contained feedback loop.
    x: Box<dyn AudioUnit>,
    /// Number of input and output channels.
    channels: usize,
    /// Current sample rate of the unit.
    sample_rate: f64,
    /// Delay in seconds.
    delay: f64,
    /// Delay in samples.
    samples: usize,
    /// Feedback buffers, one per channel, power-of-two sized.
    feedback: Vec<Vec<f32>>,
    /// Feedback buffer length minus one.
    mask: usize,
    /// Current write index into feedback buffers.
    index: usize,
    /// Buffer for assembling frames.
    tick_buffer: Vec<f32>,
    /// Second buffer for assembling frames.
    tick_buffer2: Vec<f32>,
    /// Buffer for assembling blocks.
    buffer: BufferVec,
}

impl FeedbackUnit {
    /// Create new feedback unit with integrated feedback `delay` in seconds.
    /// The delay amount is rounded to the nearest sample.
    /// The minimum delay is one sample, which may also be accomplished by setting `delay` to zero.
    /// The feedback unit mixes back delayed output of contained unit `x` to its input.
    pub fn new(delay: f64, x: Box<dyn AudioUnit>) -> Self {
        let channels = x.inputs();
        assert_eq!(channels, x.outputs());
        let mut unit = Self {
            x,
            channels,
            sample_rate: 0.0,
            delay,
            samples: 0,
            feedback: vec![Vec::new(); channels],
            mask: 0,
            index: 0,
            tick_buffer: vec![0.0; channels],
            tick_buffer2: vec![0.0; channels],
            buffer: BufferVec::new(channels),
        };
        unit.set_sample_rate(DEFAULT_SR);
        unit
    }

    /// Calculate read index to delayed sample.
    #[inline]
    fn read_index(&self, delay: usize) -> usize {
        (self.index + self.mask + 1 - delay) & self.mask
    }
}

impl AudioUnit for FeedbackUnit {
    fn reset(&mut self) {
        for feedback in self.feedback.iter_mut() {
            feedback.fill(0.0);
        }
        self.x.reset();
        self.index = 0;
    }

    fn set_sample_rate(&mut self, sample_rate: f64) {
        if self.sample_rate != sample_rate {
            self.sample_rate = sample_rate;
            self.x.set_sample_rate(sample_rate);
            self.samples = round(self.delay * sample_rate).max(1.0) as usize;
            let feedback_samples = self.samples.next_power_of_two();
            self.mask = feedback_samples - 1;
            for feedback in self.feedback.iter_mut() {
                feedback.fill(0.0);
                feedback.resize(feedback_samples, 0.0);
            }
            self.index = 0;
        }
    }

    fn tick(&mut self, input: &[f32], output: &mut [f32]) {
        super::denormal::prevent_denormals();
        let read_i = self.read_index(self.samples);
        for (channel, (tick, i)) in self.tick_buffer.iter_mut().zip(input.iter()).enumerate() {
            *tick = *i + self.feedback[channel][read_i];
        }
        self.x.tick(&self.tick_buffer, output);
        for (channel, i) in output.iter().enumerate() {
            self.feedback[channel][self.index] = *i;
        }
        self.index = (self.index + 1) & self.mask;
    }

    fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) {
        super::denormal::prevent_denormals();
        if size <= self.samples {
            // We have enough feedback samples to process the whole block at once.
            for channel in 0..self.channels {
                let mut read_i = self.read_index(self.samples);
                for (b, i) in self.buffer.channel_f32_mut(channel)[0..size]
                    .iter_mut()
                    .zip(input.channel_f32(channel)[0..size].iter())
                {
                    *b = *i + self.feedback[channel][read_i];
                    read_i = (read_i + 1) & self.mask;
                }
            }
            self.x.process(size, &self.buffer.buffer_ref(), output);
            for channel in 0..self.channels {
                let mut write_i = self.index;
                for i in output.channel_f32(channel)[0..size].iter() {
                    self.feedback[channel][write_i] = *i;
                    write_i = (write_i + 1) & self.mask;
                }
            }
        } else {
            // The feedback delay is small so we proceed sample by sample.
            let mut read_i = self.read_index(self.samples);
            let mut write_i = self.index;
            for i in 0..size {
                for (channel, tick) in self.tick_buffer.iter_mut().enumerate() {
                    *tick = input.at_f32(channel, i) + self.feedback[channel][read_i];
                }
                self.x.tick(&self.tick_buffer, &mut self.tick_buffer2);
                for (channel, tick) in self.tick_buffer2.iter().enumerate() {
                    output.set_f32(channel, i, *tick);
                    self.feedback[channel][write_i] = *tick;
                }
                read_i = (read_i + 1) & self.mask;
                write_i = (write_i + 1) & self.mask;
            }
        }
        self.index = (self.index + size) & self.mask;
    }

    fn inputs(&self) -> usize {
        self.feedback.len()
    }

    fn outputs(&self) -> usize {
        self.feedback.len()
    }

    fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame {
        Routing::Arbitrary(0.0).route(input, self.outputs())
    }

    fn get_id(&self) -> u64 {
        const ID: u64 = 79;
        ID
    }

    fn ping(&mut self, probe: bool, hash: AttoHash) -> AttoHash {
        self.x.ping(probe, hash.hash(self.get_id()))
    }

    fn footprint(&self) -> usize {
        core::mem::size_of::<Self>()
    }

    fn allocate(&mut self) {
        self.x.allocate();
    }
}