tono-core 1.10.1

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
//! presets — a factory bank of ready-to-play instruments.
//!
//! Each [`Preset`] is a named [`InstrumentDesign`] authored over the same graph
//! vocabulary you'd write by hand, so it plays out of the box and is a worked
//! example of the instrument controls (mono/legato, glide, unison, velocity,
//! a shared master). Look them up by [`preset`] or iterate [`PRESETS`]:
//!
//! ```
//! use tono_core::instrument::Instrument;
//! use tono_core::presets;
//!
//! let design = presets::preset("warm_lead").unwrap();
//! let mut inst = Instrument::new(design, 48_000).unwrap();
//! inst.note_on(tono_core::instrument::Note::C4, 0.9);
//! ```

use serde::{Deserialize, Serialize};

use crate::dsl::Adsr;
use crate::instrument::{InstrumentDesign, PlayMode};
use crate::patch::Patch;

/// What a preset is for — a coarse grouping for browsing.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Category {
    /// Cutting melodic leads.
    Lead,
    /// Low-end foundations.
    Bass,
    /// Sustained atmospheric beds.
    Pad,
    /// Piano-like struck voices.
    Keys,
    /// Short plucked/percussive tones.
    Pluck,
}

/// One factory instrument: a stable name, a category, a one-line description,
/// and a builder for its [`InstrumentDesign`].
pub struct Preset {
    /// Stable lookup id (a slug like `"warm_lead"`).
    pub name: &'static str,
    /// Coarse grouping.
    pub category: Category,
    /// One-line description of the sound.
    pub description: &'static str,
    build: fn() -> InstrumentDesign,
}

impl Preset {
    /// Build a fresh [`InstrumentDesign`] for this preset.
    pub fn design(&self) -> InstrumentDesign {
        (self.build)()
    }
}

/// Look up a factory preset's design by name.
pub fn preset(name: &str) -> Option<InstrumentDesign> {
    PRESETS.iter().find(|p| p.name == name).map(Preset::design)
}

/// Every factory preset, in a stable order.
pub static PRESETS: &[Preset] = &[
    Preset {
        name: "warm_lead",
        category: Category::Lead,
        description: "Warm saw lead — mono, legato glide, velocity opens the filter.",
        build: warm_lead,
    },
    Preset {
        name: "square_lead",
        category: Category::Lead,
        description: "Bright square lead — mono glide, a touch of chiptune.",
        build: square_lead,
    },
    Preset {
        name: "brass_stab",
        category: Category::Lead,
        description: "Horn-section stab — short and percussive, velocity opens the blat.",
        build: brass_stab,
    },
    Preset {
        name: "flute_lead",
        category: Category::Lead,
        description: "Breathy concert flute — soft attack, velocity is the breath.",
        build: flute_lead,
    },
    Preset {
        name: "supersaw_pad",
        category: Category::Pad,
        description: "Lush wide unison saw pad with a slow swell and reverb.",
        build: supersaw_pad,
    },
    Preset {
        name: "dark_pad",
        category: Category::Pad,
        description: "Dark supersaw pad — a low lowpass and slow swell, moody not bright.",
        build: dark_pad,
    },
    Preset {
        name: "hollow_pad",
        category: Category::Pad,
        description: "Soft hollow triangle pad — wide unison, roomy.",
        build: hollow_pad,
    },
    Preset {
        name: "sub_bass",
        category: Category::Bass,
        description: "Deep sub bass — sine weight plus saw body, mono, snappy.",
        build: sub_bass,
    },
    Preset {
        name: "reese_bass",
        category: Category::Bass,
        description: "Detuned reese bass — mono legato, a bit of stereo width.",
        build: reese_bass,
    },
    Preset {
        name: "fm_tine",
        category: Category::Keys,
        description: "FM electric-piano tine — velocity brightens the bell.",
        build: fm_tine,
    },
    Preset {
        name: "bell",
        category: Category::Keys,
        description: "Struck bell — inharmonic partials ring down, highs first.",
        build: bell,
    },
    Preset {
        name: "pluck",
        category: Category::Pluck,
        description: "Short bright pluck — percussive, lightly detuned.",
        build: pluck,
    },
    Preset {
        name: "marimba",
        category: Category::Pluck,
        description: "Wooden marimba — a warm thok with a fast strike, short decay.",
        build: marimba,
    },
    Preset {
        name: "nylon",
        category: Category::Pluck,
        description: "Warm nylon-string pluck — a soft, rounded playable guitar.",
        build: nylon,
    },
    Preset {
        name: "vibrato_lead",
        category: Category::Lead,
        description: "Singing lead with vibrato — a saw that breathes as you hold it.",
        build: vibrato_lead,
    },
    Preset {
        name: "wobble_bass",
        category: Category::Bass,
        description: "Wobble bass — the filter sweeps under the note (dubstep-ish).",
        build: wobble_bass,
    },
];

/// Parse a factory patch. The JSON is a compile-time constant validated by the
/// `every_preset_builds_and_sounds` test, so a failure here is a build-time bug,
/// not a runtime-fallible path.
fn patch(json: &str) -> Patch {
    serde_json::from_str(json).expect("factory preset patch must be valid")
}

fn adsr(a: f32, d: f32, s: f32, r: f32) -> Adsr {
    Adsr {
        a,
        d,
        s,
        r,
        punch: 0.0,
    }
}

fn warm_lead() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"warm_lead", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"sawtooth", "freq":220 },
                { "type":"lowpass", "cutoff":2200, "q":0.9 } ] } },
             "params": [
                { "name":"pitch",  "paths":["root.stages[0].freq"],   "min":20,  "max":8000, "default":220 },
                { "name":"cutoff", "paths":["root.stages[1].cutoff"], "min":600, "max":7000, "default":2200 } ] }"#,
    ))
    .with_amp(adsr(0.01, 0.1, 0.8, 0.15))
    .with_mode(PlayMode::Mono { legato: true })
    .with_glide(0.06)
    .with_unison(2, 8.0, 0.3)
    .with_velocity_param("cutoff")
}

fn square_lead() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"square_lead", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"square", "freq":220, "duty":0.5 },
                { "type":"lowpass", "cutoff":4000, "q":0.7 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].freq"], "min":20, "max":8000, "default":220 } ] }"#,
    ))
    .with_amp(adsr(0.005, 0.05, 0.85, 0.08))
    .with_mode(PlayMode::Mono { legato: true })
    .with_glide(0.05)
}

fn brass_stab() -> InstrumentDesign {
    // A single held seq note is the voice; the amp env cuts it short into a
    // stab, and velocity drives the note gain — the brass model's brightness.
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"brass_stab", "duration":1.0, "engine":2, "root": { "type":"seq",
                "bpm":60, "steps_per_beat":1, "wave":"brass",
                "env": { "a":0.003, "d":0.1, "s":0.0, "r":0.06 },
                "notes": [ { "step":0, "len":32, "pitch":"C4" } ] } },
             "params": [
                { "name":"bite", "paths":["root.notes[0].gain"], "min":0.2, "max":1.0, "default":0.8 } ] }"#,
    ))
    .with_amp(adsr(0.003, 0.12, 0.0, 0.08))
    .with_velocity_param("bite")
}

fn flute_lead() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"flute_lead", "duration":1.0, "engine":2, "root": { "type":"seq",
                "bpm":60, "steps_per_beat":1, "wave":"flute",
                "env": { "a":0.04, "s":1.0, "r":0.25 },
                "notes": [ { "step":0, "len":32, "pitch":"C4" } ] } },
             "params": [
                { "name":"breath", "paths":["root.notes[0].gain"], "min":0.3, "max":1.0, "default":0.8 } ] }"#,
    ))
    .with_amp(adsr(0.04, 0.0, 1.0, 0.25))
    .with_mode(PlayMode::Mono { legato: true })
    .with_glide(0.04)
    .with_velocity_param("breath")
}

fn supersaw_pad() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"supersaw_pad", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"sawtooth", "freq":220 },
                { "type":"lowpass", "cutoff":3000, "q":0.6 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].freq"], "min":20, "max":8000, "default":220 } ] }"#,
    ))
    .with_amp(adsr(0.6, 0.3, 0.8, 0.8))
    .with_unison(7, 30.0, 0.9)
    .with_master(vec![
        serde_json::from_str(r#"{ "type":"reverb", "room":0.7, "mix":0.35 }"#)
            .expect("factory master must be valid"),
    ])
}

fn dark_pad() -> InstrumentDesign {
    // The same detuned unison as supersaw_pad, but choked by a low lowpass
    // and swelling slower — the shadow to supersaw_pad's shine.
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"dark_pad", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"super", "wave":"sawtooth", "freq":220, "voices":7, "detune_cents":30 },
                { "type":"lowpass", "cutoff":700, "q":0.7 } ] } },
             "params": [
                { "name":"pitch",  "paths":["root.stages[0].freq"],   "min":20,  "max":8000, "default":220 },
                { "name":"cutoff", "paths":["root.stages[1].cutoff"], "min":200, "max":3000, "default":700 } ] }"#,
    ))
    .with_amp(adsr(0.9, 0.4, 0.75, 1.2))
    .with_master(vec![
        serde_json::from_str(r#"{ "type":"reverb", "room":0.8, "mix":0.35 }"#)
            .expect("factory master must be valid"),
    ])
}

fn hollow_pad() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"hollow_pad", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"triangle", "freq":220 },
                { "type":"lowpass", "cutoff":2500, "q":0.5 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].freq"], "min":20, "max":8000, "default":220 } ] }"#,
    ))
    .with_amp(adsr(0.4, 0.3, 0.75, 0.6))
    .with_unison(5, 18.0, 0.8)
    .with_master(vec![
        serde_json::from_str(r#"{ "type":"reverb", "room":0.6, "mix":0.3 }"#)
            .expect("factory master must be valid"),
    ])
}

fn sub_bass() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"sub_bass", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"mix", "inputs": [ { "type":"sine", "freq":55 }, { "type":"sawtooth", "freq":55 } ] },
                { "type":"lowpass", "cutoff":500, "q":0.8 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].inputs[0].freq","root.stages[0].inputs[1].freq"],
                  "min":20, "max":2000, "default":55 } ] }"#,
    ))
    .with_amp(adsr(0.005, 0.08, 0.9, 0.1))
    .with_mode(PlayMode::Mono { legato: false })
    .with_glide(0.02)
}

fn reese_bass() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"reese_bass", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"sawtooth", "freq":55 },
                { "type":"lowpass", "cutoff":700, "q":0.8 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].freq"], "min":20, "max":2000, "default":55 } ] }"#,
    ))
    .with_amp(adsr(0.005, 0.1, 0.85, 0.12))
    .with_mode(PlayMode::Mono { legato: true })
    .with_glide(0.03)
    .with_unison(3, 20.0, 0.4)
}

fn fm_tine() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"fm_tine", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"fm", "freq":220, "ratio":3.0, "index":3.5 },
                { "type":"lowpass", "cutoff":6000, "q":0.5 } ] } },
             "params": [
                { "name":"pitch",  "paths":["root.stages[0].freq"],  "min":20, "max":8000, "default":220 },
                { "name":"bright", "paths":["root.stages[0].index"], "min":1,  "max":8,    "default":3.5 } ] }"#,
    ))
    .with_amp(adsr(0.002, 0.5, 0.2, 0.4))
    .with_velocity_param("bright")
}

fn bell() -> InstrumentDesign {
    // The bell model rings on its own (the amp env just leaves the gate
    // open); a long release lets the hum outlive the key.
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"bell", "duration":1.0, "engine":2, "root": { "type":"seq",
                "bpm":60, "steps_per_beat":1, "wave":"bell",
                "env": { "a":0.001, "s":1.0, "r":2.0 },
                "notes": [ { "step":0, "len":8, "pitch":"C4" } ] } },
             "params": [
                { "name":"hit", "paths":["root.notes[0].gain"], "min":0.3, "max":1.0, "default":0.9 } ] }"#,
    ))
    .with_amp(adsr(0.001, 0.0, 1.0, 2.0))
    .with_velocity_param("hit")
}

fn pluck() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"pluck", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"sawtooth", "freq":220 },
                { "type":"lowpass", "cutoff":3200, "q":0.8 } ] } },
             "params": [
                { "name":"pitch",  "paths":["root.stages[0].freq"],   "min":20,  "max":8000, "default":220 },
                { "name":"cutoff", "paths":["root.stages[1].cutoff"], "min":800, "max":7000, "default":3200 } ] }"#,
    ))
    .with_amp(adsr(0.001, 0.18, 0.0, 0.12))
    .with_unison(2, 6.0, 0.25)
    .with_velocity_param("cutoff")
}

fn marimba() -> InstrumentDesign {
    // A short woody decay on the mallet model; velocity drives the note
    // gain, which brightens the strike partials.
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"marimba", "duration":1.0, "engine":2, "root": { "type":"seq",
                "bpm":60, "steps_per_beat":1, "wave":"mallet",
                "env": { "a":0.001, "d":0.3, "s":0.0, "r":0.1 },
                "notes": [ { "step":0, "len":4, "pitch":"C4" } ] } },
             "params": [
                { "name":"strike", "paths":["root.notes[0].gain"], "min":0.3, "max":1.0, "default":0.8 } ] }"#,
    ))
    .with_amp(adsr(0.001, 0.3, 0.0, 0.1))
    .with_velocity_param("strike")
}

fn nylon() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"nylon", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"mix", "inputs": [ { "type":"sawtooth", "freq":220 }, { "type":"triangle", "freq":220 } ] },
                { "type":"lowpass", "cutoff":2200, "q":0.7 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].inputs[0].freq","root.stages[0].inputs[1].freq"],
                  "min":20, "max":6000, "default":220 } ] }"#,
    ))
    .with_amp(adsr(0.003, 0.5, 0.0, 0.25))
    .with_unison(2, 5.0, 0.2)
}

fn vibrato_lead() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"vibrato_lead", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"sawtooth", "freq":220 },
                { "type":"lowpass", "cutoff":2600, "q":0.8 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].freq"], "min":20, "max":8000, "default":220 } ] }"#,
    ))
    .with_amp(adsr(0.02, 0.1, 0.85, 0.2))
    .with_mode(PlayMode::Mono { legato: true })
    .with_glide(0.05)
    .with_vibrato(5.5, 22.0)
}

fn wobble_bass() -> InstrumentDesign {
    InstrumentDesign::new(patch(
        r#"{ "doc": { "name":"wobble_bass", "duration":1.0, "engine":2, "root": { "type":"chain", "stages": [
                { "type":"sawtooth", "freq":55 },
                { "type":"lowpass", "cutoff":600, "q":0.9 } ] } },
             "params": [
                { "name":"pitch", "paths":["root.stages[0].freq"], "min":20, "max":2000, "default":55 } ] }"#,
    ))
    .with_amp(adsr(0.005, 0.1, 0.9, 0.15))
    .with_mode(PlayMode::Mono { legato: true })
    .with_unison(2, 16.0, 0.3)
    .with_wobble(3.5, 1.6)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::instrument::{Instrument, Note};
    use crate::runtime::AudioSource;

    fn peak(b: &[f32]) -> f32 {
        b.iter().fold(0.0f32, |m, &x| m.max(x.abs()))
    }

    #[test]
    fn every_preset_builds_and_sounds() {
        for p in PRESETS {
            let mut inst = Instrument::new(p.design(), 48_000)
                .unwrap_or_else(|e| panic!("preset {} failed to build: {e}", p.name));
            inst.note_on(Note::C4, 0.9);
            let mut out = vec![0.0f32; 4096 * 2];
            inst.fill(&mut out);
            assert!(peak(&out) > 0.0, "preset {} is silent", p.name);
        }
    }

    #[test]
    fn preset_lookup_by_name() {
        assert!(preset("warm_lead").is_some());
        assert!(preset("nope").is_none());
        assert_eq!(PRESETS.len(), 16);
    }

    #[test]
    fn presets_round_trip_through_serde() {
        for p in PRESETS {
            let json = serde_json::to_string(&p.design()).unwrap();
            let back: InstrumentDesign = serde_json::from_str(&json).unwrap();
            assert!(
                Instrument::new(back, 48_000).is_ok(),
                "preset {} recall failed",
                p.name
            );
        }
    }
}