quiver-dsp 0.1.0

A modular audio synthesis library using Arrow-style combinators and graph-based patching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Module Introspection Implementations (Integration Layer)
//!
//! This module provides `ModuleIntrospection` implementations for all built-in modules,
//! enabling GUIs to discover and control module parameters automatically.
//!
//! Most modules are fully CV-controlled and use the default empty implementation.
//! Only modules with internal state parameters provide custom implementations.

use alloc::vec;
use alloc::vec::Vec;

use crate::introspection::{ControlType, ModuleIntrospection, ParamCurve, ParamInfo, ValueFormat};

use crate::analog::{AnalogVco, Saturator, Wavefolder};
use crate::modules::{
    Adsr, Arpeggiator, Attenuverter, BernoulliGate, Bitcrusher, ChordMemory, Chorus, Clock,
    Comparator, Compressor, Crossfader, Crosstalk, DelayLine, DiodeLadderFilter, Distortion,
    Ducker, EnvelopeFollower, Euclidean, Flanger, FormantOsc, Granular, GroundLoop, KarplusStrong,
    Lfo, Limiter, LogicAnd, LogicNot, LogicOr, LogicXor, Max, MidSideDecode, MidSideEncode, Min,
    Mixer, Multiple, NoiseGate, NoiseGenerator, Offset, Oversample, ParametricEq, Phaser,
    PitchShifter, PrecisionAdder, Quantizer, Rectifier, Reverb, RingModulator, SampleAndHold,
    SamplePlayer, Scale, ScaleQuantizer, SlewLimiter, StepSequencer, StereoOutput, Supersaw, Svf,
    Tremolo, UnitDelay, VcSwitch, Vca, Vco, Vibrato, Vocoder, Wavetable,
};

// =============================================================================
// CV-Controlled Modules (use default empty implementation)
// =============================================================================

// Oscillators
impl ModuleIntrospection for Vco {}
impl ModuleIntrospection for Lfo {}
impl ModuleIntrospection for AnalogVco {}

// Filters
impl ModuleIntrospection for Svf {}
impl ModuleIntrospection for DiodeLadderFilter {}

// Envelopes & Amplifiers
impl ModuleIntrospection for Adsr {}
impl ModuleIntrospection for Vca {}

// Utilities (CV-controlled)
impl ModuleIntrospection for Mixer {}
impl ModuleIntrospection for UnitDelay {}
impl ModuleIntrospection for Attenuverter {}
impl ModuleIntrospection for Multiple {}
impl ModuleIntrospection for SlewLimiter {}
impl ModuleIntrospection for SampleAndHold {}
impl ModuleIntrospection for PrecisionAdder {}
impl ModuleIntrospection for VcSwitch {}
impl ModuleIntrospection for Min {}
impl ModuleIntrospection for Max {}
impl ModuleIntrospection for Crossfader {}
impl ModuleIntrospection for MidSideEncode {}
impl ModuleIntrospection for MidSideDecode {}

// Effects (CV-controlled)
impl ModuleIntrospection for RingModulator {}
impl ModuleIntrospection for Rectifier {}
impl ModuleIntrospection for Crosstalk {}

// Logic & Random
impl ModuleIntrospection for LogicAnd {}
impl ModuleIntrospection for LogicOr {}
impl ModuleIntrospection for LogicXor {}
impl ModuleIntrospection for LogicNot {}
impl ModuleIntrospection for Comparator {}
impl ModuleIntrospection for BernoulliGate {}

// Sequencing & I/O
impl ModuleIntrospection for Clock {}
impl ModuleIntrospection for StereoOutput {}
impl ModuleIntrospection for Arpeggiator {}

// Phase 4: Advanced DSP Modules (all CV-controlled)
impl ModuleIntrospection for ChordMemory {}
impl ModuleIntrospection for ParametricEq {}
impl ModuleIntrospection for Wavetable {}
impl ModuleIntrospection for FormantOsc {}
impl ModuleIntrospection for PitchShifter {}
impl ModuleIntrospection for Reverb {}
impl ModuleIntrospection for Vocoder {}
impl ModuleIntrospection for Granular {}

// Effects & dynamics whose controllable quantities are all input ports (rate, depth, mix,
// threshold, drive, …). They expose no non-port internal state, so the default empty impl
// is correct: their parameters are discovered and driven through the port system, and the
// `Patch` synthesizes `ParamInfo`s for those ports (see `Patch::param_infos`).
impl ModuleIntrospection for Bitcrusher {}
impl ModuleIntrospection for Chorus {}
impl ModuleIntrospection for Compressor {}
impl ModuleIntrospection for DelayLine {}
impl ModuleIntrospection for EnvelopeFollower {}
impl ModuleIntrospection for Euclidean {}
impl ModuleIntrospection for Flanger {}
impl ModuleIntrospection for KarplusStrong {}
impl ModuleIntrospection for Limiter {}
impl ModuleIntrospection for NoiseGate {}
impl ModuleIntrospection for Phaser {}
impl ModuleIntrospection for Supersaw {}
impl ModuleIntrospection for Tremolo {}
impl ModuleIntrospection for Vibrato {}
// ScaleQuantizer's `root`/`scale` selection are input ports; its only genuinely internal
// state is an optional custom-scale table (a `&[cents]` list, not a scalar value), which is
// intentionally excluded from the value-typed parameter surface.
impl ModuleIntrospection for ScaleQuantizer {}

/// Map an [`Oversample`] factor (1/2/4) to a select index (0/1/2) and back. Shared by the
/// waveshaping modules whose only non-port parameter is their opt-in oversampling factor.
fn oversample_to_index(factor: usize) -> f64 {
    match factor {
        4 => 2.0,
        2 => 1.0,
        _ => 0.0,
    }
}

fn oversample_from_index(value: f64) -> Oversample {
    // `libm::round` rather than `f64::round` so this compiles on `no_std + alloc` (the
    // introspection tier is alloc-gated, not std-gated).
    match libm::round(value) as i64 {
        2 => Oversample::X4,
        1 => Oversample::X2,
        _ => Oversample::Off,
    }
}

impl ModuleIntrospection for Distortion {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![ParamInfo::select("oversample", "Oversampling", 3)
            .with_value(oversample_to_index(self.oversample_factor()))]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "oversample" => {
                self.set_oversample(oversample_from_index(value));
                true
            }
            _ => false,
        }
    }
}

// =============================================================================
// Modules with Parameters
// =============================================================================

impl ModuleIntrospection for Offset {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![ParamInfo::new("offset", "Offset")
            .with_range(-10.0, 10.0)
            .with_default(0.0)
            .with_value(self.offset)
            .with_curve(ParamCurve::Linear)
            .with_control(ControlType::Knob)
            .with_unit("V")
            .with_format(ValueFormat::Decimal { places: 2 })]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "offset" => {
                self.set_offset(value);
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for NoiseGenerator {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![ParamInfo::percent("correlation", "Stereo Correlation")
            .with_default(0.3)
            .with_value(self.correlation)]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "correlation" => {
                self.correlation = value.clamp(0.0, 1.0);
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for StepSequencer {
    fn param_infos(&self) -> Vec<ParamInfo> {
        let mut params = Vec::with_capacity(16);

        for i in 0..8 {
            if let Some((voltage, _gate)) = self.get_step(i) {
                params.push(
                    ParamInfo::new(
                        alloc::format!("step_{}_cv", i),
                        alloc::format!("Step {} CV", i + 1),
                    )
                    .with_range(-5.0, 5.0)
                    .with_default(0.0)
                    .with_value(voltage)
                    .with_curve(ParamCurve::Linear)
                    .with_control(ControlType::Slider)
                    .with_unit("V")
                    .with_format(ValueFormat::NoteName),
                );
            }
        }

        for i in 0..8 {
            if let Some((_voltage, gate)) = self.get_step(i) {
                params.push(
                    ParamInfo::toggle(
                        alloc::format!("step_{}_gate", i),
                        alloc::format!("Step {} Gate", i + 1),
                    )
                    // Gates default ON to match the constructor (`gates: [true; 8]`). Without
                    // this the `ParamInfo::toggle` default of 0.0 would equal a legitimately
                    // OFF gate, so `to_def`'s "differs from default" filter would silently drop
                    // it and the gate would spring back ON on reload.
                    .with_default(1.0)
                    .with_value(if gate { 1.0 } else { 0.0 }),
                );
            }
        }

        params
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        if let Some(rest) = id.strip_prefix("step_") {
            if let Some((num_str, param_type)) = rest.split_once('_') {
                if let Ok(step_idx) = num_str.parse::<usize>() {
                    if step_idx < 8 {
                        if let Some((current_cv, current_gate)) = self.get_step(step_idx) {
                            match param_type {
                                "cv" => {
                                    self.set_step(step_idx, value, current_gate);
                                    return true;
                                }
                                "gate" => {
                                    self.set_step(step_idx, current_cv, value > 0.5);
                                    return true;
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }
        false
    }
}

impl ModuleIntrospection for Quantizer {
    fn param_infos(&self) -> Vec<ParamInfo> {
        let scale_value = match self.scale {
            Scale::Chromatic => 0.0,
            Scale::Major => 1.0,
            Scale::Minor => 2.0,
            Scale::PentatonicMajor => 3.0,
            Scale::PentatonicMinor => 4.0,
            Scale::Dorian => 5.0,
            Scale::Mixolydian => 6.0,
            Scale::Blues => 7.0,
        };
        vec![ParamInfo::select("scale", "Scale", 8).with_value(scale_value)]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "scale" => {
                let scale = match value as u8 {
                    0 => Scale::Chromatic,
                    1 => Scale::Major,
                    2 => Scale::Minor,
                    3 => Scale::PentatonicMajor,
                    4 => Scale::PentatonicMinor,
                    5 => Scale::Dorian,
                    6 => Scale::Mixolydian,
                    7 => Scale::Blues,
                    _ => return false,
                };
                self.set_scale(scale);
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for GroundLoop {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![ParamInfo::select("frequency", "Mains Frequency", 2)
            .with_default(1.0)
            .with_value(if self.frequency == 60.0 { 1.0 } else { 0.0 })]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "frequency" => {
                self.frequency = if value > 0.5 { 60.0 } else { 50.0 };
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for Saturator {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![ParamInfo::new("drive", "Drive")
            .with_range(1.0, 10.0)
            .with_default(1.0)
            .with_value(self.drive)
            .with_curve(ParamCurve::Exponential)
            .with_control(ControlType::Knob)
            .with_format(ValueFormat::Ratio)]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "drive" => {
                self.drive = value.clamp(1.0, 10.0);
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for Wavefolder {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![
            ParamInfo::new("threshold", "Fold Threshold")
                .with_range(0.1, 5.0)
                .with_default(1.0)
                .with_value(self.threshold)
                .with_curve(ParamCurve::Exponential)
                .with_control(ControlType::Knob)
                .with_unit("V")
                .with_format(ValueFormat::Decimal { places: 2 }),
            ParamInfo::select("oversample", "Oversampling", 3)
                .with_value(oversample_to_index(self.oversample_factor())),
        ]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "threshold" => {
                self.threshold = value.clamp(0.1, 5.0);
                true
            }
            "oversample" => {
                self.set_oversample(oversample_from_index(value));
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for SamplePlayer {
    fn param_infos(&self) -> Vec<ParamInfo> {
        vec![ParamInfo::percent("start", "Start Position")
            .with_default(0.0)
            .with_value(self.start_position())]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "start" => {
                self.set_start(value);
                true
            }
            _ => false,
        }
    }
}

impl ModuleIntrospection for Ducker {
    fn param_infos(&self) -> Vec<ParamInfo> {
        // These knob ids deliberately differ from the CV input ports "amount"/"threshold"
        // (dynamics.rs). A colliding id would be dropped by `Patch::param_infos`' shadow
        // filter (port wins) and `set_param_by_id` would route to the CV-port base (default
        // 0.0) instead of the depth/threshold knobs (defaults 1.0/0.2), leaving the primary
        // controls invisible to GUIs and un-serializable. `depth`/`thresh` are the base knobs;
        // the same-named ports remain the (bipolar CV) modulation inputs.
        vec![
            ParamInfo::percent("depth", "Duck Amount")
                .with_default(1.0)
                .with_value(self.amount()),
            ParamInfo::percent("thresh", "Threshold")
                .with_default(0.2)
                .with_value(self.threshold()),
        ]
    }

    fn set_param_by_id(&mut self, id: &str, value: f64) -> bool {
        match id {
            "depth" => {
                self.set_amount(value);
                true
            }
            "thresh" => {
                self.set_threshold(value);
                true
            }
            _ => false,
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_offset_introspection() {
        let mut offset = Offset::new(2.5);
        let params = offset.param_infos();
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].id, "offset");
        assert_eq!(params[0].value, 2.5);

        assert!(offset.set_param_by_id("offset", -3.0));
        assert_eq!(offset.param_infos()[0].value, -3.0);
        assert!(!offset.set_param_by_id("invalid", 0.0));
    }

    #[test]
    fn test_step_sequencer_introspection() {
        let mut seq = StepSequencer::new();
        seq.set_step(0, 1.0, true);
        seq.set_step(1, -0.5, false);

        let params = seq.param_infos();
        assert_eq!(params.len(), 16);

        let step0_cv = params.iter().find(|p| p.id == "step_0_cv").unwrap();
        assert_eq!(step0_cv.value, 1.0);

        let step0_gate = params.iter().find(|p| p.id == "step_0_gate").unwrap();
        assert_eq!(step0_gate.value, 1.0);

        assert!(seq.set_param_by_id("step_2_cv", 2.5));
        assert_eq!(seq.get_step(2).unwrap().0, 2.5);
    }

    #[test]
    fn test_quantizer_introspection() {
        let mut quant = Quantizer::major();
        assert_eq!(quant.param_infos()[0].value, 1.0);

        assert!(quant.set_param_by_id("scale", 2.0));
        assert_eq!(quant.param_infos()[0].value, 2.0);
    }

    #[test]
    fn test_noise_generator_introspection() {
        let mut noise = NoiseGenerator::with_correlation(0.5);
        assert!((noise.param_infos()[0].value - 0.5).abs() < 0.001);

        assert!(noise.set_param_by_id("correlation", 0.8));
        assert!((noise.param_infos()[0].value - 0.8).abs() < 0.001);
    }

    #[test]
    fn test_saturator_introspection() {
        let mut sat = Saturator::new(1.0);
        assert_eq!(sat.param_infos()[0].id, "drive");

        assert!(sat.set_param_by_id("drive", 5.0));
        assert_eq!(sat.param_infos()[0].value, 5.0);
    }

    #[test]
    fn test_wavefolder_introspection() {
        let mut wf = Wavefolder::new(1.0);
        assert_eq!(wf.param_infos()[0].id, "threshold");

        assert!(wf.set_param_by_id("threshold", 2.0));
        assert_eq!(wf.param_infos()[0].value, 2.0);
    }

    #[test]
    fn test_ground_loop_introspection() {
        let mut gl = GroundLoop::hz_50(44100.0);
        assert_eq!(gl.param_infos()[0].value, 0.0);

        assert!(gl.set_param_by_id("frequency", 1.0));
        assert_eq!(gl.param_infos()[0].value, 1.0);
    }

    #[test]
    fn test_cv_controlled_modules_have_no_params() {
        assert!(Vco::default().param_infos().is_empty());
        assert!(Lfo::default().param_infos().is_empty());
        assert!(Svf::default().param_infos().is_empty());
        assert!(Adsr::default().param_infos().is_empty());
        assert!(Vca::default().param_infos().is_empty());
        assert!(Clock::default().param_infos().is_empty());
        assert!(LogicAnd::default().param_infos().is_empty());
        // Mid/side utilities are fully port/CV-controlled.
        assert!(MidSideEncode::default().param_infos().is_empty());
        assert!(MidSideDecode::default().param_infos().is_empty());
    }

    #[test]
    fn test_sample_player_introspection() {
        let mut player = SamplePlayer::default();
        let params = player.param_infos();
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].id, "start");

        assert!(player.set_param_by_id("start", 0.5));
        assert!((player.param_infos()[0].value - 0.5).abs() < 1e-9);
        assert!(!player.set_param_by_id("invalid", 0.0));
    }

    #[test]
    fn test_ducker_introspection() {
        let mut ducker = Ducker::default();
        let params = ducker.param_infos();
        assert_eq!(params.len(), 2);
        // Knob ids are distinct from the same-named CV ports (see impl comment).
        assert_eq!(params[0].id, "depth");
        assert_eq!(params[1].id, "thresh");

        assert!(ducker.set_param_by_id("depth", 0.25));
        assert!(ducker.set_param_by_id("thresh", 0.6));
        let p = ducker.param_infos();
        assert!((p[0].value - 0.25).abs() < 1e-9);
        assert!((p[1].value - 0.6).abs() < 1e-9);
        assert!(!ducker.set_param_by_id("invalid", 0.0));
    }
}