weirdnet-audio-plugin 0.1.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::PluginError;
use std::collections::BTreeMap;

/// The type of a parameter.
#[derive(Debug, Clone, PartialEq)]
pub enum ParamKind {
    /// A number between [`ParamSpec::min`] and [`ParamSpec::max`].
    Float,
    /// On or off.
    Bool,
    /// One of a fixed list of names.
    Choice(&'static [&'static str]),
}

/// One parameter's value.
#[derive(Debug, Clone, PartialEq)]
pub enum ParamValue {
    Float(f64),
    Bool(bool),
    Choice(String),
}

/// A parameter a plugin takes.
#[derive(Debug, Clone, PartialEq)]
pub struct ParamSpec {
    pub name: &'static str,
    pub kind: ParamKind,
    /// The lowest allowed value (floats only).
    pub min: f64,
    /// The highest allowed value (floats only).
    pub max: f64,
    pub default: ParamValue,
    /// `"dB"`, `"Hz"`, `""` and so on, for display.
    pub unit: &'static str,
}

impl ParamSpec {
    pub const fn float(name: &'static str, min: f64, max: f64, default: f64, unit: &'static str) -> Self {
        ParamSpec { name, kind: ParamKind::Float, min, max, default: ParamValue::Float(default), unit }
    }

    pub const fn boolean(name: &'static str, default: bool) -> Self {
        ParamSpec { name, kind: ParamKind::Bool, min: 0.0, max: 1.0, default: ParamValue::Bool(default), unit: "" }
    }

    pub fn choice(name: &'static str, options: &'static [&'static str], default: &str) -> Self {
        assert!(options.contains(&default), "the default {default:?} of {name} is not one of its options");
        ParamSpec { name, kind: ParamKind::Choice(options), min: 0.0, max: 0.0, default: ParamValue::Choice(default.to_string()), unit: "" }
    }

    fn check(&self, value: &ParamValue) -> Result<(), PluginError> {
        match (&self.kind, value) {
            (ParamKind::Float, ParamValue::Float(x)) => {
                if !x.is_finite() {
                    Err(PluginError::invalid(self.name, "not a finite number"))
                } else if *x < self.min || *x > self.max {
                    Err(PluginError::invalid(self.name, format!("{x} is outside {} to {} {}", self.min, self.max, self.unit).trim_end().to_string()))
                } else {
                    Ok(())
                }
            }
            (ParamKind::Bool, ParamValue::Bool(_)) => Ok(()),
            (ParamKind::Choice(options), ParamValue::Choice(c)) => {
                if options.contains(&c.as_str()) {
                    Ok(())
                } else {
                    Err(PluginError::invalid(self.name, format!("{c:?} is not one of {}", options.join(", "))))
                }
            }
            _ => Err(PluginError::invalid(self.name, "the value has the wrong type")),
        }
    }
}

/// Values for one use of a plugin, by parameter name. Missing names mean the default.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ParamValues {
    values: BTreeMap<String, ParamValue>,
}

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

    pub fn set(&mut self, name: &str, value: ParamValue) {
        self.values.insert(name.to_string(), value);
    }

    pub fn with_float(mut self, name: &str, x: f64) -> Self {
        self.set(name, ParamValue::Float(x));
        self
    }

    pub fn with_bool(mut self, name: &str, b: bool) -> Self {
        self.set(name, ParamValue::Bool(b));
        self
    }

    pub fn with_choice(mut self, name: &str, c: &str) -> Self {
        self.set(name, ParamValue::Choice(c.to_string()));
        self
    }

    pub fn get(&self, name: &str) -> Option<&ParamValue> {
        self.values.get(name)
    }

    /// Entries in name order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &ParamValue)> {
        self.values.iter().map(|(k, v)| (k.as_str(), v))
    }

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

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

    /// Checks every value against `specs` (unknown names, wrong types and out-of-range values are errors) and fills in the defaults.
    /// The result has exactly one value per spec, so two uses that mean the same thing resolve to equal values.
    pub fn resolve(&self, specs: &[ParamSpec]) -> Result<ParamValues, PluginError> {
        for name in self.values.keys() {
            if !specs.iter().any(|s| s.name == name) {
                return Err(PluginError::invalid(name, "no such parameter"));
            }
        }
        let mut out = ParamValues::new();
        for spec in specs {
            let value = match self.values.get(spec.name) {
                Some(v) => {
                    spec.check(v)?;
                    v.clone()
                }
                None => spec.default.clone(),
            };
            out.values.insert(spec.name.to_string(), value);
        }
        Ok(out)
    }

    /// A resolved float. Panics if the name is not a resolved float, which only a plugin with a mismatched spec can cause.
    pub fn float(&self, name: &str) -> f64 {
        match self.values.get(name) {
            Some(ParamValue::Float(x)) => *x,
            other => panic!("parameter {name} is not a resolved float: {other:?}"),
        }
    }

    /// A resolved bool. Panics under the same condition as [`ParamValues::float`].
    pub fn bool(&self, name: &str) -> bool {
        match self.values.get(name) {
            Some(ParamValue::Bool(b)) => *b,
            other => panic!("parameter {name} is not a resolved bool: {other:?}"),
        }
    }

    /// A resolved choice. Panics under the same condition as [`ParamValues::float`].
    pub fn choice(&self, name: &str) -> &str {
        match self.values.get(name) {
            Some(ParamValue::Choice(c)) => c,
            other => panic!("parameter {name} is not a resolved choice: {other:?}"),
        }
    }
}

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

    fn specs() -> Vec<ParamSpec> {
        vec![
            ParamSpec::float("gain_db", -60.0, 24.0, 0.0, "dB"),
            ParamSpec::boolean("invert", false),
            ParamSpec::choice("type", &["low", "high"], "low"),
        ]
    }

    #[test]
    fn defaults_fill_in_and_equal_meanings_resolve_equal() {
        let empty = ParamValues::new().resolve(&specs()).unwrap();
        let explicit = ParamValues::new().with_float("gain_db", 0.0).with_bool("invert", false).with_choice("type", "low").resolve(&specs()).unwrap();
        assert_eq!(empty, explicit);
        assert_eq!(empty.len(), 3);
        assert_eq!(empty.float("gain_db"), 0.0);
        assert!(!empty.bool("invert"));
        assert_eq!(empty.choice("type"), "low");
    }

    #[test]
    fn rejects_unknown_wrong_type_and_out_of_range() {
        let s = specs();
        let err = |v: ParamValues| match v.resolve(&s) {
            Err(PluginError::InvalidParam { name, .. }) => name,
            other => panic!("expected InvalidParam, got {other:?}"),
        };
        assert_eq!(err(ParamValues::new().with_float("volume", 1.0)), "volume");
        assert_eq!(err(ParamValues::new().with_float("gain_db", 24.1)), "gain_db");
        assert_eq!(err(ParamValues::new().with_float("gain_db", -60.1)), "gain_db");
        assert_eq!(err(ParamValues::new().with_float("gain_db", f64::NAN)), "gain_db");
        assert_eq!(err(ParamValues::new().with_float("gain_db", f64::INFINITY)), "gain_db");
        assert_eq!(err(ParamValues::new().with_bool("gain_db", true)), "gain_db");
        assert_eq!(err(ParamValues::new().with_choice("type", "band")), "type");
        assert_eq!(err(ParamValues::new().with_float("invert", 1.0)), "invert");
        assert!(ParamValues::new().with_float("gain_db", 24.0).resolve(&s).is_ok(), "the limits are inclusive");
        assert!(ParamValues::new().with_float("gain_db", -60.0).resolve(&s).is_ok());
    }

    #[test]
    #[should_panic(expected = "not one of its options")]
    fn a_choice_default_must_be_an_option() {
        let _ = ParamSpec::choice("type", &["low"], "high");
    }
}