fundsp 0.20.0

Audio processing and synthesis library.
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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Delay components.

use super::audionode::*;
use super::buffer::*;
use super::math::*;
use super::setting::*;
use super::signal::*;
use super::*;
use core::marker::PhantomData;
use num_complex::Complex64;
use numeric_array::typenum::*;
extern crate alloc;
use alloc::vec::Vec;

/// Single sample delay with `N` channels.
/// - Input(s): input signal.
/// - Output(s): input signal delayed by one sample.
#[derive(Clone, Default)]
pub struct Tick<N: Size<f32>> {
    buffer: Frame<f32, N>,
    sample_rate: f64,
}

impl<N: Size<f32>> Tick<N> {
    /// Create a new single sample delay.
    pub fn new() -> Self {
        Tick {
            buffer: Frame::default(),
            sample_rate: DEFAULT_SR,
        }
    }
}

impl<N: Size<f32>> AudioNode for Tick<N> {
    const ID: u64 = 9;
    type Inputs = N;
    type Outputs = N;

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

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

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        let output = self.buffer.clone();
        self.buffer = input.clone();
        output
    }
    fn route(&mut self, input: &SignalFrame, frequency: f64) -> SignalFrame {
        let mut output = SignalFrame::new(self.outputs());
        for i in 0..self.outputs() {
            output.set(
                i,
                input.at(i).filter(0.0, |r| {
                    r * Complex64::from_polar(1.0, -f64::TAU * frequency / self.sample_rate)
                }),
            );
        }
        output
    }
}

/// Fixed delay.
/// - Allocates: the delay line.
/// - Input 0: input
/// - Output 0: delayed input
#[derive(Clone, Default)]
pub struct Delay {
    buffer: Vec<f32>,
    i: usize,
    sample_rate: f64,
    time: f64,
    time_in_samples: usize,
}

impl Delay {
    /// Create a new fixed delay. The delay `time` (`time` >= 0),
    /// which is specified in seconds, is rounded to the nearest sample.
    /// The minimum possible delay is zero samples.
    pub fn new(time: f64) -> Self {
        assert!(time >= 0.0);
        let mut node = Self {
            time,
            ..Self::default()
        };
        node.set_sample_rate(DEFAULT_SR);
        node
    }
}

impl AudioNode for Delay {
    const ID: u64 = 13;
    type Inputs = U1;
    type Outputs = U1;

    fn reset(&mut self) {
        self.i = 0;
        self.buffer.fill(0.0);
    }

    fn set_sample_rate(&mut self, sample_rate: f64) {
        if self.sample_rate != sample_rate {
            self.sample_rate = sample_rate;
            self.time_in_samples = round(self.time * sample_rate) as usize;
            let buffer_length = self.time_in_samples + 1;
            self.buffer.resize(buffer_length, 0.0);
            self.reset();
        }
    }

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        self.buffer[self.i] = input[0];
        self.i = self.i.wrapping_add(1);
        if self.i >= self.buffer.len() {
            self.i = 0;
        }
        let output = self.buffer[self.i];
        [output].into()
    }

    fn route(&mut self, input: &SignalFrame, frequency: f64) -> SignalFrame {
        let mut output = SignalFrame::new(self.outputs());
        output.set(
            0,
            input.at(0).filter(0.0, |r| {
                r * Complex64::from_polar(
                    1.0,
                    -f64::TAU * self.time_in_samples as f64 * frequency / self.sample_rate,
                )
            }),
        );
        output
    }
}

/// Variable delay line using cubic interpolation.
/// The number of taps is `N`.
/// - Allocates: the delay line.
/// - Input 0: input
/// - Inputs 1...N: delay amount in seconds.
/// - Output 0: delayed input
#[derive(Clone, Default)]
pub struct Tap<N>
where
    N: Size<f32> + Add<U1>,
    <N as Add<U1>>::Output: Size<f32>,
{
    buffer: Vec<f32>,
    i: usize,
    sample_rate: f32,
    min_delay_clamped: f32,
    max_delay_clamped: f32,
    min_delay: f32,
    max_delay: f32,
    _marker: PhantomData<N>,
}

impl<N> Tap<N>
where
    N: Size<f32> + Add<U1>,
    <N as Add<U1>>::Output: Size<f32>,
{
    /// Create a tapped delay line.
    /// Minimum and maximum delays are specified in seconds (`min_delay`, `max_delay` >= 0).
    /// Minimum possible delay is one sample.
    pub fn new(min_delay: f32, max_delay: f32) -> Self {
        assert!(min_delay >= 0.0);
        assert!(min_delay <= max_delay);
        let mut node = Self {
            min_delay,
            max_delay,
            ..Self::default()
        };
        node.set_sample_rate(DEFAULT_SR);
        node
    }
}

impl<N> AudioNode for Tap<N>
where
    N: Size<f32> + Add<U1>,
    <N as Add<U1>>::Output: Size<f32>,
{
    const ID: u64 = 50;
    type Inputs = Sum<N, U1>;
    type Outputs = U1;

    fn reset(&mut self) {
        self.i = 0;
        self.buffer.fill(0.0);
    }

    fn set_sample_rate(&mut self, sample_rate: f64) {
        let sample_rate = sample_rate as f32;
        if self.sample_rate != sample_rate {
            self.sample_rate = sample_rate;
            self.min_delay_clamped = max(self.min_delay, 1.00001 / sample_rate);
            self.max_delay_clamped = max(self.max_delay, 1.00001 / sample_rate);
            let buffer_length = ceil(self.max_delay * sample_rate) + 3.0 + SIMD_N as f32;
            let buffer_length = (buffer_length as usize).next_power_of_two();
            self.buffer.resize(buffer_length, 0.0);
            self.reset();
        }
    }

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        let mask = self.buffer.len().wrapping_sub(1);
        self.buffer[self.i] = input[0];
        let mut output = 0.0;
        for tap_i in 1..N::USIZE + 1 {
            let tap = clamp(self.min_delay_clamped, self.max_delay_clamped, input[tap_i])
                * self.sample_rate;
            // Safety: the value has been clamped.
            let tap_floor = unsafe { f32::to_int_unchecked::<usize>(tap.to_f32()) };
            let tap_i1 = self.i.wrapping_sub(tap_floor) & mask;
            let tap_i0 = tap_i1.wrapping_add(1) & mask;
            let tap_i2 = tap_i1.wrapping_sub(1) & mask;
            let tap_i3 = tap_i1.wrapping_sub(2) & mask;
            let tap_d = tap - tap_floor as f32;
            output += spline(
                self.buffer[tap_i0],
                self.buffer[tap_i1],
                self.buffer[tap_i2],
                self.buffer[tap_i3],
                tap_d,
            );
        }
        self.i = self.i.wrapping_add(1) & mask;
        [output].into()
    }

    fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) {
        let scalar_mask = self.buffer.len().wrapping_sub(1);
        let mask = I32x::splat(scalar_mask as i32);
        let d_vector = I32x::new(core::array::from_fn(|k| (SIMD_N - k) as i32));
        for i in 0..full_simd_items(size) {
            for j in 0..SIMD_N {
                self.buffer[self.i] = input.at_f32(0, (i << SIMD_S) + j);
                self.i = self.i.wrapping_add(1) & scalar_mask;
            }
            let mut out = F32x::ZERO;
            for tap_i in 1..N::USIZE + 1 {
                let tap = input
                    .at(tap_i, i)
                    .fast_max(F32x::splat(self.min_delay_clamped))
                    .fast_min(F32x::splat(self.max_delay_clamped))
                    * self.sample_rate;
                let tap_floor = tap.fast_trunc_int();
                let tap_i1 = (self.i as i32 - d_vector - tap_floor) & mask;
                let tap_i0 = (tap_i1 + 1) & mask;
                let tap_i2 = (tap_i1 - 1) & mask;
                let tap_i3 = (tap_i1 - 2) & mask;
                let tap_d = tap - tap_floor.round_float();
                out += spline(
                    F32x::new(core::array::from_fn(|k| {
                        self.buffer[tap_i0.as_array_ref()[k] as usize]
                    })),
                    F32x::new(core::array::from_fn(|k| {
                        self.buffer[tap_i1.as_array_ref()[k] as usize]
                    })),
                    F32x::new(core::array::from_fn(|k| {
                        self.buffer[tap_i2.as_array_ref()[k] as usize]
                    })),
                    F32x::new(core::array::from_fn(|k| {
                        self.buffer[tap_i3.as_array_ref()[k] as usize]
                    })),
                    tap_d,
                );
            }
            output.set(0, i, out);
        }
        self.process_remainder(size, input, output);
    }

    fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame {
        let mut output = SignalFrame::new(self.outputs());
        output.set(0, input.at(0).distort(0.0));
        output
    }
}

/// Nested allpass where the delay block is replaced by `X`.
/// The number of inputs is `N`, either 1 or 2.
/// - Input 0: input signal
/// - Input 1 (optional): feedforward coefficient
/// - Output 0: filtered signal
#[derive(Clone)]
pub struct AllNest<N, X>
where
    N: Size<f32>,
    X: AudioNode<Inputs = U1, Outputs = U1>,
{
    x: X,
    eta: f32,
    z: f32,
    _marker: PhantomData<N>,
}

impl<N, X> AllNest<N, X>
where
    N: Size<f32>,
    X: AudioNode<Inputs = U1, Outputs = U1>,
{
    /// Create new nested allpass. Feedforward `coefficient` should
    /// have an absolute value smaller than one to avoid a blowup.
    pub fn new(coefficient: f32, x: X) -> Self {
        let mut node = Self {
            x,
            eta: 0.0,
            z: 0.0,
            _marker: PhantomData,
        };
        node.set_coefficient(coefficient);
        node
    }

    /// Set feedforward `coefficient`. It should have an absolute
    /// value smaller than one to avoid a blowup.
    #[inline]
    pub fn set_coefficient(&mut self, coefficient: f32) {
        self.eta = coefficient;
    }
}

impl<N, X> AudioNode for AllNest<N, X>
where
    N: Size<f32>,
    X: AudioNode<Inputs = U1, Outputs = U1>,
{
    const ID: u64 = 83;
    type Inputs = N;
    type Outputs = U1;

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

    fn reset(&mut self) {
        self.z = 0.0;
        self.x.reset();
    }

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        if N::USIZE > 1 {
            self.set_coefficient(input[1]);
        }
        let v = input[0] - self.eta * self.z;
        let y = self.eta * v + self.z;
        self.z = self.x.tick(&[v].into())[0];
        [y].into()
    }

    fn set(&mut self, setting: Setting) {
        if let Parameter::Coefficient(value) = setting.parameter() {
            self.set_coefficient(*value);
        }
    }

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

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

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

/// Variable delay line using linear interpolation.
/// The number of taps is `N`.
/// - Allocates: the delay line.
/// - Input 0: input
/// - Inputs 1...N: delay amount in seconds.
/// - Output 0: delayed input
#[derive(Clone)]
pub struct TapLinear<N>
where
    N: Size<f32> + Add<U1>,
    <N as Add<U1>>::Output: Size<f32>,
{
    buffer: Vec<f32>,
    i: usize,
    sample_rate: f32,
    min_delay: f32,
    max_delay: f32,
    _marker: PhantomData<N>,
}

impl<N> TapLinear<N>
where
    N: Size<f32> + Add<U1>,
    <N as Add<U1>>::Output: Size<f32>,
{
    /// Create a tapped delay line. Minimum and maximum delays are specified in seconds.
    /// Minimum possible delay is zero samples.
    pub fn new(min_delay: f32, max_delay: f32) -> Self {
        assert!(min_delay >= 0.0);
        assert!(min_delay <= max_delay);
        let mut node = Self {
            buffer: Vec::new(),
            i: 0,
            sample_rate: 0.0,
            min_delay,
            max_delay,
            _marker: PhantomData,
        };
        node.set_sample_rate(DEFAULT_SR);
        node
    }
}

impl<N> AudioNode for TapLinear<N>
where
    N: Size<f32> + Add<U1>,
    <N as Add<U1>>::Output: Size<f32>,
{
    const ID: u64 = 50;
    type Inputs = Sum<N, U1>;
    type Outputs = U1;

    fn reset(&mut self) {
        self.i = 0;
        self.buffer.fill(0.0);
    }

    fn set_sample_rate(&mut self, sample_rate: f64) {
        let sample_rate = sample_rate as f32;
        if self.sample_rate != sample_rate {
            self.sample_rate = sample_rate;
            let buffer_length = ceil(self.max_delay * sample_rate) + 2.0;
            let buffer_length = (buffer_length as usize).next_power_of_two();
            self.buffer.resize(buffer_length, 0.0);
            self.reset();
        }
    }

    #[inline]
    fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> {
        let mask = self.buffer.len().wrapping_sub(1);
        self.buffer[self.i] = input[0];
        let mut output = 0.0;
        for tap_i in 1..N::USIZE + 1 {
            let tap = clamp(self.min_delay, self.max_delay, input[tap_i]) * self.sample_rate;
            // Safety: the value has been clamped.
            let tap_floor = unsafe { f32::to_int_unchecked::<usize>(tap.to_f32()) };
            let tap_i1 = self.i.wrapping_sub(tap_floor) & mask;
            let tap_i2 = tap_i1.wrapping_sub(1) & mask;
            let tap_d = tap - tap_floor as f32;
            output += lerp(self.buffer[tap_i1], self.buffer[tap_i2], tap_d);
        }
        self.i = self.i.wrapping_add(1) & mask;
        [output].into()
    }

    fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) {
        let scalar_mask = self.buffer.len().wrapping_sub(1);
        let mask = I32x::splat(scalar_mask as i32);
        let d_vector = I32x::new(core::array::from_fn(|k| (SIMD_N - k) as i32));
        for i in 0..full_simd_items(size) {
            for j in 0..SIMD_N {
                self.buffer[self.i] = input.at_f32(0, (i << SIMD_S) + j);
                self.i = self.i.wrapping_add(1) & scalar_mask;
            }
            let mut out = F32x::ZERO;
            for tap_i in 1..N::USIZE + 1 {
                let tap = input
                    .at(tap_i, i)
                    .fast_max(F32x::splat(self.min_delay))
                    .fast_min(F32x::splat(self.max_delay))
                    * self.sample_rate;
                let tap_floor = tap.fast_trunc_int();
                let tap_i1 = (self.i as i32 - d_vector - tap_floor) & mask;
                let tap_i2 = (tap_i1 - 1) & mask;
                let tap_d = tap - tap_floor.round_float();
                out += lerp(
                    F32x::new(core::array::from_fn(|k| {
                        self.buffer[tap_i1.as_array_ref()[k] as usize]
                    })),
                    F32x::new(core::array::from_fn(|k| {
                        self.buffer[tap_i2.as_array_ref()[k] as usize]
                    })),
                    tap_d,
                );
            }
            output.set(0, i, out);
        }
        self.process_remainder(size, input, output);
    }

    fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame {
        let mut output = SignalFrame::new(self.outputs());
        output.set(0, input.at(0).distort(0.0));
        output
    }
}