weirdnet-audio-plugin 0.2.0

Audio plugins for Weirdnet: the Plugin trait, typed parameters, a registry, chain processing with a content-hash cache key, and the built-ins gain, levels and frequencies.
Documentation
use crate::{ParamSpec, ParamValues, Plugin, PluginError};
use weirdnet_dsp::{BiquadCoeffs, FilterKind, MultiBiquad};
use weirdnet_media::waveform::Waveform;

/// `weirdnet.frequencies`: a biquad filter (RBJ cookbook, from `weirdnet-dsp`) on every channel.
///
/// | Parameter | Range | Default |
/// | --- | --- | --- |
/// | `type` | `peak`, `low`, `high` or `band` (peaking EQ, low-pass, high-pass, band-pass) | `peak` |
/// | `cutoff_hz` | 20 to 20000 Hz | 1000 |
/// | `q` | 0.1 to 18 | 0.7071 |
/// | `gain_db` | -24 to +24 dB, `peak` only | 0 |
///
/// 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
/// because the limit depends on the audio. A peaking filter with zero gain is an identity and returns the input's samples unchanged.
/// 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.
pub struct Frequencies;

fn specs() -> &'static [ParamSpec] {
    use std::sync::OnceLock;
    static SPECS: OnceLock<Vec<ParamSpec>> = OnceLock::new();
    SPECS.get_or_init(|| {
        vec![
            ParamSpec::choice("type", &["peak", "low", "high", "band"], "peak"),
            ParamSpec::float("cutoff_hz", 20.0, 20_000.0, 1000.0, "Hz"),
            ParamSpec::float("q", 0.1, 18.0, std::f64::consts::FRAC_1_SQRT_2, ""),
            ParamSpec::float("gain_db", -24.0, 24.0, 0.0, "dB"),
        ]
    })
}

impl Plugin for Frequencies {
    fn id(&self) -> &'static str {
        "weirdnet.frequencies"
    }

    fn params(&self) -> &[ParamSpec] {
        specs()
    }

    fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
        let kind = match values.choice("type") {
            "low" => FilterKind::LowPass,
            "high" => FilterKind::HighPass,
            "band" => FilterKind::BandPass,
            _ => FilterKind::Peaking,
        };
        let gain_db = values.float("gain_db");
        let coeffs = BiquadCoeffs::design(kind, input.sample_rate(), values.float("cutoff_hz"), values.float("q"), gain_db).map_err(|e| match e {
            weirdnet_dsp::DspError::CutoffOutOfRange { .. } => PluginError::invalid("cutoff_hz", e.to_string()),
            weirdnet_dsp::DspError::InvalidQ(_) => PluginError::invalid("q", e.to_string()),
            other => PluginError::Internal(other.to_string()),
        })?;
        if kind == FilterKind::Peaking && gain_db == 0.0 {
            return Ok(input.clone());
        }
        let mut samples = input.samples().to_vec();
        MultiBiquad::new(input.channels(), coeffs).process_interleaved(&mut samples);
        Ok(Waveform::new(input.sample_rate(), input.channels(), samples)?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Registry;

    const FS: u32 = 48_000;

    fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
        Registry::with_builtins().process("weirdnet.frequencies", input, &v)
    }

    /// The settled amplitude in dB of a sine of `hz` through the plugin (second half of one second, to skip the start-up).
    fn measure(hz: f64, v: ParamValues) -> f64 {
        let w = Waveform::tone(FS, hz, FS as usize, 0.5).unwrap();
        let out = run(&w, v).unwrap();
        let tail = &out.samples()[out.samples().len() / 2..];
        let amp = f64::from(weirdnet_dsp::rms(tail)) * std::f64::consts::SQRT_2;
        20.0 * (amp / 0.5).log10()
    }

    #[test]
    fn default_is_the_same_samples() {
        let w = Waveform::tone(FS, 440.0, 100, 0.5).unwrap();
        let out = run(&w, ParamValues::new()).unwrap();
        assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()));
    }

    #[test]
    fn low_pass_golden_response() {
        let v = || ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", 1000.0);
        assert!(measure(100.0, v()).abs() < 0.05, "passband");
        assert!((measure(1000.0, v()) + 3.01).abs() < 0.1, "-3 dB at the cutoff");
        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);
        assert!(designed < -38.0, "a decade up a second-order filter is at least -38 dB: {designed}");
        assert!((measure(10_000.0, v()) - designed).abs() < 0.5, "the audio follows the designed curve");
    }

    #[test]
    fn high_pass_and_band_pass_golden_response() {
        let hp = || ParamValues::new().with_choice("type", "high").with_float("cutoff_hz", 1000.0);
        assert!(measure(10_000.0, hp()).abs() < 0.1);
        assert!((measure(1000.0, hp()) + 3.01).abs() < 0.1);
        assert!(measure(100.0, hp()) < -38.0);
        let bp = || ParamValues::new().with_choice("type", "band").with_float("cutoff_hz", 1000.0).with_float("q", 4.0);
        assert!(measure(1000.0, bp()).abs() < 0.1, "0 dB at the centre");
        assert!(measure(100.0, bp()) < -20.0 && measure(10_000.0, bp()) < -20.0);
    }

    #[test]
    fn peaking_boosts_and_cuts_at_the_centre_only() {
        let v = |g: f64| ParamValues::new().with_float("cutoff_hz", 2000.0).with_float("q", 2.0).with_float("gain_db", g);
        assert!((measure(2000.0, v(9.0)) - 9.0).abs() < 0.1);
        assert!((measure(2000.0, v(-12.0)) + 12.0).abs() < 0.1);
        assert!(measure(100.0, v(9.0)).abs() < 0.2, "far from the centre it is flat");
    }

    #[test]
    fn matches_the_designed_curve_exactly() {
        let c = BiquadCoeffs::design(FilterKind::Peaking, FS, 3000.0, 1.5, 6.0).unwrap();
        let v = ParamValues::new().with_float("cutoff_hz", 3000.0).with_float("q", 1.5).with_float("gain_db", 6.0);
        assert!((measure(3000.0, v) - c.response_db(3000.0, FS)).abs() < 0.02);
    }

    #[test]
    fn stereo_channels_are_filtered_independently() {
        let mut s = Vec::new();
        for i in 0..4800 {
            s.push((i as f32 * 0.3).sin() * 0.5);
            s.push(0.0);
        }
        let w = Waveform::new(FS, 2, s).unwrap();
        let out = run(&w, ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", 500.0)).unwrap();
        assert_eq!(out.channels(), 2);
        assert!(out.channel_peak(0).unwrap() > 0.0);
        assert_eq!(out.channel_peak(1).unwrap(), 0.0, "silence on one side stays silent");
    }

    #[test]
    fn a_cutoff_at_or_above_nyquist_is_an_error_naming_it() {
        let w = Waveform::tone(8000, 100.0, 100, 0.5).unwrap(); // Nyquist 4000
        for hz in [4000.0, 10_000.0] {
            let e = run(&w, ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", hz)).unwrap_err();
            assert!(matches!(&e, PluginError::InvalidParam { name, .. } if name == "cutoff_hz"), "{e:?}");
        }
        assert!(run(&w, ParamValues::new().with_choice("type", "low").with_float("cutoff_hz", 3999.0)).is_ok());
        // Even the identity default checks it, so a chain fails the same way whatever the gain.
        assert!(run(&w, ParamValues::new().with_float("cutoff_hz", 5000.0)).is_err());
    }

    #[test]
    fn out_of_range_values_are_rejected() {
        let w = Waveform::silence(FS, 1, 10).unwrap();
        for (name, x) in [("cutoff_hz", 19.0), ("cutoff_hz", 20_001.0), ("q", 0.0), ("q", 19.0), ("gain_db", 25.0)] {
            assert!(matches!(run(&w, ParamValues::new().with_float(name, x)), Err(PluginError::InvalidParam { .. })), "{name}={x}");
        }
    }

    #[test]
    fn extreme_settings_stay_finite() {
        let w = Waveform::tone(FS, 1000.0, 4800, 1.0).unwrap();
        for ty in ["peak", "low", "high", "band"] {
            for hz in [20.0, 1000.0, 20_000.0] {
                for q in [0.1, 18.0] {
                    let out = run(
                        &w,
                        ParamValues::new().with_choice("type", ty).with_float("cutoff_hz", hz).with_float("q", q).with_float("gain_db", 24.0),
                    )
                    .unwrap();
                    assert!(out.samples().iter().all(|s| s.is_finite()), "{ty} {hz} {q}");
                }
            }
        }
    }
}