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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! Core parameter and event types shared between the UI thread and audio thread.
//!
//! `SynthParams` is the canonical parameter snapshot.  The UI holds a live copy
//! and sends a boxed clone to the audio thread via `AudioEvent::LoadPatch`
//! whenever a value changes.

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Oscillator waveform shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Waveform {
    /// Classic square/pulse wave; width controlled by `pulse_width`.
    Pulse,
    /// Band-limited sawtooth.
    Sawtooth,
    /// Triangle wave.
    Triangle,
    /// LFSR-based noise clocked at the oscillator period.
    Noise,
    /// 50/50 mix of pulse and sawtooth for a thicker timbre.
    PulseSaw,
    /// Pure sine wave.
    Sine,
}

impl Waveform {
    /// Ordered slice of all variants, used for cycling.
    pub const ALL: &'static [Waveform] = &[
        Waveform::Pulse,
        Waveform::Sawtooth,
        Waveform::Triangle,
        Waveform::Noise,
        Waveform::PulseSaw,
        Waveform::Sine,
    ];

    /// Short display name shown in the UI.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Waveform::Pulse => "Pulse",
            Waveform::Sawtooth => "Saw",
            Waveform::Triangle => "Tri",
            Waveform::Noise => "Noise",
            Waveform::PulseSaw => "Pls+Saw",
            Waveform::Sine => "Sine",
        }
    }

    /// Return the next variant, wrapping around.
    #[must_use]
    pub fn next(self) -> Self {
        let idx = Self::ALL.iter().position(|&w| w == self).unwrap_or(0);
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }

    /// Return the previous variant, wrapping around.
    #[must_use]
    pub fn prev(self) -> Self {
        let idx = Self::ALL.iter().position(|&w| w == self).unwrap_or(0);
        let len = Self::ALL.len();
        Self::ALL[(idx + len - 1) % len]
    }
}

/// Arpeggiator playback mode.
#[cfg(feature = "arp")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ArpMode {
    /// Play notes in ascending order, then wrap to the lowest.
    #[default]
    Up,
    /// Play notes in descending order, then wrap to the highest.
    Down,
    /// Ascend to the highest note, then descend to the lowest (no endpoint repeat).
    UpDown,
    /// Advance using a Galois LFSR, producing a pseudo-random sequence with a long period.
    Random,
}

/// Arpeggiator section parameters.
#[cfg(feature = "arp")]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ArpParams {
    /// Whether the arpeggiator is active on this channel.
    pub enabled: bool,
    /// Step rate in Hz (e.g. `10.0` = 10 notes per second).
    pub rate: f32,
    /// Gate length as a fraction of the step duration, `0.0..=1.0`.
    /// At `0.0` the note is released immediately; at `1.0` it rings until the next step.
    pub gate: f32,
    /// Playback mode.
    pub mode: ArpMode,
    /// Fixed-size note list. Only entries `0..count` are active.
    pub notes: [MidiNote; 4],
    /// Number of active entries in `notes`, `0..=4`.
    pub count: u8,
}

#[cfg(feature = "arp")]
impl Default for ArpParams {
    fn default() -> Self {
        Self {
            enabled: false,
            rate: 10.0,
            gate: 0.8,
            mode: ArpMode::Up,
            notes: [MidiNote::MIDDLE_C; 4],
            count: 0,
        }
    }
}

/// State-variable filter topology selector.
#[allow(clippy::enum_variant_names)] // LP/BP/HP suffix is standard audio industry terminology
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum FilterMode {
    /// Low-pass output.
    LowPass,
    /// Band-pass output.
    BandPass,
    /// High-pass output.
    HighPass,
}

impl FilterMode {
    /// Ordered slice of all variants, used for cycling.
    pub const ALL: &'static [FilterMode] = &[
        FilterMode::LowPass,
        FilterMode::BandPass,
        FilterMode::HighPass,
    ];

    /// Short display name shown in the UI.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            FilterMode::LowPass => "LP",
            FilterMode::BandPass => "BP",
            FilterMode::HighPass => "HP",
        }
    }

    /// Return the next variant, wrapping around.
    #[must_use]
    pub fn next(self) -> Self {
        let idx = Self::ALL.iter().position(|&m| m == self).unwrap_or(0);
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }
}

/// Selects which parameter the LFO modulates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LfoTarget {
    /// Pitch modulation (vibrato).
    Pitch,
    /// Pulse-width modulation.
    PulseWidth,
    /// Filter cutoff modulation.
    Cutoff,
    /// Amplitude modulation (tremolo).
    Volume,
}

impl LfoTarget {
    /// Ordered slice of all variants, used for cycling.
    pub const ALL: &'static [LfoTarget] = &[
        LfoTarget::Pitch,
        LfoTarget::PulseWidth,
        LfoTarget::Cutoff,
        LfoTarget::Volume,
    ];

    /// Short display name shown in the UI.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            LfoTarget::Pitch => "Pitch",
            LfoTarget::PulseWidth => "PW",
            LfoTarget::Cutoff => "Cutoff",
            LfoTarget::Volume => "Volume",
        }
    }

    /// Return the next variant, wrapping around.
    #[must_use]
    pub fn next(self) -> Self {
        let idx = Self::ALL.iter().position(|&t| t == self).unwrap_or(0);
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }

    /// Return the previous variant, wrapping around.
    #[must_use]
    pub fn prev(self) -> Self {
        let idx = Self::ALL.iter().position(|&t| t == self).unwrap_or(0);
        let len = Self::ALL.len();
        Self::ALL[(idx + len - 1) % len]
    }
}

/// Oscillator section parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OscParams {
    /// Active waveform shape.
    pub waveform: Waveform,
    /// Pulse width, 0.05 .. 0.95.
    pub pulse_width: f32,
    /// Detune in cents, −100 .. 100.
    pub detune: f32,
    /// Noise blend amount, 0 .. 1.
    pub noise_mix: f32,
}

/// Ring modulation mode between OSC1 and OSC2.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum RingModMode {
    /// No ring modulation (bypass). Default.
    #[default]
    Off,
    /// SID-style: OSC2 output multiplied by sign of OSC1 phase accumulator MSB.
    Osc2ByOsc1Sign,
    /// Reverse SID: OSC1 output multiplied by sign of OSC2 phase accumulator MSB.
    Osc1ByOsc2Sign,
    /// True analog ring mod: OSC1 × OSC2, produces sum/difference frequencies.
    Analog,
}

impl RingModMode {
    /// Ordered slice of all variants, used for cycling.
    pub const ALL: &'static [RingModMode] = &[
        RingModMode::Off,
        RingModMode::Osc2ByOsc1Sign,
        RingModMode::Osc1ByOsc2Sign,
        RingModMode::Analog,
    ];

    /// Short display name shown in the UI.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            RingModMode::Off => "Off",
            RingModMode::Osc2ByOsc1Sign => "SID",
            RingModMode::Osc1ByOsc2Sign => "Rev",
            RingModMode::Analog => "Analog",
        }
    }

    /// Return the next variant, wrapping around.
    #[must_use]
    pub fn next(self) -> Self {
        let idx = Self::ALL.iter().position(|&m| m == self).unwrap_or(0);
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }

    /// Return the previous variant, wrapping around.
    #[must_use]
    pub fn prev(self) -> Self {
        let idx = Self::ALL.iter().position(|&m| m == self).unwrap_or(0);
        let len = Self::ALL.len();
        Self::ALL[(idx + len - 1) % len]
    }
}

/// Second oscillator section parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Osc2Params {
    /// Waveform shape for the second oscillator.
    pub waveform: Waveform,
    /// Detune relative to OSC1 in cents, -100 .. 100.
    pub detune: f32,
    /// Blend of OSC2 into the output, 0..1.  At 0.0 OSC2 is bypassed.
    pub osc2_mix: f32,
    /// When true, OSC1 period boundary resets OSC2 phase (hard sync).
    pub hard_sync: bool,
    /// Ring modulation mode applied to the OSC2 contribution.
    #[cfg_attr(feature = "serde", serde(default))]
    pub ring_mod: RingModMode,
}

impl Default for Osc2Params {
    fn default() -> Self {
        Self {
            waveform: Waveform::Sawtooth,
            detune: 7.0,
            osc2_mix: 0.0,
            hard_sync: false,
            ring_mod: RingModMode::Off,
        }
    }
}

/// Amplitude envelope section parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EnvParams {
    /// Attack time in seconds.
    pub attack: f32,
    /// Decay time in seconds.
    pub decay: f32,
    /// Sustain level, 0 .. 1.
    pub sustain: f32,
    /// Release time in seconds.
    pub release: f32,
    /// When true, the envelope output is inverted (swell / duck effect).
    pub env_reverse: bool,
}

/// Filter section parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FilterParams {
    /// Filter topology (LP / BP / HP).
    pub filter_mode: FilterMode,
    /// Cutoff frequency in Hz, 20 .. 18000.
    pub cutoff: f32,
    /// Resonance, 0 .. 0.99.
    pub resonance: f32,
    /// Pre-filter drive amount, 0 .. 1.
    pub drive: f32,
}

/// Waveform shape for LFOs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LfoShape {
    /// Sine wave (smooth, classic vibrato/tremolo).
    #[default]
    Sine,
    /// Hard square wave; instant +1/-1 transitions.
    Square,
    /// Rising sawtooth; linear ramp from -1 to +1.
    Sawtooth,
    /// Sample-and-hold: random step value held until next period boundary.
    SampleHold,
}

impl LfoShape {
    /// Ordered slice of all variants, used for cycling.
    pub const ALL: &'static [LfoShape] = &[
        LfoShape::Sine,
        LfoShape::Square,
        LfoShape::Sawtooth,
        LfoShape::SampleHold,
    ];

    /// Short display name shown in the UI.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            LfoShape::Sine => "Sin",
            LfoShape::Square => "Sqr",
            LfoShape::Sawtooth => "Saw",
            LfoShape::SampleHold => "S&H",
        }
    }

    /// Return the next variant, wrapping around.
    #[must_use]
    pub fn next(self) -> Self {
        let idx = Self::ALL.iter().position(|&s| s == self).unwrap_or(0);
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }

    /// Return the previous variant, wrapping around.
    #[must_use]
    pub fn prev(self) -> Self {
        let idx = Self::ALL.iter().position(|&s| s == self).unwrap_or(0);
        Self::ALL[(idx + Self::ALL.len() - 1) % Self::ALL.len()]
    }
}

/// LFO section parameters.
#[allow(clippy::struct_field_names)] // `lfo_` prefix is intentional for clarity in a flat params struct
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LfoParams {
    /// LFO rate in Hz.
    pub lfo_rate: f32,
    /// LFO modulation depth, 0 .. 1.
    pub lfo_depth: f32,
    /// Which parameter the LFO modulates.
    pub lfo_target: LfoTarget,
    /// LFO waveform shape.
    #[cfg_attr(feature = "serde", serde(default))]
    pub lfo_shape: LfoShape,
}

impl Default for LfoParams {
    fn default() -> Self {
        Self {
            lfo_rate: 3.0,
            lfo_depth: 0.0,
            lfo_target: LfoTarget::Pitch,
            lfo_shape: LfoShape::Sine,
        }
    }
}

/// Modulation envelope parameters (filter cutoff or pitch target).
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ModEnvParams {
    /// Attack time in seconds.
    pub attack: f32,
    /// Decay time in seconds.
    pub decay: f32,
    /// Sustain level, 0 .. 1.
    pub sustain: f32,
    /// Release time in seconds.
    pub release: f32,
    /// Modulation depth, -1 .. 1.  At 0.0 the envelope has no effect.
    /// For pitch: +-1 maps to approximately +-1 octave sweep.
    /// For filter cutoff: +-1 maps to approximately +-2 octaves of cutoff.
    pub depth: f32,
}

impl Default for ModEnvParams {
    fn default() -> Self {
        Self {
            attack: 0.001,
            decay: 0.1,
            sustain: 0.0,
            release: 0.1,
            depth: 0.0,
        }
    }
}

/// FX section parameters.
#[allow(clippy::struct_field_names)] // reverb_ prefix is intentional; struct may gain non-reverb fields
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FxParams {
    /// Reverb wet/dry mix, 0 .. 1.
    pub reverb_mix: f32,
    /// Reverb room size, 0 .. 1.
    pub reverb_size: f32,
    /// Reverb high-frequency damping, 0 .. 1.
    pub reverb_damping: f32,
}

/// Bitcrusher section parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CrusherParams {
    /// Bit depth: 1.0..=16.0. At 16.0 with `rate` 1.0, the DSP path is bypassed entirely (exact pass-through).
    pub bits: f32,
    /// Sample rate divider: 1.0..=16.0. At 1.0 with `bits` 16.0, the DSP path is bypassed entirely (exact pass-through).
    pub rate: f32,
}

impl Default for CrusherParams {
    fn default() -> Self {
        Self {
            bits: 16.0,
            rate: 1.0,
        }
    }
}

/// Delay/echo FX parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DelayParams {
    /// Delay time in ms, 1.0..=2000.0.
    pub time_ms: f32,
    /// Feedback gain, 0.0..=0.95.
    pub feedback: f32,
    /// Wet/dry mix, 0.0..=1.0.
    pub mix: f32,
}

impl Default for DelayParams {
    fn default() -> Self {
        Self {
            time_ms: 375.0,
            feedback: 0.3,
            mix: 0.0,
        }
    }
}

/// Chorus FX parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ChorusParams {
    /// LFO modulation rate in Hz, 0.1..=5.0.
    pub rate: f32,
    /// Modulation depth (half-swing around 15 ms center), 0.0..=10.0 ms.
    pub depth_ms: f32,
    /// Wet/dry mix, 0.0..=1.0.
    pub mix: f32,
}

impl Default for ChorusParams {
    fn default() -> Self {
        Self {
            rate: 0.5,
            depth_ms: 3.0,
            mix: 0.0,
        }
    }
}

/// Global section parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GlobalParams {
    /// Master output volume, 0 .. 1.
    pub volume: f32,
    /// Portamento (glide) time in seconds.
    pub glide_time: f32,
}

/// Full parameter snapshot shared between the UI and audio threads.
///
/// The UI owns the authoritative copy; the audio thread receives a boxed clone
/// via `AudioEvent::LoadPatch` on every user edit.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SynthParams {
    /// Oscillator parameters.
    pub osc: OscParams,
    /// Amplitude envelope parameters.
    pub env: EnvParams,
    /// Filter parameters.
    pub filter: FilterParams,
    /// LFO parameters.
    pub lfo: LfoParams,
    /// FX parameters.
    pub fx: FxParams,
    /// Bitcrusher parameters.
    #[cfg_attr(feature = "serde", serde(default))]
    pub crusher: CrusherParams,
    /// Chorus FX parameters.
    #[cfg_attr(feature = "serde", serde(default))]
    pub chorus: ChorusParams,
    /// Delay/echo FX parameters.
    #[cfg_attr(feature = "serde", serde(default))]
    pub delay: DelayParams,
    /// Second oscillator parameters.
    #[cfg_attr(feature = "serde", serde(default))]
    pub osc2: Osc2Params,
    /// Second LFO parameters.
    #[cfg_attr(feature = "serde", serde(default))]
    pub lfo2: LfoParams,
    /// Modulation envelope routed to filter cutoff.
    #[cfg_attr(feature = "serde", serde(default))]
    pub filter_env: ModEnvParams,
    /// Modulation envelope routed to oscillator pitch.
    #[cfg_attr(feature = "serde", serde(default))]
    pub pitch_env: ModEnvParams,
    /// Arpeggiator parameters.
    #[cfg(feature = "arp")]
    #[cfg_attr(feature = "serde", serde(default))]
    pub arp: ArpParams,
    /// Global parameters.
    pub global: GlobalParams,
}

impl Default for SynthParams {
    /// Sensible starting patch: medium pulse wave, gentle filter, light reverb.
    fn default() -> Self {
        Self {
            osc: OscParams {
                waveform: Waveform::Pulse,
                pulse_width: 0.5,
                detune: 0.0,
                noise_mix: 0.0,
            },
            env: EnvParams {
                attack: 0.01,
                decay: 0.1,
                sustain: 0.8,
                release: 0.3,
                env_reverse: false,
            },
            filter: FilterParams {
                filter_mode: FilterMode::LowPass,
                cutoff: 4000.0,
                resonance: 0.3,
                drive: 0.0,
            },
            lfo: LfoParams {
                lfo_rate: 3.0,
                lfo_depth: 0.0,
                lfo_target: LfoTarget::Pitch,
                lfo_shape: LfoShape::Sine,
            },
            fx: FxParams {
                reverb_mix: 0.15,
                reverb_size: 0.5,
                reverb_damping: 0.5,
            },
            crusher: CrusherParams::default(),
            chorus: ChorusParams::default(),
            delay: DelayParams::default(),
            osc2: Osc2Params::default(),
            lfo2: LfoParams::default(),
            filter_env: ModEnvParams::default(),
            pitch_env: ModEnvParams::default(),
            #[cfg(feature = "arp")]
            arp: ArpParams::default(),
            global: GlobalParams {
                volume: 0.7,
                glide_time: 0.05,
            },
        }
    }
}

/// A named preset: a display name paired with a full parameter snapshot.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Patch {
    /// Human-readable patch name shown in the preset list.
    pub name: String,
    /// Parameter values for this patch.
    pub params: SynthParams,
}

impl Patch {
    /// Construct a new patch from a name and a parameter snapshot.
    pub fn new(name: impl Into<String>, params: SynthParams) -> Self {
        Self {
            name: name.into(),
            params,
        }
    }
}

/// A typed wrapper around a MIDI note byte.
///
/// The inner `u8` field is public for ergonomic construction with numeric
/// literals (`MidiNote(60)`).  No range check is performed; the MIDI spec
/// defines valid values as 0..=127, but values up to 255 are accepted.
/// Use [`MidiNote::new_clamped`] when constructing from untrusted input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MidiNote(pub u8);

impl MidiNote {
    /// Middle C (C4).
    pub const MIDDLE_C: Self = Self(60);
    /// A4 (440 Hz reference pitch).
    pub const A4: Self = Self(69);

    /// Clamp `v` to 0..=127 and wrap in `MidiNote`.
    #[must_use]
    pub const fn new_clamped(v: u8) -> Self {
        Self(if v > 127 { 127 } else { v })
    }

    /// Raw MIDI byte value.
    #[must_use]
    pub const fn as_u8(self) -> u8 {
        self.0
    }
}

impl From<u8> for MidiNote {
    fn from(v: u8) -> Self {
        Self(v)
    }
}

impl Default for MidiNote {
    fn default() -> Self {
        Self::MIDDLE_C
    }
}

/// Index of an independent synthesis channel (voice pool + parameter set).
///
/// Channel 0 is the default; `NoteOn` / `LoadPatch` without a channel argument
/// implicitly target it.  Values beyond the engine's `NUM_CHANNELS` limit are
/// silently ignored.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ChannelNo(pub u8);

impl ChannelNo {
    /// The implicit default channel used by the channel-less event variants.
    pub const DEFAULT: Self = Self(0);

    /// Convert to `usize` for array indexing.
    #[must_use]
    pub const fn as_usize(self) -> usize {
        self.0 as usize
    }
}

impl From<u8> for ChannelNo {
    fn from(v: u8) -> Self {
        Self(v)
    }
}

impl Default for ChannelNo {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Drum one-shot events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DrumHit {
    /// Trigger a synthesized kick drum hit.
    Kick,
    /// Trigger a short, bright closed hi-hat hit.
    HiHatClosed,
    /// Trigger a longer, ringing open hi-hat hit.
    HiHatOpen,
}

#[cfg(all(test, feature = "serde"))]
mod tests {
    use super::*;

    #[test]
    fn synth_params_osc2_defaults_when_missing_from_json() {
        // JSON from before `osc2` was added: the field should deserialise to
        // `Osc2Params::default()` rather than failing or panicking.
        let json = r#"{
            "osc":    {"waveform":"Sawtooth","pulse_width":0.5,"detune":0.0,"noise_mix":0.0},
            "env":    {"attack":0.01,"decay":0.1,"sustain":0.8,"release":0.3,"env_reverse":false},
            "filter": {"filter_mode":"LowPass","cutoff":4000.0,"resonance":0.3,"drive":0.0},
            "lfo":    {"lfo_rate":3.0,"lfo_depth":0.0,"lfo_target":"Pitch"},
            "fx":     {"reverb_mix":0.15,"reverb_size":0.5,"reverb_damping":0.5},
            "global": {"volume":0.7,"glide_time":0.05}
        }"#;

        let params: SynthParams =
            serde_json::from_str(json).expect("old-style JSON must deserialise without osc2 key");

        let def = Osc2Params::default();
        assert_eq!(params.osc2.waveform, def.waveform);
        assert!((params.osc2.detune - def.detune).abs() < f32::EPSILON);
        assert!((params.osc2.osc2_mix - def.osc2_mix).abs() < f32::EPSILON);
        assert_eq!(params.osc2.hard_sync, def.hard_sync);
        assert_eq!(params.osc2.ring_mod, def.ring_mod);
    }

    #[test]
    fn synth_params_mod_fields_default_when_missing_from_json() {
        let json = r#"{
            "osc":    {"waveform":"Sawtooth","pulse_width":0.5,"detune":0.0,"noise_mix":0.0},
            "env":    {"attack":0.01,"decay":0.1,"sustain":0.8,"release":0.3,"env_reverse":false},
            "filter": {"filter_mode":"LowPass","cutoff":4000.0,"resonance":0.3,"drive":0.0},
            "lfo":    {"lfo_rate":3.0,"lfo_depth":0.0,"lfo_target":"Pitch"},
            "fx":     {"reverb_mix":0.15,"reverb_size":0.5,"reverb_damping":0.5},
            "global": {"volume":0.7,"glide_time":0.05}
        }"#;

        let params: SynthParams =
            serde_json::from_str(json).expect("old JSON must deserialise without mod fields");

        assert_eq!(params.lfo.lfo_shape, LfoShape::Sine);
        assert_eq!(params.lfo2.lfo_shape, LfoShape::Sine);
        assert!((params.lfo2.lfo_depth).abs() < f32::EPSILON);
        assert!((params.filter_env.depth).abs() < f32::EPSILON);
        assert!((params.pitch_env.depth).abs() < f32::EPSILON);
    }

    #[cfg(feature = "arp")]
    #[test]
    fn synth_params_arp_defaults_when_missing_from_json() {
        let json = r#"{
            "osc":    {"waveform":"Sawtooth","pulse_width":0.5,"detune":0.0,"noise_mix":0.0},
            "env":    {"attack":0.01,"decay":0.1,"sustain":0.8,"release":0.3,"env_reverse":false},
            "filter": {"filter_mode":"LowPass","cutoff":4000.0,"resonance":0.3,"drive":0.0},
            "lfo":    {"lfo_rate":3.0,"lfo_depth":0.0,"lfo_target":"Pitch"},
            "fx":     {"reverb_mix":0.15,"reverb_size":0.5,"reverb_damping":0.5},
            "global": {"volume":0.7,"glide_time":0.05}
        }"#;
        let params: SynthParams =
            serde_json::from_str(json).expect("old JSON must deserialise without arp key");
        assert!(!params.arp.enabled);
        assert!((params.arp.rate - 10.0).abs() < f32::EPSILON);
        assert_eq!(params.arp.count, 0);
    }
}

/// Messages sent from the UI thread to the audio thread over the event channel.
#[derive(Default, Debug, Clone)]
pub enum AudioEvent {
    /// Immediately silence all voices and clear active note routing on all channels.
    #[default]
    Panic,
    /// Begin sustaining a note at the given MIDI note number on channel 0.
    NoteOn(MidiNote),
    /// Release the note at the given MIDI note number on channel 0.
    NoteOff(MidiNote),
    /// Replace the parameter set for channel 0 with a new snapshot.
    LoadPatch(Box<SynthParams>),
    /// Trigger a one-shot synthesized drum hit.
    Drum(DrumHit),
    /// Begin sustaining a note on the given channel at the given MIDI note number.
    NoteOnChannel(ChannelNo, MidiNote),
    /// Release the note on the given channel at the given MIDI note number.
    NoteOffChannel(ChannelNo, MidiNote),
    /// Replace the parameter set for the given channel with a new snapshot.
    LoadPatchChannel(ChannelNo, Box<SynthParams>),
    /// Load an explicit note list into the arpeggiator on the given channel.
    /// Only entries `0..count` of `notes` are used; `count` must be `<= 4`.
    #[cfg(feature = "arp")]
    ArpSetNotes(ChannelNo, [MidiNote; 4], u8),
    /// Enable or disable the arpeggiator on the given channel at runtime.
    #[cfg(feature = "arp")]
    ArpEnabled(ChannelNo, bool),
}