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
// Copyright (c) 2021 Weird Constructor <weirdconstructor@gmail.com>
// This file is a part of HexoDSP. Released under GPL-3.0-or-later.
// See README.md and COPYING for details.

use crate::dsp::{
    DspNode, GraphFun, LedPhaseVals, NodeContext, NodeGlobalRef, NodeId, ProcBuf, SAtom,
};
use crate::nodes::{NodeAudioContext, NodeExecContext};
use synfx_dsp::*;

#[macro_export]
macro_rules! fa_biqfilt_type {
    ($formatter: expr, $v: expr, $denorm_v: expr) => {{
        let s = match ($v.round() as usize) {
            0 => "BtW LP",
            1 => "Res",
            _ => "?",
        };
        write!($formatter, "{}", s)
    }};
}

#[macro_export]
macro_rules! fa_biqfilt_ord {
    ($formatter: expr, $v: expr, $denorm_v: expr) => {{
        let s = match ($v.round() as usize) {
            0 => "1",
            1 => "2",
            2 => "3",
            3 => "4",
            _ => "?",
        };
        write!($formatter, "{}", s)
    }};
}

/// A simple amplifier
#[derive(Debug, Clone)]
pub struct BiqFilt {
    cascade: Vec<Biquad>,
    srate: f32,
    ofreq: f32,
    oq: f32,
    ogain: f32,
    otype: u8,
}

impl BiqFilt {
    pub fn new(_nid: &NodeId, _node_global: &NodeGlobalRef) -> Self {
        Self {
            cascade: vec![Biquad::new(); 4],
            srate: 1.0 / 44100.0,
            otype: 99,   // value that can't be set by the user
            ofreq: -2.0, // value that can't be set by the user
            oq: -2.0,    // value that can't be set by the user
            ogain: -2.0, // value that can't be set by the user
        }
    }
    pub const inp: &'static str = "Signal input";
    pub const freq: &'static str = "Filter cutoff frequency.";
    pub const q: &'static str = "Filter Q factor.";
    pub const gain: &'static str = "Filter gain.";
    pub const ftype: &'static str = "'BtW LP' Butterworth Low-Pass, 'Res' Resonator";
    pub const order: &'static str = "";
    pub const sig: &'static str = "Filtered signal output.";
    pub const DESC: &'static str = r#"Biquad Filter

This is the implementation of a biquad filter cascade.
It is not meant for fast automation. Please use other nodes
like eg. `SFilter` for that.
"#;
    pub const HELP: &'static str = r#"Biquad Filter (Cascade)

This is the implementation of a biquad filter cascade.
It is not meant for fast automation and might blow up if you
treat it too rough. Please use other nodes like eg. `SFilter` for that.
"#;

    pub fn graph_fun() -> Option<GraphFun> {
        None
    }
}

impl DspNode for BiqFilt {
    fn set_sample_rate(&mut self, srate: f32) {
        self.srate = srate;
        self.otype = 99; // cause recalculation of the filter

        for b in &mut self.cascade {
            b.reset();
        }
    }

    fn reset(&mut self) {
        for b in &mut self.cascade {
            b.reset();
        }
    }

    #[inline]
    fn process(
        &mut self,
        ctx: &mut dyn NodeAudioContext,
        _ectx: &mut NodeExecContext,
        _nctx: &NodeContext,
        atoms: &[SAtom],
        inputs: &[ProcBuf],
        outputs: &mut [ProcBuf],
        ctx_vals: LedPhaseVals,
    ) {
        use crate::dsp::{at, denorm, inp, out};

        let inp = inp::BiqFilt::inp(inputs);
        let freq = inp::BiqFilt::freq(inputs);
        let q = inp::BiqFilt::q(inputs);
        let gain = inp::BiqFilt::gain(inputs);
        let ftype = at::BiqFilt::ftype(atoms);
        let order = at::BiqFilt::order(atoms);
        let out = out::BiqFilt::sig(outputs);

        let ftype = ftype.i() as u8;
        let cfreq = denorm::BiqFilt::freq(freq, 0);
        let cfreq = cfreq.clamp(0.0, 22000.0);
        let cq = denorm::BiqFilt::q(q, 0);
        let cgain = denorm::BiqFilt::gain(gain, 0);

        if ftype != self.otype
            || (cfreq - self.ofreq).abs() > 0.0001
            || (cq - self.oq).abs() > 0.0001
            || (cgain - self.ogain).abs() > 0.0001
        {
            // recalculate coeffs of all in the cascade
            let coefs = match ftype {
                1 => BiquadCoefs::resonator(self.srate, cfreq, cq),
                _ => BiquadCoefs::butter_lowpass(self.srate, cfreq),
            };

            for o in &mut self.cascade {
                o.set_coefs(coefs);
                o.reset();
            }

            self.otype = ftype;
            self.ofreq = cfreq;
            self.oq = cq;
            self.ogain = cgain;
        }

        let mut order = order.i() as u8;
        if ftype == 1 {
            // The resonator just blows up with higher orders.
            order = 0;
        }

        for frame in 0..ctx.nframes() {
            //            let freq  = denorm::BiqFilt::freq(freq, frame);
            //            let freq  = freq.clamp($minfreq, $maxfreq);
            //            let q     = denorm::BiqFilt::q(q, frame);
            //            let gain  = denorm::BiqFilt::gain(gain, frame);

            let mut s = inp.read(frame);
            for i in 0..=order {
                s = self.cascade[i as usize].tick(s);
            }

            out.write(frame, s);
        }

        ctx_vals[0].set(out.read(ctx.nframes() - 1));
    }
}