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
//! Built-in arpeggiator: fixed-size note list, four playback modes, per-sample
//! phase-accumulator timing, configurable gate.

use crate::params::{ArpMode, ArpParams, MidiNote};

/// Events produced by one call to [`Arpeggiator::tick`].
///
/// At most one `off` and one `on` event fire per sample. When both are `Some`,
/// apply `off` before `on` to avoid re-triggering the same voice slot.
#[cfg(feature = "arp")]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ArpEvents {
    /// Note to release this sample, if any.
    pub off: Option<MidiNote>,
    /// Note to trigger this sample, if any.
    pub on: Option<MidiNote>,
}

/// Per-channel arpeggiator with phase-accumulator timing.
///
/// Lives inside `AudioChannel`. All timing state is here; note-list state
/// lives in [`ArpParams`] so it survives param snapshots sent via `LoadPatch`.
#[cfg(feature = "arp")]
#[derive(Debug, Clone)]
pub struct Arpeggiator {
    /// Fractional position within the current step, `0.0..1.0`.
    phase: f32,
    /// Index into the active note list.
    pub(crate) step: u8,
    /// Note currently held by the arp; `None` when between steps.
    pub(crate) sounding: Option<MidiNote>,
    /// `true` once `NoteOff` has been emitted for the current step's note.
    gate_fired: bool,
    /// Direction flag for `UpDown` mode: `0` = ascending, `1` = descending.
    direction: u8,
    /// Galois LFSR state for `Random` mode.
    lfsr: u32,
}

#[cfg(feature = "arp")]
impl Default for Arpeggiator {
    fn default() -> Self {
        Self {
            phase: 0.0,
            step: 0,
            sounding: None,
            gate_fired: false,
            direction: 0,
            lfsr: 0xACE1_FEED,
        }
    }
}

#[cfg(feature = "arp")]
impl Arpeggiator {
    /// Create a new, idle arpeggiator.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Advance one sample and return any note events that fire this sample.
    ///
    /// Call once per sample from inside the audio render loop.
    /// When both `off` and `on` are `Some`, apply `off` first.
    ///
    /// The increment `params.rate / sample_rate` is clamped to `[0, 1]`, so
    /// phase always stays in `[0, 1)` after each call. Rates >= `sample_rate`
    /// are treated as one step per sample.
    pub fn tick(&mut self, sample_rate: f32, params: &ArpParams) -> ArpEvents {
        // Clamp count defensively: params.count could exceed 4 if set from
        // deserialized data without going through add_note / set_notes.
        let count = params.count.min(4);
        if count == 0 {
            return ArpEvents::default();
        }

        let gate = params.gate.clamp(0.0, 1.0);
        let mut result = ArpEvents::default();

        // Gate expiry: NoteOff fires when phase crosses the gate threshold mid-step.
        if self.sounding.is_some() && !self.gate_fired && self.phase >= gate {
            result.off = self.sounding;
            self.gate_fired = true;
        }

        // Clamp increment to [0, 1] so phase stays in [0, 2) before wrapping,
        // making a single subtraction always sufficient.
        self.phase += (params.rate / sample_rate).clamp(0.0, 1.0);

        if self.phase >= 1.0 {
            self.phase = (self.phase - 1.0).max(0.0);
            let pre_gate_fired = self.gate_fired;
            self.gate_fired = false;

            if let Some(note) = self.sounding.take() {
                // gate = 1.0 case: NoteOff deferred to step boundary.
                if !pre_gate_fired {
                    result.off = Some(note);
                }
                self.advance_step(count, params);
            }
            // If sounding was None this is the very first step boundary; don't advance.
        }

        // Start a new note whenever the arp is not currently sounding one.
        if self.sounding.is_none() {
            let note = params.notes[self.step as usize % 4];
            self.sounding = Some(note);
            result.on = Some(note);
        }

        result
    }

    fn advance_step(&mut self, count: u8, params: &ArpParams) {
        // count is already clamped to 1..=4 by tick().
        debug_assert!(count > 0 && count <= 4);
        match params.mode {
            ArpMode::Up => self.step = (self.step + 1) % count,
            ArpMode::Down => self.step = (self.step + count - 1) % count,
            ArpMode::UpDown => self.advance_step_updown(count),
            ArpMode::Random => {
                self.tick_lfsr();
                // Safe: result is always < count (<=4), fits in u8.
                #[allow(clippy::cast_possible_truncation)]
                {
                    self.step = (self.lfsr % u32::from(count)) as u8;
                }
            }
        }
    }

    fn advance_step_updown(&mut self, count: u8) {
        if count <= 1 {
            self.step = 0;
            return;
        }
        if self.direction == 0 {
            self.step += 1;
            if self.step >= count {
                // Reached top — bounce back to count-2, reverse direction.
                self.step = count.saturating_sub(2);
                self.direction = 1;
            }
        } else if self.step == 0 {
            // Reached bottom — bounce to 1, reverse direction.
            self.step = 1.min(count - 1);
            self.direction = 0;
        } else {
            self.step -= 1;
        }
    }

    fn tick_lfsr(&mut self) {
        let bit = self.lfsr & 1;
        self.lfsr >>= 1;
        if bit != 0 {
            self.lfsr ^= 0xB4BC_D35C;
        }
    }

    /// Add `note` to the arp list if it is not already present and space remains.
    pub fn add_note(&mut self, params: &mut ArpParams, note: MidiNote) {
        if params.count >= 4 {
            return;
        }
        if params.notes[..params.count as usize].contains(&note) {
            return;
        }
        params.notes[params.count as usize] = note;
        params.count += 1;
    }

    /// Remove `note` from the arp list, shifting the remaining entries down.
    ///
    /// When the last note is removed (`count` drops to 0) the playback state
    /// is reset so a subsequent `add_note` starts from a clean position.
    /// The caller (`AudioChannel::note_off`) is responsible for releasing any
    /// voice that was sounding at that moment.
    pub fn remove_note(&mut self, params: &mut ArpParams, note: MidiNote) {
        let count = params.count as usize;
        if let Some(pos) = params.notes[..count].iter().position(|&n| n == note) {
            for i in pos..count - 1 {
                params.notes[i] = params.notes[i + 1];
            }
            params.count -= 1;
            if params.count == 0 {
                self.step = 0;
                self.direction = 0;
                self.phase = 0.0;
                self.gate_fired = false;
                // sounding is left for the caller to handle (voice release)
            } else if self.step >= params.count {
                self.step = params.count - 1;
            }
        }
    }

    /// Replace the arp list with `notes` (up to 4 entries) and reset playback state.
    pub fn set_notes(&mut self, params: &mut ArpParams, notes: &[MidiNote]) {
        let n = notes.len().min(4);
        params.notes[..n].copy_from_slice(&notes[..n]);
        // Safe: n is bounded by 4, which fits in u8.
        #[allow(clippy::cast_possible_truncation)]
        {
            params.count = n as u8;
        }
        self.step = 0;
        self.direction = 0;
        self.phase = 0.0;
        self.sounding = None;
        self.gate_fired = false;
    }

    /// Clear the arp list and all playback state.
    ///
    /// `AudioChannel::panic()` silences voices directly afterwards, so no
    /// `NoteOff` event is needed here.
    pub fn panic(&mut self, params: &mut ArpParams) {
        params.count = 0;
        self.step = 0;
        self.direction = 0;
        self.phase = 0.0;
        self.sounding = None;
        self.gate_fired = false;
    }
}

#[cfg(all(test, feature = "arp"))]
mod tests {
    use super::*;
    use crate::params::{ArpMode, ArpParams, MidiNote};

    const SR: f32 = 44100.0;

    /// Helper: Up mode params with rate = SR (1 step per sample, simplifies assertions).
    fn up_params(notes: &[u8]) -> ArpParams {
        // Safe: notes.len().min(4) is always <= 4, which fits in u8.
        #[allow(clippy::cast_possible_truncation)]
        let count = notes.len().min(4) as u8;
        let mut note_arr = ArpParams::default().notes;
        for (i, &n) in notes.iter().enumerate().take(4) {
            note_arr[i] = MidiNote(n);
        }
        ArpParams {
            enabled: true,
            rate: SR,
            mode: ArpMode::Up,
            notes: note_arr,
            count,
            ..ArpParams::default()
        }
    }

    #[test]
    fn count_zero_returns_no_events() {
        let mut arp = Arpeggiator::new();
        let params = ArpParams {
            count: 0,
            ..ArpParams::default()
        };
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, None);
        assert_eq!(e.off, None);
    }

    #[test]
    fn first_tick_fires_note_on_immediately() {
        let mut arp = Arpeggiator::new();
        let params = up_params(&[60, 64, 67]);
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, Some(MidiNote(60)));
        assert_eq!(e.off, None);
    }

    #[test]
    fn up_mode_cycles_three_notes_in_order() {
        let mut arp = Arpeggiator::new();
        let params = up_params(&[60, 64, 67]);

        // Tick 1: step 0, first note on
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, Some(MidiNote(60)), "tick 1 NoteOn");
        assert_eq!(e.off, None, "tick 1 no NoteOff");

        // Tick 2: step advances to 1 (rate = SR -> phase hits 1.0 each tick)
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(60)), "tick 2 NoteOff 60");
        assert_eq!(e.on, Some(MidiNote(64)), "tick 2 NoteOn 64");

        // Tick 3: step advances to 2
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(64)), "tick 3 NoteOff 64");
        assert_eq!(e.on, Some(MidiNote(67)), "tick 3 NoteOn 67");

        // Tick 4: wraps back to step 0
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(67)), "tick 4 NoteOff 67");
        assert_eq!(e.on, Some(MidiNote(60)), "tick 4 NoteOn 60 (wrap)");
    }

    #[test]
    fn gate_fires_note_off_mid_step() {
        // rate = SR/2 -> 2 samples per step; gate = 0.5 -> NoteOff at sample boundary
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64]);
        params.rate = SR / 2.0;
        params.gate = 0.5;

        // Sample 1: phase 0->0.5, NoteOn(60), no gate fire (phase was 0 < 0.5 at gate check)
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, Some(MidiNote(60)), "s1 NoteOn");
        assert_eq!(e.off, None, "s1 no NoteOff");

        // Sample 2: gate check phase=0.5 >= 0.5 -> NoteOff(60);
        //           phase -> 1.0 -> step advance -> NoteOn(64)
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(60)), "s2 NoteOff");
        assert_eq!(e.on, Some(MidiNote(64)), "s2 NoteOn");
    }

    #[test]
    fn gate_1_fires_note_off_at_step_boundary() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64]);
        params.rate = SR / 2.0;
        params.gate = 1.0;

        // Sample 1: NoteOn(60), no NoteOff
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, Some(MidiNote(60)));
        assert_eq!(e.off, None);

        // Sample 2: phase 0.5 < 1.0 -> no gate fire; phase -> 1.0 -> boundary:
        //           NoteOff(60) at boundary, then NoteOn(64)
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(60)), "gate=1.0 NoteOff at boundary");
        assert_eq!(e.on, Some(MidiNote(64)));
    }

    #[test]
    fn down_mode_cycles_descending() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64, 67]);
        params.mode = ArpMode::Down;

        // Down starts at step 0 (lowest index), advances down.
        // Tick 1: NoteOn notes[0]=60
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, Some(MidiNote(60)));

        // Tick 2: step wraps down -> (0 + 3 - 1) % 3 = 2 -> notes[2]=67
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(60)));
        assert_eq!(e.on, Some(MidiNote(67)));

        // Tick 3: step -> (2 + 3 - 1) % 3 = 1 -> notes[1]=64
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(67)));
        assert_eq!(e.on, Some(MidiNote(64)));

        // Tick 4: step -> (1 + 3 - 1) % 3 = 0 -> notes[0]=60
        let e = arp.tick(SR, &params);
        assert_eq!(e.off, Some(MidiNote(64)));
        assert_eq!(e.on, Some(MidiNote(60)));
    }

    #[test]
    fn updown_mode_bounces_at_ends() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64, 67]);
        params.mode = ArpMode::UpDown;

        // Expected sequence: 0(60), 1(64), 2(67), 1(64), 0(60), 1(64), 2(67), ...
        let expected_notes = [60u8, 64, 67, 64, 60, 64, 67, 64, 60];
        let mut prev_on: Option<MidiNote> = None;
        for (i, &n) in expected_notes.iter().enumerate() {
            let e = arp.tick(SR, &params);
            assert_eq!(
                e.on,
                Some(MidiNote(n)),
                "tick {} expected NoteOn({})",
                i + 1,
                n
            );
            if i > 0 {
                assert_eq!(
                    e.off,
                    prev_on,
                    "tick {} expected NoteOff({:?})",
                    i + 1,
                    prev_on
                );
            }
            prev_on = e.on;
        }
    }

    #[test]
    fn random_mode_stays_in_bounds() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64, 67, 69]); // 4 notes
        params.mode = ArpMode::Random;

        // Run 1000 ticks; every triggered note must be one of the four.
        for _ in 0..1000 {
            let e = arp.tick(SR, &params);
            if let Some(note) = e.on {
                assert!(
                    params.notes[..params.count as usize].contains(&note),
                    "random arp emitted note {note:?} not in list"
                );
            }
        }
    }

    #[test]
    fn random_mode_single_note_always_returns_same_note() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60]);
        params.mode = ArpMode::Random;

        for _ in 0..20 {
            let e = arp.tick(SR, &params);
            if let Some(note) = e.on {
                assert_eq!(note, MidiNote(60));
            }
        }
    }

    #[test]
    fn add_note_appends_to_list() {
        let mut arp = Arpeggiator::new();
        let mut params = ArpParams::default();
        arp.add_note(&mut params, MidiNote(60));
        assert_eq!(params.count, 1);
        assert_eq!(params.notes[0], MidiNote(60));
    }

    #[test]
    fn add_note_ignores_duplicate() {
        let mut arp = Arpeggiator::new();
        let mut params = ArpParams::default();
        arp.add_note(&mut params, MidiNote(60));
        arp.add_note(&mut params, MidiNote(60));
        assert_eq!(params.count, 1);
    }

    #[test]
    fn add_note_caps_at_four() {
        let mut arp = Arpeggiator::new();
        let mut params = ArpParams::default();
        for n in [60u8, 62, 64, 65, 67] {
            arp.add_note(&mut params, MidiNote(n));
        }
        assert_eq!(params.count, 4, "list must not exceed 4");
        assert_eq!(params.notes[3], MidiNote(65), "5th note must be rejected");
    }

    #[test]
    fn remove_note_shifts_remaining_down() {
        let mut arp = Arpeggiator::new();
        let mut params = ArpParams::default();
        for n in [60u8, 64, 67] {
            arp.add_note(&mut params, MidiNote(n));
        }
        arp.remove_note(&mut params, MidiNote(64));
        assert_eq!(params.count, 2);
        assert_eq!(params.notes[0], MidiNote(60));
        assert_eq!(params.notes[1], MidiNote(67));
    }

    #[test]
    fn remove_note_missing_note_is_no_op() {
        let mut arp = Arpeggiator::new();
        let mut params = ArpParams::default();
        arp.add_note(&mut params, MidiNote(60));
        arp.remove_note(&mut params, MidiNote(99));
        assert_eq!(params.count, 1);
    }

    #[test]
    fn remove_note_clamps_step_when_list_shrinks() {
        let mut arp = Arpeggiator::new();
        let mut params = ArpParams::default();
        for n in [60u8, 64, 67] {
            arp.add_note(&mut params, MidiNote(n));
        }
        // Advance to step 2 by ticking (rate = SR -> 1 step per tick)
        params.enabled = true;
        params.rate = SR;
        arp.tick(SR, &params); // step 0
        arp.tick(SR, &params); // step 1 (with advance)
        arp.tick(SR, &params); // step 2 (with advance)
        // step is now 2; remove the last note so count drops to 2
        arp.remove_note(&mut params, MidiNote(67));
        assert!(arp.step < params.count, "step must be < new count");
    }

    #[test]
    fn set_notes_replaces_list_and_resets_state() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64, 67]);
        // Tick a few times to build up state
        params.rate = SR;
        arp.tick(SR, &params);
        arp.tick(SR, &params);

        let new_notes = [MidiNote(72), MidiNote(76)];
        arp.set_notes(&mut params, &new_notes);
        assert_eq!(params.count, 2);
        assert_eq!(params.notes[0], MidiNote(72));
        assert_eq!(params.notes[1], MidiNote(76));
        assert_eq!(arp.step, 0);
        assert_eq!(arp.sounding, None);

        // First tick after set_notes must fire NoteOn for the first new note
        params.enabled = true;
        params.rate = SR;
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, Some(MidiNote(72)));
    }

    #[test]
    fn panic_clears_all_state() {
        let mut arp = Arpeggiator::new();
        let mut params = up_params(&[60, 64, 67]);
        params.rate = SR;
        arp.tick(SR, &params);
        arp.tick(SR, &params);

        arp.panic(&mut params);
        assert_eq!(params.count, 0);
        assert_eq!(arp.sounding, None);
        assert_eq!(arp.step, 0);

        // After panic, tick must produce nothing (count == 0)
        let e = arp.tick(SR, &params);
        assert_eq!(e.on, None);
        assert_eq!(e.off, None);
    }
}