nooise 2.5.4

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
//! Per-layer module slots.
//!
//! A layer carries a fixed number of anonymous slots. Each slot stores *which*
//! module is loaded as a value (`kind`, an index into [`MODULE_CATALOG`]) plus
//! family-shaped params. The module's name is deliberately never part of a
//! control id: ids are permanent entries in the append-only song-code table,
//! so putting the catalog in the id space would make every future module cost
//! another block of them forever.
//!
//! See `docs/proposals/2026-07-30-module-slot-addressing.md`.

use crate::fx::filter::FilterType;

/// Slots per layer. Appending more later is a pure append to the song-id
/// table; removing any is impossible, so this starts deliberately small.
pub(crate) const MODULE_SLOTS: usize = 8;
pub(crate) const MODULE_LAYERS: usize = 9;

/// Where a module runs. Taken from the loaded module, never from the slot
/// index, so all slots stay interchangeable and the UI shows one flat chain.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Domain {
    /// Intercepts the grid trigger before a voice fires.
    Pre,
    /// Runs on the rendered signal.
    Post,
}

/// Which parameter shape a module projects through the reusable detail drill.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Family {
    /// `amount` only.
    SingleAmount,
    /// `amount` plus `time`.
    TwoKnob,
    /// Stereo delay with a persisted clock mode, left/right time, and feedback.
    Delay,
    /// Reverb with size and damping controls behind one Amount row.
    Reverb,
    /// Compressor with threshold, ratio, release, and makeup controls.
    Compression,
    /// Stereo filter with cutoff, resonance, and response type controls.
    Filter,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModuleSlotField {
    Kind,
    Amount,
    Time,
    RightTime,
    Clock,
    RightClock,
    Feedback,
    Vintage,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct EffectParameter {
    pub(crate) field: ModuleSlotField,
    pub(crate) label: &'static str,
}

const DELAY_PARAMETERS: &[EffectParameter] = &[
    EffectParameter {
        field: ModuleSlotField::Amount,
        label: "Amount",
    },
    EffectParameter {
        field: ModuleSlotField::Time,
        label: "Left Time",
    },
    EffectParameter {
        field: ModuleSlotField::RightTime,
        label: "Right Time",
    },
    EffectParameter {
        field: ModuleSlotField::Feedback,
        label: "Feedback",
    },
    EffectParameter {
        field: ModuleSlotField::Vintage,
        label: "Vintage",
    },
];

const REVERB_PARAMETERS: &[EffectParameter] = &[
    EffectParameter {
        field: ModuleSlotField::Amount,
        label: "Amount",
    },
    EffectParameter {
        field: ModuleSlotField::Time,
        label: "Size",
    },
    EffectParameter {
        field: ModuleSlotField::Feedback,
        label: "Damping",
    },
];

const COMPRESSION_PARAMETERS: &[EffectParameter] = &[
    EffectParameter {
        field: ModuleSlotField::Amount,
        label: "Amount",
    },
    EffectParameter {
        field: ModuleSlotField::Time,
        label: "Threshold",
    },
    EffectParameter {
        field: ModuleSlotField::RightTime,
        label: "Ratio",
    },
    EffectParameter {
        field: ModuleSlotField::Feedback,
        label: "Release",
    },
    EffectParameter {
        field: ModuleSlotField::Vintage,
        label: "Makeup",
    },
];

/// Cutoff leads because it is the collapsed row; the wet/dry Amount a
/// filter rarely needs sits last.
const FILTER_PARAMETERS: &[EffectParameter] = &[
    EffectParameter {
        field: ModuleSlotField::Time,
        label: "Cutoff",
    },
    EffectParameter {
        field: ModuleSlotField::RightTime,
        label: "Resonance",
    },
    EffectParameter {
        field: ModuleSlotField::Feedback,
        label: "Type",
    },
    EffectParameter {
        field: ModuleSlotField::Amount,
        label: "Amount",
    },
];

const SINGLE_AMOUNT_PARAMETERS: &[EffectParameter] = &[EffectParameter {
    field: ModuleSlotField::Amount,
    label: "Amount",
}];

const TWO_KNOB_PARAMETERS: &[EffectParameter] = &[
    EffectParameter {
        field: ModuleSlotField::Amount,
        label: "Amount",
    },
    EffectParameter {
        field: ModuleSlotField::Time,
        label: "Time",
    },
];

impl ModuleKind {
    pub(crate) fn parameters(self) -> &'static [EffectParameter] {
        match self.family {
            Family::SingleAmount => SINGLE_AMOUNT_PARAMETERS,
            Family::TwoKnob => TWO_KNOB_PARAMETERS,
            Family::Delay => DELAY_PARAMETERS,
            Family::Reverb => REVERB_PARAMETERS,
            Family::Compression => COMPRESSION_PARAMETERS,
            Family::Filter => FILTER_PARAMETERS,
        }
    }

    /// The field a loaded slot collapses to when not drilled into. Every
    /// family collapses to its wet/dry `Amount` except Filter, whose most
    /// useful single knob is `Cutoff` (`Time`) — its `Amount` mix is a
    /// detail-only control, defaulted fully wet in [`preset_slot`].
    /// Whether Enter on the collapsed row opens a detail drill: every family
    /// with more than the one knob its collapsed row already shows.
    pub(crate) fn has_detail(self) -> bool {
        self.parameters().len() > 1
    }

    pub(crate) fn collapsed_field(self) -> ModuleSlotField {
        match self.family {
            Family::Filter => ModuleSlotField::Time,
            _ => ModuleSlotField::Amount,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ModuleKind {
    /// Stable, lowercase, used for fuzzy-find matching.
    pub(crate) id: &'static str,
    pub(crate) display_name: &'static str,
    pub(crate) domain: Domain,
    pub(crate) family: Family,
}

/// The v1 catalog.
///
/// APPEND-ONLY IN EFFECT: a slot stores its module as an index into this
/// array, and those indexes are written into song codes. Reordering or
/// removing an entry silently rewrites what every saved song is using.
/// Appending is always safe.
pub(crate) const MODULE_CATALOG: &[ModuleKind] = &[
    ModuleKind {
        id: "alcohol",
        display_name: "Alcohol",
        domain: Domain::Pre,
        family: Family::SingleAmount,
    },
    ModuleKind {
        id: "swing",
        display_name: "Swing",
        domain: Domain::Pre,
        family: Family::SingleAmount,
    },
    ModuleKind {
        id: "drive",
        display_name: "Drive",
        domain: Domain::Post,
        family: Family::SingleAmount,
    },
    ModuleKind {
        id: "room",
        display_name: "Reverb",
        domain: Domain::Post,
        family: Family::Reverb,
    },
    ModuleKind {
        id: "sidechain",
        display_name: "Sidechain",
        domain: Domain::Post,
        family: Family::TwoKnob,
    },
    ModuleKind {
        id: "delay",
        display_name: "Delay",
        domain: Domain::Post,
        family: Family::Delay,
    },
    ModuleKind {
        id: "compression",
        display_name: "Compression",
        domain: Domain::Post,
        family: Family::Compression,
    },
    ModuleKind {
        id: "filter",
        display_name: "Filter",
        domain: Domain::Post,
        family: Family::Filter,
    },
];

/// The timing behavior an active delay uses. The stored time values carry
/// only the selected representation; changing modes converts them in place.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DelayClock {
    Sync,
    Free,
}

pub(crate) const DELAY_SYNC_MIN_BEATS: f32 = 0.125;
pub(crate) const DELAY_SYNC_MAX_BEATS: f32 = 4.0;
pub(crate) const DELAY_FREE_MIN_MS: f32 = 10.0;
pub(crate) const DELAY_FREE_MAX_MS: f32 = 2_000.0;
const DELAY_SYNC_STEP_BEATS: f32 = 0.125;
const DELAY_FREE_STEP_MS: f32 = 10.0;

/// Change a delay slot's persisted clock mode while preserving the closest
/// audible duration at the current tempo. One active pair is stored; there is
/// deliberately no hidden Sync/Free second state to restore later.
pub(crate) fn switch_delay_clock(slot: &mut ModuleSlot, right: bool, bpm: f32) {
    let clock = if right {
        &mut slot.right_clock
    } else {
        &mut slot.clock
    };
    let time = if right {
        &mut slot.right_time
    } else {
        &mut slot.time
    };
    let from = DelayClock::from_value(*clock);
    let (base_from, base_to, min, max, step, next_clock) = match from {
        DelayClock::Sync => (
            super::TimeBase::Beats,
            super::TimeBase::Ms,
            DELAY_FREE_MIN_MS,
            DELAY_FREE_MAX_MS,
            DELAY_FREE_STEP_MS,
            DelayClock::Free,
        ),
        DelayClock::Free => (
            super::TimeBase::Ms,
            super::TimeBase::Beats,
            DELAY_SYNC_MIN_BEATS,
            DELAY_SYNC_MAX_BEATS,
            DELAY_SYNC_STEP_BEATS,
            DelayClock::Sync,
        ),
    };
    *time = super::snap_step(
        super::convert_time_base(*time, base_from, base_to, bpm),
        step,
    )
    .clamp(min, max);
    *clock = next_clock.value();
}

/// Current milliseconds for the DSP delay line, regardless of the saved
/// control representation.
pub(crate) fn delay_time_ms(value: f32, clock: DelayClock, bpm: f32) -> f32 {
    match clock {
        DelayClock::Sync => super::beats_to_ms(value, bpm),
        DelayClock::Free => value,
    }
}

impl DelayClock {
    pub(crate) const fn value(self) -> f32 {
        match self {
            Self::Sync => 0.0,
            Self::Free => 1.0,
        }
    }

    pub(crate) fn from_value(value: f32) -> Self {
        if value.round() == Self::Free.value() {
            Self::Free
        } else {
            Self::Sync
        }
    }

    pub(crate) const fn label(self) -> &'static str {
        match self {
            Self::Sync => "Sync",
            Self::Free => "Free",
        }
    }
}

/// A Filter's cutoff dial spans the audible band on a Log2 taper.
pub(crate) const FILTER_CUTOFF_MIN_HZ: f32 = 20.0;
pub(crate) const FILTER_CUTOFF_MAX_HZ: f32 = 20_000.0;

/// Where Perc, Bass, and Kick's factory Filters sit. Their default sound was
/// voiced there, and a saved song that never touched one carries no cutoff
/// at all, so moving this would re-voice every such song.
const FACTORY_FILTER_CUTOFF_HZ: f32 = 8_000.0;

/// Clap's factory Filter cutoff, fully wet like any Filter. The clap once ran
/// its noise through a one-pole lowpass of its own (`clap.filter`, default
/// 0.7); this is the cutoff of the least-squares fit of the shared Filter to
/// that voice's rendered default clap. The fit wanted a 90% mix to keep the
/// one-pole's gentler skirt; the factory filter starts fully wet instead, so
/// the default clap is darker than the retired one (spectral centroid about
/// 1.3 kHz against 1.7 kHz) and about half a decibel louder.
pub(crate) const CLAP_FACTORY_FILTER_CUTOFF_HZ: f32 = 3_170.0;

/// Change a Filter slot's response type. Swapping Low-pass and High-pass
/// mirrors the cutoff across the dial (`min * max / hz`, the same number of
/// octaves in from the opposite end), so a filter that was nearly
/// transparent stays nearly transparent instead of a high-pass at a high
/// cutoff taking out the whole signal. Band-pass has no transparent end, so
/// a switch to or from it keeps the cutoff.
pub(crate) fn switch_filter_type(slot: &mut ModuleSlot, next: f32) {
    let flips = matches!(
        (
            FilterType::from_value(slot.feedback),
            FilterType::from_value(next)
        ),
        (FilterType::Low, FilterType::High) | (FilterType::High, FilterType::Low)
    );
    if flips {
        slot.time = (FILTER_CUTOFF_MIN_HZ * FILTER_CUTOFF_MAX_HZ / slot.time)
            .clamp(FILTER_CUTOFF_MIN_HZ, FILTER_CUTOFF_MAX_HZ);
    }
    slot.feedback = next;
}

/// `kind` value meaning "no module here". Catalog entry `n` is stored as
/// `n + 1`, so the empty slot is the default and prunes out of song codes.
pub(crate) const MODULE_EMPTY: f32 = 0.0;

/// Highest valid `kind` value. Const so the registry macro can use it as a
/// spec bound instead of restating `MODULE_CATALOG.len()`.
pub(crate) const fn module_kind_max() -> f32 {
    MODULE_CATALOG.len() as f32
}

/// The module a stored `kind` value names, or `None` for an empty slot.
pub(crate) fn module_kind_at(value: f32) -> Option<&'static ModuleKind> {
    let index = value.round();
    if index < 1.0 {
        return None;
    }
    MODULE_CATALOG.get(index as usize - 1)
}

/// Display string for a slot's `kind` row.
pub(crate) fn module_kind_label(value: f32) -> String {
    module_kind_at(value).map_or_else(|| "empty".to_string(), |kind| kind.display_name.to_string())
}

/// Label for a loaded slot's collapsed row on its page. A module with a
/// detail drill carries the same `›` the tab strip shows once inside it, so
/// the page says which rows Enter opens.
pub(crate) fn module_row_label(value: f32) -> String {
    match module_kind_at(value) {
        Some(kind) if kind.has_detail() => format!("{} ›", kind.display_name),
        _ => module_kind_label(value),
    }
}

/// One slot's stored state. Defaults to empty and inert, which is what lets a
/// module be added automatically without confirmation: nothing is audible
/// until a knob moves.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ModuleSlot {
    pub(crate) kind: f32,
    pub(crate) amount: f32,
    pub(crate) time: f32,
    pub(crate) right_time: f32,
    pub(crate) clock: f32,
    pub(crate) right_clock: f32,
    pub(crate) feedback: f32,
    pub(crate) vintage: f32,
}

impl ModuleSlot {
    pub(crate) fn is_empty(&self) -> bool {
        module_kind_at(self.kind).is_none()
    }

    pub(crate) fn kind(&self) -> Option<&'static ModuleKind> {
        module_kind_at(self.kind)
    }
}

/// Position of a catalog id in `MODULE_CATALOG`. Panics on an unknown id,
/// which can only be a typo in a compile-time constant.
pub(crate) fn module_catalog_index(id: &str) -> usize {
    MODULE_CATALOG
        .iter()
        .position(|kind| kind.id == id)
        .expect("catalog id must exist")
}

/// Index a catalog id occupies as a stored `kind` value (`MODULE_EMPTY` is
/// 0, so entry `n` is stored as `n + 1`).
pub(crate) fn module_kind_value(id: &str) -> f32 {
    module_catalog_index(id) as f32 + 1.0
}

/// One slot pre-loaded with a module at a factory amount. Used for the
/// effects that shipped as bespoke per-voice sliders before the module chain
/// existed, so the default sound is byte-identical.
pub(crate) fn preset_slot(id: &str, amount: f32) -> ModuleSlot {
    let mut slot = ModuleSlot {
        kind: module_kind_value(id),
        amount,
        clock: DelayClock::Sync.value(),
        right_clock: DelayClock::Sync.value(),
        ..ModuleSlot::default()
    };
    match id {
        "delay" => {
            slot.time = 0.5;
            slot.right_time = 0.75;
            slot.feedback = 0.35;
        }
        "room" => {
            slot.time = 0.72;
            slot.feedback = 0.45;
        }
        "compression" => {
            slot.time = -8.0;
            slot.right_time = 2.0;
            slot.feedback = 100.0;
            slot.vintage = 2.0;
        }
        "filter" => {
            // Amount (wet/dry mix) is detail-only, so it can't carry the
            // "added modules start inert" contract other families use — it
            // always sets fully wet, overriding the caller's `amount`.
            // Cutoff is the collapsed row instead, and starts maxed out
            // (audibly transparent low-pass); turning it down is the first
            // audible move, same as another module's amount starting at 0%.
            slot.amount = 1.0;
            slot.time = FILTER_CUTOFF_MAX_HZ;
            slot.right_time = 0.0;
            slot.feedback = 0.0;
        }
        _ => {}
    }
    slot
}

/// Amount of the first slot holding `id`, or zero when the chain has none.
/// The single read path for an effect that used to be a bespoke field.
pub(crate) fn chain_amount(slots: &[ModuleSlot; MODULE_SLOTS], id: &str) -> f32 {
    chain_amount_slot(slots, id).map_or(0.0, |index| slots[index].amount)
}

/// Every layer's slots. Held on `FluidControls` rather than inside each voice
/// struct so the voices stay unaware of the module chain until execution.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LayerModules {
    pub(crate) pad: [ModuleSlot; MODULE_SLOTS],
    pub(crate) perc: [ModuleSlot; MODULE_SLOTS],
    pub(crate) bass: [ModuleSlot; MODULE_SLOTS],
    pub(crate) kick: [ModuleSlot; MODULE_SLOTS],
    pub(crate) tonal: [ModuleSlot; MODULE_SLOTS],
    pub(crate) clap: [ModuleSlot; MODULE_SLOTS],
    pub(crate) arp: [ModuleSlot; MODULE_SLOTS],
    pub(crate) lead: [ModuleSlot; MODULE_SLOTS],
    pub(crate) master: [ModuleSlot; MODULE_SLOTS],
}

impl Default for LayerModules {
    /// Factory module chains. Every unlisted slot is empty.
    fn default() -> Self {
        let empty = [ModuleSlot::default(); MODULE_SLOTS];
        let with_preset = |id: &str, amount: f32| {
            let mut slots = empty;
            slots[0] = preset_slot(id, amount);
            slots
        };
        let with_factory_filter = || {
            let mut slots = with_preset("filter", 1.0);
            slots[0].time = FACTORY_FILTER_CUTOFF_HZ;
            slots
        };
        Self {
            pad: with_preset("room", 0.4),
            perc: with_factory_filter(),
            bass: {
                let mut slots = with_factory_filter();
                slots[1] = preset_slot("drive", 0.15);
                slots
            },
            kick: {
                let mut slots = with_factory_filter();
                slots[1] = preset_slot("drive", 0.2);
                slots
            },
            tonal: with_preset("room", 0.1),
            clap: {
                let mut slots = with_preset("filter", 1.0);
                slots[0].time = CLAP_FACTORY_FILTER_CUTOFF_HZ;
                slots
            },
            arp: with_preset("room", 0.0),
            // The lead's "slightly distorted" character is the shared Drive
            // module, not a bespoke control, so a player can push it further
            // or take it off like any other effect.
            lead: with_preset("drive", 0.1),
            master: {
                let mut slots = empty;
                slots[0] = preset_slot("drive", 0.05);
                slots[1] = preset_slot("compression", 0.1);
                slots
            },
        }
    }
}

impl LayerModules {
    /// The slots a tab owns, or `None` for a tab with no chain of its own.
    pub(crate) fn for_tab(&self, tab: super::Tab) -> Option<&[ModuleSlot; MODULE_SLOTS]> {
        match tab {
            super::Tab::Chords => Some(&self.pad),
            super::Tab::Perc => Some(&self.perc),
            super::Tab::Bass => Some(&self.bass),
            super::Tab::Kick => Some(&self.kick),
            super::Tab::Tonal => Some(&self.tonal),
            super::Tab::Clap => Some(&self.clap),
            super::Tab::Arp => Some(&self.arp),
            super::Tab::Lead => Some(&self.lead),
            super::Tab::Master => Some(&self.master),
        }
    }

    pub(crate) fn for_tab_mut(
        &mut self,
        tab: super::Tab,
    ) -> Option<&mut [ModuleSlot; MODULE_SLOTS]> {
        match tab {
            super::Tab::Chords => Some(&mut self.pad),
            super::Tab::Perc => Some(&mut self.perc),
            super::Tab::Bass => Some(&mut self.bass),
            super::Tab::Kick => Some(&mut self.kick),
            super::Tab::Tonal => Some(&mut self.tonal),
            super::Tab::Clap => Some(&mut self.clap),
            super::Tab::Arp => Some(&mut self.arp),
            super::Tab::Lead => Some(&mut self.lead),
            super::Tab::Master => Some(&mut self.master),
        }
    }
}

/// Whether this tab owns a module chain at all. Pure: the palette's entry
/// list depends on it and must not read live controls.
pub(crate) fn tab_has_module_chain(_tab: super::Tab) -> bool {
    true
}

/// Whether a catalog entry has a real processor on this layer. Alcohol and
/// Sidechain retain their saved catalog indexes but stay out of the add
/// palette until they have DSP; an addable row must never be inert.
pub(crate) fn module_available_on(kind: ModuleKind, tab: super::Tab) -> bool {
    match kind.id {
        "swing" => !matches!(tab, super::Tab::Chords | super::Tab::Master),
        "drive" | "room" | "delay" | "compression" | "filter" => tab_has_module_chain(tab),
        _ => false,
    }
}

pub(crate) fn module_layer_index(tab: super::Tab) -> Option<usize> {
    match tab {
        super::Tab::Chords => Some(0),
        super::Tab::Perc => Some(1),
        super::Tab::Bass => Some(2),
        super::Tab::Kick => Some(3),
        super::Tab::Tonal => Some(4),
        super::Tab::Clap => Some(5),
        super::Tab::Arp => Some(6),
        super::Tab::Lead => Some(7),
        super::Tab::Master => Some(8),
    }
}

/// Index of the first slot holding `id`.
pub(crate) fn chain_amount_slot(slots: &[ModuleSlot; MODULE_SLOTS], id: &str) -> Option<usize> {
    slots
        .iter()
        .position(|slot| slot.kind().is_some_and(|kind| kind.id == id))
}

/// Resolve pre-synthesis module values into the grid fields the voices read.
/// Post-synthesis effects execute directly through `ModuleFxBank` instead of
/// being copied back into bespoke voice controls.
pub(crate) fn resolve_module_chain(c: &mut super::FluidControls) {
    c.perc.swing = chain_amount(&c.modules.perc, "swing");
    c.kick.swing = chain_amount(&c.modules.kick, "swing");
    c.tonal.swing = chain_amount(&c.modules.tonal, "swing");
    c.arp.swing = chain_amount(&c.modules.arp, "swing");
    c.lead.swing = chain_amount(&c.modules.lead, "swing");
    c.clap.swing = chain_amount(&c.modules.clap, "swing");
    c.bass.swing = chain_amount(&c.modules.bass, "swing");
}

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

    #[test]
    fn a_default_slot_is_empty_and_therefore_inert() {
        let slot = ModuleSlot::default();
        assert!(slot.is_empty());
        assert_eq!(slot.kind, MODULE_EMPTY);
        assert_eq!(module_kind_label(slot.kind), "empty");
    }

    #[test]
    fn catalog_indexes_are_one_based_so_zero_stays_empty() {
        assert!(module_kind_at(0.0).is_none());
        assert_eq!(module_kind_at(1.0).unwrap().id, "alcohol");
        assert_eq!(
            module_kind_at(module_kind_max()).unwrap().id,
            MODULE_CATALOG.last().unwrap().id
        );
        // Past the end is empty, not a panic: a song code from a later
        // version naming an unknown module must degrade, not crash.
        assert!(module_kind_at(module_kind_max() + 1.0).is_none());
    }

    #[test]
    fn switching_delay_clock_converts_only_the_selected_channel() {
        let mut slot = ModuleSlot {
            time: 0.5,
            right_time: 0.75,
            ..ModuleSlot::default()
        };
        switch_delay_clock(&mut slot, false, 120.0);
        assert_eq!(DelayClock::from_value(slot.clock), DelayClock::Free);
        assert_eq!((slot.time, slot.right_time), (250.0, 0.75));

        switch_delay_clock(&mut slot, true, 120.0);
        assert_eq!(DelayClock::from_value(slot.right_clock), DelayClock::Free);
        assert_eq!((slot.time, slot.right_time), (250.0, 380.0));

        switch_delay_clock(&mut slot, false, 120.0);
        assert_eq!(DelayClock::from_value(slot.clock), DelayClock::Sync);
        assert_eq!((slot.time, slot.right_time), (0.5, 380.0));
    }

    #[test]
    fn every_addable_module_has_a_complete_layer_execution_contract() {
        for tab in super::super::Tab::all() {
            for kind in MODULE_CATALOG {
                let expected = match kind.id {
                    "drive" | "room" | "delay" | "compression" | "filter" => {
                        tab_has_module_chain(tab)
                    }
                    "swing" => matches!(
                        tab,
                        super::super::Tab::Perc
                            | super::super::Tab::Bass
                            | super::super::Tab::Kick
                            | super::super::Tab::Tonal
                            | super::super::Tab::Clap
                            | super::super::Tab::Arp
                            | super::super::Tab::Lead
                    ),
                    "alcohol" | "sidechain" => false,
                    other => panic!("catalog entry {other} needs an availability contract"),
                };
                assert_eq!(
                    module_available_on(*kind, tab),
                    expected,
                    "{} on {}",
                    kind.id,
                    tab.name()
                );
            }
        }
    }

    /// A detail drill opens on the knob its collapsed row showed, so the
    /// page and the drill agree on what the module's main control is.
    #[test]
    fn every_detail_drill_leads_with_its_collapsed_row() {
        for kind in MODULE_CATALOG {
            assert_eq!(
                kind.parameters()[0].field,
                kind.collapsed_field(),
                "{} detail must lead with its collapsed row",
                kind.id
            );
        }
    }

    #[test]
    fn clap_factory_filter_is_a_fully_wet_low_pass_at_its_fitted_cutoff() {
        let slot = LayerModules::default().clap[0];
        assert_eq!(slot.kind().map(|kind| kind.id), Some("filter"));
        assert_eq!(slot.amount, 1.0);
        assert_eq!(slot.time, CLAP_FACTORY_FILTER_CUTOFF_HZ);
        assert!(matches!(
            FilterType::from_value(slot.feedback),
            FilterType::Low
        ));
        assert_eq!(slot.right_time, 0.0);
    }

    #[test]
    fn an_added_filter_starts_at_the_top_of_its_dial() {
        assert_eq!(preset_slot("filter", 0.0).time, FILTER_CUTOFF_MAX_HZ);
    }

    #[test]
    fn swapping_low_and_high_pass_mirrors_the_cutoff_across_the_dial() {
        let (low, high, band) = (0.0, 1.0, 2.0);
        let mut slot = preset_slot("filter", 0.0);
        switch_filter_type(&mut slot, high);
        assert_eq!(slot.time, FILTER_CUTOFF_MIN_HZ);
        switch_filter_type(&mut slot, low);
        assert_eq!(slot.time, FILTER_CUTOFF_MAX_HZ);

        // 1 kHz is as many octaves above the floor as 400 Hz is below the top.
        slot.time = 1_000.0;
        switch_filter_type(&mut slot, high);
        assert!((slot.time - 400.0).abs() < 0.01, "{}", slot.time);

        // Band-pass has no transparent end to mirror towards.
        switch_filter_type(&mut slot, band);
        assert!((slot.time - 400.0).abs() < 0.01, "{}", slot.time);
        switch_filter_type(&mut slot, low);
        assert!((slot.time - 400.0).abs() < 0.01, "{}", slot.time);
        assert_eq!(slot.feedback, low);
    }

    #[test]
    fn catalog_ids_are_unique_and_lowercase() {
        for (i, kind) in MODULE_CATALOG.iter().enumerate() {
            assert_eq!(
                kind.id,
                kind.id.to_lowercase(),
                "{} must be lowercase",
                kind.id
            );
            assert!(
                !MODULE_CATALOG[..i].iter().any(|other| other.id == kind.id),
                "duplicate catalog id {}",
                kind.id
            );
        }
    }

    #[test]
    fn only_two_knob_modules_use_the_time_param() {
        assert!(matches!(Family::SingleAmount, Family::SingleAmount));
        assert!(matches!(Family::TwoKnob, Family::TwoKnob));
    }
}