Skip to main content

weirdnet_audio_plugin/
plugin.rs

1use crate::builtin;
2use crate::{ParamSpec, ParamValues, PluginError};
3use std::collections::BTreeMap;
4use std::sync::Arc;
5use weirdnet_media::waveform::Waveform;
6
7/// An audio effect. Implementations are pure: the same input and values give the same output, which is what lets results be cached.
8pub trait Plugin: Send + Sync {
9    /// The stable id, for example `"weirdnet.gain"`. Saved in projects, so it never changes.
10    fn id(&self) -> &'static str;
11
12    /// A version that changes whenever the output for the same input and values would change. It is part of the cache key.
13    fn version(&self) -> u32 {
14        1
15    }
16
17    /// The parameters this plugin takes.
18    fn params(&self) -> &[ParamSpec];
19
20    /// Processes `input`. `values` are already resolved against [`Plugin::params`]: complete, typed and in range.
21    /// Returns a new waveform (which may share the input's samples when nothing changed) or an error.
22    fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError>;
23}
24
25/// Plugins by id.
26#[derive(Clone, Default)]
27pub struct Registry {
28    plugins: BTreeMap<&'static str, Arc<dyn Plugin>>,
29}
30
31impl Registry {
32    pub fn new() -> Self {
33        Registry::default()
34    }
35
36    /// A registry with every built-in.
37    pub fn with_builtins() -> Self {
38        let mut r = Registry::new();
39        r.register(Arc::new(builtin::Gain));
40        r.register(Arc::new(builtin::Levels));
41        r.register(Arc::new(builtin::Frequencies));
42        r.register(Arc::new(builtin::Duration));
43        r
44    }
45
46    /// Adds a plugin, replacing one with the same id.
47    pub fn register(&mut self, plugin: Arc<dyn Plugin>) {
48        self.plugins.insert(plugin.id(), plugin);
49    }
50
51    pub fn get(&self, id: &str) -> Option<&Arc<dyn Plugin>> {
52        self.plugins.get(id)
53    }
54
55    /// Ids in order.
56    pub fn ids(&self) -> impl Iterator<Item = &'static str> + '_ {
57        self.plugins.keys().copied()
58    }
59
60    pub fn len(&self) -> usize {
61        self.plugins.len()
62    }
63
64    pub fn is_empty(&self) -> bool {
65        self.plugins.is_empty()
66    }
67
68    /// Resolves `values` against the plugin's parameters and runs it.
69    pub fn process(&self, id: &str, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
70        let plugin = self.get(id).ok_or_else(|| PluginError::Internal(format!("no plugin {id:?}")))?;
71        let resolved = values.resolve(plugin.params())?;
72        plugin.process(input, &resolved)
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn builtins_are_registered_with_unique_ids_and_defaults_that_pass_their_own_checks() {
82        let r = Registry::with_builtins();
83        assert_eq!(r.ids().collect::<Vec<_>>(), vec!["weirdnet.duration", "weirdnet.frequencies", "weirdnet.gain", "weirdnet.levels"]);
84        for id in r.ids() {
85            let p = r.get(id).unwrap();
86            assert_eq!(p.id(), id);
87            assert!(ParamValues::new().resolve(p.params()).is_ok());
88        }
89    }
90
91    #[test]
92    fn unknown_plugin_is_an_error_not_a_panic() {
93        let w = Waveform::silence(48_000, 1, 10).unwrap();
94        assert!(matches!(Registry::with_builtins().process("nope", &w, &ParamValues::new()), Err(PluginError::Internal(_))));
95    }
96
97    #[test]
98    fn registering_the_same_id_replaces() {
99        let mut r = Registry::with_builtins();
100        let n = r.len();
101        r.register(Arc::new(builtin::Gain));
102        assert_eq!(r.len(), n);
103    }
104}