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.register(Arc::new(builtin::Pitch));
44        r
45    }
46
47    /// Adds a plugin, replacing one with the same id.
48    pub fn register(&mut self, plugin: Arc<dyn Plugin>) {
49        self.plugins.insert(plugin.id(), plugin);
50    }
51
52    pub fn get(&self, id: &str) -> Option<&Arc<dyn Plugin>> {
53        self.plugins.get(id)
54    }
55
56    /// Ids in order.
57    pub fn ids(&self) -> impl Iterator<Item = &'static str> + '_ {
58        self.plugins.keys().copied()
59    }
60
61    pub fn len(&self) -> usize {
62        self.plugins.len()
63    }
64
65    pub fn is_empty(&self) -> bool {
66        self.plugins.is_empty()
67    }
68
69    /// Resolves `values` against the plugin's parameters and runs it.
70    pub fn process(&self, id: &str, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
71        let plugin = self.get(id).ok_or_else(|| PluginError::Internal(format!("no plugin {id:?}")))?;
72        let resolved = values.resolve(plugin.params())?;
73        plugin.process(input, &resolved)
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn builtins_are_registered_with_unique_ids_and_defaults_that_pass_their_own_checks() {
83        let r = Registry::with_builtins();
84        assert_eq!(
85            r.ids().collect::<Vec<_>>(),
86            vec!["weirdnet.duration", "weirdnet.frequencies", "weirdnet.gain", "weirdnet.levels", "weirdnet.pitch"]
87        );
88        for id in r.ids() {
89            let p = r.get(id).unwrap();
90            assert_eq!(p.id(), id);
91            assert!(ParamValues::new().resolve(p.params()).is_ok());
92        }
93    }
94
95    #[test]
96    fn unknown_plugin_is_an_error_not_a_panic() {
97        let w = Waveform::silence(48_000, 1, 10).unwrap();
98        assert!(matches!(Registry::with_builtins().process("nope", &w, &ParamValues::new()), Err(PluginError::Internal(_))));
99    }
100
101    #[test]
102    fn registering_the_same_id_replaces() {
103        let mut r = Registry::with_builtins();
104        let n = r.len();
105        r.register(Arc::new(builtin::Gain));
106        assert_eq!(r.len(), n);
107    }
108}