nooise 2.5.3

Ambient music generator for the terminal
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
//! The Tonal voice: melodic steps over a pentatonic scale, with an
//! evolving phrase and per-step randomness.

use super::*;

pub(crate) struct TonalEngine {
    pub(crate) sample_rate: f32,
    pub(crate) step_trigger: GridTrigger,
    pub(crate) step_index: usize,
    pub(crate) active_phrase: usize,
    pub(crate) last_cycle: Option<u64>,
    pub(crate) evolved_phrase: Vec<i32>,
    pub(crate) voices: Vec<TonalVoice>,
    pub(crate) low_cut_l: TonalLowCut,
    pub(crate) low_cut_r: TonalLowCut,
    pub(crate) rng: StdRng,
    evolution_seed: u64,
    evolution_count: u64,
    session_state: Option<LiveSession>,
}

/// The mutable melodic state a song snapshot needs to resume evolution.
/// Playback RNG stays separate because it only affects incidental random notes
/// and panning, not which future evolution mutation occurs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TonalSequenceState {
    pub(crate) phrase: usize,
    pub(crate) notes: Vec<i32>,
    pub(crate) evolution_seed: u64,
    pub(crate) evolution_count: u64,
}

impl TonalSequenceState {
    pub(crate) fn from_phrase(phrase: usize) -> Self {
        let phrase = phrase % TONAL_PHRASES.len();
        Self {
            phrase,
            notes: tonal_phrase(phrase).to_vec(),
            evolution_seed: rand::random(),
            evolution_count: 0,
        }
    }
}

pub(crate) const TONAL_LOW_CUT_HZ: f32 = 70.0;
/// Floor for the shared `decay` control (seconds). Held above zero so the amp
/// envelope always has a real fade to silence — a literal 0 would cut the note
/// at full amplitude in a single sample and click. Shared by tonal and arp.
pub(crate) const TONAL_DECAY_MIN: f32 = 0.01;
pub(crate) const TONAL_RATE_BEATS_MIN: f32 = 0.125;
pub(crate) const TONAL_RATE_BEATS_MAX: f32 = 4.0;
pub(crate) const TONAL_CYCLE_BEATS_MIN: f32 = TONAL_RATE_BEATS_MIN;
pub(crate) const TONAL_CYCLE_BEATS_MAX: f32 = 16.0;
pub(crate) const TONAL_MAX_LOOP_STEPS: usize = 64;
pub(crate) const TONAL_MAX_EVOLVE_NOTES: usize = 4;
pub(crate) const TONAL_SCALE_MIDI: [i32; 10] = [45, 48, 50, 52, 55, 57, 60, 62, 64, 67];
pub(crate) const TONAL_PIANO_HARMONIC_COUNT: usize = 16;
pub(crate) const TONAL_PIANO_PROFILE_COUNT: usize = 9;
pub(crate) const TONAL_PIANO_A_KEYFRAMES: [PianoKeyframe; 3] = [
    PianoKeyframe {
        midi: 36,
        decay_factor: 3.0,
        harmonics: [
            0.03703704, 0.07407408, 0.22222224, 0.15308644, 0.18024692, 0.21481483, 0.24691358,
            0.04938272, 0.03703704, 0.05679013, 0.11111112, 0.05432099, 0.22716051, 0.04938272,
            0.04938272, 0.03703704,
        ],
    },
    PianoKeyframe {
        midi: 48,
        decay_factor: 2.0,
        harmonics: [
            0.04368932,
            0.43689322,
            0.18786408,
            0.04368932,
            0.1485437,
            0.10048544,
            0.30582526,
            0.034951456,
            0.052427184,
            0.10048544,
            0.04805825,
            0.07427185,
            0.026213592,
            0.10048544,
            0.078640774,
            0.017475728,
        ],
    },
    PianoKeyframe {
        midi: 60,
        decay_factor: 1.0,
        harmonics: [
            0.57937425,
            0.17381229,
            0.06546929,
            0.052143686,
            0.024913093,
            0.052143686,
            0.035921205,
            0.0063731167,
            0.004634994,
            0.0011587485,
            0.0011587485,
            0.0011587485,
            0.00057937426,
            0.00028968713,
            0.00057937426,
            0.00028968713,
        ],
    },
];
pub(crate) const TONAL_MARIMBA_KEYFRAMES: [PianoKeyframe; 4] = [
    PianoKeyframe {
        midi: 36,
        decay_factor: 3.0,
        harmonics: [
            0.6043514,
            0.009669623,
            0.009669623,
            0.030217571,
            0.024174057,
            0.030217571,
            0.018130543,
            0.018130543,
            0.030217571,
            0.25987113,
            0.060435142,
            0.24174057,
            0.060435142,
            0.042304598,
            0.030217571,
            0.030217571,
        ],
    },
    PianoKeyframe {
        midi: 48,
        decay_factor: 2.0,
        harmonics: [
            0.38923132,
            0.011676939,
            0.038923133,
            0.17126179,
            0.02919235,
            0.015569253,
            0.011676939,
            0.0077846264,
            0.038923133,
            0.32695428,
            0.108984776,
            0.019461567,
            0.023353878,
            0.0031138507,
            0.002335388,
            0.0015569254,
        ],
    },
    PianoKeyframe {
        midi: 60,
        decay_factor: 1.0,
        harmonics: [
            0.6660065,
            0.0048003546,
            0.013320129,
            0.17499822,
            0.0066600647,
            0.0,
            0.002664026,
            0.00020980158,
            0.0005268287,
            0.13081412,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
        ],
    },
    PianoKeyframe {
        midi: 84,
        decay_factor: 1.0,
        harmonics: [
            0.77432626,
            0.0034792372,
            0.00040290528,
            0.0,
            0.018717118,
            0.0030744278,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
        ],
    },
];
// Electric-piano spectrum: fundamental-dominant with a soft "tine" bump
// around the 5th/6th partial and a fast upper rolloff. Warm, non-metallic —
// the reeds fade quickly so nothing rings out bright.
pub(crate) const TONAL_EP_KEYFRAMES: [PianoKeyframe; 3] = [
    PianoKeyframe {
        midi: 36,
        decay_factor: 2.6,
        harmonics: [
            0.6, 0.168, 0.072, 0.036, 0.084, 0.06, 0.024, 0.012, 0.009, 0.006, 0.0048, 0.003,
            0.0024, 0.0018, 0.0012, 0.0006,
        ],
    },
    PianoKeyframe {
        midi: 48,
        decay_factor: 1.8,
        harmonics: [
            0.6, 0.132, 0.054, 0.03, 0.06, 0.036, 0.018, 0.009, 0.006, 0.0036, 0.0024, 0.0018,
            0.0012, 0.0009, 0.0006, 0.00048,
        ],
    },
    PianoKeyframe {
        midi: 60,
        decay_factor: 1.0,
        harmonics: [
            0.6, 0.09, 0.036, 0.018, 0.03, 0.018, 0.009, 0.0048, 0.003, 0.0018, 0.0012, 0.0006,
            0.00048, 0.0003, 0.00024, 0.00018,
        ],
    },
];
// Types 1-9 (profile index = type - 1). Type 8 / profile[7] is Cloud Keys,
// the keeper, left exactly as tuned. The rest are warm, non-metallic keys
// voiced for ambient techno: soft attacks, unhurried decays, gentle tops.
pub(crate) const TONAL_PIANO_PROFILES: [PianoProfile; TONAL_PIANO_PROFILE_COUNT] = [
    // Rhodes: warm electric piano, quick bell-tine attack, mellow sustain.
    PianoProfile {
        keyframes: &TONAL_EP_KEYFRAMES,
        amplitude: 0.40,
        body_power: 0.35,
        harmonic_tilt: -0.70,
        decay_low: 0.70,
        decay_high: 4.2,
        decay_scale: 0.60,
    },
    // Wurli: reedier electric piano, a touch more bark and shorter tail.
    PianoProfile {
        keyframes: &TONAL_EP_KEYFRAMES,
        amplitude: 0.44,
        body_power: 0.45,
        harmonic_tilt: -0.85,
        decay_low: 0.50,
        decay_high: 3.6,
        decay_scale: 0.50,
    },
    // Felt: muted upright with the soft attack of a felt-covered hammer.
    PianoProfile {
        keyframes: &TONAL_PIANO_A_KEYFRAMES,
        amplitude: 0.36,
        body_power: 0.30,
        harmonic_tilt: -1.05,
        decay_low: 0.45,
        decay_high: 3.4,
        decay_scale: 0.50,
    },
    // Marimba: wooden mallet, percussive body, rounded overtones.
    PianoProfile {
        keyframes: &TONAL_MARIMBA_KEYFRAMES,
        amplitude: 0.30,
        body_power: 0.78,
        harmonic_tilt: -0.95,
        decay_low: 1.0,
        decay_high: 5.8,
        decay_scale: 0.62,
    },
    // Kalimba: plucked lamellophone, fundamental-heavy, gentle ring.
    PianoProfile {
        keyframes: &TONAL_EP_KEYFRAMES,
        amplitude: 0.34,
        body_power: 0.70,
        harmonic_tilt: -0.60,
        decay_low: 1.1,
        decay_high: 6.5,
        decay_scale: 0.50,
    },
    // Pluck: short, dry, staccato key stab for rhythmic ambient patterns.
    PianoProfile {
        keyframes: &TONAL_EP_KEYFRAMES,
        amplitude: 0.36,
        body_power: 0.85,
        harmonic_tilt: -0.70,
        decay_low: 1.2,
        decay_high: 6.0,
        decay_scale: 0.45,
    },
    // Dulcet: clear, sweet upright with a little more shimmer than Felt.
    PianoProfile {
        keyframes: &TONAL_PIANO_A_KEYFRAMES,
        amplitude: 0.38,
        body_power: 0.40,
        harmonic_tilt: -0.70,
        decay_low: 0.70,
        decay_high: 5.0,
        decay_scale: 0.68,
    },
    // Cloud Keys: the keeper. Airy, dark, slow-blooming pad piano.
    PianoProfile {
        keyframes: &TONAL_PIANO_A_KEYFRAMES,
        amplitude: 0.34,
        body_power: 0.18,
        harmonic_tilt: -1.20,
        decay_low: 0.28,
        decay_high: 2.4,
        decay_scale: 0.34,
    },
    // Haze: an even softer, slower sibling of Cloud — a breath of a key.
    PianoProfile {
        keyframes: &TONAL_PIANO_A_KEYFRAMES,
        amplitude: 0.32,
        body_power: 0.16,
        harmonic_tilt: -1.15,
        decay_low: 0.30,
        decay_high: 2.8,
        decay_scale: 0.38,
    },
];
pub(crate) const TONAL_PHRASES: [&[i32]; 8] = [
    &[45, 50, 55, 48, 52, 57, 50, 55],
    &[45, 52, 57, 60, 57, 52, 50, 48, 50, 55, 52, 45],
    &[57, 60, 64, 62, 60, 57, 52, 55],
    &[45, 48, 52, 55, 60, 57, 55, 52, 50, 52, 55, 48],
    &[52, 55, 60, 64, 67, 64, 60, 55],
    &[
        45, 50, 52, 55, 57, 55, 52, 50, 48, 50, 52, 45, 43, 45, 48, 50,
    ],
    &[60, 57, 55, 52, 50, 52, 55, 57],
    &[
        45, 48, 50, 55, 52, 57, 55, 60, 57, 64, 60, 67, 64, 60, 55, 52,
    ],
];

impl TonalEngine {
    #[cfg(test)]
    pub(crate) fn new(sample_rate: f32) -> Self {
        Self::new_with_session_state(sample_rate, None)
    }

    pub(crate) fn new_with_session_state(
        sample_rate: f32,
        session_state: Option<LiveSession>,
    ) -> Self {
        let state = session_state
            .as_ref()
            .map(|state| state.load().tonal_sequence.clone())
            .unwrap_or_else(|| TonalSequenceState::from_phrase(0));
        Self {
            sample_rate,
            step_trigger: GridTrigger::new(),
            step_index: 0,
            active_phrase: state.phrase,
            last_cycle: None,
            evolved_phrase: state.notes,
            voices: Vec::with_capacity(8),
            low_cut_l: TonalLowCut::new(sample_rate, TONAL_LOW_CUT_HZ),
            low_cut_r: TonalLowCut::new(sample_rate, TONAL_LOW_CUT_HZ),
            rng: StdRng::from_entropy(),
            evolution_seed: state.evolution_seed,
            evolution_count: state.evolution_count,
            session_state,
        }
    }

    pub(crate) fn next(
        &mut self,
        c: &TonalControls,
        tune: f32,
        timing: TimingContext,
    ) -> (f32, f32) {
        let phrase = wrapped_index(c.phrase, TONAL_PHRASES.len());
        self.sync_phrase(phrase);

        if self
            .step_trigger
            .pop_swung(timing, c.rate_beats, 0.0, c.swing)
        {
            let cycle = tonal_cycle_index(timing.beat, c.step_interval_beats);
            if self.last_cycle.is_some_and(|last| last != cycle) {
                self.evolve_phrase(c.evolve_rate);
            }
            self.last_cycle = Some(cycle);

            let loop_len = tonal_loop_len(c.step_interval_beats, c.rate_beats);
            self.step_index = tonal_cycle_step(timing.beat, c.step_interval_beats, c.rate_beats)
                % loop_len
                + tonal_offset_step(c.offset_beats, c.rate_beats);
            let note = if self.rng.gen_range(0.0f32..1.0) < c.randomness {
                TONAL_SCALE_MIDI[self.rng.gen_range(0..TONAL_SCALE_MIDI.len())]
            } else {
                self.evolved_phrase[self.step_index % self.evolved_phrase.len()]
            } + (c.octave.round() as i32) * 12;
            let hz = note_hz(note, tune);
            let pan = self.rng.gen_range(-0.5f32..0.5);
            // A silent layer still triggers nothing: skipping keeps a Level
            // of exactly 0 from accumulating inaudible voices. Every RNG draw
            // above still happens, keeping seeded renders byte-identical.
            if c.level != 0.0 {
                self.voices.push(TonalVoice::new(
                    wrapped_index(c.synth_type, TONAL_SYNTH_TYPES.len()),
                    TonalNote {
                        midi: note,
                        hz,
                        pan,
                        sample_rate: self.sample_rate,
                        attack_time: c.attack,
                        decay_time: c.decay,
                    },
                ));
            }
        }

        let (dry_l, dry_r) =
            mix_and_retain(&mut self.voices, TonalVoice::next, TonalVoice::is_done);

        // Level is applied here, to the summed voices, rather than captured
        // into each note at trigger time: a note that has already started
        // must still answer the fader. `c.level` arrives pre-smoothed from
        // `GainSmoothers`, so this stays click-free.
        //
        // It scales the low cut's *output*, never its input. The cut is a
        // high pass, so feeding it an abruptly silenced signal discharges its
        // state as a decaying thump — the filter must keep seeing the voices
        // at full level and never learn that the fader moved.
        (
            self.low_cut_l.process(dry_l) * c.level,
            self.low_cut_r.process(dry_r) * c.level,
        )
    }

    pub(crate) fn sync_phrase(&mut self, phrase: usize) {
        if phrase != self.active_phrase {
            self.active_phrase = phrase;
            self.evolved_phrase = tonal_phrase(phrase).to_vec();
            self.step_index = 0;
            self.last_cycle = None;
            self.evolution_seed = rand::random();
            self.evolution_count = 0;
            self.publish_session_state();
        }
    }

    pub(crate) fn evolve_phrase(&mut self, rate: f32) {
        let count = tonal_evolve_note_count(rate, self.evolved_phrase.len());
        if count == 0 {
            return;
        }
        let mut changed_positions = [usize::MAX; TONAL_MAX_EVOLVE_NOTES];
        for changed in 0..count {
            let mut pos = evolve_random(self.evolution_seed, self.evolution_count, changed as u64)
                as usize
                % self.evolved_phrase.len();
            while changed_positions[..changed].contains(&pos) {
                pos = (pos + 1) % self.evolved_phrase.len();
            }
            changed_positions[changed] = pos;

            let old = self.evolved_phrase[pos];
            let mut next = old;
            for attempt in 0..8 {
                next = TONAL_SCALE_MIDI[evolve_random(
                    self.evolution_seed,
                    self.evolution_count,
                    TONAL_MAX_EVOLVE_NOTES as u64 + changed as u64 * 8 + attempt,
                ) as usize
                    % TONAL_SCALE_MIDI.len()];
                if next != old {
                    break;
                }
            }
            self.evolved_phrase[pos] = next;
        }
        self.evolution_count = self.evolution_count.wrapping_add(1);
        self.publish_session_state();
    }

    fn publish_session_state(&self) {
        let Some(session_state) = &self.session_state else {
            return;
        };
        session_state.update(|snapshot| {
            snapshot.tonal_sequence = TonalSequenceState {
                phrase: self.active_phrase,
                notes: self.evolved_phrase.clone(),
                evolution_seed: self.evolution_seed,
                evolution_count: self.evolution_count,
            };
        });
    }
}

fn evolve_random(seed: u64, evolution_count: u64, draw: u64) -> u64 {
    splitmix64_mix(
        seed ^ evolution_count.wrapping_mul(0x9E37_79B9_7F4A_7C15)
            ^ draw.wrapping_mul(0xBF58_476D_1CE4_E5B9),
    )
}

pub(crate) fn tonal_phrase(phrase: usize) -> &'static [i32] {
    TONAL_PHRASES[phrase % TONAL_PHRASES.len()]
}

pub(crate) fn tonal_loop_len(cycle_beats: f32, rate_beats: f32) -> usize {
    (cycle_beats / tonal_rate_beats(rate_beats))
        .round()
        .clamp(1.0, TONAL_MAX_LOOP_STEPS as f32) as usize
}

pub(crate) fn tonal_cycle_index(beat: f64, cycle_beats: f32) -> u64 {
    let cycle = f64::from(tonal_cycle_beats(cycle_beats));
    (beat.max(0.0) / cycle).floor() as u64
}

pub(crate) fn tonal_cycle_step(beat: f64, cycle_beats: f32, rate_beats: f32) -> usize {
    let cycle = f64::from(tonal_cycle_beats(cycle_beats));
    let local = beat.rem_euclid(cycle);
    (local / f64::from(tonal_rate_beats(rate_beats))).floor() as usize
}

pub(crate) fn tonal_offset_step(offset_beats: f32, rate_beats: f32) -> usize {
    (offset_beats.max(0.0) / tonal_rate_beats(rate_beats)).floor() as usize
}

pub(crate) fn tonal_rate_beats(rate_beats: f32) -> f32 {
    rate_beats.clamp(TONAL_RATE_BEATS_MIN, TONAL_RATE_BEATS_MAX)
}

pub(crate) fn tonal_cycle_beats(cycle_beats: f32) -> f32 {
    cycle_beats.clamp(TONAL_CYCLE_BEATS_MIN, TONAL_CYCLE_BEATS_MAX)
}

pub(crate) fn tonal_evolve_note_count(rate: f32, phrase_len: usize) -> usize {
    if phrase_len == 0 || rate <= 0.0 {
        return 0;
    }
    (rate.clamp(0.0, 1.0) * TONAL_MAX_EVOLVE_NOTES as f32)
        .ceil()
        .min(phrase_len as f32) as usize
}

pub(crate) struct TonalLowCut {
    pub(crate) alpha: f32,
    pub(crate) last_input: f32,
    pub(crate) last_output: f32,
}

impl TonalLowCut {
    pub(crate) fn new(sample_rate: f32, cutoff_hz: f32) -> Self {
        let sample_rate = sample_rate.max(1.0);
        let cutoff_hz = cutoff_hz.max(1.0);
        let dt = 1.0 / sample_rate;
        let rc = 1.0 / (TAU * cutoff_hz);
        Self {
            alpha: rc / (rc + dt),
            last_input: 0.0,
            last_output: 0.0,
        }
    }

    pub(crate) fn process(&mut self, input: f32) -> f32 {
        let output = self.alpha * (self.last_output + input - self.last_input);
        self.last_input = input;
        self.last_output = output;
        output
    }
}

/// One note's trigger-time parameters, captured when its voice is created:
/// the pitch, where it sits in the stereo field, how loud it was triggered,
/// and the attack/decay that decide how long it sounds. Every synth type takes
/// exactly this set, so `synth_type` alone selects the character.
#[derive(Clone, Copy)]
pub(crate) struct TonalNote {
    /// MIDI note number. Piano profiles scale harmonics and decay with
    /// register from it; the sine voice has no register-dependent behavior and
    /// ignores it.
    pub(crate) midi: i32,
    pub(crate) hz: f32,
    pub(crate) pan: f32,
    pub(crate) sample_rate: f32,
    pub(crate) attack_time: f32,
    pub(crate) decay_time: f32,
}

pub(crate) enum TonalVoice {
    Sine(SineTonalVoice),
    Piano(Box<PianoTonalVoice>),
}

impl TonalVoice {
    /// A voice's whole life is `attack + decay` seconds: the amplitude ramps
    /// in over `attack`, then falls from the peak to silence over `decay`. The
    /// step grid only decides *when* the next note triggers, never how long
    /// this one sounds, so notes overlap freely when `decay` outlasts the step.
    pub(crate) fn new(synth_type: usize, note: TonalNote) -> Self {
        match synth_type {
            0 => Self::Sine(SineTonalVoice::new(note)),
            _ => Self::Piano(Box::new(PianoTonalVoice::new(
                piano_profile(synth_type),
                note,
            ))),
        }
    }

    pub(crate) fn next(&mut self) -> (f32, f32) {
        match self {
            Self::Sine(voice) => voice.next(),
            Self::Piano(voice) => voice.next(),
        }
    }

    pub(crate) fn is_done(&self) -> bool {
        match self {
            Self::Sine(voice) => voice.is_done(),
            Self::Piano(voice) => voice.is_done(),
        }
    }
}

/// Shape of the sine voice's decay taper: `sqrt(1 - t)`, i.e. a decay curve
/// exponent of 0.5.
const TONAL_SINE_DECAY_POWER: f32 = 0.5;

/// Attack + decay envelope shared by every tonal synth type — the one
/// foundational note shape. `elapsed`, `attack`, and `decay` are seconds:
/// the gain ramps 0->1 across the first `attack` seconds, then falls from the
/// peak back to 0 across the following `decay` seconds. A note's whole
/// sounding life is therefore `attack + decay`; the gain reaches exactly 0 at
/// that point, so a voice killed there ends in silence with no click. `power`
/// is the decay curve's shape exponent — the one piece of "harmonic
/// character" each voice keeps (the piano profile's `body_power`, or the sine
/// voice's fixed sqrt taper).
///
/// A control of exactly 0 means "instant": an attack of 0 reaches full volume
/// on the first sample, and a decay of 0 collapses the note to nothing. (The
/// registry floors `decay` above 0 so the UI can never request the hard,
/// clicking cut a literal 0 would produce.)
pub(crate) fn attack_decay_gain(elapsed: f32, attack: f32, decay: f32, power: f32) -> f32 {
    let attack_gain = if attack <= 0.0 {
        1.0
    } else {
        (elapsed / attack).clamp(0.0, 1.0)
    };

    let decay_gain = if decay <= 0.0 {
        0.0
    } else {
        let into_decay = (elapsed - attack).max(0.0);
        (1.0 - (into_decay / decay).clamp(0.0, 1.0)).powf(power)
    };

    attack_gain * decay_gain
}

/// The part of a tonal/arp note that is the same whatever synthesizes it:
/// its attack + decay lifetime clock, the shared `attack_decay_gain` envelope
/// at the voice's own decay `power`, and its pan. A voice keeps only its
/// oscillators next to one of these.
pub(crate) struct TonalNoteLife {
    samples_elapsed: u64,
    total_samples: u64,
    total_duration: f32,
    attack_time: f32,
    decay_time: f32,
    power: f32,
    pan_gains: (f32, f32),
}

impl TonalNoteLife {
    pub(crate) fn new(note: &TonalNote, power: f32) -> Self {
        let sample_rate = note.sample_rate.max(1.0);
        // The note's whole life is attack + decay; the envelope reaches zero
        // exactly at that point, so this length ends the voice in silence.
        let total = (((note.attack_time + note.decay_time) * sample_rate).round() as u64).max(1);
        Self {
            samples_elapsed: 0,
            total_samples: total,
            total_duration: total as f32 / sample_rate,
            attack_time: note.attack_time,
            decay_time: note.decay_time,
            power,
            pan_gains: StereoPanner::gains(note.pan),
        }
    }

    /// This sample's envelope gain, advancing the clock; `None` once the note
    /// has lived out its attack + decay.
    pub(crate) fn next_gain(&mut self) -> Option<f32> {
        if self.is_done() {
            return None;
        }
        let elapsed = self.samples_elapsed as f32 / self.total_samples as f32 * self.total_duration;
        self.samples_elapsed += 1;
        Some(attack_decay_gain(
            elapsed,
            self.attack_time,
            self.decay_time,
            self.power,
        ))
    }

    pub(crate) fn is_done(&self) -> bool {
        self.samples_elapsed >= self.total_samples
    }

    pub(crate) fn pan(&self, s: f32) -> (f32, f32) {
        (s * self.pan_gains.0, s * self.pan_gains.1)
    }
}

pub(crate) struct SineTonalVoice {
    pub(crate) primary: SineOscillator,
    pub(crate) detuned: SineOscillator,
    pub(crate) life: TonalNoteLife,
}

impl SineTonalVoice {
    pub(crate) fn new(note: TonalNote) -> Self {
        let sample_rate = note.sample_rate.max(1.0);
        Self {
            primary: SineOscillator::new(note.hz, sample_rate),
            detuned: SineOscillator::new(note.hz * 1.004, sample_rate),
            life: TonalNoteLife::new(&note, TONAL_SINE_DECAY_POWER),
        }
    }
    pub(crate) fn next(&mut self) -> (f32, f32) {
        let Some(gain) = self.life.next_gain() else {
            return (0.0, 0.0);
        };
        let s = soft_clip((self.primary.next() + self.detuned.next() * 0.3) * 0.4) * gain;
        self.life.pan(s)
    }
    pub(crate) fn is_done(&self) -> bool {
        self.life.is_done()
    }
}

pub(crate) struct PianoKeyframe {
    pub(crate) midi: i32,
    pub(crate) decay_factor: f32,
    pub(crate) harmonics: [f32; TONAL_PIANO_HARMONIC_COUNT],
}

#[derive(Clone, Copy)]
pub(crate) struct PianoProfile {
    pub(crate) keyframes: &'static [PianoKeyframe],
    pub(crate) amplitude: f32,
    pub(crate) body_power: f32,
    pub(crate) harmonic_tilt: f32,
    pub(crate) decay_low: f32,
    pub(crate) decay_high: f32,
    pub(crate) decay_scale: f32,
}

pub(crate) struct PianoTonalVoice {
    pub(crate) oscillators: [SineOscillator; TONAL_PIANO_HARMONIC_COUNT],
    pub(crate) profile: PianoProfile,
    pub(crate) harmonic_amplitudes: [f32; TONAL_PIANO_HARMONIC_COUNT],
    /// Per-sample multiplicative decay: `exp(-rate / total_samples)`, so
    /// running `harmonic_decay_state *= harmonic_decay_steps` each sample
    /// reproduces `exp(-t * rate)` without an `exp()` call per sample.
    pub(crate) harmonic_decay_steps: [f32; TONAL_PIANO_HARMONIC_COUNT],
    pub(crate) harmonic_decay_state: [f32; TONAL_PIANO_HARMONIC_COUNT],
    pub(crate) life: TonalNoteLife,
}

impl PianoTonalVoice {
    pub(crate) fn new(profile: PianoProfile, note: TonalNote) -> Self {
        let sample_rate = note.sample_rate.max(1.0);
        // The piano's natural per-harmonic rolloff normalizes to the decay
        // time alone, so `decay` sets how long the note rings and `attack`
        // never stretches (and slows) the timbre.
        let decay_samples = (((note.decay_time * sample_rate).round()) as u64).max(1);
        let harmonic_decay_rates = piano_harmonic_decay_rates(profile, note.midi, note.hz);
        Self {
            oscillators: std::array::from_fn(|index| {
                SineOscillator::new(note.hz * (index + 1) as f32, sample_rate)
            }),
            profile,
            harmonic_amplitudes: piano_harmonic_amplitudes(profile, note.midi),
            harmonic_decay_steps: harmonic_decay_rates
                .map(|rate| (-rate / decay_samples as f32).exp()),
            harmonic_decay_state: [1.0; TONAL_PIANO_HARMONIC_COUNT],
            life: TonalNoteLife::new(&note, profile.body_power),
        }
    }

    pub(crate) fn next(&mut self) -> (f32, f32) {
        let Some(envelope) = self.life.next_gain() else {
            return (0.0, 0.0);
        };

        let mut sample = 0.0f32;
        for index in 0..TONAL_PIANO_HARMONIC_COUNT {
            let harmonic = self.oscillators[index].next();
            let decay = self.harmonic_decay_state[index];
            self.harmonic_decay_state[index] *= self.harmonic_decay_steps[index];
            sample += harmonic * self.harmonic_amplitudes[index] * decay;
        }

        let s = soft_clip(sample * self.profile.amplitude) * envelope;
        self.life.pan(s)
    }

    pub(crate) fn is_done(&self) -> bool {
        self.life.is_done()
    }
}

pub(crate) fn piano_profile(synth_type: usize) -> PianoProfile {
    TONAL_PIANO_PROFILES[(synth_type.saturating_sub(1)) % TONAL_PIANO_PROFILES.len()]
}

pub(crate) fn piano_harmonic_amplitudes(
    profile: PianoProfile,
    midi_note: i32,
) -> [f32; TONAL_PIANO_HARMONIC_COUNT] {
    let (low, high) = piano_keyframe_pair(profile, midi_note);
    let t = ease_in_out(lerp_t(low.midi as f32, high.midi as f32, midi_note as f32));
    std::array::from_fn(|index| {
        let harmonic = (index + 1) as f32;
        let tilt = harmonic.powf(profile.harmonic_tilt);
        lerp(low.harmonics[index], high.harmonics[index], t) * tilt
    })
}

pub(crate) fn piano_harmonic_decay_rates(
    profile: PianoProfile,
    midi_note: i32,
    fundamental_hz: f32,
) -> [f32; TONAL_PIANO_HARMONIC_COUNT] {
    let (low, high) = piano_keyframe_pair(profile, midi_note);
    let t = ease_in_out(lerp_t(low.midi as f32, high.midi as f32, midi_note as f32));
    let frame_decay = lerp(low.decay_factor, high.decay_factor, t).max(0.25);
    std::array::from_fn(|index| {
        let harmonic_hz = fundamental_hz * (index + 1) as f32;
        let pitch_decay = lerp_t(80.0, 6_000.0, harmonic_hz);
        lerp(profile.decay_low, profile.decay_high, pitch_decay) * profile.decay_scale / frame_decay
    })
}

fn piano_keyframe_pair(
    profile: PianoProfile,
    midi_note: i32,
) -> (&'static PianoKeyframe, &'static PianoKeyframe) {
    let mut low = &profile.keyframes[0];
    let mut high = &profile.keyframes[profile.keyframes.len() - 1];

    for keyframe in profile.keyframes {
        if keyframe.midi <= midi_note && keyframe.midi >= low.midi {
            low = keyframe;
        }
        if keyframe.midi >= midi_note && keyframe.midi <= high.midi {
            high = keyframe;
        }
    }

    (low, high)
}

fn lerp_t(min: f32, max: f32, value: f32) -> f32 {
    if (max - min).abs() <= f32::EPSILON {
        0.0
    } else {
        ((value - min) / (max - min)).clamp(0.0, 1.0)
    }
}

fn lerp(a: f32, b: f32, t: f32) -> f32 {
    a + (b - a) * t
}

fn ease_in_out(t: f32) -> f32 {
    if t < 0.5 {
        2.0 * t * t
    } else {
        1.0 - (-2.0 * t + 2.0).powi(2) * 0.5
    }
}