firewheel-nodes 0.13.0

Official factory nodes for the Firewheel audio engine
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
use core::ops::Range;

use firewheel_core::node::NodeError;
use firewheel_core::{
    StreamInfo,
    channel_config::{ChannelConfig, ChannelCount},
    diff::{Diff, Patch},
    dsp::{
        coeff_update::{CoeffUpdateFactor, CoeffUpdateMask},
        filter::{
            butterworth::Q_BUTTERWORTH_ORD2,
            smoothing_filter::DEFAULT_SMOOTH_SECONDS,
            svf::{SvfCoeff, SvfCoeffSimd, SvfStateSimd},
        },
        volume::{Volume, db_to_amp},
    },
    event::ProcEvents,
    node::{
        AudioNode, AudioNodeInfo, AudioNodeProcessor, ConstructProcessorContext, ProcBuffers,
        ProcExtra, ProcInfo, ProcStreamCtx, ProcessStatus,
    },
    param::smoother::{SmoothedParam, SmootherConfig},
};

pub const DEFAULT_Q: f32 = Q_BUTTERWORTH_ORD2;
pub const DEFAULT_MIN_HZ: f32 = 20.0;
pub const DEFAULT_MAX_HZ: f32 = 20_480.0;
pub const DEFAULT_MIN_Q: f32 = 0.02;
pub const DEFAULT_MAX_Q: f32 = 40.0;
pub const DEFAULT_MIN_GAIN_DB: f32 = -24.0;
pub const DEFAULT_MAX_GAIN_DB: f32 = 24.0;

/// The configuration for an [`SvfNode`]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "bevy", derive(bevy_ecs::prelude::Component))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SvfNodeConfig {
    /// The minimum and maximum values for cutoff frequency in hertz.
    ///
    /// By default this is set to `20.0..20480.0`.
    ///
    /// It is generally not recommended to increase this range
    /// unless you know what you are doing.
    pub freq_range: Range<f32>,

    /// The minimum and maximum values for q values.
    ///
    /// By default this is set to `0.02..40.0`.
    ///
    /// It is generally not recommended to increase this range
    /// unless you know what you are doing.
    pub q_range: Range<f32>,

    /// The minimum and maximum values for filter gain (in decibels).
    ///
    /// By default this is set to `-24.0..24.0`.
    ///
    /// It is generally not recommended to increase this range
    /// unless you know what you are doing.
    pub gain_db_range: Range<f32>,
}

impl Default for SvfNodeConfig {
    fn default() -> Self {
        Self {
            freq_range: DEFAULT_MIN_HZ..DEFAULT_MAX_HZ,
            q_range: DEFAULT_MIN_Q..DEFAULT_MAX_Q,
            gain_db_range: DEFAULT_MIN_GAIN_DB..DEFAULT_MAX_GAIN_DB,
        }
    }
}

/// The filter type to use for an [`SvfNode`]
#[derive(Default, Diff, Patch, Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SvfType {
    // Lowpass (-12 dB per octave)
    #[default]
    Lowpass,
    // Lowpass (-24 dB per octave)
    LowpassX2,
    // Lowpass (-12 dB per octave)
    Highpass,
    // Lowpass (-24 dB per octave)
    HighpassX2,
    // Bandpass (-12 dB per octave)
    Bandpass,
    LowShelf,
    HighShelf,
    Bell,
    Notch,
    Allpass,
}

pub type SvfMonoNode = SvfNode<1>;
pub type SvfStereoNode = SvfNode<2>;

/// An SVF (state variable filter) node
///
/// This is based on the filter model developed by Andrew Simper:
/// <https://cytomic.com/files/dsp/SvfLinearTrapOptimised2.pdf>
#[cfg_attr(feature = "bevy", derive(bevy_ecs::prelude::Component))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Diff, Patch, Debug, Clone, Copy, PartialEq)]
pub struct SvfNode<const CHANNELS: usize = 2> {
    /// The type of filter
    pub filter_type: SvfType,

    /// The cutoff frequency in hertz in the range `[20.0, 20480.0]`.
    pub cutoff_hz: f32,
    /// The quality (q) factor
    ///
    /// This is also sometimes referred to as "bandwidth", but note the
    /// formula to convert bandwidth in hertz to q is:
    ///
    /// `Q = cutoff_hz / BW`
    ///
    /// and the formula to convert bandwidth in octaves to q is:
    ///
    /// `Q = sqrt(2^BW) / (2^BW - 1)`
    pub q_factor: f32,
    /// The filter gain
    ///
    /// This only has effect if the filter type is one of the following:
    /// * [`SvfType::LowShelf`]
    /// * [`SvfType::HighShelf`]
    /// * [`SvfType::Bell`]
    pub gain: Volume,

    /// The time in seconds of the internal smoothing filter.
    ///
    /// By default this is set to `0.062` (62ms). This value is chosen such that
    /// the stair-stepping effect isn't noticeable for a typical block size of 1024
    /// samples.
    pub smooth_seconds: f32,

    /// An exponent representing the rate at which DSP coefficients are
    /// updated when parameters are being smoothed.
    ///
    /// Smaller values will produce less "stair-stepping" artifacts,
    /// but will also consume more CPU.
    ///
    /// The resulting number of frames (samples in a single channel of audio)
    /// that will elapse between each update is calculated as
    /// `2^coeff_update_factor`.
    ///
    /// By default this is set to `4`.
    pub coeff_update_factor: CoeffUpdateFactor,
}

impl<const CHANNELS: usize> Default for SvfNode<CHANNELS> {
    fn default() -> Self {
        Self {
            filter_type: SvfType::Lowpass,
            cutoff_hz: 1_000.0,
            q_factor: DEFAULT_Q,
            gain: Volume::Decibels(0.0),
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor::default(),
        }
    }
}

impl<const CHANNELS: usize> SvfNode<CHANNELS> {
    /// Construct a new SVF node with the lowpass filter type of order 2.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_lowpass(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::Lowpass,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the lowpass filter type of order 4.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_lowpass_x2(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::LowpassX2,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the highpass filter type of order 2.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_highpass(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::Highpass,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the highpass filter type of order 4.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_highpass_x2(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::HighpassX2,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the bandpass filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_bandpass(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::Bandpass,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the lowshelf filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `gain` - The filter gain
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_lowshelf(cutoff_hz: f32, gain: Volume, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::LowShelf,
            cutoff_hz,
            q_factor,
            gain,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the highshelf filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `gain` - The filter gain
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_highshelf(cutoff_hz: f32, gain: Volume, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::HighShelf,
            cutoff_hz,
            q_factor,
            gain,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the bell filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `gain` - The filter gain
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_bell(cutoff_hz: f32, gain: Volume, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::Bell,
            cutoff_hz,
            q_factor,
            gain,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the notch filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_notch(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::Notch,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Construct a new SVF node with the allpass filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    /// * `enabled` - Whether or not this node is enabled
    pub const fn from_allpass(cutoff_hz: f32, q_factor: f32) -> Self {
        Self {
            filter_type: SvfType::Allpass,
            cutoff_hz,
            q_factor,
            gain: Volume::UNITY_GAIN,
            smooth_seconds: DEFAULT_SMOOTH_SECONDS,
            coeff_update_factor: CoeffUpdateFactor(5),
        }
    }

    /// Set the parameters to use a lowpass filter type of order 2.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_lowpass(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::Lowpass;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a lowpass filter type of order 4.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_lowpass_x2(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::LowpassX2;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a highpass filter type of order 2.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_highpass(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::Highpass;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a highpass filter type of order 4.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_highpass_x2(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::HighpassX2;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a bandpass filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_bandpass(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::Bandpass;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a lowshelf filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `gain` - The filter gain
    /// * `q_factor` - The quality (q) factor
    pub const fn set_lowshelf(&mut self, cutoff_hz: f32, gain: Volume, q_factor: f32) {
        self.filter_type = SvfType::LowShelf;
        self.cutoff_hz = cutoff_hz;
        self.gain = gain;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a highshelf filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `gain` - The filter gain
    /// * `q_factor` - The quality (q) factor
    pub const fn set_highshelf(&mut self, cutoff_hz: f32, gain: Volume, q_factor: f32) {
        self.filter_type = SvfType::HighShelf;
        self.cutoff_hz = cutoff_hz;
        self.gain = gain;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a bell filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `gain` - The filter gain
    /// * `q_factor` - The quality (q) factor
    pub const fn set_bell(&mut self, cutoff_hz: f32, gain: Volume, q_factor: f32) {
        self.filter_type = SvfType::Bell;
        self.cutoff_hz = cutoff_hz;
        self.gain = gain;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use a notch filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_notch(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::Notch;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the parameters to use an allpass filter type.
    ///
    /// * `cutoff_hz` - The cutoff frequency in hertz in the range `[20.0, 20480.0]`
    /// * `q_factor` - The quality (q) factor
    pub const fn set_allpass(&mut self, cutoff_hz: f32, q_factor: f32) {
        self.filter_type = SvfType::Allpass;
        self.cutoff_hz = cutoff_hz;
        self.q_factor = q_factor;
    }

    /// Set the given filter gain in a linear scale, where `0.0` is silence and
    /// `1.0` is unity gain.
    ///
    /// These units are suitable for volume sliders (simply convert percent
    /// volume to linear volume by diving the percent volume by 100).
    ///
    /// This only has effect if the filter type is one of the following:
    /// * [`SvfType::LowShelf`]
    /// * [`SvfType::HighShelf`]
    /// * [`SvfType::Bell`]
    pub const fn set_gain_linear(&mut self, linear: f32) {
        self.gain = Volume::Linear(linear);
    }

    /// Set the given filter gain in decibels, where `0.0` is unity gain and
    /// `f32::NEG_INFINITY` is silence.
    ///
    /// This only has effect if the filter type is one of the following:
    /// * [`SvfType::LowShelf`]
    /// * [`SvfType::HighShelf`]
    /// * [`SvfType::Bell`]
    pub const fn set_gain_decibels(&mut self, decibels: f32) {
        self.gain = Volume::Decibels(decibels);
    }
}

impl<const CHANNELS: usize> AudioNode for SvfNode<CHANNELS> {
    type Configuration = SvfNodeConfig;

    fn info(&self, _config: &Self::Configuration) -> Result<AudioNodeInfo, NodeError> {
        Ok(
            AudioNodeInfo::new()
                .debug_name("svf")
                .channel_config(ChannelConfig {
                    num_inputs: ChannelCount::new(CHANNELS as u32).unwrap(),
                    num_outputs: ChannelCount::new(CHANNELS as u32).unwrap(),
                })
                .in_place_buffers(true), // Use SVF node as a test for in-place buffers, even
                                         // though it currently does not improve performance
        )
    }

    fn construct_processor(
        &self,
        config: &Self::Configuration,
        cx: ConstructProcessorContext,
    ) -> Result<impl AudioNodeProcessor, NodeError> {
        let cutoff_hz = self
            .cutoff_hz
            .clamp(config.freq_range.start, config.freq_range.end);
        let q_factor = self
            .q_factor
            .clamp(config.q_range.start, config.q_range.end);

        let min_gain = db_to_amp(config.gain_db_range.start);
        let max_gain = db_to_amp(config.gain_db_range.end);
        let mut gain = self.gain.amp().clamp(min_gain, max_gain);
        if gain > 0.99999 && gain < 1.00001 {
            gain = 1.0;
        }

        let mut new_self = Processor {
            filter_0: SvfStateSimd::<CHANNELS>::default(),
            filter_1: SvfStateSimd::<CHANNELS>::default(),
            num_filters: 0,
            filter_0_coeff: SvfCoeffSimd::<CHANNELS>::default(),
            filter_1_coeff: SvfCoeffSimd::<CHANNELS>::default(),
            filter_type: self.filter_type,
            cutoff_hz: SmoothedParam::new(
                cutoff_hz,
                config.freq_range.end - config.freq_range.start,
                SmootherConfig {
                    smooth_seconds: self.smooth_seconds,
                    ..Default::default()
                },
                cx.stream_info.sample_rate,
            ),
            q_factor: SmoothedParam::new(
                q_factor,
                config.q_range.end - config.q_range.start,
                SmootherConfig {
                    smooth_seconds: self.smooth_seconds,
                    ..Default::default()
                },
                cx.stream_info.sample_rate,
            ),
            gain: SmoothedParam::new(
                gain,
                max_gain - min_gain,
                SmootherConfig {
                    smooth_seconds: self.smooth_seconds,
                    ..Default::default()
                },
                cx.stream_info.sample_rate,
            ),
            freq_range: config.freq_range.clone(),
            q_range: config.q_range.clone(),
            gain_range: min_gain..max_gain,
            coeff_update_mask: self.coeff_update_factor.mask(),
            params_changed: false,
        };

        new_self.update_coefficients(
            new_self.cutoff_hz.target_value(),
            new_self.q_factor.target_value(),
            new_self.gain.target_value(),
            cx.stream_info.sample_rate_recip as f32,
        );

        Ok(new_self)
    }
}

struct Processor<const CHANNELS: usize> {
    filter_0: SvfStateSimd<CHANNELS>,
    filter_1: SvfStateSimd<CHANNELS>,
    num_filters: usize,

    filter_0_coeff: SvfCoeffSimd<CHANNELS>,
    filter_1_coeff: SvfCoeffSimd<CHANNELS>,

    filter_type: SvfType,
    cutoff_hz: SmoothedParam,
    q_factor: SmoothedParam,
    gain: SmoothedParam,

    freq_range: Range<f32>,
    q_range: Range<f32>,
    gain_range: Range<f32>,
    coeff_update_mask: CoeffUpdateMask,
    params_changed: bool,
}

impl<const CHANNELS: usize> Processor<CHANNELS> {
    #[cold]
    #[inline(never)]
    fn update_coefficients(&mut self, cutoff_hz: f32, q: f32, gain: f32, sample_rate_recip: f32) {
        match self.filter_type {
            SvfType::Lowpass => {
                self.num_filters = 1;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::lowpass_ord2(cutoff_hz, q, sample_rate_recip));
            }
            SvfType::LowpassX2 => {
                self.num_filters = 2;

                let [coeff_0, coeff_1] = SvfCoeff::lowpass_ord4(cutoff_hz, q, sample_rate_recip);
                self.filter_0_coeff = SvfCoeffSimd::splat(coeff_0);
                self.filter_1_coeff = SvfCoeffSimd::splat(coeff_1);
            }
            SvfType::Highpass => {
                self.num_filters = 1;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::highpass_ord2(cutoff_hz, q, sample_rate_recip));
            }
            SvfType::HighpassX2 => {
                self.num_filters = 2;

                let [coeff_0, coeff_1] = SvfCoeff::highpass_ord4(cutoff_hz, q, sample_rate_recip);
                self.filter_0_coeff = SvfCoeffSimd::splat(coeff_0);
                self.filter_1_coeff = SvfCoeffSimd::splat(coeff_1);
            }
            SvfType::Bandpass => {
                self.num_filters = 2;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::lowpass_ord2(cutoff_hz, q, sample_rate_recip));
                self.filter_1_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::highpass_ord2(cutoff_hz, q, sample_rate_recip));
            }
            SvfType::LowShelf => {
                self.num_filters = 1;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::low_shelf(cutoff_hz, q, gain, sample_rate_recip));
            }
            SvfType::HighShelf => {
                self.num_filters = 1;

                self.filter_0_coeff = SvfCoeffSimd::splat(SvfCoeff::high_shelf(
                    cutoff_hz,
                    q,
                    gain,
                    sample_rate_recip,
                ));
            }
            SvfType::Bell => {
                self.num_filters = 1;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::bell(cutoff_hz, q, gain, sample_rate_recip));
            }
            SvfType::Notch => {
                self.num_filters = 1;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::notch(cutoff_hz, q, sample_rate_recip));
            }
            SvfType::Allpass => {
                self.num_filters = 1;

                self.filter_0_coeff =
                    SvfCoeffSimd::splat(SvfCoeff::allpass(cutoff_hz, q, sample_rate_recip));
            }
        }

        if self.num_filters == 1 {
            self.filter_1.reset();
        }
    }

    /// Smoothing loop for single-filter types that don't use gain
    /// (Lowpass, Highpass, Notch, Allpass).
    fn smoothing_loop_single(&mut self, info: &ProcInfo, outputs: &mut [&mut [f32]]) {
        assert!(outputs.len() == CHANNELS);
        for ch in outputs.iter() {
            assert!(ch.len() >= info.frames);
        }

        for i in 0..info.frames {
            let cutoff_hz = self.cutoff_hz.next_smoothed();
            let q = self.q_factor.next_smoothed();

            // Only recalculate coefficients every 2^coeff_update_factor frames
            if self.coeff_update_mask.do_update(i) {
                self.update_coefficients(cutoff_hz, q, 0.0, info.sample_rate_recip as f32);
            }

            let s: [f32; CHANNELS] = core::array::from_fn(|ch_i| {
                // Safety: These bounds have been checked above.
                unsafe { *outputs.get_unchecked(ch_i).get_unchecked(i) }
            });

            let out = self.filter_0.process(s, &self.filter_0_coeff);

            for (ch_i, &o) in out.iter().enumerate().take(CHANNELS) {
                // Safety: These bounds have been checked above.
                unsafe {
                    *outputs.get_unchecked_mut(ch_i).get_unchecked_mut(i) = o;
                }
            }
        }
    }

    /// Smoothing loop for single-filter types that use gain
    /// (LowShelf, HighShelf, Bell).
    fn smoothing_loop_single_with_gain(&mut self, info: &ProcInfo, outputs: &mut [&mut [f32]]) {
        assert!(outputs.len() == CHANNELS);
        for ch in outputs.iter() {
            assert!(ch.len() >= info.frames);
        }

        for i in 0..info.frames {
            let cutoff_hz = self.cutoff_hz.next_smoothed();
            let q = self.q_factor.next_smoothed();
            let gain = self.gain.next_smoothed();

            // Only recalculate coefficients every 2^coeff_update_factor frames
            if self.coeff_update_mask.do_update(i) {
                self.update_coefficients(cutoff_hz, q, gain, info.sample_rate_recip as f32);
            }

            let s: [f32; CHANNELS] = core::array::from_fn(|ch_i| {
                // Safety: These bounds have been checked above.
                unsafe { *outputs.get_unchecked(ch_i).get_unchecked(i) }
            });

            let out = self.filter_0.process(s, &self.filter_0_coeff);

            for (ch_i, &o) in out.iter().enumerate().take(CHANNELS) {
                // Safety: These bounds have been checked above.
                unsafe {
                    *outputs.get_unchecked_mut(ch_i).get_unchecked_mut(i) = o;
                }
            }
        }
    }

    /// Smoothing loop for dual-filter types that don't use gain
    /// (LowpassX2, HighpassX2, Bandpass).
    fn smoothing_loop_dual(&mut self, info: &ProcInfo, outputs: &mut [&mut [f32]]) {
        assert!(outputs.len() == CHANNELS);
        for ch in outputs.iter() {
            assert!(ch.len() >= info.frames);
        }

        for i in 0..info.frames {
            let cutoff_hz = self.cutoff_hz.next_smoothed();
            let q = self.q_factor.next_smoothed();

            // Only recalculate coefficients every 2^coeff_update_factor frames
            if self.coeff_update_mask.do_update(i) {
                self.update_coefficients(cutoff_hz, q, 0.0, info.sample_rate_recip as f32);
            }

            let s: [f32; CHANNELS] = core::array::from_fn(|ch_i| {
                // Safety: These bounds have been checked above.
                unsafe { *outputs.get_unchecked(ch_i).get_unchecked(i) }
            });

            let s = self.filter_0.process(s, &self.filter_0_coeff);
            let out = self.filter_1.process(s, &self.filter_1_coeff);

            for (ch_i, &o) in out.iter().enumerate().take(CHANNELS) {
                // Safety: These bounds have been checked above.
                unsafe {
                    *outputs.get_unchecked_mut(ch_i).get_unchecked_mut(i) = o;
                }
            }
        }
    }
}

impl<const CHANNELS: usize> Processor<CHANNELS> {
    fn reset(&mut self) {
        self.cutoff_hz.reset_to_target();
        self.filter_0.reset();
        self.filter_1.reset();
    }
}

impl<const CHANNELS: usize> AudioNodeProcessor for Processor<CHANNELS> {
    fn events(&mut self, info: &ProcInfo, events: &mut ProcEvents, _extra: &mut ProcExtra) {
        for patch in events.drain_patches::<SvfNode<CHANNELS>>() {
            match patch {
                SvfNodePatch::FilterType(filter_type) => {
                    self.params_changed = true;
                    self.filter_type = filter_type;
                }
                SvfNodePatch::CutoffHz(cutoff) => {
                    self.params_changed = true;
                    self.cutoff_hz
                        .set_value(cutoff.clamp(self.freq_range.start, self.freq_range.end));
                }
                SvfNodePatch::QFactor(q_factor) => {
                    self.params_changed = true;
                    self.q_factor
                        .set_value(q_factor.clamp(self.q_range.start, self.q_range.end));
                }
                SvfNodePatch::Gain(gain) => {
                    self.params_changed = true;
                    let mut gain = gain.amp().clamp(self.gain_range.start, self.gain_range.end);
                    if gain > 0.99999 && gain < 1.00001 {
                        gain = 1.0;
                    }
                    self.gain.set_value(gain);
                }
                SvfNodePatch::SmoothSeconds(seconds) => {
                    self.cutoff_hz.set_smooth_seconds(seconds, info.sample_rate);
                }
                SvfNodePatch::CoeffUpdateFactor(f) => {
                    self.coeff_update_mask = f.mask();
                }
            }
        }
    }

    fn bypassed(&mut self, _bypassed: bool) {
        self.reset();
    }

    fn process(
        &mut self,
        info: &ProcInfo,
        buffers: ProcBuffers,
        _extra: &mut ProcExtra,
    ) -> ProcessStatus {
        // Make sure that in-place buffer processing is being handled correctly.
        debug_assert_eq!(buffers.inputs.len(), 0);

        if info.out_silence_mask.all_channels_silent(CHANNELS) {
            // Outputs will be silent, so no need to process.

            // Reset the smoothers and filters since they don't need to smooth any
            // output.
            self.reset();

            return ProcessStatus::ClearAllOutputs;
        }

        if self.cutoff_hz.is_smoothing() || self.q_factor.is_smoothing() || self.gain.is_smoothing()
        {
            match self.filter_type {
                SvfType::Lowpass | SvfType::Highpass | SvfType::Notch | SvfType::Allpass => {
                    self.smoothing_loop_single(info, buffers.outputs)
                }
                SvfType::LowShelf | SvfType::HighShelf | SvfType::Bell => {
                    self.smoothing_loop_single_with_gain(info, buffers.outputs)
                }
                SvfType::LowpassX2 | SvfType::HighpassX2 | SvfType::Bandpass => {
                    self.smoothing_loop_dual(info, buffers.outputs)
                }
            }

            if self.cutoff_hz.settle() && self.q_factor.settle() && self.gain.settle() {
                self.update_coefficients(
                    self.cutoff_hz.target_value(),
                    self.q_factor.target_value(),
                    self.gain.target_value(),
                    info.sample_rate_recip as f32,
                );
            }
        } else {
            // The cutoff parameter is not currently smoothing, so we can optimize by
            // only updating the filter coefficients once.
            if self.params_changed {
                self.params_changed = false;
                self.update_coefficients(
                    self.cutoff_hz.target_value(),
                    self.q_factor.target_value(),
                    self.gain.target_value(),
                    info.sample_rate_recip as f32,
                );
            }

            assert!(buffers.outputs.len() == CHANNELS);
            for ch in buffers.outputs.iter() {
                assert!(ch.len() >= info.frames);
            }

            if self.num_filters == 1 {
                for i in 0..info.frames {
                    let s: [f32; CHANNELS] = core::array::from_fn(|ch_i| {
                        // Safety: These bounds have been checked above.
                        unsafe { *buffers.outputs.get_unchecked(ch_i).get_unchecked(i) }
                    });

                    let out = self.filter_0.process(s, &self.filter_0_coeff);

                    for (ch_i, &o) in out.iter().enumerate().take(CHANNELS) {
                        // Safety: These bounds have been checked above.
                        unsafe {
                            *buffers.outputs.get_unchecked_mut(ch_i).get_unchecked_mut(i) = o;
                        }
                    }
                }
            } else {
                for i in 0..info.frames {
                    let s: [f32; CHANNELS] = core::array::from_fn(|ch_i| {
                        // Safety: These bounds have been checked above.
                        unsafe { *buffers.outputs.get_unchecked(ch_i).get_unchecked(i) }
                    });

                    let s = self.filter_0.process(s, &self.filter_0_coeff);
                    let out = self.filter_1.process(s, &self.filter_1_coeff);

                    for (ch_i, &o) in out.iter().enumerate().take(CHANNELS) {
                        // Safety: These bounds have been checked above.
                        unsafe {
                            *buffers.outputs.get_unchecked_mut(ch_i).get_unchecked_mut(i) = o;
                        }
                    }
                }
            }
        }

        ProcessStatus::OutputsModified
    }

    fn new_stream(&mut self, stream_info: &StreamInfo, _context: &mut ProcStreamCtx) {
        self.cutoff_hz.update_sample_rate(stream_info.sample_rate);
        self.q_factor.update_sample_rate(stream_info.sample_rate);
        self.gain.update_sample_rate(stream_info.sample_rate);

        self.update_coefficients(
            self.cutoff_hz.target_value(),
            self.q_factor.target_value(),
            self.gain.target_value(),
            stream_info.sample_rate_recip as f32,
        );
    }
}