tono-core 1.8.0

The pure, headless audio engine behind tono: synthesis-graph DSL, DSP, deterministic renderer, instruments, songs, and analysis — no I/O, no transport.
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
//! catalog — a library of ready-to-play instruments.
//!
//! Each constructor returns a [`Voice`]: a synthesized voice with a tuned
//! envelope, mixer defaults, and voice parameters — no soundfonts, no files,
//! generated entirely from the graph and byte-identical every render. Hand one
//! to [`Song::add`](crate::song::Song::add) and write its notes on the shared
//! beat timeline.
//!
//! ```
//! use tono_core::catalog::{GrandPiano, Bass, Drums, Guitar};
//! use tono_core::song::Song;
//!
//! let doc = Song::new("demo", 120.0)
//!     .add(GrandPiano::grand(), |t| {
//!         t.at(0.0).note("C4", 1.0).at(1.0).note("E4", 1.0)
//!             .at(2.0).chord(&["C4", "E4", "G4"], 2.0);
//!     })
//!     .add(Bass::finger(), |t| {
//!         t.at(0.0).note("C2", 2.0).at(2.0).note("G1", 2.0);
//!     })
//!     .add(Drums::acoustic(), |t| {
//!         t.at(0.0).kick().at(1.0).snare().at(0.5).hat().at(1.5).hat();
//!     })
//!     .to_doc()
//!     .unwrap(); // a normal, deterministic SoundDoc
//! # assert!(matches!(doc.root, tono_core::dsl::Node::Tracks { .. }));
//! ```
//!
//! Variants (`GrandPiano::bright()`, `Guitar::steel()`, `Bass::sub()`, …) are
//! just alternate constructors. Tweak any instrument further with the builder
//! methods: `.gain(..)`, `.pan(..)`, `.named(..)`.

use serde::{Deserialize, Serialize};

use crate::dsl::{Adsr, KitStyle, SeqWave};

/// Extra per-voice synthesis parameters an instrument sets on its `seq`. Only
/// the fields the chosen `wave` reads matter — the rest are ignored (e.g.
/// `pluck_decay` only affects `Guitar`, `fm_*` only the FM voices). `None`
/// leaves the engine default in place.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct VoiceParams {
    /// Square/pulse duty, 0..1 (the `Square` voice).
    pub duty: Option<f32>,
    /// FM modulator/carrier frequency ratio (the FM voices).
    pub fm_ratio: Option<f32>,
    /// FM modulation index at the strike — brightness (the FM voices).
    pub fm_index: Option<f32>,
    /// FM strike decay in seconds — how fast the brightness fades (the FM voices).
    pub fm_strike: Option<f32>,
    /// Karplus-Strong feedback decay, 0.8..1 — string ring time (`Guitar`).
    pub pluck_decay: Option<f32>,
    /// Guitar body-resonance depth, 0..1 (`Guitar`).
    pub pluck_body: Option<f32>,
    /// Guitar pick-attack level, 0..1 (`Guitar`).
    pub pluck_pick: Option<f32>,
    /// Guitar string brightness/damping, −1..1 (`Guitar`).
    pub pluck_tone: Option<f32>,
    /// Piano hammer hardness — spectral brightness (the `Piano` voice, engine ≥ 3).
    pub piano_hammer: Option<f32>,
    /// Piano hammer strike position — the spectral comb notch (`Piano`).
    pub piano_strike: Option<f32>,
    /// Piano string-stiffness scale — inharmonic partial stretch (`Piano`).
    pub piano_inharm: Option<f32>,
    /// Piano unison detune width — the two-string beating (`Piano`).
    pub piano_detune: Option<f32>,
    /// Piano ring-time scale (`Piano`).
    pub piano_decay: Option<f32>,
    /// Drum-kit voicing (the `Kit` voice); `None` = the classic kit.
    pub kit: Option<KitStyle>,
    /// Bass filter floor / sweep / body / sub / drive knobs (the `Bass` voice).
    pub bass_cutoff: Option<f32>,
    /// Bass fixed cutoff-sweep depth above the floor, Hz (`Bass`).
    pub bass_env: Option<f32>,
    /// Bass velocity-scaled sweep depth, Hz (`Bass`).
    pub bass_env_vel: Option<f32>,
    /// Bass filter-sweep time constant, seconds (`Bass`).
    pub bass_decay: Option<f32>,
    /// Bass pick-tick attack bump, Hz (`Bass`).
    pub bass_click: Option<f32>,
    /// Bass filtered-saw body level (`Bass`).
    pub bass_body: Option<f32>,
    /// Bass sine-sub level (`Bass`).
    pub bass_sub: Option<f32>,
    /// Bass sub frequency ratio to the note (`Bass`).
    pub bass_sub_ratio: Option<f32>,
    /// Bass tanh saturation, 0..1 (`Bass`).
    pub bass_drive: Option<f32>,
    /// Bass note body decay, seconds (`Bass`).
    pub bass_body_decay: Option<f32>,
}

/// A ready-to-play song voice: a synth wave plus a tuned envelope, mixer
/// defaults, and [`VoiceParams`]. Build one from the catalog constructors
/// ([`GrandPiano`], [`Bass`], [`Drums`], …) and add it to a
/// [`Song`](crate::song::Song).
///
/// Named `Voice` because the crate has three instrument-shaped layers: this
/// catalog voice (what a song track plays), a preset
/// [`InstrumentDesign`](crate::instrument::InstrumentDesign) (what the live
/// keyboard plays), and the playable
/// [`Instrument`](crate::instrument::Instrument) engine itself.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Voice {
    /// Display name — becomes the song track / rendered layer id.
    pub name: String,
    /// The synthesized voice.
    pub wave: SeqWave,
    /// The per-note amplitude envelope.
    pub env: Adsr,
    /// Channel fader, 0..2 (1 = unity).
    pub gain: f32,
    /// Stereo position, −1 (hard left) .. 1 (hard right).
    pub pan: f32,
    /// Reverb send, 0..1 — wraps the track in a reverb (0 = dry, default).
    pub reverb: f32,
    /// Per-track swing override (0..1); `None` uses the song's swing.
    pub swing: Option<f32>,
    /// Per-track humanize override (0..1); `None` uses the song's humanize.
    pub humanize: Option<f32>,
    /// Voice-specific synthesis parameters.
    pub voice: VoiceParams,
}

/// The old name of [`Voice`] — it collided with the live-playable
/// [`crate::instrument::Instrument`], the crate's other `Instrument`.
/// Deleted at 2.0.
#[deprecated(since = "1.6.0", note = "renamed to `catalog::Voice`")]
pub type Instrument = Voice;

impl Voice {
    /// Rename the instrument (the track / layer id). Handy when a song has two
    /// of the same instrument.
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set the channel fader, 0..2 (1 = unity).
    pub fn gain(mut self, gain: f32) -> Self {
        self.gain = gain;
        self
    }

    /// Set the stereo position, −1 (hard left) .. 1 (hard right).
    pub fn pan(mut self, pan: f32) -> Self {
        self.pan = pan;
        self
    }

    /// Set the reverb send, 0..1 (0 = dry). Wraps this track in a reverb.
    pub fn reverb(mut self, amount: f32) -> Self {
        self.reverb = amount;
        self
    }

    /// Override the song's swing for this track, 0..1.
    pub fn swing(mut self, swing: f32) -> Self {
        self.swing = Some(swing);
        self
    }

    /// Override the song's humanize for this track, 0..1.
    pub fn humanize(mut self, humanize: f32) -> Self {
        self.humanize = Some(humanize);
        self
    }
}

/// A short constructor: an instrument with unity gain, centered, no voice params.
fn voice(name: &str, wave: SeqWave, env: Adsr) -> Voice {
    Voice {
        name: name.to_string(),
        wave,
        env,
        gain: 1.0,
        pan: 0.0,
        reverb: 0.0,
        swing: None,
        humanize: None,
        voice: VoiceParams::default(),
    }
}

/// The piano envelope hint from the `Piano` voice: instant attack, full sustain
/// (the model shapes the natural decay), a short release = the damper falling.
fn piano_env(release: f32) -> Adsr {
    Adsr {
        a: 0.002,
        d: 0.0,
        s: 1.0,
        r: release,
        punch: 0.0,
    }
}

/// The acoustic **grand piano** — an inharmonic additive model (engine 3):
/// stretched partials, each with its own decay (the bright attack mellowing to a
/// warm sustain), a hammer-strike spectrum opened by velocity, over a detuned
/// unison pair. Bass rings for seconds, treble dies fast. The flagship voice;
/// play it like a piano and let `len` (note length) hold the key.
pub struct GrandPiano;

impl GrandPiano {
    /// The concert grand — the reference voice, all tone knobs at default.
    pub fn grand() -> Voice {
        voice("grand piano", SeqWave::Piano, piano_env(0.35))
    }

    /// Hard-voiced and forward — a harder hammer and a higher strike lift the
    /// upper partials; cuts through a busy mix.
    pub fn bright() -> Voice {
        Voice {
            gain: 1.05,
            voice: VoiceParams {
                piano_hammer: Some(1.6),
                piano_strike: Some(0.11),
                piano_decay: Some(1.05),
                ..VoiceParams::default()
            },
            ..voice(
                "bright piano",
                SeqWave::Piano,
                Adsr {
                    punch: 0.15,
                    r: 0.22,
                    ..piano_env(0.22)
                },
            )
        }
    }

    /// Soft-voiced ballad grand — a softer hammer rounds off the top over a long
    /// pedal decay. Warm, but still a full grand.
    pub fn mellow() -> Voice {
        Voice {
            gain: 0.9,
            voice: VoiceParams {
                piano_hammer: Some(0.65),
                piano_strike: Some(0.14),
                piano_decay: Some(1.1),
                ..VoiceParams::default()
            },
            ..voice("mellow piano", SeqWave::Piano, piano_env(0.6))
        }
    }

    /// Intimate felt piano — a blanket over the strings: a very soft hammer
    /// strips the highs to a muffled core, the hammer thump sitting proud.
    pub fn felt() -> Voice {
        Voice {
            gain: 0.85,
            voice: VoiceParams {
                piano_hammer: Some(0.35),
                piano_strike: Some(0.16),
                piano_decay: Some(0.8),
                ..VoiceParams::default()
            },
            ..voice("felt piano", SeqWave::Piano, piano_env(0.5))
        }
    }

    /// Boxy parlour upright — short, stiff strings stretch the partials sharp
    /// (a metallic jangle); slightly hard, dry, no pedal.
    pub fn upright() -> Voice {
        Voice {
            voice: VoiceParams {
                piano_hammer: Some(1.15),
                piano_strike: Some(0.115),
                piano_inharm: Some(1.6),
                piano_detune: Some(1.3),
                piano_decay: Some(0.7),
                ..VoiceParams::default()
            },
            ..voice("upright piano", SeqWave::Piano, piano_env(0.12))
        }
    }

    /// Tack/bar piano — a wide, deliberately out-of-tune unison warble over
    /// short inharmonic strings and a bright tinny attack. Plinky, fast-decaying.
    pub fn honky_tonk() -> Voice {
        Voice {
            voice: VoiceParams {
                piano_hammer: Some(1.5),
                piano_strike: Some(0.11),
                piano_inharm: Some(1.7),
                piano_detune: Some(12.0),
                piano_decay: Some(0.65),
                ..VoiceParams::default()
            },
            ..voice("honky-tonk piano", SeqWave::Piano, piano_env(0.12))
        }
    }
}

/// The **electric piano** — a Rhodes-style tine voice: soft FM body plus a
/// bright tine that pings on the attack and fades. Velocity opens the tine.
pub struct ElectricPiano;

impl ElectricPiano {
    /// Classic Rhodes — warm body, bell-like tine.
    pub fn rhodes() -> Voice {
        voice(
            "electric piano",
            SeqWave::Epiano,
            Adsr {
                a: 0.002,
                d: 0.0,
                s: 0.7,
                r: 0.3,
                punch: 0.0,
            },
        )
    }

    /// Barkier, shorter — a Wurlitzer-ish reed with quicker decay.
    pub fn wurli() -> Voice {
        voice(
            "wurli",
            SeqWave::Epiano,
            Adsr {
                a: 0.002,
                d: 0.0,
                s: 0.55,
                r: 0.18,
                punch: 0.1,
            },
        )
    }

    /// A glassy DX-style FM electric piano — the two-operator FM voice tuned to
    /// a 1:1 ratio with a short bright strike.
    pub fn dx() -> Voice {
        Voice {
            voice: VoiceParams {
                fm_ratio: Some(1.0),
                fm_index: Some(3.5),
                fm_strike: Some(0.4),
                ..VoiceParams::default()
            },
            ..voice(
                "dx piano",
                SeqWave::Fm,
                Adsr {
                    a: 0.002,
                    d: 0.0,
                    s: 0.6,
                    r: 0.3,
                    punch: 0.0,
                },
            )
        }
    }
}

/// The **organ** — a tonewheel drawbar voice that sustains at full level while
/// the key is held; `len` does the phrasing.
pub struct Organ;

impl Organ {
    /// Full drawbars, gentle key-click percussion.
    pub fn tonewheel() -> Voice {
        voice(
            "organ",
            SeqWave::Organ,
            Adsr {
                a: 0.005,
                d: 0.0,
                s: 1.0,
                r: 0.08,
                punch: 0.0,
            },
        )
    }

    /// Punchier attack for rock stabs.
    pub fn rock() -> Voice {
        voice(
            "rock organ",
            SeqWave::Organ,
            Adsr {
                a: 0.002,
                d: 0.0,
                s: 1.0,
                r: 0.05,
                punch: 0.2,
            },
        )
        .gain(1.05)
    }
}

/// The **string ensemble** — three detuned band-limited saws per note with a
/// slow bow swell. Notes bloom ~150 ms after the attack, so write them slightly
/// early.
pub struct Strings;

impl Strings {
    /// A balanced ensemble swell — pads, sustained chords.
    pub fn ensemble() -> Voice {
        voice(
            "strings",
            SeqWave::Strings,
            Adsr {
                a: 0.15,
                d: 0.0,
                s: 1.0,
                r: 0.4,
                punch: 0.0,
            },
        )
    }

    /// Warmer and slower — a longer swell and tail for cinematic beds.
    pub fn warm() -> Voice {
        voice(
            "warm strings",
            SeqWave::Strings,
            Adsr {
                a: 0.3,
                d: 0.0,
                s: 1.0,
                r: 0.7,
                punch: 0.0,
            },
        )
        .gain(0.95)
    }
}

/// The **bass** — the low end. Variants trade the voice under the hood.
pub struct Bass;

impl Bass {
    /// Fingered electric bass — a filtered saw whose cutoff snaps with velocity
    /// over a solid sine sub. Punchy, dark, sits under the mix.
    pub fn finger() -> Voice {
        voice(
            "bass",
            SeqWave::Bass,
            Adsr {
                a: 0.005,
                d: 0.1,
                s: 0.9,
                r: 0.12,
                punch: 0.0,
            },
        )
    }

    /// Picked — a bright plectrum tick, a fast-closing filter, a touch of grit.
    pub fn pick() -> Voice {
        Voice {
            voice: VoiceParams {
                bass_cutoff: Some(300.0),
                bass_env: Some(800.0),
                bass_env_vel: Some(1200.0),
                bass_decay: Some(0.08),
                bass_click: Some(2500.0),
                bass_body: Some(0.75),
                bass_sub: Some(0.40),
                bass_sub_ratio: Some(1.0),
                bass_drive: Some(0.05),
                bass_body_decay: Some(1.6),
                ..VoiceParams::default()
            },
            ..voice(
                "pick bass",
                SeqWave::Bass,
                Adsr {
                    a: 0.002,
                    d: 0.08,
                    s: 0.85,
                    r: 0.08,
                    punch: 0.25,
                },
            )
        }
    }

    /// A pure **sub** bass — a deep sine with a whisper of body so it still
    /// translates on small speakers; long hold, felt more than heard.
    pub fn sub() -> Voice {
        Voice {
            voice: VoiceParams {
                bass_cutoff: Some(100.0),
                bass_env: Some(150.0),
                bass_env_vel: Some(200.0),
                bass_decay: Some(0.25),
                bass_click: Some(0.0),
                bass_body: Some(0.22),
                bass_sub: Some(0.95),
                bass_sub_ratio: Some(1.0),
                bass_drive: Some(0.0),
                bass_body_decay: Some(4.0),
                ..VoiceParams::default()
            },
            ..voice(
                "sub bass",
                SeqWave::Bass,
                Adsr {
                    a: 0.005,
                    d: 0.0,
                    s: 1.0,
                    r: 0.1,
                    punch: 0.0,
                },
            )
        }
    }

    /// A bright, wide, tanh-driven synth bass over a fat octave-down sub — the
    /// modern electronic/EDM voice.
    pub fn synth() -> Voice {
        Voice {
            voice: VoiceParams {
                bass_cutoff: Some(600.0),
                bass_env: Some(1500.0),
                bass_env_vel: Some(800.0),
                bass_decay: Some(0.25),
                bass_click: Some(0.0),
                bass_body: Some(0.85),
                bass_sub: Some(0.35),
                bass_sub_ratio: Some(0.5),
                bass_drive: Some(0.35),
                bass_body_decay: Some(6.0),
                ..VoiceParams::default()
            },
            ..voice(
                "synth bass",
                SeqWave::Bass,
                Adsr {
                    a: 0.003,
                    d: 0.06,
                    s: 0.8,
                    r: 0.08,
                    punch: 0.1,
                },
            )
        }
    }
}

/// The **guitar** — a Karplus-Strong plucked string: a noise burst rings
/// through a tuned feedback loop. `pluck_decay` sets how long it rings, which is
/// what separates the variants (nylon is warm and short, steel bright, electric
/// sustains).
pub struct Guitar;

impl Guitar {
    /// Nylon-string — warm and short: a dark loop, a big woody body, barely any
    /// pick attack. A soft fingerpicked classical tone.
    pub fn nylon() -> Voice {
        Voice {
            voice: VoiceParams {
                pluck_decay: Some(0.90),
                pluck_tone: Some(-0.35),
                pluck_body: Some(0.55),
                pluck_pick: Some(0.05),
                ..VoiceParams::default()
            },
            ..voice("nylon guitar", SeqWave::Pluck, pluck_env(0.25))
        }
    }

    /// Steel-string acoustic — a sizzly bright loop, a present body, a clear pick
    /// attack. Longer-ringing.
    pub fn steel() -> Voice {
        Voice {
            voice: VoiceParams {
                pluck_decay: Some(0.965),
                pluck_tone: Some(0.30),
                pluck_body: Some(0.45),
                pluck_pick: Some(0.30),
                ..VoiceParams::default()
            },
            ..voice("steel guitar", SeqWave::Pluck, pluck_env(0.35))
        }
    }

    /// Electric — the brightest loop, no acoustic body, a pick click, long clean
    /// sustain. The solid-body pickup tone.
    pub fn electric() -> Voice {
        Voice {
            voice: VoiceParams {
                pluck_decay: Some(0.99),
                pluck_tone: Some(0.45),
                pluck_pick: Some(0.25),
                ..VoiceParams::default() // pluck_body None ⇒ 0.0 = solid body
            },
            ..voice("electric guitar", SeqWave::Pluck, pluck_env(0.5))
        }
    }
}

/// The pluck envelope: near-instant attack, full sustain (the string decays on
/// its own via feedback), a short release when the note ends.
fn pluck_env(release: f32) -> Adsr {
    Adsr {
        a: 0.001,
        d: 0.0,
        s: 1.0,
        r: release,
        punch: 0.0,
    }
}

/// The **drum kit** — the General MIDI drum map. Hit drums by name from the
/// track writer (`.kick()`, `.snare()`, `.hat()`, …) or by GM note.
pub struct Drums;

impl Drums {
    /// A deeper, more realistic acoustic kit — the go-to.
    pub fn acoustic() -> Voice {
        drum_kit("drums", KitStyle::Acoustic)
    }

    /// The original synthesized GM kit (byte-frozen).
    pub fn classic() -> Voice {
        // Built directly (not via drum_kit): the classic kit ships NO kit key,
        // keeping old documents byte-frozen.
        voice("classic drums", SeqWave::Kit, drum_env())
    }

    /// Clean synthesized electronic drums — tight, punchy, crisp.
    pub fn electronic() -> Voice {
        drum_kit("electronic drums", KitStyle::Electronic)
    }

    /// Roland TR-808 style — a long booming sub kick and ringy cowbell.
    pub fn tr808() -> Voice {
        drum_kit("808 drums", KitStyle::Eight08)
    }
}

/// The shared kit envelope (instant attack, full sustain, short release).
fn drum_env() -> Adsr {
    Adsr {
        a: 0.001,
        d: 0.0,
        s: 1.0,
        r: 0.05,
        punch: 0.0,
    }
}

/// A drum kit on the GM map with the given [`KitStyle`].
fn drum_kit(name: &str, style: KitStyle) -> Voice {
    Voice {
        voice: VoiceParams {
            kit: Some(style),
            ..VoiceParams::default()
        },
        ..voice(name, SeqWave::Kit, drum_env())
    }
}

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

    #[test]
    fn every_constructor_builds_a_distinct_named_instrument() {
        let all = [
            GrandPiano::grand(),
            GrandPiano::bright(),
            GrandPiano::mellow(),
            GrandPiano::felt(),
            GrandPiano::upright(),
            GrandPiano::honky_tonk(),
            ElectricPiano::rhodes(),
            ElectricPiano::wurli(),
            ElectricPiano::dx(),
            Organ::tonewheel(),
            Organ::rock(),
            Strings::ensemble(),
            Strings::warm(),
            Bass::finger(),
            Bass::pick(),
            Bass::sub(),
            Bass::synth(),
            Guitar::nylon(),
            Guitar::steel(),
            Guitar::electric(),
            Drums::acoustic(),
            Drums::classic(),
            Drums::electronic(),
            Drums::tr808(),
        ];
        for i in &all {
            assert!(!i.name.is_empty());
            assert!(i.gain > 0.0);
        }
    }

    #[test]
    fn grand_is_the_default_voice_and_variants_set_tone_knobs() {
        // The flagship grand leaves every knob at default (byte-identical to the
        // bare engine-3 piano); the variants each set a distinct spectrum.
        assert_eq!(GrandPiano::grand().voice, VoiceParams::default());
        assert_eq!(GrandPiano::bright().voice.piano_hammer, Some(1.6));
        assert!(
            GrandPiano::felt().voice.piano_hammer.unwrap() < 0.5,
            "felt is soft"
        );
        assert_eq!(GrandPiano::honky_tonk().voice.piano_detune, Some(12.0));
        assert_eq!(GrandPiano::upright().voice.piano_inharm, Some(1.6));
    }

    #[test]
    fn bass_variants_set_tone_and_finger_is_the_default_voice() {
        assert_eq!(Bass::finger().voice, VoiceParams::default());
        assert_eq!(Bass::pick().voice.bass_click, Some(2500.0)); // plectrum tick
        assert_eq!(Bass::synth().voice.bass_sub_ratio, Some(0.5)); // octave-down sub
        assert_eq!(Bass::sub().wave, SeqWave::Bass); // sub now uses the Bass voice
    }

    #[test]
    fn guitar_variants_set_body_and_tone() {
        assert_eq!(Guitar::nylon().voice.pluck_body, Some(0.55));
        assert!(
            Guitar::nylon().voice.pluck_tone.unwrap() < 0.0,
            "nylon is dark"
        );
        assert!(
            Guitar::steel().voice.pluck_tone.unwrap() > 0.0,
            "steel is bright"
        );
        assert_eq!(
            Guitar::electric().voice.pluck_body,
            None,
            "electric = solid body"
        );
    }

    #[test]
    fn guitar_variants_differ_in_ring_time() {
        let n = Guitar::nylon().voice.pluck_decay.unwrap();
        let s = Guitar::steel().voice.pluck_decay.unwrap();
        let e = Guitar::electric().voice.pluck_decay.unwrap();
        assert!(n < s && s < e, "nylon rings shortest, electric longest");
    }

    #[test]
    fn builder_methods_override_defaults() {
        let i = Bass::finger().named("low end").gain(0.8).pan(-0.3);
        assert_eq!(i.name, "low end");
        assert_eq!(i.gain, 0.8);
        assert_eq!(i.pan, -0.3);
    }

    #[test]
    fn round_trips_through_serde() {
        let i = Guitar::steel();
        let json = serde_json::to_string(&i).unwrap();
        let back: Voice = serde_json::from_str(&json).unwrap();
        assert_eq!(i, back);
    }
}