nooise 1.2.0

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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
use super::*;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;

const SAMPLE_RATE: f32 = 48_000.0;

fn assert_close(actual: f32, expected: f32) {
    assert!(
        (actual - expected).abs() < f32::EPSILON,
        "expected {expected}, got {actual}"
    );
}

fn assert_near(actual: f32, expected: f32) {
    assert!(
        (actual - expected).abs() < 1e-5,
        "expected {expected}, got {actual}"
    );
}

fn timing(sample: u64, bpm: f32) -> TimingContext {
    let sample_rate = f64::from(SAMPLE_RATE);
    let bpm = f64::from(bpm);
    let beat = sample as f64 * bpm / (60.0 * sample_rate);
    TimingContext::new(sample_rate, bpm, beat)
}

fn append_record_to_code(code: &str, record_type: u8, payload: &[u8]) -> String {
    let encoded = code.strip_prefix("n1_").unwrap();
    let mut bytes = URL_SAFE_NO_PAD.decode(encoded).unwrap();
    song::write_record(record_type, payload, &mut bytes).unwrap();
    format!("n1_{}", URL_SAFE_NO_PAD.encode(bytes))
}

fn write_test_str(value: &str, out: &mut Vec<u8>) {
    out.push(value.len() as u8);
    out.extend_from_slice(value.as_bytes());
}

fn automation_payload(target_id: &str, route: LfoRoute) -> Vec<u8> {
    let mut payload = Vec::new();
    payload.push(2);
    payload.extend_from_slice(&1u16.to_le_bytes());
    write_test_str(target_id, &mut payload);
    payload.extend_from_slice(&route.cycle_beats.to_le_bytes());
    payload.extend_from_slice(&route.depth_ratio.to_le_bytes());
    payload.push(0);
    payload.extend_from_slice(&route.phase_offset_beats.to_le_bytes());
    payload
}

fn buffer_text(buffer: &Buffer) -> String {
    buffer
        .content
        .iter()
        .map(|cell| cell.symbol())
        .collect::<String>()
}

#[test]
fn midi_to_hz_matches_known_notes() {
    assert_close(midi_to_hz(69), 440.0); // A4
    assert_close(midi_to_hz(45), 110.0); // A2
    assert_close(midi_to_hz(60), 440.0 * 2f32.powf((60.0 - 69.0) / 12.0)); // C4
}

#[test]
fn pad_chord_converts_progression_a_first_chord() {
    let chord = pad_chord(0, 0, 0.0);
    assert_close(chord[0], 110.0); // A2
    assert_close(chord[1], 440.0 * 2f32.powf((50.0 - 69.0) / 12.0)); // D3
    assert_close(chord[2], 440.0 * 2f32.powf((55.0 - 69.0) / 12.0)); // G3
    assert_close(chord[3], 440.0 * 2f32.powf((60.0 - 69.0) / 12.0)); // C4
}

#[test]
fn pad_chord_applies_master_tune_offset() {
    let flat = pad_chord(0, 0, 0.0);
    let up_octave = pad_chord(0, 0, 12.0);
    let down_octave = pad_chord(0, 0, -12.0);
    for i in 0..4 {
        assert_close(up_octave[i], flat[i] * 2.0);
        assert_close(down_octave[i], flat[i] * 0.5);
    }
}

#[test]
fn pad_chord_converts_progression_d_last_chord() {
    let chord = pad_chord(3, 7, 0.0);
    assert_close(chord[0], 440.0 * 2f32.powf((43.0 - 69.0) / 12.0)); // G2
    assert_close(chord[1], 440.0 * 2f32.powf((50.0 - 69.0) / 12.0)); // D3
    assert_close(chord[2], 440.0 * 2f32.powf((55.0 - 69.0) / 12.0)); // G3
    assert_close(chord[3], 440.0 * 2f32.powf((64.0 - 69.0) / 12.0)); // E4
}

#[test]
fn pad_chord_wraps_progression_and_step_index() {
    let wrapped_progression = pad_chord(4, 0, 0.0);
    let base_progression = pad_chord(0, 0, 0.0);
    assert_eq!(wrapped_progression, base_progression);

    let wrapped_step = pad_chord(0, 8, 0.0);
    let base_step = pad_chord(0, 0, 0.0);
    assert_eq!(wrapped_step, base_step);
}

#[test]
fn tonal_phrase_a_keeps_existing_zero_randomness_melody() {
    assert_eq!(tonal_phrase(0), &[45, 50, 55, 48, 52, 57, 50, 55]);
}

#[test]
fn tonal_note_applies_master_tune_offset() {
    let flat = tonal_note_hz(45, 0.0);
    assert_close(tonal_note_hz(45, 12.0), flat * 2.0);
    assert_close(tonal_note_hz(45, -12.0), flat * 0.5);
}

#[test]
fn tonal_low_cut_reduces_sub_energy_without_thinning_low_notes() {
    fn filtered_sine_rms(hz: f32) -> f32 {
        let mut low_cut = TonalLowCut::new(SAMPLE_RATE, TONAL_LOW_CUT_HZ);
        let total = SAMPLE_RATE as u64 * 2;
        let warmup = SAMPLE_RATE as u64 / 2;
        let mut sum = 0.0f32;
        let mut count = 0u64;

        for sample in 0..total {
            let phase = TAU * hz * sample as f32 / SAMPLE_RATE;
            let filtered = low_cut.process(phase.sin());
            if sample >= warmup {
                sum += filtered * filtered;
                count += 1;
            }
        }

        (sum / count as f32).sqrt()
    }

    let sub = filtered_sine_rms(TONAL_LOW_CUT_HZ * 0.5);
    let low_a = filtered_sine_rms(110.0);

    assert!(sub < 0.4, "sub rms should be reduced, got {sub}");
    assert!(
        low_a > 0.55,
        "lowest tonal fundamental should stay present, got {low_a}"
    );
    assert!(
        low_a > sub * 1.5,
        "low note should survive more than sub energy: sub {sub}, low_a {low_a}"
    );
}

#[test]
fn tonal_cycle_crops_phrase_without_stretching_rate() {
    assert_eq!(tonal_loop_len(4.0, 0.5), 8);
    assert_eq!(tonal_loop_len(16.0, 0.5), 32);
    assert_eq!(tonal_loop_len(4.0, 1.0), 4);
    assert_eq!(tonal_cycle_step(3.75, 4.0, 0.0, 0.5), 7);
    assert_eq!(tonal_cycle_step(3.75, 4.0, 0.0, 1.0), 3);
    assert_eq!(tonal_cycle_step(4.0, 4.0, 0.0, 0.5), 0);
}

#[test]
fn tonal_rate_controls_trigger_spacing_independent_of_cycle() {
    let controls = TonalControls {
        rate_beats: 1.0,
        step_interval_beats: 4.0,
        randomness: 0.0,
        ..TonalControls::default()
    };
    let mut tonal = TonalEngine::new(SAMPLE_RATE);

    let _ = tonal.next(
        &controls,
        0.0,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 0.0),
    );
    assert_eq!(tonal.step_index, 0);

    let _ = tonal.next(
        &controls,
        0.0,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 0.5),
    );
    assert_eq!(tonal.step_index, 0);

    let _ = tonal.next(
        &controls,
        0.0,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 1.0),
    );
    assert_eq!(tonal.step_index, 1);
}

#[test]
fn tonal_evolve_rate_maps_to_actual_notes_per_cycle() {
    assert_eq!(tonal_evolve_note_count(0.0, 8), 0);
    assert_eq!(tonal_evolve_note_count(0.01, 8), 1);
    assert_eq!(tonal_evolve_note_count(0.50, 8), 2);
    assert_eq!(tonal_evolve_note_count(1.0, 8), 4);
}

#[test]
fn tonal_engine_evolves_one_actual_note_at_low_rate() {
    let mut tonal = TonalEngine::new(SAMPLE_RATE);
    tonal.rng = StdRng::seed_from_u64(5);
    let before = tonal.evolved_phrase.clone();

    tonal.evolve_phrase(0.01);

    let changed = before
        .iter()
        .zip(&tonal.evolved_phrase)
        .filter(|(before, after)| before != after)
        .count();
    assert_eq!(changed, 1);
}

#[test]
fn tonal_engine_evolves_more_notes_at_high_rate() {
    let mut tonal = TonalEngine::new(SAMPLE_RATE);
    tonal.rng = StdRng::seed_from_u64(5);
    let before = tonal.evolved_phrase.clone();

    tonal.evolve_phrase(1.0);

    let changed = before
        .iter()
        .zip(&tonal.evolved_phrase)
        .filter(|(before, after)| before != after)
        .count();
    assert_eq!(changed, 4);
}

#[test]
fn pad_defaults_use_progression_a_and_sixteen_beat_chords() {
    let controls = PadControls::default();
    assert_close(controls.chord_bars, 4.0);
    assert_close(controls.progression, 0.0);
}

#[test]
fn tab_previous_wraps_back_one_tab() {
    assert_eq!(Tab::Master.previous(), Tab::Clap);
    assert_eq!(Tab::Kick.previous(), Tab::Bass);
    assert_eq!(Tab::Bass.previous(), Tab::Chords);
}

#[test]
fn render_fluid_draws_without_terminal_backend() {
    let controls = FluidControls::default();
    let fluid = FluidState::new();
    let backend = TestBackend::new(100, 32);
    let mut terminal = Terminal::new(backend).unwrap();
    let items = tab_controls(Tab::Master, &controls);
    let automation = AutomationState::default();

    terminal
        .draw(|f| {
            render(
                f,
                &items,
                Tab::Master,
                0,
                0,
                0.0,
                NumericDisplay::empty(),
                &fluid,
                &automation,
                None,
            )
        })
        .unwrap();
}

#[test]
fn automation_open_or_create_uses_safe_lfo_defaults() {
    let mut automation = AutomationState::default();
    let address = ControlAddress::new("master.level");

    let route = automation.open_or_create(address);

    assert_close(route.cycle_beats, 2.0);
    assert_close(route.depth_ratio, 0.0);
    assert_eq!(route.shape, LfoShape::Sine);
    assert_close(route.phase_offset_beats, 0.0);
    assert_eq!(automation.active_address(), Some(address));
}

#[test]
fn lfo_field_adjust_steps_and_clamps() {
    let mut route = LfoRoute::default();

    route.adjust_field_at(LfoField::Amount, 1.0, 0.0);
    assert_close(route.depth_ratio, 0.01);
    route.set_field_at(LfoField::Amount, 0.0, 0.0);
    route.adjust_field_at(LfoField::Amount, -1.0, 0.0);
    assert_close(route.depth_ratio, 0.0);

    route.adjust_field_at(LfoField::Interval, 1.0, 0.0);
    assert_close(route.cycle_beats, 2.25);
    for _ in 0..100 {
        route.adjust_field_at(LfoField::Interval, 1.0, 0.0);
    }
    assert_close(route.cycle_beats, 16.0);
    for _ in 0..100 {
        route.adjust_field_at(LfoField::Interval, -1.0, 0.0);
    }
    assert_close(route.cycle_beats, 0.25);

    route.adjust_field_at(LfoField::Offset, -1.0, 0.0);
    assert_close(route.phase_offset_beats, 0.0);
    route.adjust_field_at(LfoField::Offset, 1.0, 0.0);
    assert_close(route.phase_offset_beats, 0.25);
    for _ in 0..100 {
        route.adjust_field_at(LfoField::Offset, 1.0, 0.0);
    }
    assert_close(route.phase_offset_beats, 4.0);
}

#[test]
fn lfo_field_set_snaps_to_quarter_beat_grid() {
    let mut route = LfoRoute::default();

    route.set_field_at(LfoField::Interval, 3.1, 0.0);
    assert_close(route.cycle_beats, 3.0);
    route.set_field_at(LfoField::Interval, 100.0, 0.0);
    assert_close(route.cycle_beats, 16.0);
    route.set_field_at(LfoField::Amount, 130.0, 0.0);
    assert_close(route.depth_ratio, 1.0);
    route.set_field_at(LfoField::Amount, 40.0, 0.0);
    assert_close(route.depth_ratio, 0.4);
    route.set_field_at(LfoField::Offset, 1.3, 0.0);
    assert_close(route.phase_offset_beats, 1.25);
    route.set_field_at(LfoField::Offset, 9.0, 0.0);
    assert_close(route.phase_offset_beats, 4.0);
}

#[test]
fn lfo_field_reset_uses_slider_minimums() {
    let mut route = LfoRoute {
        cycle_beats: 4.0,
        depth_ratio: 0.75,
        phase_offset_beats: 2.0,
        ..LfoRoute::default()
    };

    route.reset_field_at(LfoField::Amount, 1.0);
    assert_close(route.depth_ratio, 0.0);
    route.reset_field_at(LfoField::Interval, 1.0);
    assert_close(route.cycle_beats, MIN_LFO_CYCLE_BEATS);
    route.reset_field_at(LfoField::Offset, 1.0);
    assert_close(route.phase_offset_beats, 0.0);
}

#[test]
fn lfo_interval_edits_preserve_live_phase_when_possible() {
    let mut route = LfoRoute {
        cycle_beats: 2.0,
        phase_offset_beats: 0.0,
        ..LfoRoute::default()
    };
    let beat = 4.0;
    let before = route.phase_at(beat);

    route.adjust_field_at(LfoField::Interval, 1.0, beat);

    assert_close(route.cycle_beats, 2.25);
    assert!((route.phase_at(beat) - before).abs() < 1e-9);
}

#[test]
fn close_editor_deletes_zero_depth_route() {
    let mut automation = AutomationState::default();
    let address = ControlAddress::new("master.level");
    automation.open_or_create(address).depth_ratio = 0.0;

    automation.close_editor();

    assert!(automation.route(address).is_none());
    assert!(!automation.is_editor_open());

    automation.open_or_create(address);
    automation.close_editor();
    assert!(automation.route(address).is_none());
}

#[test]
fn engine_publishes_beat_telemetry() {
    let controls = Arc::new(ArcSwap::from_pointee(FluidControls::default()));
    let automation = Arc::new(ArcSwap::from_pointee(AutomationState::default()));
    let telemetry = Arc::new(FluidTelemetry::default());
    let bpm = f64::from(controls.load().master.bpm);
    let mut engine = FluidEngine::new(44_100.0, controls, automation, Arc::clone(&telemetry));

    for _ in 0..512 {
        engine.next_stereo();
    }

    let expected = 256.0 * bpm / (60.0 * 44_100.0);
    let beat = telemetry.beat();
    assert!(beat > 0.0);
    assert!(
        (beat - expected).abs() / expected < 0.01,
        "expected ~{expected}, got {beat}"
    );
}

#[test]
fn ambient_reverb_send_ducks_dry_sources_by_mix() {
    let mut send = AmbientReverbSend::new(SAMPLE_RATE);

    let frame = send.process((1.0, -1.0), (0.5, -0.5), 1.0, 0.5);

    assert_near(frame.pad_l, AmbientReverbSend::dry_gain(1.0));
    assert_near(frame.pad_r, -AmbientReverbSend::dry_gain(1.0));
    assert_near(frame.tonal_l, 0.5 * AmbientReverbSend::dry_gain(0.5));
    assert_near(frame.tonal_r, -0.5 * AmbientReverbSend::dry_gain(0.5));
    assert_close(frame.wet_l, 0.0);
    assert_close(frame.wet_r, 0.0);
}

#[test]
fn full_pad_reverb_does_not_boost_pad_rms() {
    fn pad_rms(reverb_mix: f32) -> f32 {
        let controls = PadControls {
            reverb_mix,
            attack_time: 0.01,
            release_time: 0.1,
            ..PadControls::default()
        };
        let mut pad = PadEngine::new(SAMPLE_RATE, &controls, Arc::new(FluidTelemetry::default()));
        pad.rng = StdRng::seed_from_u64(7);
        let mut send = AmbientReverbSend::new(SAMPLE_RATE);
        let mut sum = 0.0;
        let mut count = 0;
        let total = SAMPLE_RATE as u64 * 4;
        let warmup = SAMPLE_RATE as u64;

        for sample in 0..total {
            let dry = pad.next(&controls, 0.0, timing(sample, 120.0));
            let frame = send.process(dry, (0.0, 0.0), controls.reverb_mix, 0.0);
            if sample >= warmup {
                let l = frame.pad_l + frame.wet_l;
                let r = frame.pad_r + frame.wet_r;
                sum += l * l + r * r;
                count += 2;
            }
        }

        (sum / count as f32).sqrt()
    }

    let dry = pad_rms(0.0);
    let wet = pad_rms(1.0);

    assert!(
        wet <= dry * 1.05,
        "full reverb should not make pad much louder: dry rms {dry}, wet rms {wet}"
    );
}

#[test]
fn full_tonal_reverb_does_not_boost_tonal_rms() {
    fn tonal_rms(reverb_mix: f32) -> f32 {
        let controls = TonalControls {
            level: 0.8,
            randomness: 0.0,
            note_length_beats: 1.0,
            step_interval_beats: 4.0,
            reverb_mix,
            ..TonalControls::default()
        };
        let mut tonal = TonalEngine::new(SAMPLE_RATE);
        tonal.rng = StdRng::seed_from_u64(11);
        let mut send = AmbientReverbSend::new(SAMPLE_RATE);
        let mut sum = 0.0;
        let mut count = 0;
        let total = SAMPLE_RATE as u64 * 4;
        let warmup = SAMPLE_RATE as u64;

        for sample in 0..total {
            let dry = tonal.next(&controls, 0.0, timing(sample, 120.0));
            let frame = send.process((0.0, 0.0), dry, 0.0, controls.reverb_mix);
            if sample >= warmup {
                let l = frame.tonal_l + frame.wet_l;
                let r = frame.tonal_r + frame.wet_r;
                sum += l * l + r * r;
                count += 2;
            }
        }

        (sum / count as f32).sqrt()
    }

    let dry = tonal_rms(0.0);
    let wet = tonal_rms(1.0);

    assert!(
        wet <= dry * 1.05,
        "full reverb should not make tonal much louder: dry rms {dry}, wet rms {wet}"
    );
}

#[test]
fn lfo_phase_at_uses_cycle_and_offset() {
    let route = LfoRoute {
        cycle_beats: 2.0,
        phase_offset_beats: 0.5,
        ..LfoRoute::default()
    };

    assert!((route.phase_at(1.0) - 0.75).abs() < 1e-9);
    assert!((route.phase_at(2.0) - 0.25).abs() < 1e-9);
}

#[test]
fn render_fluid_draws_lfo_submenu_and_animated_lane() {
    let controls = FluidControls::default();
    let fluid = FluidState::new();
    let items = tab_controls(Tab::Master, &controls);
    let mut automation = AutomationState::default();
    automation.open_or_create(ControlAddress::new(items[0].id));

    let draw_at = |beat: f64| {
        let backend = TestBackend::new(120, 40);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(
                    f,
                    &items,
                    Tab::Master,
                    0,
                    1,
                    beat,
                    NumericDisplay::empty(),
                    &fluid,
                    &automation,
                    None,
                )
            })
            .unwrap();
        terminal.backend().buffer().clone()
    };

    let at_start = draw_at(0.0);
    let text = buffer_text(&at_start);
    assert!(text.contains("amount"));
    assert!(text.contains("interval"));
    assert!(text.contains("offset"));
    assert!(text.contains("0%"));

    // Default cycle is 2 beats, so beat 1.0 is the opposite phase: the lane's
    // bright head has moved even though the 0% wave glyphs are flat.
    let at_half_cycle = draw_at(1.0);
    assert_ne!(at_start, at_half_cycle);
}

#[test]
fn lfo_lane_is_phase_locked() {
    let route = LfoRoute::default();

    let start = lfo_lane_line(&route, 0.0, 24, true);
    let same_phase = lfo_lane_line(&route, 2.0, 24, true);
    let opposite_phase = lfo_lane_line(&route, 1.0, 24, true);

    let styles =
        |line: &ratatui::text::Line<'_>| line.spans.iter().map(|s| s.style).collect::<Vec<_>>();
    assert_eq!(styles(&start), styles(&same_phase));
    assert_ne!(styles(&start), styles(&opposite_phase));
}

#[test]
fn automation_applies_bounded_lfo_offset_and_clamps_to_spec_range() {
    let mut controls = FluidControls::default();
    controls.master.level = 0.9;
    let mut automation = AutomationState::default();
    let route = automation.open_or_create(ControlAddress::new("master.level"));
    route.depth_ratio = 0.5;

    apply_automation(
        &mut controls,
        &automation,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 0.5),
    );

    assert_close(controls.master.level, 1.0);
}

#[test]
fn automation_uses_beat_cycle_phase_for_opposite_lfo_offsets() {
    let mut automation = AutomationState::default();
    let route = automation.open_or_create(ControlAddress::new("master.level"));
    route.cycle_beats = 2.0;
    route.depth_ratio = 0.25;

    let mut positive = FluidControls::default();
    positive.master.level = 0.5;
    apply_automation(
        &mut positive,
        &automation,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 0.5),
    );

    let mut negative = FluidControls::default();
    negative.master.level = 0.5;
    apply_automation(
        &mut negative,
        &automation,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 1.5),
    );

    assert_near(positive.master.level, 0.75);
    assert_near(negative.master.level, 0.25);
}

#[test]
fn automation_preserves_base_controls_and_modulates_only_effective_clone() {
    let mut base = FluidControls::default();
    base.master.level = 0.5;
    let mut effective = base.clone();
    let mut automation = AutomationState::default();
    let route = automation.open_or_create(ControlAddress::new("master.level"));
    route.depth_ratio = 0.25;

    apply_automation(
        &mut effective,
        &automation,
        TimingContext::new(f64::from(SAMPLE_RATE), 120.0, 0.5),
    );

    assert_near(effective.master.level, 0.75);
    assert_close(base.master.level, 0.5);
}

#[test]
fn defaults_match_current_mix() {
    let controls = FluidControls::default();

    assert_close(controls.master.bpm, 82.0);
    assert_close(controls.master.drive, 0.1);
    assert_close(controls.master.comp_threshold, -8.0);

    assert_close(controls.perc.decay_ms, 200.0);
    assert_close(controls.perc.filter, 0.7);
    assert_close(controls.perc.interval_beats, 0.25);
    assert_close(controls.perc.offset_beats, 0.0);

    assert_close(controls.kick.start_freq, 160.0);
    assert_close(controls.kick.pitch_decay_ms, 55.0);
    assert_close(controls.kick.amp_decay_ms, 250.0);

    assert_close(controls.tonal.phrase, 0.0);
    assert_close(controls.tonal.rate_beats, 0.5);
    assert_close(controls.tonal.step_interval_beats, 16.0);
    assert_close(controls.tonal.note_length_beats, 1.5);
    assert_close(controls.tonal.randomness, 0.5);
    assert_close(controls.tonal.evolve_rate, 0.0);

    assert_close(controls.clap.room, 0.0);
}

#[test]
fn apply_min_moves_selected_control_to_floor() {
    let mut controls = FluidControls::default();

    controls.master.drive = 0.8;
    apply_min(Tab::Master, 8, &mut controls);
    assert_close(controls.master.drive, 0.0);

    controls.master.bpm = 120.0;
    apply_min(Tab::Master, 6, &mut controls);
    assert_close(controls.master.bpm, MASTER_BPM_MIN);

    controls.master.tone = 0.5;
    apply_min(Tab::Master, 12, &mut controls);
    assert_close(controls.master.tone, -1.0);

    controls.pad.chord_bars = 16.0;
    apply_min(Tab::Chords, 1, &mut controls);
    assert_close(controls.pad.chord_bars, 1.0);
}

#[test]
fn apply_value_accepts_percent_style_unit_controls() {
    let mut controls = FluidControls::default();

    apply_value(Tab::Master, 7, 42.0, &mut controls);
    assert_close(controls.master.level, 0.42);

    apply_value(Tab::Master, 7, 0.7, &mut controls);
    assert_close(controls.master.level, 0.7);
}

#[test]
fn apply_value_snaps_direct_numeric_entry_to_control_grid() {
    let mut controls = FluidControls::default();

    apply_value(Tab::Kick, 1, 1.13, &mut controls);
    assert_close(controls.kick.interval_beats, 1.25);

    apply_value(Tab::Chords, 1, 12.0, &mut controls);
    assert_close(controls.pad.chord_bars, 16.0);

    apply_value(Tab::Clap, 3, 3.6, &mut controls);
    assert_close(controls.clap.slap_count, 4.0);
}

#[test]
fn tab_controls_classify_each_slider_kind() {
    use ControlKind::{Continuous, Discrete, Gain, Timing};

    let controls = FluidControls::default();
    let cases = [
        (
            Tab::Master,
            vec![
                Gain, Gain, Gain, Gain, Gain, Gain, Timing, Gain, Gain, Continuous, Continuous,
                Timing, Continuous, Discrete,
            ],
        ),
        (Tab::Perc, vec![Gain, Timing, Timing, Timing, Gain]),
        (
            Tab::Chords,
            vec![
                Gain, Timing, Discrete, Gain, Gain, Gain, Gain, Timing, Timing,
            ],
        ),
        (
            Tab::Bass,
            vec![
                Gain, Timing, Timing, Discrete, Discrete, Timing, Timing, Gain,
            ],
        ),
        (
            Tab::Kick,
            vec![
                Gain, Timing, Timing, Continuous, Timing, Timing, Gain, Gain, Gain, Timing, Gain,
                Gain, Gain,
            ],
        ),
        (
            Tab::Tonal,
            vec![
                Gain, Discrete, Timing, Timing, Timing, Gain, Continuous, Timing, Gain,
            ],
        ),
        (
            Tab::Clap,
            vec![
                Gain, Timing, Timing, Discrete, Timing, Timing, Gain, Gain, Gain,
            ],
        ),
    ];

    for (tab, expected) in cases {
        let actual: Vec<_> = tab_controls(tab, &controls)
            .into_iter()
            .map(|item| item.kind)
            .collect();
        assert_eq!(actual, expected, "unexpected kind map for {}", tab.name());
    }
}

#[test]
fn control_registry_specs_are_internally_consistent() {
    let tabs = [
        Tab::Master,
        Tab::Perc,
        Tab::Chords,
        Tab::Bass,
        Tab::Kick,
        Tab::Tonal,
        Tab::Clap,
    ];
    for tab in tabs {
        for spec in tab_specs(tab) {
            let ctx = format!("{} / {}", tab.name(), spec.label);
            assert!(!spec.id.is_empty(), "{ctx}: empty stable id");
            assert!(!spec.label.is_empty(), "{ctx}: empty label");
            assert!(spec.min < spec.max, "{ctx}: min must be below max");
            assert!(
                spec.reset >= spec.min && spec.reset <= spec.max,
                "{ctx}: reset outside [min, max]"
            );
            if spec.bar == Bar::Log2 {
                assert!(spec.min > 0.0, "{ctx}: log bar needs positive min");
            }
            if let Step::Linear(step) = spec.step {
                assert!(step > 0.0, "{ctx}: step must be positive");
            }

            // get/set must address the same field.
            let mut c = FluidControls::default();
            (spec.set)(&mut c, spec.max);
            assert!(
                ((spec.get)(&c) - spec.max).abs() < 1e-6,
                "{ctx}: get/set roundtrip failed at max"
            );
            (spec.set)(&mut c, spec.reset);
            assert!(
                ((spec.get)(&c) - spec.reset).abs() < 1e-6,
                "{ctx}: get/set roundtrip failed at reset"
            );
        }
    }
}

#[test]
fn song_code_round_trips_quantized_snapshot_values() {
    let mut controls = FluidControls::default();
    controls.master.bpm = 123.4;
    controls.pad.chord_bars = 12.0;
    controls.kick.echo_time_beats = 0.33;
    controls.clap.slap_count = 6.6;

    let code = song::encode_song_code(&SongState::from_controls(controls)).unwrap();
    let decoded = song::decode_song_code(&code).unwrap();

    assert_close(decoded.controls.master.bpm, 123.0);
    assert_close(decoded.controls.pad.chord_bars, 16.0);
    assert_close(decoded.controls.kick.echo_time_beats, 0.375);
    assert_close(decoded.controls.clap.slap_count, 7.0);
}

#[test]
fn song_code_decodes_missing_controls_as_defaults() {
    let mut controls = FluidControls::default();
    controls.master.bpm = 120.0;

    let code = song::encode_song_code(&SongState::from_controls(controls)).unwrap();
    let decoded = song::decode_song_code(&code).unwrap();

    assert_close(
        decoded.controls.pad.level,
        FluidControls::default().pad.level,
    );
}

#[test]
fn song_code_decodes_snapshot_only_payload_with_empty_automation() {
    let mut controls = FluidControls::default();
    controls.master.bpm = 120.0;
    let code = song::encode_song_code(&SongState::from_controls(controls)).unwrap();

    let decoded = song::decode_song_code(&code).unwrap();

    assert_eq!(decoded.automation.routes().count(), 0);
}

#[test]
fn song_code_round_trips_lfo_automation_record() {
    let mut controls = FluidControls::default();
    controls.master.level = 0.6;
    let mut automation = AutomationState::default();
    automation.set_route(
        ControlAddress::new("master.level"),
        LfoRoute {
            cycle_beats: 4.0,
            depth_ratio: 0.4,
            shape: LfoShape::Sine,
            phase_offset_beats: 0.25,
        },
    );
    let song = SongState {
        controls,
        automation,
    };

    let code = song::encode_song_code(&song).unwrap();
    let decoded = song::decode_song_code(&code).unwrap();
    let route = decoded
        .automation
        .route(ControlAddress::new("master.level"))
        .unwrap();

    assert_close(decoded.controls.master.level, 0.6);
    assert_close(route.cycle_beats, 4.0);
    assert_close(route.depth_ratio, 0.4);
    assert_eq!(route.shape, LfoShape::Sine);
    assert_close(route.phase_offset_beats, 0.25);
}

#[test]
fn song_code_skips_unknown_records() {
    let mut controls = FluidControls::default();
    controls.master.tune = 5.0;
    let code = song::encode_song_code(&SongState::from_controls(controls)).unwrap();
    let code = append_record_to_code(&code, 99, &[1, 2, 3, 4]);

    let decoded = song::decode_song_code(&code).unwrap();

    assert_close(decoded.controls.master.tune, 5.0);
}

#[test]
fn song_code_skips_unknown_control_ids() {
    let code = song::encode_song_code(&SongState::default()).unwrap();
    let mut payload = Vec::new();
    let id = b"future.control.id";
    payload.extend_from_slice(&1u16.to_le_bytes());
    payload.push(id.len() as u8);
    payload.extend_from_slice(id);
    payload.extend_from_slice(&0.75f32.to_le_bytes());
    let code = append_record_to_code(&code, song::SNAPSHOT_RECORD, &payload);

    let decoded = song::decode_song_code(&code).unwrap();

    assert_close(
        decoded.controls.master.level,
        FluidControls::default().master.level,
    );
}

#[test]
fn song_code_skips_unknown_automation_target_control_ids() {
    let code = song::encode_song_code(&SongState::default()).unwrap();
    let payload = automation_payload(
        "future.control.id",
        LfoRoute {
            depth_ratio: 0.2,
            ..LfoRoute::default()
        },
    );
    let code = append_record_to_code(&code, song::AUTOMATION_RECORD, &payload);

    let decoded = song::decode_song_code(&code).unwrap();

    assert_eq!(decoded.automation.routes().count(), 0);
}

#[test]
fn launch_line_is_cli_launchable() {
    let line = launch_line(&SongState::default()).unwrap();

    assert!(line.starts_with("nooise n1_"));
}

#[test]
fn control_kind_smoothing_policy_is_explicit() {
    assert!(ControlKind::Gain.smooths_audio());
    assert!(!ControlKind::Continuous.smooths_audio());
    assert!(!ControlKind::Timing.smooths_audio());
    assert!(!ControlKind::Discrete.smooths_audio());
}

#[test]
fn gain_smoother_reaches_target_over_ramp() {
    let mut smoother = GainSmoother::new(0.0);
    smoother.set_target(1.0, 10);

    assert_close(smoother.next(), 0.1);
    for _ in 0..8 {
        smoother.next();
    }
    assert_close(smoother.next(), 1.0);
    assert_close(smoother.next(), 1.0);
}

#[test]
fn gain_smoothers_ramp_live_gain_controls_without_timing_changes() {
    let mut controls = FluidControls::default();
    controls.pad.level = 0.0;
    controls.pad.reverb_mix = 0.0;
    controls.perc.filter = 0.5;
    controls.kick.click = 0.0;
    controls.kick.drive = 0.0;
    controls.kick.filter = 0.0;
    controls.kick.echo_amount = 0.0;
    controls.tonal.randomness = 0.0;
    controls.clap.filter = 0.5;
    controls.clap.body = 0.0;
    controls.master.level = 0.0;
    controls.master.drive = 0.0;
    controls.bass.drive = 0.0;

    let mut smoothers = GainSmoothers::new(&controls);
    controls.pad.level = 1.0;
    controls.pad.reverb_mix = 1.0;
    controls.perc.filter = 1.0;
    controls.kick.click = 0.2;
    controls.kick.drive = 1.0;
    controls.kick.filter = 1.0;
    controls.kick.echo_amount = 0.9;
    controls.tonal.randomness = 1.0;
    controls.clap.filter = 1.0;
    controls.clap.body = 1.0;
    controls.master.level = 0.5;
    controls.master.drive = 1.0;
    controls.master.bpm = 123.0;
    controls.bass.drive = 1.0;
    smoothers.set_targets(&controls, 100.0);

    let next = smoothers.next_controls(&controls);
    assert_close(next.master.bpm, 123.0);
    assert!(next.pad.level > 0.0 && next.pad.level < 1.0);
    assert!(next.pad.reverb_mix > 0.0 && next.pad.reverb_mix < 1.0);
    assert!(next.perc.filter > 0.5 && next.perc.filter < 1.0);
    assert!(next.kick.click > 0.0 && next.kick.click < 0.2);
    assert!(next.kick.drive > 0.0 && next.kick.drive < 1.0);
    assert!(next.kick.filter > 0.0 && next.kick.filter < 1.0);
    assert!(next.kick.echo_amount > 0.0 && next.kick.echo_amount < 0.9);
    assert!(next.tonal.randomness > 0.0 && next.tonal.randomness < 1.0);
    assert!(next.clap.filter > 0.5 && next.clap.filter < 1.0);
    assert!(next.clap.body > 0.0 && next.clap.body < 1.0);
    assert!(next.master.level > 0.0 && next.master.level < 0.5);
    assert!(next.master.drive > 0.0 && next.master.drive < 1.0);
    assert!(next.bass.drive > 0.0 && next.bass.drive < 1.0);
}

#[test]
fn gain_smoothers_cover_every_unique_gain_spec() {
    let controls = FluidControls::default();
    let smoothers = GainSmoothers::new(&controls);
    let expected: std::collections::BTreeSet<_> = all_specs()
        .filter(|spec| spec.kind == ControlKind::Gain)
        .map(|spec| spec.id)
        .collect();
    let actual: std::collections::BTreeSet<_> = smoothers
        .smoothers
        .iter()
        .map(|smoother| smoother.spec.unwrap().id)
        .collect();

    assert_eq!(actual, expected);
}

#[test]
fn chords_tab_shows_progression_row_with_letter_display() {
    let mut controls = FluidControls::default();
    let rows = tab_controls(Tab::Chords, &controls);
    assert_eq!(rows[2].label, "Progression");
    assert_eq!(rows[2].display, "A");

    controls.pad.progression = 2.0;
    let rows = tab_controls(Tab::Chords, &controls);
    assert_eq!(rows[2].display, "C");
}

#[test]
fn tonal_tab_separates_rate_from_cycle() {
    let rows = tab_controls(Tab::Tonal, &FluidControls::default());

    assert_eq!(rows[2].id, "tonal.rate_beats");
    assert_eq!(rows[2].label, "Rate");
    assert_eq!(rows[2].display, "0.50 beats");
    assert_eq!(rows[3].id, "tonal.step_interval_beats");
    assert_eq!(rows[3].label, "Cycle");
    assert_eq!(rows[3].display, "16.00 beats");
}

#[test]
fn chords_progression_adjusts_and_clamps() {
    let mut controls = FluidControls::default();

    apply_delta(Tab::Chords, 2, 1.0, &mut controls);
    assert_close(controls.pad.progression, 1.0);

    controls.pad.progression = 3.0;
    apply_delta(Tab::Chords, 2, 1.0, &mut controls);
    assert_close(controls.pad.progression, 3.0);

    controls.pad.progression = 0.0;
    apply_delta(Tab::Chords, 2, -1.0, &mut controls);
    assert_close(controls.pad.progression, 0.0);

    controls.pad.progression = 2.0;
    apply_min(Tab::Chords, 2, &mut controls);
    assert_close(controls.pad.progression, 0.0);
}

#[test]
fn bass_rhythms_have_expected_hit_counts() {
    assert_eq!(BASS_RHYTHMS[0].iter().filter(|&&b| b).count(), 4);
    assert!(BASS_RHYTHMS[0][0]);
    assert!(BASS_RHYTHMS[1].iter().filter(|&&b| b).count() > 4);
    assert_eq!(BASS_RHYTHMS[2].iter().filter(|&&b| b).count(), 8);
}

#[test]
fn bass_root_note_follows_authored_bass_line() {
    assert_eq!(bass_root_note(0, 0), 45);
    // Progression A's authored line diverges from the chord's lowest
    // tone at step 3 (B chord's min is 47) — proves the bass line is
    // independent data, not derived from PROGRESSIONS.
    assert_eq!(bass_root_note(0, 3), 43);
    assert_eq!(bass_root_note(2, 3), 43);
}

#[test]
fn bass_defaults_are_silent_quarter_note_a() {
    let controls = BassControls::default();
    assert_close(controls.level, 0.0);
    assert_close(controls.rhythm, 0.0);
    assert_close(controls.octave, -1.0);
    assert_close(controls.interval_beats, 4.0);
}

#[test]
fn bass_tab_shows_rhythm_row_with_letter_display() {
    let mut controls = FluidControls::default();
    let rows = tab_controls(Tab::Bass, &controls);
    assert_eq!(rows[3].label, "Rhythm");
    assert_eq!(rows[3].display, "A");

    controls.bass.rhythm = 3.0;
    let rows = tab_controls(Tab::Bass, &controls);
    assert_eq!(rows[3].display, "D");
}

#[test]
fn bass_controls_adjust_and_clamp() {
    let mut controls = FluidControls::default();

    apply_delta(Tab::Bass, 3, 1.0, &mut controls);
    assert_close(controls.bass.rhythm, 1.0);

    controls.bass.rhythm = 3.0;
    apply_delta(Tab::Bass, 3, 1.0, &mut controls);
    assert_close(controls.bass.rhythm, 3.0);

    controls.bass.octave = -1.0;
    apply_delta(Tab::Bass, 4, -1.0, &mut controls);
    apply_delta(Tab::Bass, 4, -1.0, &mut controls);
    assert_close(controls.bass.octave, -3.0);

    apply_min(Tab::Bass, 0, &mut controls);
    assert_close(controls.bass.level, 0.0);

    controls.bass.decay_time = 0.4;
    apply_delta(Tab::Bass, 6, 1.0, &mut controls);
    assert!(controls.bass.decay_time > 0.4);

    apply_min(Tab::Bass, 6, &mut controls);
    assert_close(controls.bass.decay_time, 0.005);
}

#[test]
fn bass_engine_follows_pad_chord_root_across_advances() {
    let sample_rate = 48_000.0;
    let mut bass = BassEngine::new(sample_rate);
    let pad = PadControls {
        chord_bars: 1.0 / 4.0, // advance every beat, fast enough to observe within the test
        ..PadControls::default()
    };
    let bass_controls = BassControls {
        interval_beats: 1.0,
        rhythm: 0.0,
        ..BassControls::default()
    };
    let mut clock = TempoClock::new(sample_rate, 120.0);

    // Step far enough to guarantee at least one chord advance and one
    // rhythm hit have occurred.
    for _ in 0..(sample_rate as usize) {
        let timing = clock.tick(120.0);
        bass.next(&bass_controls, &pad, 0.0, timing);
    }

    assert_ne!(bass.step_index, 0);
    assert!(bass.rhythm_step < BASS_RHYTHMS[0].len());
}

#[test]
fn bass_voice_decays_to_silence_without_sustaining() {
    let sample_rate = 48_000.0;
    let mut voice = BassVoice::new(110.0, 0.005, 0.05, 0.0, sample_rate);

    // Well past attack+decay (0.055s); a sustaining envelope would still
    // be holding at ~0.85 gain here, an AD envelope has decayed to ~0.
    for _ in 0..(sample_rate * 0.5) as usize {
        voice.next();
    }

    let (l, r) = voice.next();
    assert!(l.abs() < 0.001 && r.abs() < 0.001);
}

#[test]
fn bass_interval_crops_phrase_instead_of_stretching_it() {
    // Step duration is always a fixed 16th note; `interval_beats` only
    // decides how many steps of the 16-step phrase play before looping
    // back to step 0.
    let hits_within = |rhythm: usize, loop_len: usize| -> Vec<usize> {
        (0..loop_len)
            .filter(|&s| s < BASS_RHYTHMS[rhythm].len() && BASS_RHYTHMS[rhythm][s])
            .collect()
    };

    // Progression A (quarter notes) hits every 4 steps; cropping to a
    // 4-step (1 beat) loop still only exposes step 0, which recurs at
    // the same cadence as the full 16-step phrase - no audible change.
    assert_eq!(hits_within(0, 16), vec![0, 4, 8, 12]);
    assert_eq!(hits_within(0, 4), vec![0]);
    assert_eq!(hits_within(0, 8), vec![0, 4]);

    // A busier pattern's crop is audibly different: only its first half
    // survives an 8-step (2 beat) loop.
    let full = hits_within(1, 16);
    let cropped = hits_within(1, 8);
    assert!(cropped.len() < full.len());
    assert!(cropped.iter().all(|s| full.contains(s)));
}

#[test]
fn chords_reverb_mix_row_shifted_to_index_three() {
    let controls = FluidControls::default();
    let rows = tab_controls(Tab::Chords, &controls);
    assert_eq!(rows[3].label, "Reverb Mix");
}

#[test]
fn chords_release_row_present_with_lowered_attack_floor() {
    let controls = FluidControls::default();
    let rows = tab_controls(Tab::Chords, &controls);
    assert_eq!(rows[7].label, "Attack");
    assert_close(rows[7].min, 0.05);
    assert_eq!(rows[8].label, "Release");
    assert_close(rows[8].value, 8.0);
    assert_close(rows[8].min, 0.05);
    assert_close(rows[8].max, 20.0);
}

#[test]
fn chords_attack_and_release_adjust_and_clamp_low() {
    let mut controls = FluidControls::default();

    controls.pad.attack_time = 0.1;
    apply_delta(Tab::Chords, 7, -1.0, &mut controls);
    assert_close(controls.pad.attack_time, 0.05);
    apply_min(Tab::Chords, 7, &mut controls);
    assert_close(controls.pad.attack_time, 0.05);

    controls.pad.release_time = 0.1;
    apply_delta(Tab::Chords, 8, -1.0, &mut controls);
    assert_close(controls.pad.release_time, 0.05);
    apply_min(Tab::Chords, 8, &mut controls);
    assert_close(controls.pad.release_time, 0.05);
}

#[test]
fn kick_interval_floor_is_quarter_beat() {
    let mut controls = FluidControls::default();
    controls.kick.interval_beats = 1.0;
    apply_min(Tab::Kick, 1, &mut controls);
    assert_close(controls.kick.interval_beats, 0.25);

    controls.kick.interval_beats = 0.25;
    apply_delta(Tab::Kick, 1, -1.0, &mut controls);
    assert_close(controls.kick.interval_beats, 0.25);
}

#[test]
fn perc_continuous_mode_pushes_no_hits() {
    let controls = PercControls {
        level: 1.0,
        interval_beats: 4.25,
        ..Default::default()
    };

    let mut engine = PercEngine::new(SAMPLE_RATE);
    engine.rng = StdRng::seed_from_u64(7);
    let bpm = 82.0;
    for sample in 0..(SAMPLE_RATE as u64 * 2) {
        let t = timing(sample, bpm);
        engine.next(&controls, t);
    }
    assert!(engine.hits.is_empty());
}

#[test]
fn perc_continuous_mode_has_no_periodic_rms_dips() {
    let controls = PercControls {
        level: 1.0,
        interval_beats: 4.25,
        ..Default::default()
    };

    let mut engine = PercEngine::new(SAMPLE_RATE);
    engine.rng = StdRng::seed_from_u64(7);
    let bpm = 82.0;
    let window_samples = (SAMPLE_RATE * 0.01) as usize;
    let total_samples = SAMPLE_RATE as usize * 2;
    let mut window_rms = Vec::new();
    let mut window = Vec::with_capacity(window_samples);

    for sample in 0..total_samples as u64 {
        let t = timing(sample, bpm);
        let out = engine.next(&controls, t);
        window.push(out);
        if window.len() == window_samples {
            let sum_sq: f32 = window.iter().map(|x| x * x).sum();
            window_rms.push((sum_sq / window.len() as f32).sqrt());
            window.clear();
        }
    }

    let settle_windows = (SAMPLE_RATE * 0.25) as usize / window_samples;
    let rms_tail = &window_rms[settle_windows..];

    let min_rms = rms_tail.iter().cloned().fold(f32::INFINITY, f32::min);
    let max_rms = rms_tail.iter().cloned().fold(f32::NEG_INFINITY, f32::max);

    assert!(
        min_rms > 0.0,
        "continuous mode produced silence in a window"
    );
    assert!(
        max_rms / min_rms < 2.0,
        "windowed RMS varies too much ({min_rms}..{max_rms}), suggests periodic triggering survived"
    );
}

#[test]
fn perc_tab_controls_include_interval_and_offset() {
    let controls = FluidControls::default();
    let rows = tab_controls(Tab::Perc, &controls);
    assert_eq!(rows.len(), 5);
    assert_eq!(rows[1].label, "Interval");
    assert_close(rows[1].min, 0.25);
    assert_close(rows[1].max, 4.25);
    assert_eq!(rows[2].label, "Offset");
    assert_close(rows[2].min, 0.0);
    assert_close(rows[2].max, 4.0);
}

#[test]
fn perc_interval_displays_continuous_at_top() {
    let mut controls = FluidControls::default();
    controls.perc.interval_beats = 4.25;
    let rows = tab_controls(Tab::Perc, &controls);
    assert_eq!(rows[1].display, "Continuous");
}

#[test]
fn perc_interval_and_offset_adjust_and_clamp() {
    let mut controls = FluidControls::default();

    apply_delta(Tab::Perc, 1, 1.0, &mut controls);
    assert_close(controls.perc.interval_beats, 0.5);

    controls.perc.interval_beats = 4.25;
    apply_delta(Tab::Perc, 1, 1.0, &mut controls);
    assert_close(controls.perc.interval_beats, 4.25);

    apply_delta(Tab::Perc, 2, 1.0, &mut controls);
    assert_close(controls.perc.offset_beats, 0.25);

    controls.perc.offset_beats = 4.0;
    apply_delta(Tab::Perc, 2, 1.0, &mut controls);
    assert_close(controls.perc.offset_beats, 4.0);

    apply_min(Tab::Perc, 1, &mut controls);
    assert_close(controls.perc.interval_beats, 0.25);

    apply_min(Tab::Perc, 2, &mut controls);
    assert_close(controls.perc.offset_beats, 0.0);
}

#[test]
fn pad_engine_caps_released_layers() {
    let controls = PadControls {
        chord_bars: 1.0,
        attack_time: 1.0,
        ..PadControls::default()
    };
    let mut pad = PadEngine::new(SAMPLE_RATE, &controls, Arc::new(FluidTelemetry::default()));

    for chord in 1..12 {
        let sample = chord * SAMPLE_RATE as u64 * 2;
        let _ = pad.next(&controls, 0.0, timing(sample, 120.0));
        assert!(pad.layers.len() <= MAX_PAD_LAYERS);
    }
}

#[test]
fn pad_engine_step_index_wraps_at_eight() {
    let controls = PadControls {
        chord_bars: 1.0,
        attack_time: 1.0,
        ..PadControls::default()
    };
    let mut pad = PadEngine::new(SAMPLE_RATE, &controls, Arc::new(FluidTelemetry::default()));

    // chord_bars=1.0 means chord_trigger fires every 4.0 beats; at 120 BPM
    // that's 2 seconds of samples per chord. Render 9 chord-advances worth
    // of samples (18 seconds) and confirm the telemetry index wrapped past 8.
    for chord in 1..=9 {
        let sample = chord * SAMPLE_RATE as u64 * 2;
        let _ = pad.next(&controls, 0.0, timing(sample, 120.0));
    }
    let final_index = pad.telemetry.chord_index.load(Ordering::Relaxed);
    assert!(
        final_index < 8,
        "step_index must wrap into 0..8, got {final_index}"
    );
}

#[test]
fn pad_engine_progression_switch_retriggers_immediately() {
    let mut controls = PadControls {
        chord_bars: 64.0, // long chord length so no chord-advance trigger fires
        // Short attack so the original layer's envelope is already audible
        // (not still ~0 from the very first sample) by the time it's released;
        // otherwise the release phase completes in the same tick it starts and
        // `retain` prunes it before this test can observe the pushed layer.
        attack_time: 0.001,
        ..PadControls::default()
    };
    let mut pad = PadEngine::new(SAMPLE_RATE, &controls, Arc::new(FluidTelemetry::default()));

    // Warm up the original layer's envelope (still progression 0, so no push
    // happens here) so its level is non-negligible before it gets released;
    // otherwise the Adsr release completes in the same tick it starts and
    // `retain` prunes the layer before this test can observe the pushed one.
    for sample in 0..10 {
        let _ = pad.next(&controls, 0.0, timing(sample, 120.0));
    }
    let layers_before = pad.layers.len();

    // Flip progression with no further elapsed time / no chord-advance trigger.
    controls.progression = 1.0;
    let _ = pad.next(&controls, 0.0, timing(10, 120.0));

    assert!(
        pad.layers.len() > layers_before,
        "switching progression must push a new layer immediately, without waiting for chord_trigger"
    );
}

#[test]
fn kick_delay_buffer_covers_max_echo_at_min_bpm() {
    let max_delay =
        ((KICK_ECHO_TIME_BEATS_MAX * 60.0 / MASTER_BPM_MIN) * SAMPLE_RATE).ceil() as usize;
    let delay = KickDelay::new(max_kick_echo_delay_samples(SAMPLE_RATE));

    assert_eq!(delay.buf_l.len(), max_delay + 1);
}

#[test]
fn tempo_clock_preserves_beat_phase_when_bpm_changes() {
    let mut clock = TempoClock::new(SAMPLE_RATE, 120.0);
    let mut before = clock.tick(120.0);

    for _ in 1..20_000 {
        before = clock.tick(120.0);
    }

    let after = clock.tick(60.0);

    assert!(after.beat > before.beat);
    assert!(after.beat - before.beat < 0.001);
    assert!(after.bpm < before.bpm);
    assert!(after.bpm > 60.0);
}

#[test]
fn grid_trigger_keeps_next_hit_when_only_bpm_changes() {
    let mut clock = TempoClock::new(SAMPLE_RATE, 120.0);
    let mut trigger = GridTrigger::new();

    for _ in 0..25_000 {
        let timing = clock.tick(120.0);
        let _ = trigger.pop(timing, 1.0, 0.0);
    }

    let before = trigger.next_hit.map(|hit| hit.beat);
    let timing = clock.tick(60.0);
    let fired = trigger.pop(timing, 1.0, 0.0);
    let after = trigger.next_hit.map(|hit| hit.beat);

    assert!(!fired);
    assert_eq!(before, after);
}

#[test]
fn grid_trigger_fires_identically_for_same_params() {
    let mut a = GridTrigger::new();
    let mut b = GridTrigger::new();
    let mut a_hits = Vec::new();
    let mut b_hits = Vec::new();

    for sample in 0..(SAMPLE_RATE as u64 * 6) {
        let timing = timing(sample, 120.0);
        if a.pop(timing, 2.0, 1.0) {
            a_hits.push(sample);
        }
        if b.pop(timing, 2.0, 1.0) {
            b_hits.push(sample);
        }
    }

    assert!(a_hits.len() >= 3);
    assert_eq!(a_hits, b_hits);
}

#[test]
fn grid_trigger_no_silence_after_bpm_decrease() {
    let change_at = 50_000u64;
    let mut clock = TempoClock::new(SAMPLE_RATE, 120.0);
    let mut kick = GridTrigger::new();
    let mut clap = GridTrigger::new();
    let mut kick_hits: Vec<u64> = Vec::new();
    let mut clap_hits: Vec<u64> = Vec::new();

    for sample in 0..change_at {
        let timing = clock.tick(120.0);
        if kick.pop(timing, 1.0, 0.0) {
            kick_hits.push(sample);
        }
        if clap.pop(timing, 2.0, 1.0) {
            clap_hits.push(sample);
        }
    }

    for sample in change_at..(SAMPLE_RATE as u64 * 8) {
        let timing = clock.tick(60.0);
        if kick.pop(timing, 1.0, 0.0) {
            kick_hits.push(sample);
        }
        if clap.pop(timing, 2.0, 1.0) {
            clap_hits.push(sample);
        }
    }

    // Kick should fire within one new beat period after the change
    let one_beat_samples = (60.0 / 60.0 * SAMPLE_RATE as f64) as u64;
    let first_post = kick_hits.iter().copied().find(|&s| s >= change_at);
    assert!(
        first_post.is_some_and(|s| s - change_at <= one_beat_samples),
        "kick stalled after BPM decrease"
    );
}

#[test]
fn grid_trigger_no_silence_after_interval_increase() {
    let change_at = 50_000u64;
    let mut trigger = GridTrigger::new();
    let mut hits: Vec<u64> = Vec::new();

    for sample in 0..change_at {
        if trigger.pop(timing(sample, 120.0), 0.5, 0.0) {
            hits.push(sample);
        }
    }

    for sample in change_at..(SAMPLE_RATE as u64 * 8) {
        if trigger.pop(timing(sample, 120.0), 4.0, 0.0) {
            hits.push(sample);
        }
    }

    let new_interval_samples = (4.0 * 60.0 / 120.0 * SAMPLE_RATE) as u64;
    let first_post = hits.iter().copied().find(|&s| s >= change_at);
    assert!(
        first_post.is_some_and(|s| s - change_at <= new_interval_samples),
        "trigger stalled after interval increase"
    );
}

fn max_hit_gap(hit_beats: &[f64], total_beats: f64) -> f64 {
    let mut max_gap = 0.0f64;
    let mut prev = 0.0f64;
    for &beat in hit_beats {
        max_gap = max_gap.max(beat - prev);
        prev = beat;
    }
    max_gap.max(total_beats - prev)
}

#[test]
fn grid_trigger_survives_continuous_interval_sweep() {
    let total_beats = 32.0;
    let samples = (total_beats * 60.0 / 120.0 * f64::from(SAMPLE_RATE)) as u64;
    let mut trigger = GridTrigger::new();
    let mut hit_beats = Vec::new();

    for sample in 0..samples {
        let t = timing(sample, 120.0);
        let interval = 1.0 + 0.75 * (std::f64::consts::TAU * t.beat / 8.0).sin() as f32;
        if trigger.pop(t, interval, 0.0) {
            hit_beats.push(t.beat);
        }
    }

    let max_gap = max_hit_gap(&hit_beats, total_beats);
    assert!(
        max_gap <= 2.0,
        "trigger starved during interval sweep: max gap {max_gap:.2} beats"
    );
}

#[test]
fn grid_trigger_survives_sliding_offset() {
    let total_beats = 32.0;
    let samples = (total_beats * 60.0 / 120.0 * f64::from(SAMPLE_RATE)) as u64;
    let mut trigger = GridTrigger::new();
    let mut hit_beats = Vec::new();

    for sample in 0..samples {
        let t = timing(sample, 120.0);
        let offset = 2.0 + 2.0 * (std::f64::consts::TAU * t.beat / 8.0).sin() as f32;
        if trigger.pop(t, 1.0, offset) {
            hit_beats.push(t.beat);
        }
    }

    let max_gap = max_hit_gap(&hit_beats, total_beats);
    assert!(
        max_gap <= 1.5,
        "trigger starved during offset slide: max gap {max_gap:.2} beats"
    );
}

fn automation_with_route(
    target_id: &'static str,
    depth_ratio: f32,
    cycle_beats: f32,
) -> AutomationState {
    let mut automation = AutomationState::default();
    automation.set_route(
        ControlAddress::new(target_id),
        LfoRoute {
            depth_ratio,
            cycle_beats,
            phase_offset_beats: 0.0,
            shape: LfoShape::Sine,
        },
    );
    automation
}

#[test]
fn modulated_control_value_snaps_like_the_engine() {
    let spec = spec_by_id("kick.interval_beats").unwrap();
    let route = LfoRoute {
        depth_ratio: 0.4,
        cycle_beats: 8.0,
        phase_offset_beats: 0.0,
        shape: LfoShape::Sine,
    };

    // Peak of the sine: raw value 1.0 + 0.4 * 3.75 = 2.5 must land on 2.0.
    let peak = modulated_control_value(spec, &route, 1.0, 2.0);
    assert_close(peak, 2.0);

    // Trough: 1.0 - 1.5 clamps to the minimum subdivision.
    let trough = modulated_control_value(spec, &route, 1.0, 6.0);
    assert_close(trough, 0.25);
}

#[test]
fn lfo_interval_modulation_snaps_to_power_of_two() {
    let mut controls = FluidControls::default();
    controls.kick.interval_beats = 1.0;
    let automation = automation_with_route("kick.interval_beats", 0.4, 8.0);

    for sample in (0..(SAMPLE_RATE as u64 * 16)).step_by(64) {
        let mut effective = controls.clone();
        apply_automation(&mut effective, &automation, timing(sample, 120.0));
        let v = effective.kick.interval_beats;
        assert!(
            [0.25f32, 0.5, 1.0, 2.0, 4.0]
                .iter()
                .any(|&q| (v - q).abs() < 1e-4),
            "modulated interval {v} is not a power-of-two subdivision"
        );
    }
}

#[test]
fn lfo_offset_modulation_snaps_to_quarter_beats() {
    let mut controls = FluidControls::default();
    controls.kick.offset_beats = 2.0;
    let automation = automation_with_route("kick.offset_beats", 0.4, 8.0);

    for sample in (0..(SAMPLE_RATE as u64 * 16)).step_by(64) {
        let mut effective = controls.clone();
        apply_automation(&mut effective, &automation, timing(sample, 120.0));
        let v = effective.kick.offset_beats;
        let snapped = (v / 0.25).round() * 0.25;
        assert!(
            (v - snapped).abs() < 1e-4,
            "modulated offset {v} is not on the 0.25-beat grid"
        );
    }
}

#[test]
fn lfo_interval_sweep_plays_on_grid_breakdown() {
    let mut controls = FluidControls::default();
    controls.kick.interval_beats = 1.0;
    controls.kick.offset_beats = 0.0;
    let automation = automation_with_route("kick.interval_beats", 0.4, 8.0);

    let total_beats = 32.0;
    let samples = (total_beats * 60.0 / 120.0 * f64::from(SAMPLE_RATE)) as u64;
    let mut trigger = GridTrigger::new();
    let mut hit_beats = Vec::new();

    for sample in 0..samples {
        let t = timing(sample, 120.0);
        let mut effective = controls.clone();
        apply_automation(&mut effective, &automation, t);
        if trigger.pop(t, effective.kick.interval_beats, effective.kick.offset_beats) {
            hit_beats.push(t.beat);
        }
    }

    // Every hit stays locked to the absolute 16th grid.
    for &beat in &hit_beats {
        let snapped = (beat / 0.25).round() * 0.25;
        assert!(
            (beat - snapped).abs() < 1e-3,
            "hit at beat {beat:.4} is off the 0.25 grid"
        );
    }

    // The sweep actually breaks down through multiple subdivisions.
    let mut gaps: Vec<i64> = hit_beats
        .windows(2)
        .map(|w| ((w[1] - w[0]) / 0.25).round() as i64)
        .collect();
    gaps.sort_unstable();
    gaps.dedup();
    assert!(
        gaps.len() >= 3,
        "expected at least 3 distinct hit spacings, got {gaps:?}"
    );

    let max_gap = max_hit_gap(&hit_beats, total_beats);
    assert!(
        max_gap <= 2.0 + 1e-3,
        "trigger starved during breakdown sweep: max gap {max_gap:.2} beats"
    );
}

#[test]
fn clap_voice_starts_first_burst_at_local_sample_zero() {
    let controls = ClapControls {
        level: 1.0,
        slap_count: 4.0,
        slap_spread_ms: 40.0,
        ..ClapControls::default()
    };
    let mut rng = StdRng::seed_from_u64(99);
    let mut voice = ClapVoice::new(&controls, SAMPLE_RATE, &mut rng);

    assert_eq!(voice.scheduled.first().copied(), Some(0));
    let _ = voice.next(&mut rng);
    assert_eq!(voice.current, 1);
    assert!(!voice.bursts.is_empty());
    assert!(voice.scheduled.iter().all(|&sample| sample > 0));
}