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::builtin;
use crate::{ParamSpec, ParamValues, PluginError};
use std::collections::BTreeMap;
use std::sync::Arc;
use weirdnet_media::waveform::Waveform;

/// An audio effect. Implementations are pure: the same input and values give the same output, which is what lets results be cached.
pub trait Plugin: Send + Sync {
    /// The stable id, for example `"weirdnet.gain"`. Saved in projects, so it never changes.
    fn id(&self) -> &'static str;

    /// A version that changes whenever the output for the same input and values would change. It is part of the cache key.
    fn version(&self) -> u32 {
        1
    }

    /// The parameters this plugin takes.
    fn params(&self) -> &[ParamSpec];

    /// Processes `input`. `values` are already resolved against [`Plugin::params`]: complete, typed and in range.
    /// Returns a new waveform (which may share the input's samples when nothing changed) or an error.
    fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError>;
}

/// Plugins by id.
#[derive(Clone, Default)]
pub struct Registry {
    plugins: BTreeMap<&'static str, Arc<dyn Plugin>>,
}

impl Registry {
    pub fn new() -> Self {
        Registry::default()
    }

    /// A registry with every built-in.
    pub fn with_builtins() -> Self {
        let mut r = Registry::new();
        r.register(Arc::new(builtin::Gain));
        r.register(Arc::new(builtin::Levels));
        r.register(Arc::new(builtin::Frequencies));
        r.register(Arc::new(builtin::Duration));
        r
    }

    /// Adds a plugin, replacing one with the same id.
    pub fn register(&mut self, plugin: Arc<dyn Plugin>) {
        self.plugins.insert(plugin.id(), plugin);
    }

    pub fn get(&self, id: &str) -> Option<&Arc<dyn Plugin>> {
        self.plugins.get(id)
    }

    /// Ids in order.
    pub fn ids(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.plugins.keys().copied()
    }

    pub fn len(&self) -> usize {
        self.plugins.len()
    }

    pub fn is_empty(&self) -> bool {
        self.plugins.is_empty()
    }

    /// Resolves `values` against the plugin's parameters and runs it.
    pub fn process(&self, id: &str, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
        let plugin = self.get(id).ok_or_else(|| PluginError::Internal(format!("no plugin {id:?}")))?;
        let resolved = values.resolve(plugin.params())?;
        plugin.process(input, &resolved)
    }
}

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

    #[test]
    fn builtins_are_registered_with_unique_ids_and_defaults_that_pass_their_own_checks() {
        let r = Registry::with_builtins();
        assert_eq!(r.ids().collect::<Vec<_>>(), vec!["weirdnet.duration", "weirdnet.frequencies", "weirdnet.gain", "weirdnet.levels"]);
        for id in r.ids() {
            let p = r.get(id).unwrap();
            assert_eq!(p.id(), id);
            assert!(ParamValues::new().resolve(p.params()).is_ok());
        }
    }

    #[test]
    fn unknown_plugin_is_an_error_not_a_panic() {
        let w = Waveform::silence(48_000, 1, 10).unwrap();
        assert!(matches!(Registry::with_builtins().process("nope", &w, &ParamValues::new()), Err(PluginError::Internal(_))));
    }

    #[test]
    fn registering_the_same_id_replaces() {
        let mut r = Registry::with_builtins();
        let n = r.len();
        r.register(Arc::new(builtin::Gain));
        assert_eq!(r.len(), n);
    }
}