weirdnet-audio-plugin 0.3.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::{ParamValue, ParamValues, PluginError, Registry};
use weirdnet_media::waveform::Waveform;

/// One use of a plugin in a chain.
#[derive(Debug, Clone, PartialEq)]
pub struct PluginInstance {
    /// The plugin id, for example `"weirdnet.gain"`.
    pub plugin: String,
    pub values: ParamValues,
    /// A bypassed instance is skipped.
    pub bypass: bool,
}

impl PluginInstance {
    pub fn new(plugin: &str, values: ParamValues) -> Self {
        PluginInstance { plugin: plugin.to_string(), values, bypass: false }
    }
}

/// Why a chain failed, and where.
#[derive(Debug, Clone, PartialEq)]
pub enum ChainError {
    /// A step names a plugin that is not registered.
    UnknownPlugin { step: usize, plugin: String },
    /// A step's plugin returned an error (including invalid parameters).
    Step { step: usize, plugin: String, error: PluginError },
}

impl ChainError {
    /// The zero-based index of the failing step.
    pub fn step(&self) -> usize {
        match self {
            ChainError::UnknownPlugin { step, .. } | ChainError::Step { step, .. } => *step,
        }
    }
}

impl std::fmt::Display for ChainError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChainError::UnknownPlugin { step, plugin } => write!(f, "step {} ({plugin}): no such plugin", step + 1),
            ChainError::Step { step, plugin, error } => write!(f, "step {} ({plugin}): {error}", step + 1),
        }
    }
}

impl std::error::Error for ChainError {}

/// Runs `chain` over `input`, in order, skipping bypassed instances. An empty chain returns a clone of the input.
pub fn apply_chain(registry: &Registry, input: &Waveform, chain: &[PluginInstance]) -> Result<Waveform, ChainError> {
    let mut current = input.clone();
    for (step, instance) in chain.iter().enumerate() {
        if instance.bypass {
            continue;
        }
        if registry.get(&instance.plugin).is_none() {
            return Err(ChainError::UnknownPlugin { step, plugin: instance.plugin.clone() });
        }
        current = registry.process(&instance.plugin, &current, &instance.values).map_err(|error| ChainError::Step {
            step,
            plugin: instance.plugin.clone(),
            error,
        })?;
    }
    Ok(current)
}

/// The BLAKE3 hash of a waveform's content (sample rate, channels and every sample's bits). Use it as the `source` of [`chain_cache_key`]
/// for audio that has no content hash of its own.
pub fn waveform_hash(w: &Waveform) -> [u8; 32] {
    let mut h = blake3::Hasher::new_derive_key("weirdnet-audio-plugin 2026 waveform hash");
    h.update(&w.sample_rate().to_le_bytes());
    h.update(&w.channels().to_le_bytes());
    for s in w.samples() {
        h.update(&canonical_bits(*s).to_le_bytes());
    }
    *h.finalize().as_bytes()
}

fn canonical_bits(x: f32) -> u32 {
    if x == 0.0 { 0 } else { x.to_bits() }
}

fn put_str(h: &mut blake3::Hasher, s: &str) {
    h.update(&(s.len() as u64).to_le_bytes());
    h.update(s.as_bytes());
}

/// The key a cache uses for "`source` through `chain`".
///
/// It covers the source hash, and for each step that is not bypassed the plugin id, the plugin's [`version`](crate::Plugin::version) and the
/// parameter values after defaults are filled in. So an explicit default and an omitted one give the same key, bypassed steps and their values
/// do not matter, and a change to any parameter, to the order, or to a plugin's version gives a different key. Fields are length-prefixed so
/// no two different chains can produce the same bytes. Errors are the same as [`apply_chain`]'s for the unknown plugin or invalid values, since a
/// chain that cannot run has no result to cache.
pub fn chain_cache_key(registry: &Registry, source: &[u8; 32], chain: &[PluginInstance]) -> Result<[u8; 32], ChainError> {
    let mut h = blake3::Hasher::new_derive_key("weirdnet-audio-plugin 2026 chain cache key");
    h.update(source);
    for (step, instance) in chain.iter().enumerate() {
        if instance.bypass {
            continue;
        }
        let plugin = registry.get(&instance.plugin).ok_or_else(|| ChainError::UnknownPlugin { step, plugin: instance.plugin.clone() })?;
        let resolved = instance.values.resolve(plugin.params()).map_err(|error| ChainError::Step { step, plugin: instance.plugin.clone(), error })?;
        h.update(&[1]); // a step follows
        put_str(&mut h, plugin.id());
        h.update(&plugin.version().to_le_bytes());
        h.update(&(resolved.len() as u64).to_le_bytes());
        for (name, value) in resolved.iter() {
            put_str(&mut h, name);
            match value {
                ParamValue::Float(x) => {
                    h.update(&[0]);
                    h.update(&(if *x == 0.0 { 0.0f64 } else { *x }).to_bits().to_le_bytes());
                }
                ParamValue::Bool(b) => {
                    h.update(&[1, u8::from(*b)]);
                }
                ParamValue::Choice(c) => {
                    h.update(&[2]);
                    put_str(&mut h, c);
                }
            }
        }
    }
    h.update(&[0]); // end
    Ok(*h.finalize().as_bytes())
}

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

    fn gain(db: f64) -> PluginInstance {
        PluginInstance::new("weirdnet.gain", ParamValues::new().with_float("gain_db", db))
    }

    fn src() -> Waveform {
        Waveform::tone(48_000, 440.0, 4800, 0.5).unwrap()
    }

    #[test]
    fn an_empty_chain_is_the_input() {
        let w = src();
        assert_eq!(apply_chain(&Registry::with_builtins(), &w, &[]).unwrap(), w);
    }

    #[test]
    fn steps_run_in_order_and_bypass_skips() {
        let r = Registry::with_builtins();
        let w = src();
        let out = apply_chain(&r, &w, &[gain(-6.0), gain(-6.0)]).unwrap();
        let direct = w.gain_db(-12.0).unwrap();
        assert!((out.peak() - direct.peak()).abs() < 1e-6);
        let mut skipped = gain(-60.0);
        skipped.bypass = true;
        assert_eq!(apply_chain(&r, &w, &[skipped]).unwrap(), w);
        // Order matters when steps do not commute: a ceiling then gain, against gain then a ceiling.
        let ceil = PluginInstance::new("weirdnet.levels", ParamValues::new().with_float("ceiling_db", -6.0));
        let a = apply_chain(&r, &w, &[ceil.clone(), gain(12.0)]).unwrap();
        let b = apply_chain(&r, &w, &[gain(12.0), ceil]).unwrap();
        assert!(a.peak() > b.peak() * 3.0, "{} vs {}", a.peak(), b.peak());
    }

    #[test]
    fn errors_name_the_failing_step() {
        let r = Registry::with_builtins();
        let w = src();
        let bad = gain(100.0);
        let e = apply_chain(&r, &w, &[gain(-1.0), bad]).unwrap_err();
        assert_eq!(e.step(), 1);
        assert!(
            matches!(&e, ChainError::Step { plugin, error: PluginError::InvalidParam { name, .. }, .. } if plugin == "weirdnet.gain" && name == "gain_db")
        );
        assert!(e.to_string().starts_with("step 2 (weirdnet.gain): parameter gain_db"), "{e}");
        let e = apply_chain(&r, &w, &[PluginInstance::new("weirdnet.reverb", ParamValues::new())]).unwrap_err();
        assert_eq!(e, ChainError::UnknownPlugin { step: 0, plugin: "weirdnet.reverb".into() });
        // A bypassed bad step is not run, so it is not an error.
        let mut ignored = gain(100.0);
        ignored.bypass = true;
        assert!(apply_chain(&r, &w, &[ignored]).is_ok());
    }

    #[test]
    fn cache_key_is_stable_and_golden() {
        // A regression pin of the key for one chain (generated by this code, not an independent reference). Changing the key encoding invalidates every cache on disk, so it must be a deliberate change.
        let r = Registry::with_builtins();
        let key = chain_cache_key(&r, &[7u8; 32], &[gain(-3.0)]).unwrap();
        let hex: String = key.iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(hex, GOLDEN_KEY, "if this is intended, update GOLDEN_KEY");
    }
    const GOLDEN_KEY: &str = "b0e154e38294b95799a47997d84e655cc2baa0c9258487239c3623ffb12993df";

    #[test]
    fn cache_key_ignores_spelled_out_defaults_and_bypassed_steps() {
        let r = Registry::with_builtins();
        let s = [1u8; 32];
        let plain = chain_cache_key(&r, &s, &[gain(-3.0)]).unwrap();
        let spelled = PluginInstance::new("weirdnet.gain", ParamValues::new().with_float("gain_db", -3.0).with_bool("invert", false));
        assert_eq!(plain, chain_cache_key(&r, &s, &[spelled]).unwrap());
        let mut bypassed = gain(12.0);
        bypassed.bypass = true;
        assert_eq!(plain, chain_cache_key(&r, &s, &[bypassed.clone(), gain(-3.0), bypassed]).unwrap());
        // -0.0 and 0.0 are the same gain.
        assert_eq!(chain_cache_key(&r, &s, &[gain(0.0)]).unwrap(), chain_cache_key(&r, &s, &[gain(-0.0)]).unwrap());
    }

    #[test]
    fn cache_key_changes_with_anything_that_changes_the_result() {
        let r = Registry::with_builtins();
        let s = [1u8; 32];
        let base = chain_cache_key(&r, &s, &[gain(-3.0), gain(-6.0)]).unwrap();
        let mut seen = vec![base];
        let mut check = |k: [u8; 32], what: &str| {
            assert!(!seen.contains(&k), "{what} should change the key");
            seen.push(k);
        };
        check(chain_cache_key(&r, &[2u8; 32], &[gain(-3.0), gain(-6.0)]).unwrap(), "the source");
        check(chain_cache_key(&r, &s, &[gain(-6.0), gain(-3.0)]).unwrap(), "the order");
        check(chain_cache_key(&r, &s, &[gain(-3.0), gain(-6.1)]).unwrap(), "a parameter");
        check(chain_cache_key(&r, &s, &[gain(-3.0)]).unwrap(), "a missing step");
        check(chain_cache_key(&r, &s, &[]).unwrap(), "an empty chain");
        let inv = PluginInstance::new("weirdnet.gain", ParamValues::new().with_float("gain_db", -3.0).with_bool("invert", true));
        check(chain_cache_key(&r, &s, &[inv, gain(-6.0)]).unwrap(), "a bool");
        let lv = PluginInstance::new("weirdnet.levels", ParamValues::new());
        check(chain_cache_key(&r, &s, &[lv]).unwrap(), "another plugin");
    }

    #[test]
    fn cache_key_of_an_invalid_chain_is_an_error() {
        let r = Registry::with_builtins();
        assert!(matches!(chain_cache_key(&r, &[0; 32], &[gain(99.0)]), Err(ChainError::Step { step: 0, .. })));
        assert!(matches!(chain_cache_key(&r, &[0; 32], &[PluginInstance::new("x", ParamValues::new())]), Err(ChainError::UnknownPlugin { .. })));
    }

    #[test]
    fn cache_key_changes_with_a_plugin_version() {
        struct V(u32);
        impl crate::Plugin for V {
            fn id(&self) -> &'static str {
                "test.v"
            }
            fn version(&self) -> u32 {
                self.0
            }
            fn params(&self) -> &[crate::ParamSpec] {
                &[]
            }
            fn process(&self, input: &Waveform, _: &ParamValues) -> Result<Waveform, PluginError> {
                Ok(input.clone())
            }
        }
        let mut r1 = Registry::new();
        r1.register(std::sync::Arc::new(V(1)));
        let mut r2 = Registry::new();
        r2.register(std::sync::Arc::new(V(2)));
        let chain = [PluginInstance::new("test.v", ParamValues::new())];
        assert_ne!(chain_cache_key(&r1, &[0; 32], &chain).unwrap(), chain_cache_key(&r2, &[0; 32], &chain).unwrap());
    }

    #[test]
    fn waveform_hash_covers_content_rate_and_channels() {
        let a = Waveform::new(48_000, 1, vec![0.1, 0.2]).unwrap();
        assert_eq!(waveform_hash(&a), waveform_hash(&a.clone()));
        assert_ne!(waveform_hash(&a), waveform_hash(&Waveform::new(48_000, 1, vec![0.1, 0.3]).unwrap()));
        assert_ne!(waveform_hash(&a), waveform_hash(&Waveform::new(44_100, 1, vec![0.1, 0.2]).unwrap()));
        assert_ne!(waveform_hash(&a), waveform_hash(&Waveform::new(48_000, 2, vec![0.1, 0.2]).unwrap()));
        assert_eq!(waveform_hash(&Waveform::new(1, 1, vec![0.0]).unwrap()), waveform_hash(&Waveform::new(1, 1, vec![-0.0]).unwrap()));
    }
}