nooise 2.5.1

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
//! The Pad voice: sustained chord drones, the chord source Bass and Arp
//! both follow.

use crate::fx::crossfade::{Outgoing, mix};

use super::*;

pub(crate) const MAX_PAD_LAYERS: usize = 4;
/// How long a `pad.type` change takes to crossfade from the outgoing
/// character stage to the incoming one, inside each already-sounding tone.
///
/// This is short because it does not have to hide an onset: the oscillators
/// and the amplitude envelope keep running untouched across a type change, so
/// the only discontinuity to smooth is the step between two stages' outputs
/// (a filter starting from zero state, a different output trim). Both sides
/// are the same oscillators through different post-stages, so they are
/// strongly correlated and a linear crossfade holds the level steady.
const PAD_TYPE_CROSSFADE_SECONDS: f32 = 0.03;

pub(crate) struct PadEngine {
    pub(crate) sample_rate: f32,
    pub(crate) layers: Vec<PadLayer>,
    pub(crate) chord_trigger: GridTrigger,
    pub(crate) step_index: usize,
    pub(crate) active_progression: usize,
    pub(crate) active_chord_count: usize,
    pub(crate) active_character: usize,
    pub(crate) last_chord_notes: [i32; 4],
    pub(crate) width_lfo: DriftingLfo,
    pub(crate) air: WhiteNoise,
    pub(crate) rng: StdRng,
    pub(crate) telemetry: Arc<FluidTelemetry>,
}

impl PadEngine {
    /// `tune` is `master.tune` at construction. It must be passed in rather
    /// than assumed neutral: the opening chord is voiced here and holds for a
    /// whole `chord_bars` (~12 s at defaults, its release bleeding into the
    /// next chord), so a session started from a song code with a non-zero
    /// tune would play its first chord at concert pitch while Bass, Tonal and
    /// Arp — which read tune per note — are all transposed.
    pub(crate) fn new(
        sample_rate: f32,
        c: &PadControls,
        tune: f32,
        telemetry: Arc<FluidTelemetry>,
    ) -> Self {
        let active_progression = progression_index(c.progression);
        let active_character = wrapped_index(c.voice_type, PAD_TYPES.len());
        let initial_notes = pad_chord_tones(c, active_progression, 0);
        Self {
            sample_rate,
            layers: vec![PadLayer::new(
                active_character,
                initial_notes,
                tune,
                sample_rate,
                c.attack_time,
                c.release_time,
            )],
            chord_trigger: GridTrigger::after_start(),
            step_index: 0,
            active_progression,
            active_chord_count: pad_chord_count(c),
            active_character,
            last_chord_notes: initial_notes,
            width_lfo: DriftingLfo::new(1.0 / 54.0, sample_rate),
            air: WhiteNoise::new(),
            rng: StdRng::from_entropy(),
            telemetry,
        }
    }

    pub(crate) fn next(&mut self, c: &PadControls, tune: f32, timing: TimingContext) -> (f32, f32) {
        let progression = progression_index(c.progression);
        let chord_count = pad_chord_count(c);

        let advance = self.chord_trigger.pop(timing, c.chord_bars * 4.0, 0.0);
        advance_pad_progression(
            &mut self.step_index,
            &mut self.active_chord_count,
            &mut self.active_progression,
            chord_count,
            progression,
            advance,
        );
        let chord_notes = pad_chord_tones(c, self.active_progression, self.step_index);
        let chord_edited = chord_notes != self.last_chord_notes;
        let character = wrapped_index(c.voice_type, PAD_TYPES.len());
        let character_changed = character != self.active_character;
        self.last_chord_notes = chord_notes;
        self.active_character = character;

        // A type change is a change of character, not a new note. Every
        // character runs the same oscillator stack and differs only in the
        // stage after it, so the sounding tones swap that stage in place —
        // no new layer, no restarted envelope, no oscillator phase reset.
        // Voicing a fresh layer instead meant a full chord re-attacking from
        // silence with all its oscillators phase-aligned, which is an onset
        // transient, and it cut off every sustaining tail to do it.
        if character_changed {
            for layer in &mut self.layers {
                layer.set_character(character, self.sample_rate);
            }
        }

        if advance || chord_edited {
            for layer in &mut self.layers {
                layer.release();
            }
            self.telemetry
                .chord_index
                .store(self.step_index as u64, Ordering::Relaxed);
            if self.layers.len() >= MAX_PAD_LAYERS {
                let remove_count = self.layers.len() + 1 - MAX_PAD_LAYERS;
                self.layers.drain(0..remove_count);
            }
            self.layers.push(PadLayer::new(
                character,
                chord_notes,
                tune,
                self.sample_rate,
                c.attack_time,
                c.release_time,
            ));
        }

        let width = c.stereo_width
            * (0.58
                + normalized_lfo(self.width_lfo.next(&mut self.rng, 1.0 / 86.0, 1.0 / 38.0))
                    * 0.16);
        let detune_mix = c.detune * 0.84;
        let octave_mix = c.octave_mix * 0.32;

        let (dry_l, dry_r) = mix_and_retain(
            &mut self.layers,
            |layer| layer.next_stereo(width, detune_mix, octave_mix),
            PadLayer::is_done,
        );

        let air = self.air.next_filtered(&mut self.rng, 0.0002) * 0.00025;

        // Headroom trim on the summed layer output, not a character control —
        // `pad.level` at 100% should reach close to full scale on its own,
        // leaving final safety margin to the master bus's soft-clip/compressor.
        const OUTPUT_TRIM: f32 = 0.95;
        (
            (dry_l * OUTPUT_TRIM + air) * c.level,
            (dry_r * OUTPUT_TRIM + air) * c.level,
        )
    }
}

pub(crate) struct PadLayer {
    pub(crate) tones: Vec<PadTone>,
}

impl PadLayer {
    pub(crate) fn new(
        character: usize,
        notes: [i32; 4],
        tune: f32,
        sample_rate: f32,
        attack_time: f32,
        release_time: f32,
    ) -> Self {
        Self {
            tones: pad_tones(
                character,
                notes,
                tune,
                sample_rate,
                attack_time,
                release_time,
            ),
        }
    }
    pub(crate) fn next_stereo(
        &mut self,
        width: f32,
        detune_mix: f32,
        octave_mix: f32,
    ) -> (f32, f32) {
        let (mut l, mut r) = (0.0f32, 0.0f32);
        for t in &mut self.tones {
            let (tl, tr) = t.next_stereo(width, detune_mix, octave_mix);
            l += tl;
            r += tr;
        }
        (l, r)
    }
    pub(crate) fn release(&mut self) {
        for t in &mut self.tones {
            t.release();
        }
    }
    /// Swaps every tone onto a new `pad.type` character in place, leaving
    /// their oscillators and envelopes running.
    pub(crate) fn set_character(&mut self, character: usize, sample_rate: f32) {
        for t in &mut self.tones {
            t.set_character(character, sample_rate);
        }
    }
    pub(crate) fn is_done(&self) -> bool {
        self.tones.iter().all(PadTone::is_done)
    }
}

/// Shared oscillator/envelope/pan/gain stack behind every `pad.type`
/// character: fundamental, slightly detuned, one octave up, an ADSR, and the
/// pan/gain the layer was authored with. `PadTone` wraps this with the one
/// extra stage its character adds to `stack_sum`'s output.
pub(crate) struct PadOscStack {
    pub(crate) primary: SineOscillator,
    pub(crate) detuned: SineOscillator,
    pub(crate) octave: SineOscillator,
    pub(crate) envelope: Adsr,
    pub(crate) pan: f32,
    pub(crate) gain: f32,
}

impl PadOscStack {
    pub(crate) fn new(
        hz: f32,
        pan: f32,
        gain: f32,
        attack_time: f32,
        release_time: f32,
        sample_rate: f32,
    ) -> Self {
        Self {
            primary: SineOscillator::new(hz, sample_rate),
            detuned: SineOscillator::new(hz * 1.003, sample_rate),
            octave: SineOscillator::new(hz * 2.0, sample_rate),
            envelope: Adsr::new(attack_time, 12.0, 0.86, release_time, sample_rate),
            pan,
            gain,
        }
    }
    #[inline]
    pub(crate) fn stack_sum(&mut self, detune_mix: f32, octave_mix: f32) -> f32 {
        self.primary.next() + self.detuned.next() * detune_mix + self.octave.next() * octave_mix
    }
    pub(crate) fn release(&mut self) {
        self.envelope.note_off();
    }
    pub(crate) fn is_done(&self) -> bool {
        self.envelope.is_done()
    }
}

/// One-pole lowpass coefficient shared by the Dark tone's per-sample
/// smoothing; low enough to noticeably round off the upper harmonic content
/// contributed by the detune/octave layers without muffling the fundamental.
const PAD_DARK_LOWPASS_COEFF: f32 = 0.18;
/// Output trim compensating for the lowpass stage's energy loss so Dark sits
/// at a comparable perceived level to Warm/Glass.
const PAD_DARK_OUTPUT_GAIN: f32 = 1.22;
/// Fixed mix level of the Glass tone's shimmer layer (two octaves above the
/// fundamental), independent of the user-facing `pad.octave_mix` control.
const PAD_GLASS_SHIMMER_MIX: f32 = 0.09;
/// Output trim compensating for the shimmer layer's added energy so Glass
/// sits at a comparable perceived level to Warm/Dark.
const PAD_GLASS_OUTPUT_GAIN: f32 = 0.93;
/// Fixed upper-partial range for Choir's gently moving breath layer.
const PAD_CHOIR_PARTIAL_MIX_MIN: f32 = 0.04;
const PAD_CHOIR_PARTIAL_MIX_RANGE: f32 = 0.07;
const PAD_CHOIR_OUTPUT_GAIN: f32 = 0.94;
/// Hollow pulls the shared stack back and replaces some energy with a
/// sub-octave sine, leaving a quieter center beneath the chord.
const PAD_HOLLOW_STACK_MIX: f32 = 0.82;
const PAD_HOLLOW_SUB_MIX: f32 = 0.18;
const PAD_HOLLOW_OUTPUT_GAIN: f32 = 1.1;
/// Tape rounds the stack and adds a slow, shallow level drift.
const PAD_TAPE_LOWPASS_COEFF: f32 = 0.32;
const PAD_TAPE_OUTPUT_GAIN: f32 = 1.16;

/// The one thing a `pad.type` character adds between the shared oscillator
/// stack and the soft-clipper. Warm — the legacy tone — adds nothing, so its
/// signal path through `PadTone::next_stereo` is the original one unchanged.
pub(crate) enum PadStage {
    /// Warm: the summed stack goes straight to the soft-clipper.
    None,
    /// Dark: a gentle fixed one-pole lowpass rounding off the highs the
    /// detune and octave layers contribute.
    Lowpass { state: f32 },
    /// Glass: a quiet fixed oscillator two octaves above the fundamental,
    /// added for upper harmonic content.
    Shimmer { oscillator: SineOscillator },
    /// Choir: a quiet third harmonic swells independently behind each tone.
    Choir {
        partial: SineOscillator,
        movement: SineOscillator,
    },
    /// Hollow: a sub-octave sine replaces part of the shared stack.
    Hollow { sub: SineOscillator },
    /// Tape: a fixed lowpass and slow level drift soften the shared stack.
    Tape {
        state: f32,
        movement: SineOscillator,
    },
}

impl PadStage {
    #[inline]
    fn apply(&mut self, s: f32) -> f32 {
        match self {
            Self::None => s,
            Self::Lowpass { state } => {
                *state += PAD_DARK_LOWPASS_COEFF * (s - *state);
                *state
            }
            Self::Shimmer { oscillator } => s + oscillator.next() * PAD_GLASS_SHIMMER_MIX,
            Self::Choir { partial, movement } => {
                let partial_mix = PAD_CHOIR_PARTIAL_MIX_MIN
                    + normalized_lfo(movement.next()) * PAD_CHOIR_PARTIAL_MIX_RANGE;
                s + partial.next() * partial_mix
            }
            Self::Hollow { sub } => s * PAD_HOLLOW_STACK_MIX + sub.next() * PAD_HOLLOW_SUB_MIX,
            Self::Tape { state, movement } => {
                *state += PAD_TAPE_LOWPASS_COEFF * (s - *state);
                *state * (0.94 + normalized_lfo(movement.next()) * 0.06)
            }
        }
    }
}

/// `pad.type` selects the tone character used for every layer's tones: index 0
/// (`Warm`, the default) is three sines summed, soft-clipped, and shaped by the
/// shared ADSR. Every other index selects one character stage before the
/// soft-clipper. The characters differ only in that stage and in the output
/// trim that keeps them at a comparable perceived level, so switching type
/// never touches chord selection, trigger timing, attack/release, or pan.
/// The character stage a tone is fading out of after a `pad.type` change,
/// held only for the length of the crossfade.
struct OutgoingStage {
    stage: PadStage,
    output_gain: f32,
}

pub(crate) struct PadTone {
    pub(crate) stack: PadOscStack,
    pub(crate) stage: PadStage,
    pub(crate) output_gain: f32,
    /// Kept so a later character swap can rebuild stages whose oscillators
    /// are pitched relative to this tone's own note.
    hz: f32,
    outgoing: Option<Outgoing<OutgoingStage>>,
}

/// Builds the one stage a `pad.type` character adds after the shared stack,
/// plus the output trim that keeps it level with the others.
fn pad_stage(character: usize, hz: f32, sample_rate: f32) -> (PadStage, f32) {
    match character {
        0 => (PadStage::None, 1.0),
        1 => (PadStage::Lowpass { state: 0.0 }, PAD_DARK_OUTPUT_GAIN),
        2 => (
            PadStage::Shimmer {
                oscillator: SineOscillator::new(hz * 4.0, sample_rate),
            },
            PAD_GLASS_OUTPUT_GAIN,
        ),
        3 => (
            PadStage::Choir {
                partial: SineOscillator::new(hz * 3.0, sample_rate),
                movement: SineOscillator::new(0.17, sample_rate),
            },
            PAD_CHOIR_OUTPUT_GAIN,
        ),
        4 => (
            PadStage::Hollow {
                sub: SineOscillator::new(hz * 0.5, sample_rate),
            },
            PAD_HOLLOW_OUTPUT_GAIN,
        ),
        5 => (
            PadStage::Tape {
                state: 0.0,
                movement: SineOscillator::new(0.11, sample_rate),
            },
            PAD_TAPE_OUTPUT_GAIN,
        ),
        _ => (PadStage::None, 1.0),
    }
}

impl PadTone {
    pub(crate) fn new(
        character: usize,
        hz: f32,
        pan: f32,
        gain: f32,
        attack_time: f32,
        release_time: f32,
        sample_rate: f32,
    ) -> Self {
        let (stage, output_gain) = pad_stage(character, hz, sample_rate);
        Self {
            stack: PadOscStack::new(hz, pan, gain, attack_time, release_time, sample_rate),
            stage,
            output_gain,
            hz,
            outgoing: None,
        }
    }

    /// Swaps in a new character stage, crossfading from the old one. The
    /// oscillator stack and the amplitude envelope are untouched, so the note
    /// keeps sounding exactly where it was in its own life.
    pub(crate) fn set_character(&mut self, character: usize, sample_rate: f32) {
        let (stage, output_gain) = pad_stage(character, self.hz, sample_rate);
        self.outgoing = Some(Outgoing::start(
            OutgoingStage {
                stage: std::mem::replace(&mut self.stage, stage),
                output_gain: std::mem::replace(&mut self.output_gain, output_gain),
            },
            PAD_TYPE_CROSSFADE_SECONDS * sample_rate,
        ));
    }

    pub(crate) fn next_stereo(
        &mut self,
        width: f32,
        detune_mix: f32,
        octave_mix: f32,
    ) -> (f32, f32) {
        let raw = self.stack.stack_sum(detune_mix, octave_mix);
        // Read once and shared by both stages: the envelope is the note's
        // own life and must not advance twice, or run differently, just
        // because a character change happens to be in flight.
        let envelope = self.stack.envelope.next();
        let mut shaped =
            soft_clip(self.stage.apply(raw) * 0.55) * envelope * self.stack.gain * self.output_gain;

        if let Some(outgoing) = &mut self.outgoing {
            let previous = soft_clip(outgoing.inner.stage.apply(raw) * 0.55)
                * envelope
                * self.stack.gain
                * outgoing.inner.output_gain;
            shaped = mix(shaped, previous, outgoing.advance());
            if outgoing.is_done() {
                self.outgoing = None;
            }
        }

        StereoPanner::equal_power(shaped, self.stack.pan * width)
    }

    pub(crate) fn release(&mut self) {
        self.stack.release();
    }

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

pub(crate) fn pad_tones(
    character: usize,
    notes: [i32; 4],
    tune: f32,
    sample_rate: f32,
    attack_time: f32,
    release_time: f32,
) -> Vec<PadTone> {
    let freqs = notes.map(|note| note_hz(note, tune));
    let pans = [-0.52_f32, -0.18, 0.16, 0.46];
    let gains = [0.17_f32, 0.132, 0.126, 0.098];
    freqs
        .iter()
        .zip(pans)
        .zip(gains)
        .map(|((hz, pan), gain)| {
            PadTone::new(
                character,
                *hz,
                pan,
                gain,
                attack_time,
                release_time,
                sample_rate,
            )
        })
        .collect()
}

pub(crate) const PROGRESSIONS: [[[i32; 4]; 8]; 8] = [
    // Progression A: with an 8s release, each chord rings well into the next
    // (and beyond), so voicings are chosen to hold at least one common tone
    // across every step, including the loop back to step 0.
    [
        [45, 50, 55, 60], // Am
        [43, 50, 57, 60], // G   (holds D3/C4 from Am)
        [45, 52, 57, 60], // Am (alt voicing, holds A3/C4 from G)
        [47, 52, 55, 62], // B   (holds E3 from Am)
        [45, 52, 57, 64], // Am (alt voicing, holds E3 from B)
        [43, 50, 55, 62], // G   (parallel shift from Am, glides in stepwise)
        [48, 55, 60, 64], // C   (holds G3 from G)
        [55, 59, 64, 67], // Em (holds G3/C4 from C, and G3 back into Am)
    ],
    [
        [45, 50, 57, 60], // Am
        [50, 53, 57, 62], // Dm
        [48, 55, 60, 64], // C
        [43, 50, 55, 59], // G
        [41, 48, 53, 57], // F
        [52, 59, 64, 67], // Em
        [45, 52, 57, 60], // Am
        [43, 50, 55, 59], // G (non-tonic close, leads back to Am)
    ],
    [
        [45, 48, 52, 55], // Am7
        [41, 45, 48, 52], // Fmaj7
        [48, 52, 55, 59], // Cmaj7
        [43, 47, 50, 53], // G7
        [50, 53, 57, 60], // Dm7
        [52, 55, 59, 62], // Em7
        [47, 50, 53, 57], // Bm7b5 (half-diminished ii)
        [43, 50, 55, 59], // G (non-tonic close)
    ],
    [
        [45, 52, 57, 60], // Am, wide
        [41, 45, 48, 55], // Fmaj9-flavor
        [48, 55, 59, 62], // Cmaj9-flavor
        [43, 50, 53, 57], // G9-flavor
        [50, 57, 60, 64], // Dm9-flavor
        [52, 55, 59, 64], // Em, open
        [47, 53, 57, 64], // Bm7b5, wide (the "ache" chord)
        [43, 50, 55, 64], // G, wide (non-tonic close)
    ],
    // Progression E: dark, phrygian-leaning modal (A phrygian: A Bb C D E F G).
    // Suspended/added-tone voicings throughout; the bII-over-tonic close
    // (step 7) is deliberately dissonant, resolving into the Am at step 0.
    [
        [45, 48, 52, 57], // Am
        [46, 50, 53, 57], // Bbmaj7 (holds A3 from Am)
        [48, 53, 55, 60], // Csus4 (holds F3 from Bbmaj7)
        [50, 53, 60, 62], // Dm7, no 5th (holds C4 from Csus4)
        [52, 59, 62, 64], // Em7sus, no 3rd (holds D4 from Dm7)
        [55, 59, 62, 64], // G6 (holds B3/D4/E4 from Em7sus)
        [55, 58, 62, 65], // Gm7 (holds G3/D4 from G6)
        [45, 52, 58, 62], // Bbmaj7/A, ache (holds Bb3/D4 from Gm7, resolves to Am)
    ],
    // Progression F: suspended drone, phrygian-tinged E pedal (open fifths,
    // sus chords). Harmonic rhythm barely moves; the E pedal keeps ringing
    // through nearly every step for a moody, unresolved feel.
    [
        [52, 55, 59, 64], // Em (drone)
        [47, 52, 59, 64], // E5/B, open (holds E3/B3/E4 from Em)
        [50, 59, 62, 67], // G/D, sus (holds B3 from E5/B)
        [45, 57, 62, 65], // Dm/A (holds D4 from G/D)
        [45, 52, 57, 64], // Asus, open (holds A3/E4 from Dm/A)
        [52, 60, 64, 67], // Cmaj/E (holds E3/E4 from Asus)
        [55, 60, 62, 65], // Gsus4 (add C/D/F) (holds C4 from Cmaj/E)
        [52, 55, 59, 62], // Em7 (holds G3 from Gsus4, resolves to Em drone)
    ],
    // Progression G: bright C-major pop loop (I-V-vi-IV), common-tone rich.
    [
        [48, 52, 55, 60], // C
        [55, 60, 62, 67], // G (add C) (holds G3/C4 from C)
        [45, 57, 60, 64], // Am (holds C4 from G)
        [53, 57, 60, 65], // F (holds A3/C4 from Am)
        [48, 52, 60, 65], // C (add F) (holds C4/F4 from F)
        [55, 60, 62, 67], // G (add C) (holds C4 from C add F)
        [53, 57, 60, 65], // F (holds C4 from G add C)
        [48, 55, 60, 64], // C (open, add E) (holds C4 from F, loops to C)
    ],
    // Progression H: bright G-major "axis" loop (I-V-iii-vi, spelled here as
    // G-D-Em7-C, played twice with varied voicings), uplifting pop feel.
    [
        [55, 59, 62, 67], // G
        [50, 54, 57, 62], // D (holds D4 from G)
        [52, 55, 59, 62], // Em7 (holds D4 from D)
        [48, 52, 55, 60], // C (holds E3/G3 from Em7)
        [43, 55, 62, 67], // G, wide (holds G3 from C)
        [50, 57, 62, 66], // D (holds D4 from G)
        [52, 59, 62, 64], // Em7 (holds D4 from D)
        [48, 55, 60, 64], // C (holds E4 from Em7, loops to G)
    ],
];

/// The pad's current chord as raw MIDI note numbers (pre-`midi_to_hz`/tune),
/// for voices — like Arp — that need to build their own note list (e.g.
/// octave-extended cycles) rather than four fixed frequencies.
pub(crate) fn pad_chord_midi(progression: usize, step: usize) -> [i32; 4] {
    PROGRESSIONS[progression % PROGRESSIONS.len()][step % 8]
}

// ============================================================
// Custom chord-slot progression
//
// A ninth progression choice ("Custom") built from user-authored chord
// slots instead of a fixed table. `progression_index`/`pad_chord_tones`
// are the single chord-source path shared by Pad, Bass, and Arp: every
// voice resolves "what chord is playing at this step" through here so a
// custom progression drives all three identically. Built-in progressions
// (0..PROGRESSIONS.len()) are untouched — this only adds one more index.
// ============================================================

/// Selecting this progression index switches Pad/Bass/Arp onto the user's
/// chord slots (`PadControls::chord_slots`) instead of the `PROGRESSIONS`
/// table.
pub(crate) const CUSTOM_PROGRESSION_INDEX: usize = PROGRESSIONS.len();

/// Resolve `pad.progression`'s raw control value to a progression index,
/// wrapping across the built-ins plus the one Custom slot.
pub(crate) fn progression_index(value: f32) -> usize {
    wrapped_index(value, CUSTOM_PROGRESSION_INDEX + 1)
}

pub(crate) fn is_custom_progression(progression: usize) -> bool {
    progression == CUSTOM_PROGRESSION_INDEX
}

/// Number of chords actually cycled through, for every progression: a
/// built-in's 8-step table is truncated to its first `chord_count` chords
/// exactly as a custom progression is, so the control never reads a length
/// the engines don't play. `CHORD_SLOT_COUNT` matches the built-in tables'
/// fixed 8-step length, so it bounds both cases.
pub(crate) fn pad_chord_count(c: &PadControls) -> usize {
    c.chord_count.round().clamp(1.0, CHORD_SLOT_COUNT as f32) as usize
}

/// Advances one shared progression cursor. Count and progression changes are
/// staged until the current loop reaches its final chord, so they never cut
/// off the chord presently sounding.
/// How Bass and Arp follow the Pad's chord loop without reaching into
/// `PadEngine`: an independent trigger on the same `pad.chord_bars` grid and
/// the same step/loop bookkeeping, so the follower's step always matches the
/// pad's. The active loop is adopted from the first frame's controls and then
/// only re-read at a loop boundary, exactly as the pad itself does.
pub(crate) struct ProgressionFollower {
    chord_trigger: GridTrigger,
    pub(crate) step_index: usize,
    active_chord_count: Option<usize>,
    active_progression: Option<usize>,
}

impl ProgressionFollower {
    pub(crate) fn new() -> Self {
        Self {
            chord_trigger: GridTrigger::after_start(),
            step_index: 0,
            active_chord_count: None,
            active_progression: None,
        }
    }

    /// Advances on the pad's chord grid and returns the `(progression, step)`
    /// to voice this frame.
    pub(crate) fn follow(&mut self, pad: &PadControls, timing: TimingContext) -> (usize, usize) {
        let progression = progression_index(pad.progression);
        let active_chord_count = self.active_chord_count.get_or_insert(pad_chord_count(pad));
        let active_progression = self.active_progression.get_or_insert(progression);
        advance_pad_progression(
            &mut self.step_index,
            active_chord_count,
            active_progression,
            pad_chord_count(pad),
            progression,
            self.chord_trigger.pop(timing, pad.chord_bars * 4.0, 0.0),
        );
        (*active_progression, self.step_index)
    }
}

pub(crate) fn advance_pad_progression(
    step_index: &mut usize,
    active_chord_count: &mut usize,
    active_progression: &mut usize,
    requested_chord_count: usize,
    requested_progression: usize,
    advance: bool,
) {
    if !advance {
        return;
    }

    *step_index += 1;
    if *step_index == *active_chord_count {
        *step_index = 0;
        *active_chord_count = requested_chord_count;
        *active_progression = requested_progression;
    }
}

/// The shared chord-source entry point for an engine step already bounded by
/// that engine's active progression length. It deliberately ignores a newly
/// requested count while the previous loop finishes.
pub(crate) fn pad_chord_tones(c: &PadControls, progression: usize, step: usize) -> [i32; 4] {
    if is_custom_progression(progression) {
        pad_chord_notes_with_slot(&c.chord_slots[step])
    } else {
        pad_chord_midi(progression, step)
    }
}

/// A custom chord slot's four voiced tones: root (tonic-relative diatonic
/// degree + accidental), then third/fifth (diatonic, with the third
/// overridable by `quality` for modal interchange), then a top voice chosen
/// by `extension`, finally reshuffled by `inversion` and de-duplicated
/// upward so inversions/accidentals never collide two voices onto one note.
pub(crate) fn pad_chord_notes_with_slot(slot: &ChordSlotControls) -> [i32; 4] {
    let root = slot_root(slot);
    let accidental = slot.accidental.round().clamp(-1.0, 1.0) as i32;
    let extension = slot.extension.round().clamp(0.0, 3.0) as i32;
    let inversion = slot.inversion.round().clamp(0.0, 3.0) as i32;
    let third = slot_third(slot, root);
    let top = match extension {
        1 => shift_diatonic(root, 6),
        2 => shift_diatonic(root, 8),
        3 => shift_diatonic(root, 10),
        _ => root + 12,
    };
    let mut notes = [root, third, shift_diatonic(root, 4), top];
    apply_inversion(&mut notes, inversion);
    if accidental != 0 {
        notes = notes.map(|note| note + accidental);
    }
    dedupe_upwards(&mut notes);
    notes
}

/// A custom chord slot's root note alone (root + accidental, before
/// extension/inversion reshuffle) — what Bass follows instead of the pad's
/// full voicing.
pub(crate) fn pad_chord_root_note(slot: &ChordSlotControls) -> i32 {
    slot_root(slot) + slot.accidental.round().clamp(-1.0, 1.0) as i32
}

/// Whether a slot's resolved third is minor — honors a forced `quality`,
/// otherwise reports what the diatonic scale gives at this degree. Drives the
/// Quality row's "scale (min)"-style display so the inherit position still
/// tells the user what they're hearing.
pub(crate) fn pad_chord_slot_is_minor(slot: &ChordSlotControls) -> bool {
    let root = slot_root(slot);
    slot_third(slot, root) - root == 3
}

/// A2, matching `PROGRESSIONS`' shared tonal center: the note a custom
/// slot's `degree` counts from.
const CUSTOM_TONIC: i32 = 45;

/// A custom slot's root before its accidental: the tonic shifted by the
/// slot's diatonic degree.
fn slot_root(slot: &ChordSlotControls) -> i32 {
    shift_diatonic(CUSTOM_TONIC, slot.degree.round().clamp(-7.0, 7.0) as i32)
}

/// A custom slot's third: forced minor/major by `quality`, otherwise the
/// diatonic third above `root`.
fn slot_third(slot: &ChordSlotControls, root: i32) -> i32 {
    match slot.quality.round().clamp(-1.0, 1.0) as i32 {
        -1 => root + 3,
        1 => root + 4,
        _ => shift_diatonic(root, 2),
    }
}

/// Move `note` by `steps` positions on the diatonic major scale (not raw
/// semitones), preserving octave-crossing correctly in either direction.
fn shift_diatonic(note: i32, steps: i32) -> i32 {
    const SCALE: [i32; 7] = [0, 2, 4, 5, 7, 9, 11];
    let octave = note.div_euclid(12);
    let pitch = note.rem_euclid(12);
    let degree = SCALE
        .iter()
        .position(|&pc| pc == pitch)
        .map(|index| octave * 7 + index as i32)
        .unwrap_or_else(|| octave * 7);
    let shifted = degree + steps;
    let shifted_octave = shifted.div_euclid(7);
    let shifted_degree = shifted.rem_euclid(7) as usize;
    shifted_octave * 12 + SCALE[shifted_degree]
}

/// Move the lowest voice(s) up an octave `inversion` times, re-sorting after
/// each move so successive inversions keep stacking correctly.
fn apply_inversion(notes: &mut [i32; 4], inversion: i32) {
    notes.sort_unstable();
    for _ in 0..inversion {
        notes[0] += 12;
        notes.sort_unstable();
    }
}

/// Nudge any voice that lands on or below the one before it up by diatonic
/// steps until the chord is strictly ascending — accidentals or inversions
/// can otherwise stack two voices onto the same (or a crossed) pitch.
fn dedupe_upwards(notes: &mut [i32; 4]) {
    notes.sort_unstable();
    for i in 1..notes.len() {
        while notes[i] <= notes[i - 1] {
            notes[i] = shift_diatonic(notes[i], 1);
        }
    }
}