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