synthie 0.4.0

Chiptune-focused synthesizer engine: dual OSC, ring mod, filters, envelopes, LFO, arpeggiator, and FX (reverb, delay, chorus, bitcrusher)
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Monophonic voice pipeline.
//!
//! `Voice` connects oscillator, envelope, filter, and LFO in a single
//! sample-by-sample render path.

use crate::audio::{
    crusher::Bitcrusher,
    env::{EnvStage, Envelope},
    filter::SvFilter,
    osc::{Lfo, Oscillator, detune_hz, midi_to_hz},
};
use crate::params::{MidiNote, RingModMode, SynthParams};

/// Per-sample modulation accumulator.
///
/// All modulation sources (LFOs, envelopes) write additively into these slots.
/// `Voice::process()` applies them in one pass, keeping the signal chain readable.
#[derive(Default)]
struct ModBus {
    /// Pitch modulation, applied as `freq *= 2^(pitch * 0.1)`.
    /// LFO contribution: `lfo_val * depth`. Env contribution: `env_out * depth * 10`.
    pitch: f32,
    /// Pulse-width modulation, applied as `pw += pw_mod * 0.4` (clamped 0.05..0.95).
    pw: f32,
    /// Filter cutoff modulation, applied as `cutoff *= 2^(bus.cutoff * 2.0)`.
    cutoff: f32,
    /// Volume/tremolo modulation, applied as `amp *= (1 - volume * 0.5)`.
    volume: f32,
}

impl ModBus {
    /// Add an LFO contribution to the appropriate slot.
    fn add_lfo(&mut self, lfo_val: f32, depth: f32, target: crate::params::LfoTarget) {
        use crate::params::LfoTarget;
        let c = lfo_val * depth;
        match target {
            LfoTarget::Pitch => self.pitch += c,
            LfoTarget::PulseWidth => self.pw += c,
            LfoTarget::Cutoff => self.cutoff += c,
            LfoTarget::Volume => self.volume += c,
        }
    }
}

/// Monophonic synthesiser voice combining oscillator, envelope, filter, and LFO.
pub struct Voice {
    /// Whether the voice is currently producing sound.
    pub active: bool,
    /// MIDI note number of the current target pitch.
    pub target_note: MidiNote,
    /// Target frequency in Hz (includes detune).
    pub target_freq: f32,
    /// Current glide-smoothed frequency in Hz.
    pub current_freq: f32,
    /// Waveform generator.
    pub osc: Oscillator,
    /// Second oscillator for unison/detune/hard-sync effects.
    pub osc2: Oscillator,
    /// Bitcrusher (bit depth and sample rate reduction).
    pub crusher: Bitcrusher,
    /// Amplitude envelope.
    pub env: Envelope,
    /// State-variable filter.
    pub filter: SvFilter,
    /// Low-frequency oscillator.
    pub lfo: Lfo,
    /// Second low-frequency oscillator.
    pub lfo2: Lfo,
    /// Modulation envelope for filter cutoff.
    pub filter_env: Envelope,
    /// Modulation envelope for oscillator pitch.
    pub pitch_env: Envelope,
    /// Per-sample portamento smoothing coefficient (0 = instant, ~1 = very slow).
    pub glide_coeff: f32,
}

impl Default for Voice {
    fn default() -> Self {
        Self::new()
    }
}

impl Voice {
    /// Construct a voice with default state at A4 (440 Hz).
    #[must_use]
    pub fn new() -> Self {
        Self {
            active: false,
            target_note: MidiNote::A4,
            target_freq: 440.0,
            current_freq: 440.0,
            osc: Oscillator::default(),
            osc2: Oscillator::default(),
            crusher: Bitcrusher::default(),
            env: Envelope::default(),
            filter: SvFilter::default(),
            lfo: Lfo::default(),
            lfo2: Lfo::seeded(0xDEAD_BEEF),
            filter_env: Envelope::default(),
            pitch_env: Envelope::default(),
            glide_coeff: 0.0,
        }
    }

    /// Recompute the portamento smoothing coefficient from glide time and sample rate.
    pub fn update_glide(&mut self, glide_time: f32, sample_rate: f32) {
        self.glide_coeff = if glide_time < 1e-4 {
            0.0
        } else {
            crate::math::expf(-1.0_f32 / (glide_time * sample_rate))
        };
    }

    /// Start a new note (or retrigger legato if the voice is already active).
    pub fn note_on(&mut self, note: impl Into<MidiNote>, params: &SynthParams, sample_rate: f32) {
        let note = note.into();
        let legato = self.active;
        self.target_note = note;
        let base = midi_to_hz(note);
        self.target_freq = detune_hz(base, params.osc.detune);
        if !legato {
            // No glide on fresh attacks – snap to pitch immediately.
            self.current_freq = self.target_freq;
            self.crusher.reset();
        }
        self.active = true;
        self.update_glide(params.global.glide_time, sample_rate);
        self.env.note_on(legato);
        self.filter_env.note_on(legato);
        self.pitch_env.note_on(legato);
    }

    /// Begin the envelope release phase.
    pub fn note_off(&mut self) {
        self.env.note_off();
        self.filter_env.note_off();
        self.pitch_env.note_off();
    }

    /// Immediately silence the voice and reset DSP state (all-notes-off / panic).
    pub fn panic(&mut self) {
        self.active = false;
        self.env.reset();
        self.filter.reset();
        self.filter_env.reset();
        self.pitch_env.reset();
        self.crusher.reset();
    }

    /// Render one sample.  Called from the audio callback – no allocation.
    pub fn process(&mut self, params: &SynthParams, sample_rate: f32) -> f32 {
        if !self.active && !self.env.is_active() {
            return 0.0;
        }

        if self.env.stage == EnvStage::Idle && !self.env.is_active() {
            self.active = false;
        }

        // --- Modulation bus: fill from all sources, then read once ---

        let mut bus = ModBus::default();

        // LFO 1
        let lfo1 = self
            .lfo
            .next(params.lfo.lfo_rate, params.lfo.lfo_shape, sample_rate);
        bus.add_lfo(lfo1, params.lfo.lfo_depth, params.lfo.lfo_target);

        // LFO 2
        let lfo2 = self
            .lfo2
            .next(params.lfo2.lfo_rate, params.lfo2.lfo_shape, sample_rate);
        bus.add_lfo(lfo2, params.lfo2.lfo_depth, params.lfo2.lfo_target);

        // Filter envelope (0..1 output, scaled by depth)
        let fenv = self.filter_env.process(
            params.filter_env.attack,
            params.filter_env.decay,
            params.filter_env.sustain,
            params.filter_env.release,
            false,
            sample_rate,
        );
        bus.cutoff += fenv * params.filter_env.depth;

        // Pitch envelope (scaled ×10 so depth=1 ≈ ±1 octave vs. the 0.1 LFO scale)
        let penv = self.pitch_env.process(
            params.pitch_env.attack,
            params.pitch_env.decay,
            params.pitch_env.sustain,
            params.pitch_env.release,
            false,
            sample_rate,
        );
        bus.pitch += penv * params.pitch_env.depth * 10.0;

        // --- Signal chain ---

        // Glide (portamento)
        let gc = self.glide_coeff;
        self.current_freq = self.target_freq + (self.current_freq - self.target_freq) * gc;
        let freq = self.current_freq;

        // Pitch modulation (vibrato + pitch env)
        let modded_freq = freq * crate::math::powf(2.0_f32, bus.pitch * 0.1);
        let final_freq = modded_freq;

        // Pulse width modulation
        let pw = (params.osc.pulse_width + bus.pw * 0.4).clamp(0.05, 0.95);

        // Oscillator 1
        let osc_out = self.osc.next_sample(
            final_freq,
            sample_rate,
            params.osc.waveform,
            pw,
            params.osc.noise_mix,
        );

        // Oscillator 2 with optional ring modulation
        let osc_out = if params.osc2.osc2_mix > 0.001 {
            if params.osc2.hard_sync && self.osc.just_wrapped() {
                self.osc2.reset();
            }
            let osc2_freq = detune_hz(final_freq, params.osc2.detune);
            let secondary =
                self.osc2
                    .next_sample(osc2_freq, sample_rate, params.osc2.waveform, pw, 0.0);

            let modulated = match params.osc2.ring_mod {
                RingModMode::Off => secondary,
                RingModMode::Osc2ByOsc1Sign => secondary * self.osc.phase_sign(),
                RingModMode::Osc1ByOsc2Sign => osc_out * self.osc2.phase_sign(),
                RingModMode::Analog => osc_out * secondary,
            };

            osc_out * (1.0 - params.osc2.osc2_mix) + modulated * params.osc2.osc2_mix
        } else {
            osc_out
        };

        // Bitcrusher (pre-filter)
        let osc_out = self
            .crusher
            .process(osc_out, params.crusher.bits, params.crusher.rate);

        // Amplitude envelope
        let env_val = self.env.process(
            params.env.attack,
            params.env.decay,
            params.env.sustain,
            params.env.release,
            params.env.env_reverse,
            sample_rate,
        );

        // Volume modulation (tremolo)
        let vol_mod = (1.0 - bus.volume * 0.5).max(0.0);

        // Filter cutoff modulation
        let cutoff_mod = (params.filter.cutoff * crate::math::powf(2.0_f32, bus.cutoff * 2.0))
            .clamp(20.0, 18000.0);

        // Filter
        let filtered = self.filter.process(
            osc_out * env_val,
            params.filter.filter_mode,
            cutoff_mod,
            params.filter.resonance,
            params.filter.drive,
            sample_rate,
        );

        filtered * env_val * vol_mod * params.global.volume
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::params::{MidiNote, RingModMode, SynthParams, Waveform};

    #[test]
    fn voice_osc2_mix_zero_is_finite() {
        let mut voice = Voice::new();
        let params = SynthParams::default(); // osc2_mix = 0.0
        voice.note_on(MidiNote::A4, &params, 44100.0);
        for _ in 0..1000 {
            let s = voice.process(&params, 44100.0);
            assert!(s.is_finite(), "non-finite sample with osc2 off: {s}");
        }
    }

    #[test]
    fn voice_osc2_hard_sync_is_finite() {
        let mut voice = Voice::new();
        let mut params = SynthParams::default();
        params.osc2.osc2_mix = 0.5;
        params.osc2.hard_sync = true;
        params.osc2.waveform = Waveform::Sawtooth;
        params.osc2.detune = 7.0;
        voice.note_on(MidiNote::A4, &params, 44100.0);
        for _ in 0..1000 {
            let s = voice.process(&params, 44100.0);
            assert!(s.is_finite(), "non-finite sample with hard sync on: {s}");
        }
    }

    #[test]
    fn voice_hard_sync_resets_osc2_phase() {
        // With hard sync, OSC2 resets to phase 0 each time OSC1 wraps.
        // OSC2 (sawtooth) immediately after reset starts at phase ≈ 0, giving
        // output ≈ -1.  This is observable even through the envelope and filter
        // because OSC2 is the sole source (osc2_mix = 1.0) and the filter is
        // transparent at low resonance.  Without sync the same OSC2 would be at
        // an arbitrary phase after 5+ free cycles, frequently yielding positive
        // values; with sync the output must be strongly negative at every wrap.
        use crate::params::{EnvParams, FilterMode, FilterParams, GlobalParams};
        let mut params = SynthParams::default();
        params.osc.waveform = Waveform::Sawtooth;
        params.osc2.waveform = Waveform::Sawtooth;
        params.osc2.detune = 700.0; // OSC2 ~5.3× faster than OSC1
        params.osc2.osc2_mix = 1.0; // 100% OSC2 so the reset is the sole signal
        params.osc2.hard_sync = true;
        params.env = EnvParams {
            attack: 0.0,
            decay: 0.0,
            sustain: 1.0,
            release: 0.0,
            env_reverse: false,
        };
        params.filter = FilterParams {
            filter_mode: FilterMode::LowPass,
            cutoff: 20000.0,
            resonance: 0.0,
            drive: 0.0,
        };
        params.global = GlobalParams {
            volume: 1.0,
            glide_time: 0.0,
        };

        let mut voice = Voice::new();
        voice.note_on(MidiNote::A4, &params, 44100.0);

        // 440 Hz at 44100 Hz → wrap every ~100 samples; 600 samples covers ≥5 wraps.
        let mut wrap_samples: Vec<f32> = Vec::new();
        for _ in 0..600 {
            let s = voice.process(&params, 44100.0);
            if voice.osc.just_wrapped() {
                wrap_samples.push(s);
            }
        }

        assert!(
            wrap_samples.len() >= 4,
            "expected ≥4 OSC1 wraps in 600 samples, got {}",
            wrap_samples.len()
        );

        // After the first wrap (envelope may still settle), each wrap-point
        // must produce strongly negative output (OSC2 sawtooth just off phase 0).
        // Phase step ≈ 659 Hz / 44100 Hz ≈ 0.015 → sawtooth ≈ -0.97.
        // Allow headroom for filter state and slight envelope drift.
        for (i, &s) in wrap_samples[1..].iter().enumerate() {
            assert!(
                s < -0.5,
                "wrap sample {}: expected output near -1 (OSC2 reset to phase 0), got {s}",
                i + 1
            );
        }

        // Contrast: without hard sync, OSC2 runs freely and after 5+ free
        // cycles will often be at a positive phase.  Collect and verify at least
        // one wrap-point sample is clearly positive (proving the sync test is
        // discriminating rather than vacuously satisfied).
        let mut params_free = params.clone();
        params_free.osc2.hard_sync = false;
        let mut voice_free = Voice::new();
        voice_free.note_on(MidiNote::A4, &params_free, 44100.0);

        let mut any_positive = false;
        for _ in 0..600 {
            let s = voice_free.process(&params_free, 44100.0);
            if voice_free.osc.just_wrapped() && s > 0.0 {
                any_positive = true;
                break;
            }
        }
        assert!(
            any_positive,
            "unsynced OSC2 should produce positive values at some OSC1 wrap-points"
        );
    }

    #[test]
    fn filter_env_opens_cutoff() {
        use crate::params::{
            EnvParams, FilterMode, FilterParams, GlobalParams, ModEnvParams, Waveform,
        };

        // Start with a very low cutoff so most signal is blocked.
        // Fast-attack filter env at full positive depth (opens toward higher cutoff).
        let mut params = SynthParams {
            filter: FilterParams {
                filter_mode: FilterMode::LowPass,
                cutoff: 200.0,
                resonance: 0.0,
                drive: 0.0,
            },
            filter_env: ModEnvParams {
                attack: 0.001,
                decay: 4.0,
                sustain: 1.0,
                release: 4.0,
                depth: 1.0,
            },
            env: EnvParams {
                attack: 0.001,
                decay: 0.0,
                sustain: 1.0,
                release: 4.0,
                env_reverse: false,
            },
            global: GlobalParams {
                volume: 1.0,
                glide_time: 0.0,
            },
            ..SynthParams::default()
        };
        params.osc.waveform = Waveform::Sawtooth;
        params.lfo.lfo_depth = 0.0;
        params.lfo2.lfo_depth = 0.0;
        params.pitch_env.depth = 0.0;

        // With filter env open (depth = 1.0).
        let mut v_open = Voice::new();
        v_open.note_on(MidiNote::A4, &params, 44100.0);
        let rms_open: f32 = (0..4410)
            .map(|_| v_open.process(&params, 44100.0).powi(2))
            .sum::<f32>()
            .sqrt();

        // With filter env off (depth = 0.0) — filter stays closed at 200 Hz.
        let mut params_closed = params.clone();
        params_closed.filter_env.depth = 0.0;
        let mut v_closed = Voice::new();
        v_closed.note_on(MidiNote::A4, &params_closed, 44100.0);
        let rms_closed: f32 = (0..4410)
            .map(|_| v_closed.process(&params_closed, 44100.0).powi(2))
            .sum::<f32>()
            .sqrt();

        assert!(
            rms_open > rms_closed * 1.5,
            "filter env depth=1 should pass more signal than depth=0: open={rms_open:.4}, closed={rms_closed:.4}"
        );
    }

    #[test]
    fn pitch_env_is_finite() {
        use crate::params::ModEnvParams;

        let params = SynthParams {
            pitch_env: ModEnvParams {
                attack: 0.001,
                decay: 0.5,
                sustain: 0.0,
                release: 0.1,
                depth: 1.0,
            },
            ..SynthParams::default()
        };
        let mut voice = Voice::new();
        voice.note_on(MidiNote::A4, &params, 44100.0);
        for i in 0..4410 {
            let s = voice.process(&params, 44100.0);
            assert!(
                s.is_finite(),
                "non-finite sample at {i} with pitch env: {s}"
            );
        }
    }

    #[test]
    fn lfo2_and_lfo1_both_active_is_finite() {
        use crate::params::LfoShape;

        let mut params = SynthParams::default();
        params.lfo.lfo_depth = 0.5;
        params.lfo.lfo_shape = LfoShape::Square;
        params.lfo.lfo_target = crate::params::LfoTarget::Pitch;
        params.lfo2.lfo_depth = 0.5;
        params.lfo2.lfo_shape = LfoShape::Sawtooth;
        params.lfo2.lfo_target = crate::params::LfoTarget::Pitch;
        let mut voice = Voice::new();
        voice.note_on(MidiNote::A4, &params, 44100.0);
        for i in 0..4410 {
            let s = voice.process(&params, 44100.0);
            assert!(s.is_finite(), "non-finite sample at {i} with two LFOs: {s}");
        }
    }

    #[test]
    fn ring_mod_modes_alter_output() {
        // Each active RingModMode must produce output different from Off.
        // Sawtooth (non-symmetric) avoids signed-sum cancellation.
        // Comparison uses cumulative absolute per-sample difference (robust to phase).
        use crate::params::EnvParams;

        let base_params = {
            let mut p = SynthParams::default();
            p.osc.waveform = Waveform::Sawtooth;
            p.osc2.osc2_mix = 1.0;
            p.osc2.waveform = Waveform::Sawtooth;
            p.osc2.detune = 700.0; // ~5x faster than OSC1, ensures phase difference
            p.env = EnvParams {
                attack: 0.0,
                decay: 0.0,
                sustain: 1.0,
                release: 0.0,
                env_reverse: false,
            };
            p
        };

        // Collect Off-mode samples as baseline.
        let mut params_off = base_params.clone();
        params_off.osc2.ring_mod = RingModMode::Off;
        let mut voice_off = Voice::new();
        voice_off.note_on(MidiNote::A4, &params_off, 44100.0);
        let samples_off: Vec<f32> = (0..500)
            .map(|_| voice_off.process(&params_off, 44100.0))
            .collect();

        for mode in [
            RingModMode::Osc2ByOsc1Sign,
            RingModMode::Osc1ByOsc2Sign,
            RingModMode::Analog,
        ] {
            let mut params_rm = base_params.clone();
            params_rm.osc2.ring_mod = mode;
            let mut voice_rm = Voice::new();
            voice_rm.note_on(MidiNote::A4, &params_rm, 44100.0);
            let abs_diff: f32 = samples_off
                .iter()
                .map(|&off| {
                    let rm = voice_rm.process(&params_rm, 44100.0);
                    (rm - off).abs()
                })
                .sum();
            assert!(
                abs_diff > 0.1,
                "RingModMode::{mode:?}: cumulative |diff| vs Off = {abs_diff:.6} (expected > 0.1)"
            );
        }
    }

    #[test]
    fn ring_mod_analog_output_is_finite() {
        // Analog mode multiplies osc1 × osc2. Both oscillators are in -1..1,
        // so the product is bounded; verify no NaN/Inf escapes through the
        // voice pipeline regardless of waveform or detune ratio.
        use crate::params::EnvParams;

        let mut params = SynthParams::default();
        params.osc2.osc2_mix = 1.0;
        params.osc2.waveform = Waveform::Sawtooth;
        params.osc2.detune = 700.0;
        params.osc2.ring_mod = RingModMode::Analog;
        params.env = EnvParams {
            attack: 0.0,
            decay: 0.0,
            sustain: 1.0,
            release: 0.0,
            env_reverse: false,
        };

        let mut voice = Voice::new();
        voice.note_on(MidiNote::A4, &params, 44100.0);
        for i in 0..1000 {
            let s = voice.process(&params, 44100.0);
            assert!(s.is_finite(), "sample {i}: non-finite output: {s}");
        }
    }

    #[test]
    fn ring_mod_off_is_deterministic() {
        // Two voices with identical params (ring_mod = Off) must produce
        // bit-identical output — guards against any stochastic side effects.
        let mut params_a = SynthParams::default();
        params_a.osc2.osc2_mix = 0.5;
        params_a.osc2.waveform = Waveform::Sawtooth;
        params_a.osc2.detune = 7.0;
        params_a.osc2.ring_mod = RingModMode::Off;

        let params_b = params_a.clone();

        let mut voice_a = Voice::new();
        voice_a.note_on(MidiNote::A4, &params_a, 44100.0);
        let mut voice_b = Voice::new();
        voice_b.note_on(MidiNote::A4, &params_b, 44100.0);

        for i in 0..200 {
            let a = voice_a.process(&params_a, 44100.0);
            let b = voice_b.process(&params_b, 44100.0);
            assert!(
                a.to_bits() == b.to_bits(),
                "sample {i}: Off mode is non-deterministic: {a} != {b}"
            );
        }
    }
}