Skip to main content

weirdnet_audio_plugin/builtin/
frequencies.rs

1use crate::{ParamSpec, ParamValues, Plugin, PluginError};
2use weirdnet_dsp::{BiquadCoeffs, FilterKind, MultiBiquad};
3use weirdnet_media::waveform::Waveform;
4
5/// `weirdnet.frequencies`: a biquad filter (RBJ cookbook, from `weirdnet-dsp`) on every channel.
6///
7/// | Parameter | Range | Default |
8/// | --- | --- | --- |
9/// | `type` | `peak`, `low`, `high` or `band` (peaking EQ, low-pass, high-pass, band-pass) | `peak` |
10/// | `cutoff_hz` | 20 to 20000 Hz | 1000 |
11/// | `q` | 0.1 to 18 | 0.7071 |
12/// | `gain_db` | -24 to +24 dB, `peak` only | 0 |
13///
14/// A cutoff at or above half the waveform's sample rate is [`PluginError::InvalidParam`]: it is a different error from an out-of-range value
15/// because the limit depends on the audio. A peaking filter with zero gain is an identity and returns the input's samples unchanged.
16/// The filter starts from rest and output has the input's length, so a high-Q filter's ring is cut off at the end of the sound.
17pub struct Frequencies;
18
19fn specs() -> &'static [ParamSpec] {
20    use std::sync::OnceLock;
21    static SPECS: OnceLock<Vec<ParamSpec>> = OnceLock::new();
22    SPECS.get_or_init(|| {
23        vec![
24            ParamSpec::choice("type", &["peak", "low", "high", "band"], "peak"),
25            ParamSpec::float("cutoff_hz", 20.0, 20_000.0, 1000.0, "Hz"),
26            ParamSpec::float("q", 0.1, 18.0, std::f64::consts::FRAC_1_SQRT_2, ""),
27            ParamSpec::float("gain_db", -24.0, 24.0, 0.0, "dB"),
28        ]
29    })
30}
31
32impl Plugin for Frequencies {
33    fn id(&self) -> &'static str {
34        "weirdnet.frequencies"
35    }
36
37    fn params(&self) -> &[ParamSpec] {
38        specs()
39    }
40
41    fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
42        let kind = match values.choice("type") {
43            "low" => FilterKind::LowPass,
44            "high" => FilterKind::HighPass,
45            "band" => FilterKind::BandPass,
46            _ => FilterKind::Peaking,
47        };
48        let gain_db = values.float("gain_db");
49        let coeffs = BiquadCoeffs::design(kind, input.sample_rate(), values.float("cutoff_hz"), values.float("q"), gain_db).map_err(|e| match e {
50            weirdnet_dsp::DspError::CutoffOutOfRange { .. } => PluginError::invalid("cutoff_hz", e.to_string()),
51            weirdnet_dsp::DspError::InvalidQ(_) => PluginError::invalid("q", e.to_string()),
52            other => PluginError::Internal(other.to_string()),
53        })?;
54        if kind == FilterKind::Peaking && gain_db == 0.0 {
55            return Ok(input.clone());
56        }
57        let mut samples = input.samples().to_vec();
58        MultiBiquad::new(input.channels(), coeffs).process_interleaved(&mut samples);
59        Ok(Waveform::new(input.sample_rate(), input.channels(), samples)?)
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::Registry;
67
68    const FS: u32 = 48_000;
69
70    fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
71        Registry::with_builtins().process("weirdnet.frequencies", input, &v)
72    }
73
74    /// The settled amplitude in dB of a sine of `hz` through the plugin (second half of one second, to skip the start-up).
75    fn measure(hz: f64, v: ParamValues) -> f64 {
76        let w = Waveform::tone(FS, hz, FS as usize, 0.5).unwrap();
77        let out = run(&w, v).unwrap();
78        let tail = &out.samples()[out.samples().len() / 2..];
79        let amp = f64::from(weirdnet_dsp::rms(tail)) * std::f64::consts::SQRT_2;
80        20.0 * (amp / 0.5).log10()
81    }
82
83    #[test]
84    fn default_is_the_same_samples() {
85        let w = Waveform::tone(FS, 440.0, 100, 0.5).unwrap();
86        let out = run(&w, ParamValues::new()).unwrap();
87        assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()));
88    }
89
90    #[test]
91    fn low_pass_golden_response() {
92        let v = || ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", 1000.0);
93        assert!(measure(100.0, v()).abs() < 0.05, "passband");
94        assert!((measure(1000.0, v()) + 3.01).abs() < 0.1, "-3 dB at the cutoff");
95        let designed = BiquadCoeffs::design(FilterKind::LowPass, FS, 1000.0, std::f64::consts::FRAC_1_SQRT_2, 0.0).unwrap().response_db(10_000.0, FS);
96        assert!(designed < -38.0, "a decade up a second-order filter is at least -38 dB: {designed}");
97        assert!((measure(10_000.0, v()) - designed).abs() < 0.5, "the audio follows the designed curve");
98    }
99
100    #[test]
101    fn high_pass_and_band_pass_golden_response() {
102        let hp = || ParamValues::new().with_choice("type", "high").with_float("cutoff_hz", 1000.0);
103        assert!(measure(10_000.0, hp()).abs() < 0.1);
104        assert!((measure(1000.0, hp()) + 3.01).abs() < 0.1);
105        assert!(measure(100.0, hp()) < -38.0);
106        let bp = || ParamValues::new().with_choice("type", "band").with_float("cutoff_hz", 1000.0).with_float("q", 4.0);
107        assert!(measure(1000.0, bp()).abs() < 0.1, "0 dB at the centre");
108        assert!(measure(100.0, bp()) < -20.0 && measure(10_000.0, bp()) < -20.0);
109    }
110
111    #[test]
112    fn peaking_boosts_and_cuts_at_the_centre_only() {
113        let v = |g: f64| ParamValues::new().with_float("cutoff_hz", 2000.0).with_float("q", 2.0).with_float("gain_db", g);
114        assert!((measure(2000.0, v(9.0)) - 9.0).abs() < 0.1);
115        assert!((measure(2000.0, v(-12.0)) + 12.0).abs() < 0.1);
116        assert!(measure(100.0, v(9.0)).abs() < 0.2, "far from the centre it is flat");
117    }
118
119    #[test]
120    fn matches_the_designed_curve_exactly() {
121        let c = BiquadCoeffs::design(FilterKind::Peaking, FS, 3000.0, 1.5, 6.0).unwrap();
122        let v = ParamValues::new().with_float("cutoff_hz", 3000.0).with_float("q", 1.5).with_float("gain_db", 6.0);
123        assert!((measure(3000.0, v) - c.response_db(3000.0, FS)).abs() < 0.02);
124    }
125
126    #[test]
127    fn stereo_channels_are_filtered_independently() {
128        let mut s = Vec::new();
129        for i in 0..4800 {
130            s.push((i as f32 * 0.3).sin() * 0.5);
131            s.push(0.0);
132        }
133        let w = Waveform::new(FS, 2, s).unwrap();
134        let out = run(&w, ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", 500.0)).unwrap();
135        assert_eq!(out.channels(), 2);
136        assert!(out.channel_peak(0).unwrap() > 0.0);
137        assert_eq!(out.channel_peak(1).unwrap(), 0.0, "silence on one side stays silent");
138    }
139
140    #[test]
141    fn a_cutoff_at_or_above_nyquist_is_an_error_naming_it() {
142        let w = Waveform::tone(8000, 100.0, 100, 0.5).unwrap(); // Nyquist 4000
143        for hz in [4000.0, 10_000.0] {
144            let e = run(&w, ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", hz)).unwrap_err();
145            assert!(matches!(&e, PluginError::InvalidParam { name, .. } if name == "cutoff_hz"), "{e:?}");
146        }
147        assert!(run(&w, ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", 3999.0)).is_ok());
148        // Even the identity default checks it, so a chain fails the same way whatever the gain.
149        assert!(run(&w, ParamValues::new().with_float("cutoff_hz", 5000.0)).is_err());
150    }
151
152    #[test]
153    fn out_of_range_values_are_rejected() {
154        let w = Waveform::silence(FS, 1, 10).unwrap();
155        for (name, x) in [("cutoff_hz", 19.0), ("cutoff_hz", 20_001.0), ("q", 0.0), ("q", 19.0), ("gain_db", 25.0)] {
156            assert!(matches!(run(&w, ParamValues::new().with_float(name, x)), Err(PluginError::InvalidParam { .. })), "{name}={x}");
157        }
158    }
159
160    #[test]
161    fn extreme_settings_stay_finite() {
162        let w = Waveform::tone(FS, 1000.0, 4800, 1.0).unwrap();
163        for ty in ["peak", "low", "high", "band"] {
164            for hz in [20.0, 1000.0, 20_000.0] {
165                for q in [0.1, 18.0] {
166                    let out = run(
167                        &w,
168                        ParamValues::new().with_choice("type", ty).with_float("cutoff_hz", hz).with_float("q", q).with_float("gain_db", 24.0),
169                    )
170                    .unwrap();
171                    assert!(out.samples().iter().all(|s| s.is_finite()), "{ty} {hz} {q}");
172                }
173            }
174        }
175    }
176}