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
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
//! The synthesis-graph [`Node`] enum — every source, combinator, and
//! processor in the DSL — with its per-family serde defaults co-located.

use super::{
    Adsr, Bus, DriveShape, KitStyle, Mode, NoiseColor, SeqNote, SeqWave, SuperWave, TempoPoint,
    Track, Value, WavetableKind, default_gain,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

// Serde `default = "..."` requires free functions. Values with non-obvious
// origins: q 0.707 is Butterworth (maximally flat).
fn default_duty() -> Value {
    Value::Const(0.5)
}
// Wavetable morph starts at the first (darkest) sub-wave.
fn default_wavetable_position() -> Value {
    Value::Const(0.0)
}
fn default_q() -> f32 {
    0.707
}
fn default_steps_per_beat() -> u32 {
    4
}
// Shared by chorus / flanger / phaser ("mod fx").
fn default_mod_depth() -> f32 {
    0.5
}
fn default_mod_mix() -> f32 {
    0.5
}
fn default_chorus_rate() -> f32 {
    1.5
}
// Classic amp/tremolo rate.
fn default_tremolo_rate() -> f32 {
    6.0
}
fn default_flanger_rate() -> f32 {
    0.25
}
fn default_flanger_feedback() -> f32 {
    0.5
}
fn default_phaser_rate() -> f32 {
    0.4
}
fn default_phaser_feedback() -> f32 {
    0.3
}
fn default_comp_attack() -> f32 {
    0.005
}
fn default_comp_release() -> f32 {
    0.08
}
fn default_voices() -> u32 {
    7
}
fn default_detune() -> f32 {
    15.0
}
// Seq instrument defaults: ratio 1 + decaying index ≈ an FM piano strike;
// pluck decay 0.996 rings ~1 s in the mid register.
fn default_seq_fm_ratio() -> f32 {
    1.0
}
fn default_seq_fm_index() -> f32 {
    5.0
}
fn default_seq_fm_strike() -> f32 {
    0.2
}
fn default_pluck_decay() -> f32 {
    0.996
}
// Guitar tone stages on the `pluck` voice. All default to identity (0.0), so
// omitting them renders byte-identically and draws no extra RNG.
fn default_pluck_body() -> f32 {
    0.0
}
fn default_pluck_pick() -> f32 {
    0.0
}
fn default_pluck_tone() -> f32 {
    0.0
}
// Piano tone knobs (engine-3 additive `piano` voice). Every default reproduces
// the concert-grand kernel bit-for-bit (x*1.0==x, x/1.0==x, 0.125==1.0/8.0 in
// f32), so a doc that omits them renders byte-identically. Variants set others.
fn default_piano_hammer() -> f32 {
    1.0
}
fn default_piano_strike() -> f32 {
    0.125
}
fn default_piano_inharm() -> f32 {
    1.0
}
fn default_piano_detune() -> f32 {
    1.0
}
fn default_piano_decay() -> f32 {
    1.0
}
// Bass tone knobs (the `bass` voice). Every default is the current voice's
// hard-coded constant, so omitting them renders byte-identically.
fn default_bass_cutoff() -> f32 {
    250.0
}
fn default_bass_env() -> f32 {
    700.0
}
fn default_bass_env_vel() -> f32 {
    1100.0
}
fn default_bass_decay() -> f32 {
    0.15
}
fn default_bass_click() -> f32 {
    0.0
}
fn default_bass_body() -> f32 {
    0.7
}
fn default_bass_sub() -> f32 {
    0.45
}
fn default_bass_sub_ratio() -> f32 {
    1.0
}
fn default_bass_drive() -> f32 {
    0.0
}
fn default_bass_body_decay() -> f32 {
    2.0
}
fn default_duck_amount() -> f32 {
    0.8
}
fn default_duck_attack() -> f32 {
    0.005
}
fn default_duck_release() -> f32 {
    0.25
}
fn default_modal_mix() -> f32 {
    1.0
}
fn default_impact_hardness() -> f32 {
    0.5
}
fn default_dust_decay() -> f32 {
    0.02
}
fn default_convolve_decay() -> f32 {
    1.5
}
fn default_convolve_damp() -> f32 {
    0.3
}
fn default_convolve_mix() -> f32 {
    0.35
}
fn default_granular_grain_ms() -> f32 {
    80.0
}
fn default_granular_density() -> f32 {
    25.0
}
fn default_granular_pitch() -> f32 {
    1.0
}
fn default_granular_spread() -> f32 {
    0.3
}
fn default_granular_mix() -> f32 {
    0.5
}

/// A node in the synthesis graph. Every node evaluates to a mono signal.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Node {
    // --- Sources (output audio in [-1, 1]) ---
    /// Square/pulse wave with variable duty cycle. `duty` may be a modulator
    /// (e.g. an `lfo`) for PWM — the classic moving chiptune lead.
    Square {
        /// Frequency in Hz.
        freq: Value,
        /// Fraction of the period spent "high", 0..1 (0.5 = symmetric square).
        #[serde(default = "default_duty")]
        duty: Value,
    },
    /// Triangle wave.
    Triangle {
        /// Frequency in Hz.
        freq: Value,
    },
    /// Sawtooth wave.
    Sawtooth {
        /// Frequency in Hz.
        freq: Value,
    },
    /// Sine wave.
    Sine {
        /// Frequency in Hz.
        freq: Value,
    },
    /// Noise source (percussion / explosion / texture). White by default;
    /// `pink` is warmer (−3 dB/oct, good for wind/rumble), `brown` darker still.
    Noise {
        /// Spectral colour of the noise.
        #[serde(default)]
        color: NoiseColor,
    },
    /// Two-operator FM: a carrier at `freq` is phase-modulated by an operator
    /// at `freq * ratio` with modulation `index`. Bells, e-piano, metallic
    /// basses. Slide `index` down for a struck/plucked attack.
    Fm {
        /// Carrier frequency in Hz.
        freq: Value,
        /// Modulator frequency as a multiple of the carrier (e.g. 2.0, 3.5).
        ratio: f32,
        /// Modulation index (depth). Higher ⇒ brighter / more sidebands.
        index: Value,
    },
    /// Unison "super" oscillator: `voices` detuned copies of a band-limited
    /// saw/square, summed for a fat, wide lead or pad (the supersaw). Detune is
    /// spread symmetrically across `detune_cents`.
    Super {
        /// Oscillator shape for every voice.
        #[serde(default)]
        wave: SuperWave,
        /// Centre frequency in Hz (modulatable).
        freq: Value,
        /// Number of detuned voices (1..=16).
        #[serde(default = "default_voices")]
        voices: u32,
        /// Total detune spread in cents across all voices.
        #[serde(default = "default_detune")]
        detune_cents: f32,
    },
    /// Morphing wavetable oscillator: `position` (0..1) sweeps across an
    /// ordered set of built-in, single-cycle tables (see [`WavetableKind`]),
    /// crossfading between adjacent sub-waves — the classic wavetable sweep.
    /// Modulate `position` (an `lfo` or `env`) for the signature moving timbre:
    /// a vocal morph on `formant`, a brightness swell on `harmonics`. Tables
    /// are generated deterministically at build time (additive, band-limited to
    /// 32 partials — darker sub-waves use fewer), so no table files are needed;
    /// very high pitches at bright positions can fold.
    Wavetable {
        /// Which table set to morph across.
        #[serde(default)]
        wave: WavetableKind,
        /// Frequency in Hz (modulatable).
        freq: Value,
        /// Morph position across the sub-waves, 0..1 (modulatable).
        #[serde(default = "default_wavetable_position")]
        position: Value,
    },
    /// A note sequencer: plays `notes` on a tempo grid, each with its own pitch,
    /// length, and a shared per-note ADSR. This is how you write real melodies,
    /// basslines, and drum patterns (rests = gaps between notes).
    Seq {
        /// Tempo in beats per minute.
        bpm: f32,
        /// Tempo changes on the beat grid at exact rational positions,
        /// applied segment-wise (ADR 0002): a note's start and end convert to
        /// seconds through the segments in f64 and land on frames with halves
        /// rounded away from zero. Empty = the constant-tempo `bpm` behavior
        /// — the only behavior documents had before this field existed, so
        /// they render byte-identically. The first point must sit at beat 0.
        /// Not supported on the `sampler` wave (validation rejects it).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        tempo_map: Vec<TempoPoint>,
        /// Grid resolution: steps per beat (4 = sixteenth notes).
        #[serde(default = "default_steps_per_beat")]
        steps_per_beat: u32,
        /// Instrument used for every note.
        wave: SeqWave,
        /// Duty cycle when `wave` is `square` (may be modulated for PWM).
        #[serde(default = "default_duty")]
        duty: Value,
        /// FM voice knobs (`wave: "fm"`), flattened onto the node.
        #[serde(flatten)]
        fm: FmKnobs,
        /// Plucked-string knobs (`wave: "pluck"`), flattened onto the node.
        #[serde(flatten)]
        pluck: PluckKnobs,
        /// Piano tone knobs (`wave: "piano"`, engine ≥ 3), flattened onto the node.
        #[serde(flatten)]
        piano: PianoKnobs,
        /// Drum-kit voicing when `wave` is `kit`. Omitted ⇒ `classic` (the
        /// original kit, byte-identical); `acoustic`/`electronic`/`808` are
        /// alternate synthesized kits.
        #[serde(default)]
        kit: KitStyle,
        /// Bass tone knobs (`wave: "bass"`), flattened onto the node.
        #[serde(flatten)]
        bass: BassKnobs,
        /// SoundFont sampler settings (`wave: "sampler"`), flattened onto the node.
        #[serde(flatten)]
        sf2: Sf2Knobs,
        /// Swing, 0..1: every off-beat grid step is delayed by this fraction
        /// of a step (0 = straight, ~0.55 = classic shuffle). Off-beats are
        /// odd steps, so set `steps_per_beat` to the swung subdivision.
        #[serde(default)]
        swing: f32,
        /// Humanize, 0..1: deterministic per-note timing and velocity jitter
        /// (from the doc's seed) so repeats stop sounding machine-perfect.
        /// 0.1–0.25 is a tasteful player; 1 is sloppy.
        #[serde(default)]
        humanize: f32,
        /// Per-note amplitude envelope.
        env: Adsr,
        /// The notes to play.
        notes: Vec<SeqNote>,
    },

    /// Impact exciter: a short excitation burst that models the contact force
    /// of a strike — a single raised-cosine force pulse whose width is set by
    /// `hardness` (hard = brief, bright click; soft = wider, duller thud),
    /// scaled by `velocity`. On its own it is a faint tick; its job is to
    /// *excite* a resonant body — put it before a `modal` bank (or any
    /// resonant filter) in a `chain`: `chain[ impact, modal ]` is a struck
    /// object. The harder the strike, the more high modes it lights up.
    Impact {
        /// Strike hardness, 0..1 (1 = hardest / brightest / shortest contact).
        #[serde(default = "default_impact_hardness")]
        hardness: f32,
        /// Strike velocity / level, 0..1.
        #[serde(default = "default_gain")]
        velocity: f32,
    },
    /// Sparse stochastic impulses — a Poisson click train. `density` events per
    /// second fire at random times with random ± amplitude, each decaying over
    /// `decay` seconds (0 = bare single-sample impulses). The grain generator
    /// behind crackle textures: fire, rain, geiger ticks, sparks, debris. Feed
    /// it through a `bandpass`/`highpass` (for tone) or a `modal` (for pitched
    /// debris). Its randomness draws from the layer's deterministic stream, so
    /// like `noise` it is edit-stable within its own mixer layer.
    Dust {
        /// Mean events per second.
        density: f32,
        /// Per-grain decay time in seconds (0 = single-sample impulses).
        #[serde(default = "default_dust_decay")]
        decay: f32,
    },

    // --- Envelope (outputs a 0..1 control signal) ---
    /// ADSR amplitude envelope with an sfxr-style `punch` transient.
    Env {
        /// Envelope shape.
        #[serde(flatten)]
        adsr: Adsr,
    },

    // --- Combinators ---
    /// The mixing console — only valid as the document root. Each track is a
    /// mono graph placed on the stereo stage with its own pan and gain
    /// (sampler tracks keep their native stereo); `master` is a processor
    /// chain applied to the stereo bus (compressor glue, reverb — the reverb
    /// runs with decorrelated left/right tails). This is how multi-
    /// instrument music gets a real stereo image instead of a mono sum.
    Tracks {
        /// The mixer channels.
        tracks: Vec<Track>,
        /// Processors applied to the stereo master bus, in order.
        #[serde(default)]
        master: Vec<Node>,
        /// Mix buses: named submixes with their own insert chains, returned
        /// onto the master bus (see [`Bus`](crate::dsl::Bus)). Empty ⇒ the
        /// flat mixer documents have always had, byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        buses: Vec<Bus>,
    },
    /// Sum (layer) all inputs.
    Mix {
        /// Branches to add together.
        inputs: Vec<Node>,
    },
    /// Multiply all inputs (typically `source × envelope`).
    Mul {
        /// Branches to multiply together.
        inputs: Vec<Node>,
    },
    /// Serial pipe: stage 0 is a source, each later stage processes the prior output.
    Chain {
        /// Ordered processing stages.
        stages: Vec<Node>,
    },

    // --- Processors (transform the preceding signal in a chain) ---
    /// Resonant low-pass filter.
    Lowpass {
        /// Cutoff frequency in Hz.
        cutoff: Value,
        /// Resonance / quality factor.
        #[serde(default = "default_q")]
        q: f32,
    },
    /// Resonant high-pass filter.
    Highpass {
        /// Cutoff frequency in Hz.
        cutoff: Value,
        /// Resonance / quality factor.
        #[serde(default = "default_q")]
        q: f32,
    },
    /// Band-pass filter.
    Bandpass {
        /// Center frequency in Hz.
        cutoff: Value,
        /// Resonance / quality factor.
        #[serde(default = "default_q")]
        q: f32,
    },
    /// Notch (band-reject) filter: removes a narrow band around `cutoff` (hum /
    /// resonance removal).
    Notch {
        /// Center frequency in Hz.
        cutoff: Value,
        /// Quality factor (higher ⇒ narrower notch).
        #[serde(default = "default_q")]
        q: f32,
    },
    /// Peaking EQ: boost or cut a band around `cutoff` by `gain_db` (surgical
    /// tone shaping — act on the brightness/centroid the analyzer reports).
    Peak {
        /// Center frequency in Hz.
        cutoff: Value,
        /// Quality factor (bandwidth).
        #[serde(default = "default_q")]
        q: f32,
        /// Gain in dB (positive boosts, negative cuts).
        #[serde(default)]
        gain_db: f32,
    },
    /// Low shelf: boost/cut everything below `cutoff` by `gain_db` (add weight or
    /// thin out lows).
    Lowshelf {
        /// Shelf corner frequency in Hz.
        cutoff: Value,
        /// Gain in dB.
        #[serde(default)]
        gain_db: f32,
    },
    /// High shelf: boost/cut everything above `cutoff` by `gain_db` (air / de-ess).
    Highshelf {
        /// Shelf corner frequency in Hz.
        cutoff: Value,
        /// Gain in dB.
        #[serde(default)]
        gain_db: f32,
    },
    /// Scale the signal by a (possibly modulated) factor.
    Gain {
        /// Multiplier.
        amount: Value,
    },
    /// Quantize amplitude to `bits` of resolution for crunch.
    Bitcrush {
        /// Bit depth, 1..16.
        bits: u8,
    },
    /// Sample-rate reduction by an integer `factor` for lo-fi grit.
    Downsample {
        /// Hold each sample for this many samples.
        factor: u32,
    },
    /// Feedback delay (echo / comb).
    Delay {
        /// Delay time in seconds.
        secs: f32,
        /// Feedback amount, 0..1.
        #[serde(default)]
        feedback: f32,
    },
    /// Schroeder-style reverb.
    Reverb {
        /// Room size, 0..1 (larger ⇒ longer tail).
        #[serde(default)]
        room: f32,
        /// Dry/wet mix, 0..1.
        #[serde(default)]
        mix: f32,
    },
    /// Modal resonator bank: a set of damped sinusoidal partials (`modes`)
    /// excited by the incoming signal — a struck/resonant object's *body*.
    /// Bells, glass, metal bars, wood, ceramic, coins, and the resonant ping
    /// of UI/impact sounds, none of which the oscillators can voice cleanly.
    /// Each mode is one 2-pole resonator (a constant-peak-gain bandpass), so a
    /// bank is N parallel resonators — cheap, stable, deterministic. Use it as
    /// a chain stage after an excitation: `chain[ impact, modal ]`. The
    /// excitation's brightness lights the modes; the modes' frequencies and
    /// decays define the timbre. Author modes explicitly — the cookbook's
    /// struck-bodies guidance (harmonic vs off-harmonic ratios, short vs long
    /// decays) is the map from material to mode list.
    Modal {
        /// The resonant partials (1..=64). Each is a damped sine.
        modes: Vec<Mode>,
        /// Wet/dry mix, 0..1 (1 = pure resonance; lower keeps some of the raw
        /// excitation transient for extra attack click).
        #[serde(default = "default_modal_mix")]
        mix: f32,
    },
    /// Waveshaper for saturation / distortion. `amount` is pre-gain; `shape`
    /// chooses the curve (warm `tanh`, aggressive `hard` clip, or `fold`back).
    Drive {
        /// Drive amount (pre-gain into the shaper).
        amount: Value,
        /// Distortion curve.
        #[serde(default)]
        shape: DriveShape,
        /// Antiderivative anti-aliasing. The waveshaper's harmonics fold back
        /// as inharmonic alias dirt at the base rate; ADAA suppresses that for
        /// a clean, hi-fi distortion. Honoured only when the document's
        /// `engine` is ≥ 1 (so legacy documents stay bit-exact); within an
        /// engine-1 document it is on by default — set `false` to hear the raw
        /// aliasing curve. Omitted ⇒ follow the engine.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        aa: Option<bool>,
    },
    /// Ring modulation: multiply the signal by a sine carrier at `freq`. Metallic,
    /// clangorous, robotic textures.
    RingMod {
        /// Carrier frequency in Hz.
        freq: Value,
    },
    /// Tremolo: per-sample amplitude modulation — the gain swings between
    /// `1 - depth` and 1 at `rate` Hz. Unlike a modulated `gain` (which does
    /// not stream), the gain is a closed-form function of the absolute sample
    /// index, so tremolo streams natively and byte-identically to the offline
    /// render.
    Tremolo {
        /// LFO rate in Hz.
        #[serde(default = "default_tremolo_rate")]
        rate: f32,
        /// Modulation depth, 0..1 (0 = transparent passthrough, 1 = full cut).
        #[serde(default = "default_mod_depth")]
        depth: f32,
    },
    /// Flanger: a very short modulated delay with feedback — the classic jet
    /// sweep / metallic whoosh. Stronger and more resonant than chorus.
    Flanger {
        /// LFO rate in Hz.
        #[serde(default = "default_flanger_rate")]
        rate: f32,
        /// Modulation depth, 0..1.
        #[serde(default = "default_mod_depth")]
        depth: f32,
        /// Feedback amount, 0..1 (more ⇒ more resonant).
        #[serde(default = "default_flanger_feedback")]
        feedback: f32,
        /// Dry/wet mix, 0..1.
        #[serde(default = "default_mod_mix")]
        mix: f32,
    },
    /// Phaser: swept all-pass notches — a hollow, swooshing movement for pads,
    /// lasers, and sci-fi textures.
    Phaser {
        /// LFO sweep rate in Hz.
        #[serde(default = "default_phaser_rate")]
        rate: f32,
        /// Sweep depth, 0..1.
        #[serde(default = "default_mod_depth")]
        depth: f32,
        /// Feedback amount, 0..1.
        #[serde(default = "default_phaser_feedback")]
        feedback: f32,
        /// Dry/wet mix, 0..1.
        #[serde(default = "default_mod_mix")]
        mix: f32,
    },
    /// Chorus: a short modulated delay mixed with the dry signal for thickening
    /// and width.
    Chorus {
        /// LFO rate in Hz.
        #[serde(default = "default_chorus_rate")]
        rate: f32,
        /// Modulation depth, 0..1.
        #[serde(default = "default_mod_depth")]
        depth: f32,
        /// Dry/wet mix, 0..1.
        #[serde(default = "default_mod_mix")]
        mix: f32,
    },
    /// Sidechain duck: gain-reduces the chained signal whenever `trigger` is
    /// loud — the pumping that glues a bass or pad to the kick. The trigger
    /// is rendered silently (it only steers the gain); chain the audible
    /// kick separately in the mix.
    Duck {
        /// The signal whose loudness drives the ducking (e.g. the kick seq).
        trigger: Box<Node>,
        /// Duck depth, 0..1 (1 = fully silent at the trigger's peak).
        #[serde(default = "default_duck_amount")]
        amount: f32,
        /// Gain-reduction attack in seconds.
        #[serde(default = "default_duck_attack")]
        attack: f32,
        /// Recovery time in seconds (the "pump" length).
        #[serde(default = "default_duck_release")]
        release: f32,
    },
    /// Dynamic-range compressor: tames peaks above `threshold` (dBFS) by `ratio`,
    /// with `attack`/`release` ballistics, then applies `makeup` gain (dB). The
    /// glue behind loud, punchy game audio.
    Compress {
        /// Threshold in dBFS (e.g. -18).
        threshold: f32,
        /// Compression ratio (e.g. 4 = 4:1).
        ratio: f32,
        /// Attack time in seconds.
        #[serde(default = "default_comp_attack")]
        attack: f32,
        /// Release time in seconds.
        #[serde(default = "default_comp_release")]
        release: f32,
        /// Make-up gain in dB.
        #[serde(default)]
        makeup: f32,
    },
    /// Convolution reverb with a synthesized impulse response — the "put it in
    /// a real space" effect, with zero assets: instead of loading an IR file,
    /// the node *generates* its own IR deterministically from its parameters
    /// and its structural position in the graph (the same node at the same
    /// graph position always builds the same IR — edit-stable like the
    /// structurally-seeded RNG sources of engine 2 and later). The IR is a
    /// white-noise burst under an exponential
    /// decay envelope reaching −60 dB at `decay` seconds (RT60-style), capped
    /// at `size` seconds, darkened over time by a one-pole lowpass whose
    /// cutoff falls per `damp`, and shifted right by `predelay` (the gap
    /// between the dry hit and the room's answer — larger rooms answer later).
    /// Convolution is FFT-based (single-shot, the whole block at once) and
    /// normalized to unit IR energy, so the wet level stays put as `decay` /
    /// `size` change. Like `reverb`, the tail folds into the document: the
    /// output is truncated to the document length rather than extended. `mix`
    /// crossfades dry/wet (0 = transparent passthrough). This node is
    /// **offline only**: convolution needs the whole input buffer, so the
    /// streaming renderer refuses it with a named reason (bounce it offline
    /// and keep the streamed graph causal).
    Convolve {
        /// RT60-ish decay time in seconds (tail reaches −60 dB at this point).
        #[serde(default = "default_convolve_decay")]
        decay: f32,
        /// IR length cap in seconds (0 = `decay`, i.e. no extra truncation).
        #[serde(default)]
        size: f32,
        /// Silence before the IR starts, in seconds (pre-delay).
        #[serde(default)]
        predelay: f32,
        /// High-frequency damping, 0..1: how fast the tail darkens (0 = the
        /// burst stays white, 1 = it closes to a rumble by the end).
        #[serde(default = "default_convolve_damp")]
        damp: f32,
        /// Dry/wet mix, 0..1.
        #[serde(default = "default_convolve_mix")]
        mix: f32,
    },
    /// Granular texture: chops the incoming signal into overlapping
    /// Hann-windowed grains of `grain_ms` milliseconds at `density` grains per
    /// second, replays each at `pitch` (playback ratio — 2 = octave up, 0.5 =
    /// octave down) with deterministic onset/source jitter and detune of depth
    /// `spread` (drawn from the node's structurally-seeded stream in a fixed
    /// order, so the texture is stable under edits), sums them (normalized by
    /// the window overlap so loudness tracks the dry signal), and crossfades
    /// with the dry signal per `mix`. Frozen pads and shimmer from any source
    /// material: chain it after a note or a noise burst and let `spread`
    /// smear it into a cloud. `mix` 0 = transparent passthrough. **Offline
    /// only** — grains read the whole input out of order, so the streaming
    /// renderer refuses it with a named reason (bounce it offline and keep the
    /// streamed graph causal).
    Granular {
        /// Grain length in milliseconds (5..=500).
        #[serde(default = "default_granular_grain_ms")]
        grain_ms: f32,
        /// Grains per second (overlap = grain_ms × density / 1000).
        #[serde(default = "default_granular_density")]
        density: f32,
        /// Grain playback ratio (1 = source pitch, 2 = octave up).
        #[serde(default = "default_granular_pitch")]
        pitch: f32,
        /// Randomization depth, 0..1: onset jitter and per-grain detune.
        #[serde(default = "default_granular_spread")]
        spread: f32,
        /// Dry/wet mix, 0..1.
        #[serde(default = "default_granular_mix")]
        mix: f32,
    },
}

impl Node {
    /// True if this node only makes sense as a non-first stage of a `chain`
    /// (it transforms an incoming signal rather than generating one).
    pub fn is_processor(&self) -> bool {
        matches!(
            self,
            Node::Lowpass { .. }
                | Node::Highpass { .. }
                | Node::Bandpass { .. }
                | Node::Notch { .. }
                | Node::Peak { .. }
                | Node::Lowshelf { .. }
                | Node::Highshelf { .. }
                | Node::Gain { .. }
                | Node::Bitcrush { .. }
                | Node::Downsample { .. }
                | Node::Delay { .. }
                | Node::Reverb { .. }
                | Node::Modal { .. }
                | Node::Drive { .. }
                | Node::RingMod { .. }
                | Node::Tremolo { .. }
                | Node::Chorus { .. }
                | Node::Flanger { .. }
                | Node::Phaser { .. }
                | Node::Compress { .. }
                | Node::Duck { .. }
                | Node::Convolve { .. }
                | Node::Granular { .. }
        )
    }

    /// Every direct child of this node — the nested graphs of the combinator
    /// variants: `mix`/`mul` inputs, `chain` stages, a `tracks`' layers then
    /// its `master` chain, and a `duck`'s trigger. The ONE traversal
    /// definition every walker shares, so a new variant can never be silently
    /// skipped the way the hand-written walkers were (the `duck`-trigger
    /// omissions in the vary and MIDI walkers were exactly that class). The
    /// match is exhaustive *on purpose*: adding a variant without a children
    /// decision is a compile error, never a silent skip.
    pub fn children(&self) -> Children<'_> {
        let kind = match self {
            Node::Mix { inputs } | Node::Mul { inputs } => ChildrenKind::Slice(inputs.iter()),
            Node::Chain { stages } => ChildrenKind::Slice(stages.iter()),
            Node::Tracks {
                tracks,
                master,
                buses,
            } => ChildrenKind::Tracks {
                tracks: tracks.iter(),
                master: master.iter(),
                buses: buses.iter(),
                bus_fx: [].iter(),
            },
            Node::Duck { trigger, .. } => ChildrenKind::One(Some(trigger)),
            Node::Square { .. }
            | Node::Triangle { .. }
            | Node::Sawtooth { .. }
            | Node::Sine { .. }
            | Node::Noise { .. }
            | Node::Fm { .. }
            | Node::Super { .. }
            | Node::Wavetable { .. }
            | Node::Seq { .. }
            | Node::Impact { .. }
            | Node::Dust { .. }
            | Node::Env { .. }
            | Node::Lowpass { .. }
            | Node::Highpass { .. }
            | Node::Bandpass { .. }
            | Node::Notch { .. }
            | Node::Peak { .. }
            | Node::Lowshelf { .. }
            | Node::Highshelf { .. }
            | Node::Gain { .. }
            | Node::Bitcrush { .. }
            | Node::Downsample { .. }
            | Node::Delay { .. }
            | Node::Reverb { .. }
            | Node::Modal { .. }
            | Node::Drive { .. }
            | Node::RingMod { .. }
            | Node::Tremolo { .. }
            | Node::Chorus { .. }
            | Node::Flanger { .. }
            | Node::Phaser { .. }
            | Node::Compress { .. }
            | Node::Convolve { .. }
            | Node::Granular { .. } => ChildrenKind::None,
        };
        Children { kind }
    }

    /// Mutable form of [`children`](Self::children).
    pub fn children_mut(&mut self) -> ChildrenMut<'_> {
        let kind = match self {
            Node::Mix { inputs } | Node::Mul { inputs } => {
                ChildrenMutKind::Slice(inputs.iter_mut())
            }
            Node::Chain { stages } => ChildrenMutKind::Slice(stages.iter_mut()),
            Node::Tracks {
                tracks,
                master,
                buses,
            } => ChildrenMutKind::Tracks {
                tracks: tracks.iter_mut(),
                master: master.iter_mut(),
                buses: buses.iter_mut(),
                bus_fx: [].iter_mut(),
            },
            Node::Duck { trigger, .. } => ChildrenMutKind::One(Some(trigger)),
            Node::Square { .. }
            | Node::Triangle { .. }
            | Node::Sawtooth { .. }
            | Node::Sine { .. }
            | Node::Noise { .. }
            | Node::Fm { .. }
            | Node::Super { .. }
            | Node::Wavetable { .. }
            | Node::Seq { .. }
            | Node::Impact { .. }
            | Node::Dust { .. }
            | Node::Env { .. }
            | Node::Lowpass { .. }
            | Node::Highpass { .. }
            | Node::Bandpass { .. }
            | Node::Notch { .. }
            | Node::Peak { .. }
            | Node::Lowshelf { .. }
            | Node::Highshelf { .. }
            | Node::Gain { .. }
            | Node::Bitcrush { .. }
            | Node::Downsample { .. }
            | Node::Delay { .. }
            | Node::Reverb { .. }
            | Node::Modal { .. }
            | Node::Drive { .. }
            | Node::RingMod { .. }
            | Node::Tremolo { .. }
            | Node::Chorus { .. }
            | Node::Flanger { .. }
            | Node::Phaser { .. }
            | Node::Compress { .. }
            | Node::Convolve { .. }
            | Node::Granular { .. } => ChildrenMutKind::None,
        };
        ChildrenMut { kind }
    }

    /// Apply `f` to this node and every descendant, depth-first (parents
    /// before children, in document order).
    pub fn walk(&self, f: &mut impl FnMut(&Node)) {
        f(self);
        for c in self.children() {
            c.walk(f);
        }
    }

    /// Mutable form of [`walk`](Self::walk).
    pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Node)) {
        f(self);
        for c in self.children_mut() {
            c.walk_mut(f);
        }
    }
}

/// The iterator returned by [`Node::children`].
pub struct Children<'a> {
    kind: ChildrenKind<'a>,
}

enum ChildrenKind<'a> {
    None,
    One(Option<&'a Node>),
    Slice(std::slice::Iter<'a, Node>),
    Tracks {
        tracks: std::slice::Iter<'a, Track>,
        master: std::slice::Iter<'a, Node>,
        buses: std::slice::Iter<'a, Bus>,
        bus_fx: std::slice::Iter<'a, Node>,
    },
}

impl<'a> Iterator for Children<'a> {
    type Item = &'a Node;
    fn next(&mut self) -> Option<&'a Node> {
        match &mut self.kind {
            ChildrenKind::None => None,
            ChildrenKind::One(x) => x.take(),
            ChildrenKind::Slice(it) => it.next(),
            ChildrenKind::Tracks {
                tracks,
                master,
                buses,
                bus_fx,
            } => {
                if let Some(t) = tracks.next() {
                    return Some(&t.node);
                }
                if let Some(m) = master.next() {
                    return Some(m);
                }
                loop {
                    if let Some(fx) = bus_fx.next() {
                        return Some(fx);
                    }
                    let b = buses.next()?;
                    *bus_fx = b.effects.iter();
                }
            }
        }
    }
}

/// The iterator returned by [`Node::children_mut`].
pub struct ChildrenMut<'a> {
    kind: ChildrenMutKind<'a>,
}

enum ChildrenMutKind<'a> {
    None,
    One(Option<&'a mut Node>),
    Slice(std::slice::IterMut<'a, Node>),
    Tracks {
        tracks: std::slice::IterMut<'a, Track>,
        master: std::slice::IterMut<'a, Node>,
        buses: std::slice::IterMut<'a, Bus>,
        bus_fx: std::slice::IterMut<'a, Node>,
    },
}

impl<'a> Iterator for ChildrenMut<'a> {
    type Item = &'a mut Node;
    fn next(&mut self) -> Option<&'a mut Node> {
        match &mut self.kind {
            ChildrenMutKind::None => None,
            ChildrenMutKind::One(x) => x.take(),
            ChildrenMutKind::Slice(it) => it.next(),
            ChildrenMutKind::Tracks {
                tracks,
                master,
                buses,
                bus_fx,
            } => {
                if let Some(t) = tracks.next() {
                    return Some(&mut t.node);
                }
                if let Some(m) = master.next() {
                    return Some(m);
                }
                loop {
                    if let Some(fx) = bus_fx.next() {
                        return Some(fx);
                    }
                    let b = buses.next()?;
                    *bus_fx = b.effects.iter_mut();
                }
            }
        }
    }
}

/// FM voice knobs of a `seq` node (`wave: "fm"`), flattened onto the node in
/// JSON. Defaults ≈ an FM piano strike (ratio 1 + decaying index).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct FmKnobs {
    /// Modulator frequency ratio (1 = e-piano/piano, 3.5 = bell, 14 = tine).
    #[serde(default = "default_seq_fm_ratio")]
    pub fm_ratio: f32,
    /// Modulation index at the strike (brightness; also scaled by each note's
    /// velocity, so louder notes ring brighter).
    #[serde(default = "default_seq_fm_index")]
    pub fm_index: f32,
    /// Strike decay in seconds: how fast the index (brightness) fades after
    /// each note's attack. Short = percussive e-piano, long = bell shimmer.
    #[serde(default = "default_seq_fm_strike")]
    pub fm_strike: f32,
}

/// Plucked-string knobs of a `seq` node (`wave: "pluck"`), flattened onto the
/// node in JSON. The tone stages default to identity, so omitting them renders
/// byte-identically and draws no extra RNG.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct PluckKnobs {
    /// String feedback decay, 0.8..1 (higher rings longer; low notes
    /// naturally ring longer than high ones).
    #[serde(default = "default_pluck_decay")]
    pub pluck_decay: f32,
    /// Acoustic body-resonance depth, 0..1 — mixes in a fixed guitar-body
    /// mode bank. 0 = solid-body (default).
    #[serde(default = "default_pluck_body")]
    pub pluck_body: f32,
    /// Pick/attack transient level, 0..1. 0 = none.
    #[serde(default = "default_pluck_pick")]
    pub pluck_pick: f32,
    /// String brightness/damping, −1..1. 0 = the current loop filter;
    /// + brightens, − darkens.
    #[serde(default = "default_pluck_tone")]
    pub pluck_tone: f32,
}

/// Piano tone knobs of a `seq` node (`wave: "piano"`, engine ≥ 3), flattened
/// onto the node in JSON. Every default reproduces the concert-grand kernel
/// bit-for-bit, so a doc that omits them renders byte-identically.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct PianoKnobs {
    /// Hammer hardness: spectral brightness. 1 = concert grand; > 1
    /// harder/brighter, < 1 softer/darker.
    #[serde(default = "default_piano_hammer")]
    pub piano_hammer: f32,
    /// Hammer strike position (fraction along the string): the comb-notch
    /// that thins the spectrum. 0.125 = grand; toward the bridge is brighter.
    #[serde(default = "default_piano_strike")]
    pub piano_strike: f32,
    /// String-stiffness scale: stretches the partials sharp. 1 = grand;
    /// > 1 = short/stiff upright jangle.
    #[serde(default = "default_piano_inharm")]
    pub piano_inharm: f32,
    /// Unison detune width: the two-string beating. 1 ≈ ±1 cent (grand
    /// shimmer); ~12 = honky-tonk warble.
    #[serde(default = "default_piano_detune")]
    pub piano_detune: f32,
    /// Ring-time scale. 1 = grand; < 1 = shorter, damped; > 1 = longer.
    #[serde(default = "default_piano_decay")]
    pub piano_decay: f32,
}

/// Bass tone knobs of a `seq` node (`wave: "bass"`), flattened onto the node
/// in JSON. Every default is the original voice's hard-coded constant, so
/// omitting them renders byte-identically.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct BassKnobs {
    /// Filter resting floor in Hz. Low = dark/round.
    #[serde(default = "default_bass_cutoff")]
    pub bass_cutoff: f32,
    /// Fixed cutoff-sweep depth above the floor, Hz.
    #[serde(default = "default_bass_env")]
    pub bass_env: f32,
    /// Velocity-scaled sweep depth, Hz (× note velocity).
    #[serde(default = "default_bass_env_vel")]
    pub bass_env_vel: f32,
    /// Filter-sweep time constant, seconds — how fast the cutoff closes.
    #[serde(default = "default_bass_decay")]
    pub bass_decay: f32,
    /// Pick-tick: an extra attack cutoff bump over ~8 ms, Hz. 0 = none.
    #[serde(default = "default_bass_click")]
    pub bass_click: f32,
    /// Filtered-saw body level.
    #[serde(default = "default_bass_body")]
    pub bass_body: f32,
    /// Sine-sub level.
    #[serde(default = "default_bass_sub")]
    pub bass_sub: f32,
    /// Sub frequency ratio to the note. 1 = reinforce; 0.5 = octave down.
    #[serde(default = "default_bass_sub_ratio")]
    pub bass_sub_ratio: f32,
    /// tanh saturation, 0..1. 0 = clean; > 0 = synth-bass grit.
    #[serde(default = "default_bass_drive")]
    pub bass_drive: f32,
    /// Note body decay, seconds (on top of the ADSR). Longer = sustained.
    #[serde(default = "default_bass_body_decay")]
    pub bass_body_decay: f32,
}

/// SoundFont sampler settings of a `seq` node (`wave: "sampler"`), flattened
/// onto the node in JSON.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Sf2Knobs {
    /// Path to a SoundFont (.sf2) file.
    #[serde(default)]
    pub sf2: String,
    /// General MIDI program number (0..=127).
    #[serde(default)]
    pub sf2_preset: u32,
    /// SoundFont bank (0 = melodic, 128 = the percussion bank / GM drum map).
    #[serde(default)]
    pub sf2_bank: u32,
}