Skip to main content

wavecraft_dsp/combinators/
chain.rs

1//! Chain combinator for serial processor composition.
2
3use crate::traits::{ParamSpec, Processor, ProcessorParams, Transport};
4
5/// Combines two processors in series: A → B.
6///
7/// Audio flows through processor A, then through processor B.
8/// Parameters from both processors are merged.
9pub struct Chain<A, B> {
10    pub first: A,
11    pub second: B,
12}
13
14impl<A, B> Default for Chain<A, B>
15where
16    A: Default,
17    B: Default,
18{
19    fn default() -> Self {
20        Self {
21            first: A::default(),
22            second: B::default(),
23        }
24    }
25}
26
27/// Combined parameters for chained processors.
28///
29/// Merges parameter specs from both processors.
30pub struct ChainParams<PA, PB> {
31    pub first: PA,
32    pub second: PB,
33}
34
35impl<PA, PB> Default for ChainParams<PA, PB>
36where
37    PA: Default,
38    PB: Default,
39{
40    fn default() -> Self {
41        Self {
42            first: PA::default(),
43            second: PB::default(),
44        }
45    }
46}
47
48impl<PA, PB> ProcessorParams for ChainParams<PA, PB>
49where
50    PA: ProcessorParams,
51    PB: ProcessorParams,
52{
53    fn param_specs() -> &'static [ParamSpec] {
54        fn extend_specs(target: &mut Vec<ParamSpec>, source: &[ParamSpec]) {
55            for spec in source {
56                target.push(ParamSpec {
57                    name: spec.name,
58                    id_suffix: spec.id_suffix,
59                    range: spec.range.clone(),
60                    default: spec.default,
61                    unit: spec.unit,
62                    group: spec.group,
63                });
64            }
65        }
66
67        // WORKAROUND FOR HOT-RELOAD HANG:
68        //
69        // Do NOT use OnceLock or any locking primitive here. On macOS, when the
70        // subprocess calls dlopen() → wavecraft_get_params_json() → param_specs(),
71        // initialization of OnceLock statics can hang indefinitely (30s timeout).
72        //
73        // Instead, we allocate and leak the merged specs on EVERY call. This is
74        // acceptable because:
75        // 1. param_specs() is called at most once per plugin load (startup only)
76        // 2. The leak is ~hundreds of bytes (not per-sample, not per-frame)
77        // 3. Plugin lifetime = process lifetime (no meaningful leak)
78        // 4. Hot-reload works correctly (no 30s hang)
79        //
80        // This is a pragmatic trade-off: small memory leak vs. broken hot-reload.
81        // Future work: investigate root cause of OnceLock hang on macOS dlopen.
82
83        let first_specs = PA::param_specs();
84        let second_specs = PB::param_specs();
85
86        let mut merged = Vec::with_capacity(first_specs.len() + second_specs.len());
87
88        extend_specs(&mut merged, first_specs);
89        extend_specs(&mut merged, second_specs);
90
91        // Leak to get 'static reference (intentional - see comment above)
92        Box::leak(merged.into_boxed_slice())
93    }
94
95    fn from_param_defaults() -> Self {
96        Self {
97            first: PA::from_param_defaults(),
98            second: PB::from_param_defaults(),
99        }
100    }
101
102    fn apply_plain_values(&mut self, values: &[f32]) {
103        let first_count = PA::param_specs().len();
104        let split_at = first_count.min(values.len());
105        let (first_values, second_values) = values.split_at(split_at);
106
107        self.first.apply_plain_values(first_values);
108        self.second.apply_plain_values(second_values);
109    }
110}
111
112impl<A, B> Processor for Chain<A, B>
113where
114    A: Processor,
115    B: Processor,
116{
117    type Params = ChainParams<A::Params, B::Params>;
118
119    fn process(&mut self, buffer: &mut [&mut [f32]], transport: &Transport, params: &Self::Params) {
120        // Process first, then second (serial chain)
121        self.first.process(buffer, transport, &params.first);
122        self.second.process(buffer, transport, &params.second);
123    }
124
125    fn set_sample_rate(&mut self, sample_rate: f32) {
126        self.first.set_sample_rate(sample_rate);
127        self.second.set_sample_rate(sample_rate);
128    }
129
130    fn reset(&mut self) {
131        self.first.reset();
132        self.second.reset();
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use crate::builtins::{GainDsp, GainParams, PassthroughDsp, PassthroughParams};
140    use std::sync::{
141        Arc,
142        atomic::{AtomicBool, AtomicU32, Ordering},
143    };
144
145    #[derive(Clone)]
146    struct TestParams;
147
148    impl Default for TestParams {
149        fn default() -> Self {
150            Self
151        }
152    }
153
154    impl ProcessorParams for TestParams {
155        fn param_specs() -> &'static [ParamSpec] {
156            &[]
157        }
158    }
159
160    struct LifecycleProbe {
161        set_sample_rate_calls: Arc<AtomicU32>,
162        reset_calls: Arc<AtomicU32>,
163        last_sample_rate_bits: Arc<AtomicU32>,
164        touched_process: Arc<AtomicBool>,
165    }
166
167    impl LifecycleProbe {
168        fn new() -> Self {
169            Self {
170                set_sample_rate_calls: Arc::new(AtomicU32::new(0)),
171                reset_calls: Arc::new(AtomicU32::new(0)),
172                last_sample_rate_bits: Arc::new(AtomicU32::new(0)),
173                touched_process: Arc::new(AtomicBool::new(false)),
174            }
175        }
176    }
177
178    impl Processor for LifecycleProbe {
179        type Params = TestParams;
180
181        fn process(
182            &mut self,
183            _buffer: &mut [&mut [f32]],
184            _transport: &Transport,
185            _params: &Self::Params,
186        ) {
187            self.touched_process.store(true, Ordering::SeqCst);
188        }
189
190        fn set_sample_rate(&mut self, sample_rate: f32) {
191            self.set_sample_rate_calls.fetch_add(1, Ordering::SeqCst);
192            self.last_sample_rate_bits
193                .store(sample_rate.to_bits(), Ordering::SeqCst);
194        }
195
196        fn reset(&mut self) {
197            self.reset_calls.fetch_add(1, Ordering::SeqCst);
198        }
199    }
200
201    #[test]
202    fn test_chain_processes_in_order() {
203        let mut chain = Chain {
204            first: GainDsp::default(),
205            second: GainDsp::default(),
206        };
207
208        let mut left = [1.0_f32, 1.0_f32];
209        let mut right = [1.0_f32, 1.0_f32];
210        let mut buffer = [&mut left[..], &mut right[..]];
211
212        let transport = Transport::default();
213        let params = ChainParams {
214            first: GainParams { level: 0.5 },
215            second: GainParams { level: 2.0 },
216        };
217
218        chain.process(&mut buffer, &transport, &params);
219
220        // Expected: 1.0 * 0.5 * 2.0 = 1.0
221        assert!((buffer[0][0] - 1.0_f32).abs() < 1e-6);
222        assert!((buffer[1][0] - 1.0_f32).abs() < 1e-6);
223    }
224
225    #[test]
226    fn test_chain_with_passthrough() {
227        let mut chain = Chain {
228            first: PassthroughDsp,
229            second: GainDsp::default(),
230        };
231
232        let mut left = [2.0_f32, 2.0_f32];
233        let mut right = [2.0_f32, 2.0_f32];
234        let mut buffer = [&mut left[..], &mut right[..]];
235
236        let transport = Transport::default();
237        let params = ChainParams {
238            first: PassthroughParams,
239            second: GainParams { level: 0.5 },
240        };
241
242        chain.process(&mut buffer, &transport, &params);
243
244        // Expected: 2.0 * 1.0 * 0.5 = 1.0
245        assert!((buffer[0][0] - 1.0_f32).abs() < 1e-6);
246    }
247
248    #[test]
249    fn test_chain_params_merge() {
250        let specs = <ChainParams<GainParams, GainParams>>::param_specs();
251        assert_eq!(specs.len(), 2); // Both gain params
252
253        // Both should have "Level" name
254        assert_eq!(specs[0].name, "Level");
255        assert_eq!(specs[1].name, "Level");
256    }
257
258    #[test]
259    fn test_chain_default() {
260        let _chain: Chain<GainDsp, PassthroughDsp> = Chain::default();
261        let _params: ChainParams<GainParams, PassthroughParams> = ChainParams::default();
262    }
263
264    #[test]
265    fn test_chain_from_param_defaults_uses_children_spec_defaults() {
266        let defaults = <ChainParams<GainParams, GainParams>>::from_param_defaults();
267        assert!((defaults.first.level - 1.0).abs() < 1e-6);
268        assert!((defaults.second.level - 1.0).abs() < 1e-6);
269    }
270
271    #[test]
272    fn test_chain_apply_plain_values_splits_by_child_param_count() {
273        let mut params = <ChainParams<GainParams, GainParams>>::from_param_defaults();
274        params.apply_plain_values(&[0.25, 1.75]);
275
276        assert!((params.first.level - 0.25).abs() < 1e-6);
277        assert!((params.second.level - 1.75).abs() < 1e-6);
278    }
279
280    #[test]
281    fn test_chain_propagates_set_sample_rate_to_both_processors() {
282        let first = LifecycleProbe::new();
283        let second = LifecycleProbe::new();
284
285        let first_calls = Arc::clone(&first.set_sample_rate_calls);
286        let second_calls = Arc::clone(&second.set_sample_rate_calls);
287        let first_sr = Arc::clone(&first.last_sample_rate_bits);
288        let second_sr = Arc::clone(&second.last_sample_rate_bits);
289
290        let mut chain = Chain { first, second };
291        chain.set_sample_rate(48_000.0);
292
293        assert_eq!(first_calls.load(Ordering::SeqCst), 1);
294        assert_eq!(second_calls.load(Ordering::SeqCst), 1);
295        assert_eq!(f32::from_bits(first_sr.load(Ordering::SeqCst)), 48_000.0);
296        assert_eq!(f32::from_bits(second_sr.load(Ordering::SeqCst)), 48_000.0);
297    }
298
299    #[test]
300    fn test_chain_propagates_reset_to_both_processors() {
301        let first = LifecycleProbe::new();
302        let second = LifecycleProbe::new();
303
304        let first_resets = Arc::clone(&first.reset_calls);
305        let second_resets = Arc::clone(&second.reset_calls);
306
307        let mut chain = Chain { first, second };
308        chain.reset();
309
310        assert_eq!(first_resets.load(Ordering::SeqCst), 1);
311        assert_eq!(second_resets.load(Ordering::SeqCst), 1);
312    }
313}