Skip to main content

weirdnet_audio_plugin/
chain.rs

1use crate::{ParamValue, ParamValues, PluginError, Registry};
2use weirdnet_media::waveform::Waveform;
3
4/// One use of a plugin in a chain.
5#[derive(Debug, Clone, PartialEq)]
6pub struct PluginInstance {
7    /// The plugin id, for example `"weirdnet.gain"`.
8    pub plugin: String,
9    pub values: ParamValues,
10    /// A bypassed instance is skipped.
11    pub bypass: bool,
12}
13
14impl PluginInstance {
15    pub fn new(plugin: &str, values: ParamValues) -> Self {
16        PluginInstance { plugin: plugin.to_string(), values, bypass: false }
17    }
18}
19
20/// Why a chain failed, and where.
21#[derive(Debug, Clone, PartialEq)]
22pub enum ChainError {
23    /// A step names a plugin that is not registered.
24    UnknownPlugin { step: usize, plugin: String },
25    /// A step's plugin returned an error (including invalid parameters).
26    Step { step: usize, plugin: String, error: PluginError },
27}
28
29impl ChainError {
30    /// The zero-based index of the failing step.
31    pub fn step(&self) -> usize {
32        match self {
33            ChainError::UnknownPlugin { step, .. } | ChainError::Step { step, .. } => *step,
34        }
35    }
36}
37
38impl std::fmt::Display for ChainError {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            ChainError::UnknownPlugin { step, plugin } => write!(f, "step {} ({plugin}): no such plugin", step + 1),
42            ChainError::Step { step, plugin, error } => write!(f, "step {} ({plugin}): {error}", step + 1),
43        }
44    }
45}
46
47impl std::error::Error for ChainError {}
48
49/// Runs `chain` over `input`, in order, skipping bypassed instances. An empty chain returns a clone of the input.
50pub fn apply_chain(registry: &Registry, input: &Waveform, chain: &[PluginInstance]) -> Result<Waveform, ChainError> {
51    let mut current = input.clone();
52    for (step, instance) in chain.iter().enumerate() {
53        if instance.bypass {
54            continue;
55        }
56        if registry.get(&instance.plugin).is_none() {
57            return Err(ChainError::UnknownPlugin { step, plugin: instance.plugin.clone() });
58        }
59        current = registry.process(&instance.plugin, &current, &instance.values).map_err(|error| ChainError::Step {
60            step,
61            plugin: instance.plugin.clone(),
62            error,
63        })?;
64    }
65    Ok(current)
66}
67
68/// 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`]
69/// for audio that has no content hash of its own.
70pub fn waveform_hash(w: &Waveform) -> [u8; 32] {
71    let mut h = blake3::Hasher::new_derive_key("weirdnet-audio-plugin 2026 waveform hash");
72    h.update(&w.sample_rate().to_le_bytes());
73    h.update(&w.channels().to_le_bytes());
74    for s in w.samples() {
75        h.update(&canonical_bits(*s).to_le_bytes());
76    }
77    *h.finalize().as_bytes()
78}
79
80fn canonical_bits(x: f32) -> u32 {
81    if x == 0.0 { 0 } else { x.to_bits() }
82}
83
84fn put_str(h: &mut blake3::Hasher, s: &str) {
85    h.update(&(s.len() as u64).to_le_bytes());
86    h.update(s.as_bytes());
87}
88
89/// The key a cache uses for "`source` through `chain`".
90///
91/// 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
92/// parameter values after defaults are filled in. So an explicit default and an omitted one give the same key, bypassed steps and their values
93/// 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
94/// 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
95/// chain that cannot run has no result to cache.
96pub fn chain_cache_key(registry: &Registry, source: &[u8; 32], chain: &[PluginInstance]) -> Result<[u8; 32], ChainError> {
97    let mut h = blake3::Hasher::new_derive_key("weirdnet-audio-plugin 2026 chain cache key");
98    h.update(source);
99    for (step, instance) in chain.iter().enumerate() {
100        if instance.bypass {
101            continue;
102        }
103        let plugin = registry.get(&instance.plugin).ok_or_else(|| ChainError::UnknownPlugin { step, plugin: instance.plugin.clone() })?;
104        let resolved = instance.values.resolve(plugin.params()).map_err(|error| ChainError::Step { step, plugin: instance.plugin.clone(), error })?;
105        h.update(&[1]); // a step follows
106        put_str(&mut h, plugin.id());
107        h.update(&plugin.version().to_le_bytes());
108        h.update(&(resolved.len() as u64).to_le_bytes());
109        for (name, value) in resolved.iter() {
110            put_str(&mut h, name);
111            match value {
112                ParamValue::Float(x) => {
113                    h.update(&[0]);
114                    h.update(&(if *x == 0.0 { 0.0f64 } else { *x }).to_bits().to_le_bytes());
115                }
116                ParamValue::Bool(b) => {
117                    h.update(&[1, u8::from(*b)]);
118                }
119                ParamValue::Choice(c) => {
120                    h.update(&[2]);
121                    put_str(&mut h, c);
122                }
123            }
124        }
125    }
126    h.update(&[0]); // end
127    Ok(*h.finalize().as_bytes())
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn gain(db: f64) -> PluginInstance {
135        PluginInstance::new("weirdnet.gain", ParamValues::new().with_float("gain_db", db))
136    }
137
138    fn src() -> Waveform {
139        Waveform::tone(48_000, 440.0, 4800, 0.5).unwrap()
140    }
141
142    #[test]
143    fn an_empty_chain_is_the_input() {
144        let w = src();
145        assert_eq!(apply_chain(&Registry::with_builtins(), &w, &[]).unwrap(), w);
146    }
147
148    #[test]
149    fn steps_run_in_order_and_bypass_skips() {
150        let r = Registry::with_builtins();
151        let w = src();
152        let out = apply_chain(&r, &w, &[gain(-6.0), gain(-6.0)]).unwrap();
153        let direct = w.gain_db(-12.0).unwrap();
154        assert!((out.peak() - direct.peak()).abs() < 1e-6);
155        let mut skipped = gain(-60.0);
156        skipped.bypass = true;
157        assert_eq!(apply_chain(&r, &w, &[skipped]).unwrap(), w);
158        // Order matters when steps do not commute: a ceiling then gain, against gain then a ceiling.
159        let ceil = PluginInstance::new("weirdnet.levels", ParamValues::new().with_float("ceiling_db", -6.0));
160        let a = apply_chain(&r, &w, &[ceil.clone(), gain(12.0)]).unwrap();
161        let b = apply_chain(&r, &w, &[gain(12.0), ceil]).unwrap();
162        assert!(a.peak() > b.peak() * 3.0, "{} vs {}", a.peak(), b.peak());
163    }
164
165    #[test]
166    fn errors_name_the_failing_step() {
167        let r = Registry::with_builtins();
168        let w = src();
169        let bad = gain(100.0);
170        let e = apply_chain(&r, &w, &[gain(-1.0), bad]).unwrap_err();
171        assert_eq!(e.step(), 1);
172        assert!(
173            matches!(&e, ChainError::Step { plugin, error: PluginError::InvalidParam { name, .. }, .. } if plugin == "weirdnet.gain" && name == "gain_db")
174        );
175        assert!(e.to_string().starts_with("step 2 (weirdnet.gain): parameter gain_db"), "{e}");
176        let e = apply_chain(&r, &w, &[PluginInstance::new("weirdnet.reverb", ParamValues::new())]).unwrap_err();
177        assert_eq!(e, ChainError::UnknownPlugin { step: 0, plugin: "weirdnet.reverb".into() });
178        // A bypassed bad step is not run, so it is not an error.
179        let mut ignored = gain(100.0);
180        ignored.bypass = true;
181        assert!(apply_chain(&r, &w, &[ignored]).is_ok());
182    }
183
184    #[test]
185    fn cache_key_is_stable_and_golden() {
186        // 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.
187        let r = Registry::with_builtins();
188        let key = chain_cache_key(&r, &[7u8; 32], &[gain(-3.0)]).unwrap();
189        let hex: String = key.iter().map(|b| format!("{b:02x}")).collect();
190        assert_eq!(hex, GOLDEN_KEY, "if this is intended, update GOLDEN_KEY");
191    }
192    const GOLDEN_KEY: &str = "b0e154e38294b95799a47997d84e655cc2baa0c9258487239c3623ffb12993df";
193
194    #[test]
195    fn cache_key_ignores_spelled_out_defaults_and_bypassed_steps() {
196        let r = Registry::with_builtins();
197        let s = [1u8; 32];
198        let plain = chain_cache_key(&r, &s, &[gain(-3.0)]).unwrap();
199        let spelled = PluginInstance::new("weirdnet.gain", ParamValues::new().with_float("gain_db", -3.0).with_bool("invert", false));
200        assert_eq!(plain, chain_cache_key(&r, &s, &[spelled]).unwrap());
201        let mut bypassed = gain(12.0);
202        bypassed.bypass = true;
203        assert_eq!(plain, chain_cache_key(&r, &s, &[bypassed.clone(), gain(-3.0), bypassed]).unwrap());
204        // -0.0 and 0.0 are the same gain.
205        assert_eq!(chain_cache_key(&r, &s, &[gain(0.0)]).unwrap(), chain_cache_key(&r, &s, &[gain(-0.0)]).unwrap());
206    }
207
208    #[test]
209    fn cache_key_changes_with_anything_that_changes_the_result() {
210        let r = Registry::with_builtins();
211        let s = [1u8; 32];
212        let base = chain_cache_key(&r, &s, &[gain(-3.0), gain(-6.0)]).unwrap();
213        let mut seen = vec![base];
214        let mut check = |k: [u8; 32], what: &str| {
215            assert!(!seen.contains(&k), "{what} should change the key");
216            seen.push(k);
217        };
218        check(chain_cache_key(&r, &[2u8; 32], &[gain(-3.0), gain(-6.0)]).unwrap(), "the source");
219        check(chain_cache_key(&r, &s, &[gain(-6.0), gain(-3.0)]).unwrap(), "the order");
220        check(chain_cache_key(&r, &s, &[gain(-3.0), gain(-6.1)]).unwrap(), "a parameter");
221        check(chain_cache_key(&r, &s, &[gain(-3.0)]).unwrap(), "a missing step");
222        check(chain_cache_key(&r, &s, &[]).unwrap(), "an empty chain");
223        let inv = PluginInstance::new("weirdnet.gain", ParamValues::new().with_float("gain_db", -3.0).with_bool("invert", true));
224        check(chain_cache_key(&r, &s, &[inv, gain(-6.0)]).unwrap(), "a bool");
225        let lv = PluginInstance::new("weirdnet.levels", ParamValues::new());
226        check(chain_cache_key(&r, &s, &[lv]).unwrap(), "another plugin");
227    }
228
229    #[test]
230    fn cache_key_of_an_invalid_chain_is_an_error() {
231        let r = Registry::with_builtins();
232        assert!(matches!(chain_cache_key(&r, &[0; 32], &[gain(99.0)]), Err(ChainError::Step { step: 0, .. })));
233        assert!(matches!(chain_cache_key(&r, &[0; 32], &[PluginInstance::new("x", ParamValues::new())]), Err(ChainError::UnknownPlugin { .. })));
234    }
235
236    #[test]
237    fn cache_key_changes_with_a_plugin_version() {
238        struct V(u32);
239        impl crate::Plugin for V {
240            fn id(&self) -> &'static str {
241                "test.v"
242            }
243            fn version(&self) -> u32 {
244                self.0
245            }
246            fn params(&self) -> &[crate::ParamSpec] {
247                &[]
248            }
249            fn process(&self, input: &Waveform, _: &ParamValues) -> Result<Waveform, PluginError> {
250                Ok(input.clone())
251            }
252        }
253        let mut r1 = Registry::new();
254        r1.register(std::sync::Arc::new(V(1)));
255        let mut r2 = Registry::new();
256        r2.register(std::sync::Arc::new(V(2)));
257        let chain = [PluginInstance::new("test.v", ParamValues::new())];
258        assert_ne!(chain_cache_key(&r1, &[0; 32], &chain).unwrap(), chain_cache_key(&r2, &[0; 32], &chain).unwrap());
259    }
260
261    #[test]
262    fn waveform_hash_covers_content_rate_and_channels() {
263        let a = Waveform::new(48_000, 1, vec![0.1, 0.2]).unwrap();
264        assert_eq!(waveform_hash(&a), waveform_hash(&a.clone()));
265        assert_ne!(waveform_hash(&a), waveform_hash(&Waveform::new(48_000, 1, vec![0.1, 0.3]).unwrap()));
266        assert_ne!(waveform_hash(&a), waveform_hash(&Waveform::new(44_100, 1, vec![0.1, 0.2]).unwrap()));
267        assert_ne!(waveform_hash(&a), waveform_hash(&Waveform::new(48_000, 2, vec![0.1, 0.2]).unwrap()));
268        assert_eq!(waveform_hash(&Waveform::new(1, 1, vec![0.0]).unwrap()), waveform_hash(&Waveform::new(1, 1, vec![-0.0]).unwrap()));
269    }
270}