ferrosintesis 0.21.59

A pure-Rust General MIDI synthesizer and MIDI-to-WAV renderer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
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
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
//! The render engine: walks the event list in 64-sample blocks, spawns and
//! mixes voices per channel, applies each channel's strip (program-aware
//! distortion insert, CC74 brightness filter + CC71 resonance, CC7 volume,
//! CC11 expression, CC1 mod-wheel vibrato / Leslie ramp, CC64 sustain and
//! CC66 sostenuto pedals, CC67 una corda, CC5/CC65/CC84 portamento, CC70 choir
//! vowel morph, CC2 breath, channel and polyphonic aftertouch,
//! RPN 0/1 bend range and fine tune,
//! CC10 pan with a Haas micro-delay for real width, CC91 reverb send) and
//! three global buses: a hall reverb, a stereo chorus (ensembles breathe),
//! and a tempo-derived ping-pong echo (the classic delayed-lead sound).
//! Every controller here is opt-in ("authored"): a file that never sends one
//! renders exactly as it did before that controller existed. That is correct
//! MIDI semantics, not conservatism — an unauthored controller must be inert.

use crate::dsp::{key_freq, Biquad, DelayLine, OnePole, Rng};
use crate::midi::{EvKind, Song};
use crate::reverb::{CathedralReverb, Reverb};
use crate::{drums, voices};
use std::f32::consts::{FRAC_PI_2, TAU};

const BLOCK: usize = 64;

// CC1 mod wheel. Melodic sustained voices (plucks, bowed, winds) get an
// engine-level vibrato LFO per channel, multiplied on top of the channel's
// pitch-bend; organs morph their tremulant toward Leslie-fast instead.
const VIB_RATE_HZ: f32 = 5.3; // vibrato LFO rate
const VIB_DEPTH_CENTS: f32 = 35.0; // pitch depth at mod = 1
const ST_CC1_VIB_DEPTH: f32 = 0.012; // alt-bank strings: full-wheel per-layer section vibrato depth
const LESLIE_SLOW_HZ: f32 = 0.9; // tremulant rate the rotor brakes down to (chorale)
const LESLIE_FAST_HZ: f32 = 6.8; // tremulant rate the rotor spins up to
const LESLIE_INERTIA_S: f32 = 1.5; // rotor time constant (spin-up/down)
const LESLIE_DEPTH_ADD: f32 = 0.10; // extra tremulant depth at mod = 1

// The cathedral room runs hotter than the shared hall: the biggest single
// "presence" lever for the organ is the wet return, and scaling it here (rather
// than the global `--wet`) leaves every other instrument's hall untouched and
// keeps CC91 semantics intact. Bounded above by the low-chord headroom test.
const CATHEDRAL_WET_SCALE: f32 = 1.30;

// CC11 swell → cathedral-organ reed-rasp drive. Thresholded, not linear: a chorus
// reed is on/off with registration and the snarl belongs to the top of the
// dynamic. In (squared) expression terms the knee 0.25 lands at CC11 ≈ 64 (a
// half-open swell stays smooth), and γ > 1 concentrates the snarl's growth in the
// last quarter of pedal travel — how a swell crescendo feels. Opt-in: unauthored
// CC11 ⇒ drive 0 ⇒ byte-identical.
const ORGAN_SWELL_KNEE: f32 = 0.25;
const ORGAN_SWELL_GAMMA: f32 = 1.6;

// CC74 brightness: a resonant 2-pole lowpass on the channel's dry path,
// ahead of the bus sends, so the wah colours the reverb and echo too.
// 0..127 maps exponentially WAH_MIN_HZ..WAH_MAX_HZ; 127 is a true bypass.
const WAH_MIN_HZ: f32 = 300.0;
const WAH_MAX_HZ: f32 = 12000.0;
const WAH_Q: f32 = 1.4;
const WAH_SLEW_S: f32 = 0.02; // cutoff smoothing so a CC74 LFO doesn't zipper

// CC71 resonance: Q of the CC74 filter, 0..127 exponential. A channel that
// never authors CC71 stays at WAH_Q exactly.
const RES_MIN_Q: f32 = 0.7;
const RES_MAX_Q: f32 = 8.0;

// CC5 portamento time: 0..127 maps exponentially PORTA_MIN_S..PORTA_MAX_S.
const PORTA_MIN_S: f32 = 0.005;
const PORTA_MAX_S: f32 = 0.6;

// D10: default drum-room send level (un-highpassed so the kick keeps its
// body; the room is pre-hall). An authored CC91 scales this default across
// the full dry-to-room range; unauthored channels take this exact constant.
const ROOM_SEND: f32 = 0.35;

// D10e: overall drum-bus level relative to the band. The +6 dB "drum forward"
// lift (was 2.0) is REMOVED — a global kit lift is a MIXING decision baked into
// the instrument, and it dominated most mixes. A scalar -18 LUFS normalize is
// balance-transparent (it multiplies every channel equally), so the fader passes
// straight through as RELATIVE drums-vs-band level; the old comment's "+6 nominal
// -> ~+3 audible via limiter absorption" was an ear-estimate under a backwards
// model (the limiter only clamps transients above the ceiling, not integrated
// loudness). The synth now presents the kit level-matched to the band (1.0),
// consistent with the SC-55 reference; an album that genuinely wants drums forward
// authors that as ch-10 CC7 in its own mix. Kept as a tunable constant rather than
// deleted so the drums-vs-band point can be re-seated by ear.
// See wrk_docs/2026.07.20 - HLD - instrument balance oracle + drum-forward recalibration.md.
const DRUM_FORWARD: f32 = 1.0;

// Channel aftertouch (0xDn): "crescendo inside a held note" — pressure adds
// vibrato depth and gain on the sustained melodic families.
const AT_VIB_RATE_HZ: f32 = 5.0;
const AT_VIB_CENTS: f32 = 25.0; // pitch depth at full pressure
const AT_GAIN_DB: f32 = 2.5; // gain lift at full pressure
const BAGPIPE_DRONE_KEY: u8 = u8::MAX;
/// Chanter silence (with no drone-control hold) after which the latched
/// bagpipe drone is released — the bag emptying at the end of the tune. Long
/// enough to bridge musical rests and articulation gaps, short enough that
/// the drone dies inside a normal render tail.
const BAGPIPE_DRONE_HANG_S: f32 = 1.0;

/// Melodic sustained families that take the engine-level CC1 vibrato:
/// plucks (except palm-mute 28), bowed strings, SawStack strings/choir, harmonica,
/// winds, synth leads. Drums, Leslie organs, pads and modal instruments (piano,
/// bells) are left alone.
fn vibrato_family(program: u8) -> bool {
    // guitars (no palm-mute 28), basses, bowed strings, harp, SawStack strings/choir,
    // brass (56-63), reeds (64-71/109/111), winds, leads, banjo, fiddle. Orchestra hit (55)
    // is excluded — a one-shot stab does not vibrato (symmetric with timpani).
    matches!(
        program,
        22 | 24..=27 | 29..=46 | 48..=54 | 56..=71 | 72..=79 | 80..=87 | 104..=107
            | 109..=111
    )
}

fn organ_leslie_family(program: u8, bank: u8) -> bool {
    // 16..=18 always. GM19 is the Leslie drawbar on the default bank and the
    // CC0=1 legacy bank; the CC0=2 bank is the restored CathedralOrgan pipe
    // model, which has its own wind-chest motion and takes no Leslie ramp.
    matches!(program, 16..=18) || (program == 19 && bank != 2)
}

fn cathedral_organ(program: u8, bank: u8) -> bool {
    // GM19 on the CC0=2 alt bank: the restored cathedral pipe organ (wind-chest
    // breathing + CC11 reed-rasp swell + its own dedicated stone-room reverb).
    // Default-bank and CC0=1 GM19 are the Leslie drawbar and are NOT cathedral.
    program == 19 && bank == 2
}

fn cc1_pitch_vibrato_target(program: u8, alt: bool) -> bool {
    vibrato_family(program) && !(alt && matches!(program, 52..=54 | 22))
}

/// Families that answer channel aftertouch: the vibrato families plus
/// Modal, organ, string/choir SawStack and pad programs. Drums stay out:
/// pressure is not a pitched-body gesture for percussion.
fn aftertouch_family(program: u8) -> bool {
    vibrato_family(program)
        || matches!(
            program,
            0..=23 | 47 | 48..=54 | 80..=95 | 96 | 98 | 100 | 102 | 108
        )
}

/// Programs carrying a vocal formant bank, so CC70 can morph their vowel.
/// GM 85 (Lead 6, voice) joined on 2026-07-25 with MM-REQ-KILN-00022: a voice
/// that speaks through formants but cannot be re-vowelled would be an odd gap.
/// Opt-in as always — the arms guarded by this are reached only once a channel
/// has AUTHORED CC70, so a lead that never sends it renders exactly as before.
fn vowel_family(program: u8) -> bool {
    matches!(program, 52..=54 | 85 | 91)
}

// CC70 vowel morph anchors for the choir programs (52-54). Bass/baritone
// formant values; "mm" keeps the closed hum the v0.6 onset morph starts from,
// with the upper bands shaded down the way closed lips actually mute them.
/// The interpolated vowel a voice's formant bank is retuned to: three band
/// centre frequencies (Hz), their Qs, and their linear gains.
type Vowel = ([f32; 3], [f32; 3], [f32; 3]);
/// One CC70 morph anchor: the CC value it sits at (0..127) paired with the
/// `Vowel` (band frequencies, Qs, gains) the choir speaks at that value.
type VowelAnchor = (f32, [f32; 3], [f32; 3], [f32; 3]);
const VOWEL_ANCHORS: [VowelAnchor; 4] = [
    (
        0.0,
        [500.0, 1400.0, 2400.0],
        [12.0, 10.0, 9.0],
        [1.0, 0.30, 0.10],
    ), // mm
    (
        42.0,
        [350.0, 600.0, 2400.0],
        [10.0, 12.0, 9.0],
        [1.0, 0.35, 0.10],
    ), // oo
    (
        84.0,
        [600.0, 1040.0, 2250.0],
        [9.0, 10.0, 9.0],
        [1.0, 0.60, 0.35],
    ), // ah
    (
        127.0,
        [400.0, 1900.0, 2600.0],
        [9.0, 10.0, 9.0],
        [1.0, 0.85, 0.50],
    ), // eh
];

/// Interpolate the vowel tables at a (smoothed) CC70 position.
///
/// `pub(crate)` because GM 85 (Lead 6, voice) builds its default formant bank
/// from this same table rather than carrying its own copy of the numbers
/// (MM-REQ-KILN-00022) — a second hand-written vowel table is exactly the
/// drift this repo keeps paying for.
pub(crate) fn vowel_at(pos: f32) -> Vowel {
    let p = pos.clamp(0.0, 127.0);
    let hi = VOWEL_ANCHORS
        .iter()
        .position(|a| a.0 >= p)
        .unwrap_or(VOWEL_ANCHORS.len() - 1);
    if hi == 0 {
        let a = &VOWEL_ANCHORS[0];
        return (a.1, a.2, a.3);
    }
    let (a, b) = (&VOWEL_ANCHORS[hi - 1], &VOWEL_ANCHORS[hi]);
    let t = (p - a.0) / (b.0 - a.0);
    let mut f = [0f32; 3];
    let mut q = [0f32; 3];
    let mut g = [0f32; 3];
    for i in 0..3 {
        f[i] = a.1[i] + (b.1[i] - a.1[i]) * t;
        q[i] = a.2[i] + (b.2[i] - a.2[i]) * t;
        g[i] = a.3[i] + (b.3[i] - a.3[i]) * t;
    }
    (f, q, g)
}

/// The GM programs that get the overdrive/cabinet channel insert — the
/// single source of truth for the Prog handler and oracle 36.
pub(crate) fn needs_drive(prog: u8) -> bool {
    matches!(prog, 29 | 30)
}

/// Driven guitar strings can sustain indefinitely while physically/pedal held.
/// Eight voices preserve two power chords plus lead/doubling while bounding the
/// per-channel CPU and level wall from pathological stacked MIDI.
const DRIVEN_GUITAR_VOICE_LIMIT: usize = 8;

/// D9: static per-piece kit placement (drummer's perspective) in pan space
/// [0, 1], 0.5 = centre. Kick/snare stay centred; hats sit left; the toms
/// sweep across; ride/bell and china/crash-2 sit right, crash-1 left.
/// Authored CC10 OFFSETS this table (centre leaves it verbatim).
///
/// Ride 2 (59) sits just outside ride 1, mirroring the SC-55's own proportion.
/// That ROM separates its two RIDES by 10 panpot units where it separates the
/// two CRASHES by 40 (see `sampler::SECOND_CYMBAL_REPITCH` for the decode), and
/// the reason is physical: a drummer's two crashes are at opposite ends of the
/// kit, while a second ride sits alongside the first. 10/128 of the field is
/// 0.078 here, so 0.70 -> 0.78 — further from centre in the same direction the
/// rides already occupy. Copying the crashes' wide split would place two
/// cymbals that belong next to each other across the stereo image.
pub(crate) fn drum_pan(key: u8) -> f32 {
    match key {
        42 | 44 | 46 => 0.33,
        41 => 0.55,
        43 | 45 => 0.62,
        47 | 48 => 0.42,
        50 => 0.32,
        51 | 53 => 0.70,
        59 => 0.78,
        49 | 55 => 0.25,
        52 | 57 => 0.75,
        _ => 0.5,
    }
}

/// D10d: per-key kit-balance trim. The kit voicing — the sampled `DRUM_LEVEL`
/// table and the modeled kit it is level-matched to — inherited a balance where,
/// measured on the Hey Jude reference, the hi-hats sit ~19 dB under the kick/snare
/// while the crash/ride sit only ~2 dB under them. That reads as "the hats vanish
/// and the cymbals are too loud." This trim corrects it for BOTH kits at once
/// (applied in the drum mix, so it scales the sampled and modeled voices equally
/// and preserves their level parity): the hi-hats come up ~+11 dB, the loud accent
/// cymbals come down, and the backbone (kick/snare/toms/stick/aux) stays put.
fn kit_balance(key: u8) -> f32 {
    match key {
        42 | 44 | 46 => 4.5,                // hi-hats: ~19 dB too quiet -> up ~+13 dB
        38 | 40 => 1.8, // snare: well forward (it sat behind the toms; +2.6 -> ~+5 dB)
        41 | 43 | 45 | 47 | 48 | 50 => 1.6, // toms: forward ~+4 dB
        49 => 0.5,      // crash 1 (hard-left, used rhythmically): pulled down further
        57 => 0.68,     // crash 2 (right): stays an accent
        51 | 59 => 0.55, // ride: too loud and too sustained
        53 => 0.72,     // ride bell
        52 => 0.68,     // china
        55 => 0.68,     // splash
        _ => 1.0,       // kick/side-stick/tamb/cowbell: unchanged
    }
}

/// The 5-biquad speaker-cabinet model (HLD G1): low-end resonance, a mid
/// scoop, a presence peak, and a two-pole-pair cliff that both voices the
/// amp and acts as the decimation filter for the 2× nonlinear path. Built
/// at the 2× rate; shared with the oracle-3 response test.
pub(crate) fn cab_biquads(sr2: f32) -> [Biquad; 5] {
    cab_from_spec(cab_spec(), sr2)
}

/// The rhythm cabinet as raw parameter triples: three `peak` (Hz, Q, dB) and
/// two lowpass-cliff (Hz, Q) specs. Split out from [`cab_biquads`] so the SAME
/// literals feed both the built biquads and [`DriveBase`] (the score-authored
/// amp offsets in the part-A HLD need the base values, and a live `Biquad`
/// cannot be read back). [`cab_biquads`] is bit-identical either way.
fn cab_spec() -> CabSpec {
    (
        [(100.0, 1.2, 4.0), (500.0, 1.0, -3.0), (2600.0, 1.5, 5.0)],
        // elements CAB_CLIFF.. are the anti-alias decimation cliff and must
        // stay LAST in Drive::chain (MicroCab inserts before them)
        [(4000.0, 0.9), (3800.0, 0.8)],
    )
}

/// A cabinet as raw specs: 3 `peak` (Hz, Q, dB) then 2 lowpass (Hz, Q). The
/// `CAB_CLIFF`-split topology of [`cab_biquads`] is preserved by construction.
type CabSpec = ([(f32, f32, f32); 3], [(f32, f32); 2]);

fn cab_from_spec((peaks, cliff): CabSpec, sr2: f32) -> [Biquad; 5] {
    [
        Biquad::peak(peaks[0].0, peaks[0].1, peaks[0].2, sr2),
        Biquad::peak(peaks[1].0, peaks[1].1, peaks[1].2, sr2),
        Biquad::peak(peaks[2].0, peaks[2].1, peaks[2].2, sr2),
        Biquad::lowpass(cliff[0].0, cliff[0].1, sr2),
        Biquad::lowpass(cliff[1].0, cliff[1].1, sr2),
    ]
}

/// Index of the first lowpass-cliff biquad in [`cab_biquads`]'s array — the
/// named seam `Drive::chain` splits at so the fine-structure FIR can never
/// silently drift to the wrong side of the anti-alias cliff (review A3).
///
/// [`cab_biquads_lead`] MUST keep the same 3-peaks-then-2-lowpasses topology,
/// because this one index splits the chain for BOTH cabinets.
pub(crate) const CAB_CLIFF: usize = 3;

/// The LEAD speaker cabinet — the CC0 alt bank's own cab (2026.07.23 amp+cab
/// HLD). Same 5-biquad topology as [`cab_biquads`] (so [`CAB_CLIFF`] still
/// splits it correctly), voiced for a soaring lead instead of a rhythm chug.
///
/// A driven guitar's identity lives in its amp and cabinet, and until now the
/// alt bank borrowed the rhythm cab wholesale — only the [`MicroCab`] ripple
/// depth differed — which is why Arthur heard "GM029 main sounds the same as
/// GM029 alt" and why the lead sounded THIN.
///
/// **This cabinet is where the lead's tone actually comes from.** Both `tanh`
/// stages run deeply saturated at the shipped operating points, so the
/// pre-clip EQ (`voice`/`tilt`) mostly decides *which partials dominate the
/// clipper* rather than acting as tone control — the cab is the only truly
/// LINEAR tone stage in the chain. Curing "thin" is therefore a cab job.
/// Three moves against [`cab_biquads`]:
///
/// * **Body FILLED, not scooped** (a −3 dB dip at 500 Hz becomes a broad
///   +2 dB lift at 700 Hz, Q 0.8). The rhythm cab's mid scoop is what makes a
///   power chord sit under a vocal; on a single-note lead the same scoop
///   hollows out exactly where the note lives. Deliberately WIDE and centred
///   at 700: its skirt still leaves ~+4 dB at 500 Hz against the rhythm cab
///   while filling 400–1200 Hz, which is the fundamental-and-low-harmonic
///   band for the keys 57–69 lead register (f0 220–440 Hz). Single biggest
///   cure for "thin".
/// * **Tighter, higher low resonance** (100 Hz +4 dB → 120 Hz +2 dB). A lead
///   does not need the chug's low-end bloom, and trimming it keeps the lead
///   amp's body in the MIDRANGE instead of flub.
/// * **Presence moved up and OPENED, not cranked** (2600 Hz +5 dB Q 1.5 →
///   2800 Hz +4.5 dB Q 1.2). A lead cuts here — but 3–3.5 kHz at high Q is the
///   ear-canal harshness band, and a narrow peak sitting just under the cliff
///   reads as a cocked-wah honk. Presence is the garnish; the body fill above
///   is the cure.
///
/// **The anti-alias cliff is deliberately IDENTICAL to [`cab_biquads`]**
/// (4000/3800 Hz). Raising it for "air" was considered and dropped: on a
/// driven guitar 5–7 kHz is fizz rather than sparkle, and the cliff is the
/// first thing to retreat on if the alt alias margin tightens — the 2× shaper
/// can fold harmonics straight into the passband, which no cliff can fix.
/// `drive_alias_floor` covers `alt=true` to keep that measured, not assumed.
///
/// **Why the lead cab is keyed on the program while the rhythm cab is not.**
/// The first cut shared ONE lead cab between 29 and 30, and it failed
/// `driven_banks_diverge_at_lead_pitches`: 30's lead was only 0.68–0.78 dB from
/// its own main at keys 63/65. The cause is that 30's lead deliberately keeps a
/// deep pre-clip SCOOP (it inherits the distortion amp's chuggy saturation
/// character — that is what makes it 30 and not 29), which cancels most of a
/// shared cab's body fill. So 30's cab has to put back MORE body to reach the
/// same "vocal lead" destination.
///
/// That also resolves a constraint clash. 30's lead must differ from 30's main
/// (more body) AND from 29's lead — and if both leads are separated on the same
/// mid axis, those two pull against each other. They are therefore separated on
/// the axis that is musically true of the pair instead: **29's lead is the
/// brighter, more open overdrive lead; 30's is the darker, thicker distortion
/// lead.** Body and presence move in opposite directions between them.
pub(crate) fn cab_biquads_lead(sr2: f32, program: u8) -> [Biquad; 5] {
    cab_from_spec(cab_spec_lead(program), sr2)
}

/// The lead cabinet as raw parameter triples (see [`cab_spec`]).
fn cab_spec_lead(program: u8) -> CabSpec {
    // (body lift, presence centre, presence lift)
    let (body, pres_hz, pres) = if program == 30 {
        (4.5, 2600.0, 3.0) // darker, thicker
    } else {
        (2.5, 2800.0, 5.0) // brighter, more open
    };
    (
        [(120.0, 1.0, 2.0), (600.0, 0.75, body), (pres_hz, 1.2, pres)],
        // elements CAB_CLIFF.. are the anti-alias decimation cliff and must
        // stay LAST in Drive::chain (MicroCab inserts before them)
        [(4000.0, 0.9), (3800.0, 0.8)],
    )
}

/// MicroCab taps: (delay ms, gain), numerically optimized against the full
/// constraint set at once (250 k-candidate search, journal 2026.07.18):
/// ≥ 6 magnitude alternations of ≥ 1.5 dB across 900–3600 Hz, total swing
/// 6.2 dB (musical, not gutting), 3→6 kHz tilt −0.07 dB (the decimation
/// cliff's margin is untouched), ≤ 1.6 dB span below 800 Hz (review I8's
/// real concern — the drive voicing EQs and the asymmetry-oracle bins stay
/// clean; delays beyond I8's draft 0.55 ms cap are fine BECAUSE this
/// low-band bound is enforced directly), |H| peak 1.52 (≫ alias margin).
/// Hand-picking taps kept failing one bound or another — a delay tap
/// ripples at every frequency equally, so only joint optimization finds
/// the corner of the constraint box.
const MICRO_CAB_TAPS: [(f32, f32); 5] = [
    (0.360, 0.110),
    (0.593, 0.110),
    (0.625, -0.157),
    (0.783, 0.115),
    (0.895, -0.238),
];

/// Ripple depth for the SUSTAINING driven lead (the CC0 alt bank,
/// `voices::DRIVE_LEAD`) as a fraction of `MICRO_CAB_TAPS`.
///
/// `MicroCab` normalizes its ripple to unity on the 900–3600 Hz band
/// AVERAGE, which makes it level-neutral for broadband material — a chugging
/// rhythm guitar spreads its energy across the band and averages the comb
/// out. That assumption fails for a lead that HOLDS ONE PITCH for seconds:
/// it samples the ripple at exactly one frequency and keeps whatever it
/// finds there. With only 5 taps at 0.36–0.90 ms the comb is coarse (ripple
/// periods 1.1–2.8 kHz), so a held tone can park squarely in a null:
/// measured on Three-Sixty-One's finale, C6 lost 2.08 dB and E6 1.03 dB at
/// the fundamental while their 2nd/3rd harmonics gained 2.8 dB — the note
/// went thin, not merely quiet, and Arthur heard the lead recede
/// (2026.07.20 journal).
///
/// So the depth is a property of the BANK, not of the amp: the default bank
/// keeps the full ripple Arthur approved for rhythm work (depth 1.0 —
/// bit-identical), and the sustaining lead gets a quarter of it. At 0.25 the
/// worst deviation any held pitch can suffer anywhere in the band falls
/// 3.39 dB → 0.85 dB (C6 −0.47, E6 −0.24) while the ripple stays measurably
/// present at 1.54 dB swing, so the lead still speaks through a cabinet
/// rather than a DI. The macro cab shape (`cab_biquads`) is untouched either
/// way — this scales only the fine structure on top of it.
pub(crate) const MICRO_CAB_LEAD_DEPTH: f32 = 0.25;

// ---- Score-authored amp parameters (MM-REQ-KILN-00028, part-A HLD) --------
//
// Six per-channel knobs that let a MIDI file AUTHOR the driven-guitar amp and
// cabinet, addressed by NRPN MSB `AMP_NRPN_MSB` / LSB = the index below, value
// via Data Entry MSB (CC6). Every value is a SIGNED OFFSET from the shipped
// program voicing with 64 = "as shipped", so a channel that authors nothing
// runs the existing path bit-identically (the inertness invariant), and the
// oracle-tuned 29/30 x main/alt matrix survives. The offsets are applied in
// place by `Drive::apply_params` — no rebuild, no allocation, click-free.

/// NRPN MSB (CC99) selecting the ferrosintesis amp block. NRPN has no
/// manufacturer namespace, so this is CONTAINED, not collision-free: the
/// parameters are inert on any channel not playing GM29/30, and the worst case
/// on a driven channel is a timbre tweak (never a stuck note or wrong pitch).
const AMP_NRPN_MSB: u8 = 0x30;
const AMP_PARAM_COUNT: usize = 6;
/// Data Entry MSB value meaning "as shipped" — the neutral every knob is a
/// signed offset from, and the midpoint of the 0..127 range (so it is also the
/// span below neutral). Named because it is part of the PROTOCOL, not an
/// implementation detail: `amp-lab` publishes the same number as `amp::NEUTRAL`
/// and the README states it, and `amp_protocol_has_one_definition`
/// (MM-REQ-KILN-00030) checks all three still agree.
const AMP_NEUTRAL: u8 = 64;
const AMP_DRIVE: usize = 0; // pedal gain: g1, g2 (+ derived post makeup)
const AMP_TONE: usize = 1; // pre-clip voice EQ gain (dynamics-dependent by nature)
const AMP_TIGHT: usize = 2; // pre-shaper high-pass corner
const AMP_BODY: usize = 3; // cabinet low-mid peak gain (cab[1])
const AMP_PRES: usize = 4; // cabinet presence peak gain (cab[2])
const AMP_CABTONE: usize = 5; // cabinet high-frequency cliff, DOWNWARD only

/// Oversampling factor for the driven-guitar shaper. The nonlinearity runs at
/// `sr * this`, and the cabinet's lowpass cliff is the decimation filter.
///
/// **Raised 2 -> 4 on 2026-07-23, and it is the enabling change for the whole
/// score-authored amp.** The `tanh` stages generate harmonics far above the
/// internal Nyquist; those fold back INTO the audible band, where no downstream
/// filter can remove them. At 2x, that fold-back consumed the entire -40 dBc
/// budget with Drive alone at maximum, so every EQ knob had to stay narrow or the
/// combination breached (measured: Drive 127 + Tone + Presence = -35.0 dBc). At 4x
/// the same worst case measures -44.8 dBc — 9.8 dB of headroom bought back, which
/// is what lets the knobs be genuinely wide.
///
/// The cost is small and was measured, not assumed: one driven channel goes from
/// 0.4 % to 0.9 % of a core (241x -> 118x realtime). It also slightly cleans up
/// every driven-guitar render, which is a timbre change Arthur accepted
/// deliberately (2026-07-23) rather than a silent side effect.
const DRIVE_OVERSAMPLE: usize = 4;

/// Drive gain exponent: `g1 *= 2^(k*n)`, `g2 *= 2^(k*n/2)`, `n in [-1, +0.984]`.
/// The TOP of this knob is bounded by the alias floor, not taste — the 2x
/// shaper folds harmonics into the passband and `drive_alias_floor` asserts
/// -40 dBc.
///
/// Widened 1.2 -> 2.0 once [`DRIVE_OVERSAMPLE`] went to 4x, spanning g1
/// x0.25 .. x3.91 (1.7x the old range: near-clean at 0, heavy at 127).
///
/// At 2x this constant was pinned AT the alias ceiling — k=1.2 measured -42.5 dBc
/// and k=1.5 already breached. At 4x that ceiling is gone: `amp_drive_ceiling
/// _sweep` reads -52.6 dBc here and even k=3.0 is safe at -49.4 dBc. **So the
/// bound on this number is no longer aliasing — it is the LEVEL residual.** A
/// wider gain span pulls the makeup trim further out of its depth (see
/// [`AMP_DRIVE_POST_C`]); 2.0 keeps the worst-case residual at 8.2 dB, and going
/// to 2.5 pushed it past 10 dB, which starts to make the knob feel like a volume
/// control rather than a gain control.
const AMP_DRIVE_K: f32 = 2.0;
/// Makeup trim: `post *= 2^(-c*n)`. Strictly positive at every n and k (unlike
/// the reciprocal `amp_sim` form, which goes singular for n<0). c is set by the
/// level residual, not asserted — see `amp_drive_level_residual_bounded`.
///
/// Re-balanced 0.9 -> 1.6 when [`AMP_DRIVE_K`] widened to 2.0, and 1.6 is the
/// measured MINIMAX rather than a guess: swept at k=2.0 the worst-case residual
/// is 9.40 dB at c=1.4, **8.21 dB at c=1.6**, and 9.40 dB again at c=1.8.
///
/// It cannot do better than that, for a reason worth stating: the error depends
/// on INPUT LEVEL as much as on knob position. At low drive a quiet note never
/// reaches the knee, so its output tracks gain almost linearly and wants a lot of
/// makeup; a loud note at the same setting still clips and wants almost none. One
/// static exponent has to sit between those, so the residual is irreducible, not
/// under-tuned. Drive is a gain control and will change level — CC7 is the
/// balance control, exactly as on a real amp.
const AMP_DRIVE_POST_C: f32 = 1.6;
/// Body / Presence CABINET EQ swing at the knob extremes, in dB (`+/- this * n`).
///
/// Widened 9 -> 15 dB (Arthur, 2026-07-23: "I like the variance... we could allow
/// more"). Measured headroom (`amp_range_headroom_sweep`): the Body axis spreads
/// 14.7 dB at +/-9 and 24.0 dB at +/-15, with peak 0.22 and DC 1.9e-5. Free of
/// alias cost because these two are POST-clip linear cabinet EQ — nothing they do
/// reaches the shaper.
const AMP_EQ_DB: f32 = 15.0;
/// TONE swing. Separate from the cabinet EQ because Tone is PRE-clip: its boost
/// feeds the clipper harder, so it spends the same alias budget Drive does.
///
/// At 2x that coupling forced an awkward asymmetric range (+5 boost / -15 cut),
/// because the joint ceiling with Drive at 127 crossed -40 dBc between +5 and +6.
/// At 4x the same sweep sits at about -53 dBc across the whole 4..9 dB span, so
/// the constraint no longer binds and the knob is symmetric again — the
/// asymmetry existed only to dodge a limit that is now gone. Kept a little under
/// the cabinet's +/-15 because a pre-clip EQ is largely swallowed by the shaper,
/// so extra range there buys less than it does post-clip.
const AMP_TONE_DB: f32 = 12.0;
/// Tightness pre-HPF corner: `pre_hz *= 2^(TIGHT_OCT*n)`, clamped `<= TIGHT_MAX`.
/// Kept modest: a wide corner MUTES the low register (round 1 measured a 120 Hz
/// corner costing ~7.5 dB at E2) rather than voicing it, so this widened only
/// 0.6 -> 0.9 octaves with the cap lifted 180 -> 200 Hz.
const AMP_TIGHT_OCT: f32 = 0.9;
const AMP_TIGHT_MAX_HZ: f32 = 200.0;
/// Cab Tone: `cliff *= 2^(CABTONE_OCT*n)` for `n <= 0` (downward only, so it can
/// only ever strengthen alias rejection). 1.74 octaves puts the knob's dark end
/// at x0.30 — a 4000 Hz cliff closing to 1200 Hz. Measured: the HF axis spreads
/// 11.3 dB at the old x0.50 and 20.7 dB here, and x0.25 adds only 0.1 dB more,
/// so this is the point of diminishing return rather than an arbitrary pick.
const AMP_CABTONE_OCT: f32 = 1.74;

/// Cabinet fine structure (guitar-realism HLD §5): the dense magnitude
/// ripple a real cab's cone breakup and edge reflections put on top of the
/// smooth biquad response — a sparse FIR (direct + 5 taps, `MICRO_CAB_TAPS`)
/// normalized so the 900–3600 Hz band-average magnitude is unity (the
/// ripple recolors the band without moving its level, review D9). Runs
/// inside the cab section BEFORE the two lowpass cliff biquads, so the
/// anti-alias cliff stays the last element of the 2× nonlinear path
/// (review I5/D6 resolution). This deliberately revives the guitar-v2
/// decision-log "ripple comb (deferred)" — v2 parked it as polish; this is
/// that polish (review S10).
///
/// `depth` scales the tap gains before normalization (see
/// [`MICRO_CAB_LEAD_DEPTH`]); the band-average stays unity at every depth,
/// so depth changes the ripple's DEVIATION, never the band's level.
pub(crate) struct MicroCab {
    buf: Vec<f32>,
    pos: usize,
    taps: [(usize, f32); 5],
    direct: f32,
}

impl MicroCab {
    /// `depth` 1.0 is the full cabinet ripple (the default driven bank);
    /// [`MICRO_CAB_LEAD_DEPTH`] is the sustaining lead's shallower one.
    pub(crate) fn with_depth(sr2: f32, depth: f32) -> Self {
        let taps_s: Vec<(usize, f32)> = MICRO_CAB_TAPS
            .iter()
            .map(|&(ms, g)| (((ms * 1e-3 * sr2).round() as usize).max(1), g * depth))
            .collect();
        // band-average |H| over 900–3600 Hz (closed form for the sparse FIR)
        let mut avg = 0.0;
        let grid: Vec<f32> = (0..28).map(|k| 900.0 + k as f32 * 100.0).collect();
        for &f in &grid {
            let w = std::f32::consts::TAU * f / sr2;
            let (mut re, mut im) = (1.0f32, 0.0f32);
            for &(d, g) in &taps_s {
                re += g * (w * d as f32).cos();
                im -= g * (w * d as f32).sin();
            }
            avg += (re * re + im * im).sqrt();
        }
        avg /= grid.len() as f32;
        let norm = 1.0 / avg.max(1e-6);
        let max_d = taps_s.iter().map(|&(d, _)| d).max().unwrap_or(1);
        let mut taps = [(0usize, 0f32); 5];
        for (o, &(d, g)) in taps.iter_mut().zip(&taps_s) {
            *o = (d, g * norm);
        }
        MicroCab {
            buf: vec![0.0; (max_d + 1).next_power_of_two()],
            pos: 0,
            taps,
            direct: norm,
        }
    }

    #[inline]
    pub(crate) fn process(&mut self, x: f32) -> f32 {
        let mask = self.buf.len() - 1;
        self.buf[self.pos] = x;
        let mut y = self.direct * x;
        for &(d, g) in &self.taps {
            y += g * self.buf[(self.pos + self.buf.len() - d) & mask];
        }
        self.pos = (self.pos + 1) & mask;
        y
    }
}

/// Overdrive/distortion channel insert for GM programs 29/30 (guitar v2,
/// HLD §3.C): program-keyed pre-voicing → stage-1 biased (asymmetric) tanh
/// → interstage tilt EQ → stage-2 tanh → DC blocker → speaker cabinet, the
/// whole nonlinear chain at 2× rate. The cab's cliff replaces the old
/// box-average decimator, so the shaper fizz dies in the cabinet instead
/// of aliasing down.
///
/// The chain is STATIC: the loudest instant (the pick) drives the tanh
/// stages hardest, which is exactly how a real amp clips. The old
/// "power-supply sag" gain (`sag_target / env`, slewing UP to 4× as the
/// note decayed) had the temporal polarity backwards — it faked sustain by
/// blooming the tail — and was deleted (voice-quality overhaul §2.6);
/// held-note sustain is the string's e-bow sustainer (`DRIVE.sustain`).
/// The program+bank base voicing an authored offset is measured from. A live
/// `Biquad` cannot report its own centre/Q/gain, so the knob-relevant base
/// values are stored here (written once by `from_stages` from the literals in
/// `Drive::new`) and read by `apply_params` — one source of truth, so a future
/// re-voicing (part B) cannot silently desync from the offset math.
#[derive(Clone, Copy)]
struct DriveBase {
    pre_hz: f32,
    voice: (f32, f32, f32), // Tone knob: (Hz, Q, dB)
    g1: f32,
    g2: f32,
    post: f32,
    cab1: (f32, f32, f32),  // Body knob: cab[1] (Hz, Q, dB)
    cab2: (f32, f32, f32),  // Presence knob: cab[2] (Hz, Q, dB)
    cliff: [(f32, f32); 2], // Cab Tone knob: cab[3]/cab[4] (Hz, Q)
}

struct Drive {
    program: u8,
    /// Whether this insert was built for the CC0 alt bank (the sustaining
    /// `DRIVE_LEAD` voicing). Stored so the strip can tell a stale insert
    /// from a current one when the bank changes mid-song; it selects the
    /// `MicroCab` depth at construction and is DSP-irrelevant thereafter.
    alt: bool,
    pre: Biquad,
    voice: Biquad,
    g1: f32,
    bias: f32,
    tilt: Biquad,
    g2: f32,
    post: f32,
    dcb: Biquad,
    cab: [Biquad; 5],
    micro: MicroCab,
    prev: f32,
    // ---- score-authored amp parameters (MM-REQ-KILN-00028) ----
    // All inert unless the strip authors an amp NRPN: `apply_params` is only
    // called for an authored channel, so `active` stays false and `process`
    // runs the original path. `base` is this insert's shipped voicing; the
    // `*_target` scalars are the block-rate goals the per-sample slew chases so
    // a swept Drive cannot staircase at the block frequency.
    base: DriveBase,
    sr_os: f32,
    g1_target: f32,
    g2_target: f32,
    post_target: f32,
    slew: f32,
    active: bool,
}

impl Drive {
    /// `alt` = the channel's CC0 bank is non-zero, i.e. the strip is playing
    /// the sustaining `DRIVE_LEAD` voicing rather than the decaying default.
    ///
    /// It selects a WHOLE AMP, not a trim (2026.07.23 amp+cab HLD): the main
    /// bank is the rhythm amp, the alt bank a soaring lead amp with its own
    /// gain staging, voicing EQ and cabinet ([`cab_biquads_lead`]). Before
    /// that, `alt` moved only the cabinet fine-structure depth
    /// ([`MICRO_CAB_LEAD_DEPTH`]) — so main and alt ran the IDENTICAL amp, and
    /// the two banks were told apart only by their string (a decaying pluck vs
    /// the e-bow sustainer). Arthur heard them converge ("GM029 main sounds the
    /// same as GM029 alt"), with the lead thin.
    ///
    /// Measured, the two inserts differed by 0.05 dB in the low end — they were
    /// the same amp. And the string does NOT cover for that: its sustain gap is
    /// large and GROWS with pitch (14→60 dB over keys 45–69). It simply is not
    /// audible on the material, because a lead line's notes last a few hundred
    /// milliseconds and that gap lives in a tail nobody hears — over the span
    /// that is audible, both banks went through one amp.
    ///
    /// The main bank is UNCHANGED and stays bit-identical.
    fn new(program: u8, alt: bool, sr: f32) -> Self {
        let sr_os = sr * DRIVE_OVERSAMPLE as f32;
        if alt {
            // ---- LEAD amp (CC0 alt bank) -------------------------------
            // A lead amp is not a louder rhythm amp. Three things make it, and
            // NONE of them is "more presence into the clipper":
            //
            // 1. FOCUS — cut lows BEFORE the shaper (`pre` 90→120 Hz). This is
            //    the biggest single lever and the one the old design missed.
            //    Low end that enters a clipper eats headroom and smears
            //    intermodulation sidebands across every harmonic; that mush is
            //    generated INSIDE the nonlinearity, so no amount of post-cab EQ
            //    removes it. Cutting it first is what makes a lead channel
            //    sound tight and vocal rather than woolly. 120 rather than 130
            //    is the deliberate compromise: the alt bank does carry low
            //    notes (Slipstream authors CC0=1 down to key 36), and a 2-pole
            //    corner at 130 would thin them audibly.
            // 2. BODY — carried by the cabinet ([`cab_biquads_lead`]), which is
            //    the only linear tone stage here. See its docs.
            // 3. A DARKER feed into stage 2 (`tilt`). The rhythm amps push
            //    700–1200 Hz into stage 2 for bite; a lead pushes LOWER and
            //    gentler (1400 Hz, +2.5 dB). Boosting presence into a clipper
            //    multiplies its harmonic/IMD skirt — that is fizz, not cut —
            //    so presence is added AFTER the shapers, linearly, in the cab.
            //
            // NOT a lever, despite the intuition: extra g2 does NOT buy
            // sustain here. Amp compression lengthens a DECAYING note by
            // holding it at the knee, but the alt bank's string is the e-bow
            // sustainer (`voices::DRIVE_LEAD`, sustain 0.6), which already
            // holds at constant level — so g2 changes the TONE of the hold
            // (denser odd harmonics, squarer duty), not its length. It is
            // therefore raised only modestly, for edge thickness.
            //
            // 29 vs 30 inside the alt bank is preserved on the SAME axis the
            // main banks use — pre-clip push vs pre-clip scoop — plus aligned
            // g1 and g2. Three coherent axes, rather than several sub-audible
            // ones: a small shift of `tilt` centre or of g2 alone would be
            // inaudible through a saturated stage, and the two leads would
            // collapse into each other the way main and alt just did. The
            // measured signature is that 29 compresses LESS than its own main
            // (the open, dynamic lead) while 30 compresses MORE (the saturated
            // one) — see `alt_bank_gain_staging_separates_the_two_leads`.
            //
            // `bias` is deliberately NOT one of those axes and stays 0.85 on
            // both. It was tempting (0.8 vs 0.9 reads as "open vs warm"), but
            // dropping to 0.8 raises small-signal gain ~1.2 dB while shrinking
            // the duty asymmetry that generates H2 — measured, 29's H2 falls
            // ~3.5 dB while H3 rises, against `driven_sustain_stays_distorted`
            // floors that only carry 1.4–4.1 dB of margin. 0.85 keeps useful
            // H2 on both; below ~0.75 the referenced-tanh asymmetry washes out
            // altogether.
            //
            // `post` is level-matched to the main bank (`drive_level_probe`,
            // measured on a 300–3400 Hz band so the low-resonance difference
            // does not skew it) so the A/B isolates TIMBRE, not loudness.
            let (g1, g2, post, bias, voice, tilt) = if program == 30 {
                (
                    9.0,
                    3.4,
                    0.0714,
                    0.85,
                    // 30 keeps a pre-clip SCOOP, shallower than the rhythm
                    // amp's −5: the saturation character stays chuggy/dark
                    // while the lead cab restores the body post-clip.
                    (650.0, 1.0, -4.5),
                    // and a scooped feed into stage 2, gentler and LOWER than
                    // the rhythm 30's −4 dB @ 700
                    Biquad::peak(800.0, 0.9, -2.0, sr_os),
                )
            } else {
                (
                    8.0,
                    2.8,
                    0.0789,
                    0.85,
                    // 29 is the OPEN lead: a pre-clip mid push, higher and
                    // broader than the rhythm 29's +4 dB @ 800.
                    (1000.0, 0.8, 4.0),
                    // a gentle, LOW feed into stage 2 (see note 3 above) —
                    // deliberately NOT a presence boost, which would fizz
                    Biquad::peak(1400.0, 0.8, 2.5, sr_os),
                )
            };
            return Drive::from_stages(
                program,
                alt,
                sr_os,
                120.0,
                voice,
                g1,
                bias,
                tilt,
                g2,
                post,
                cab_biquads_lead(sr_os, program),
                cab_spec_lead(program),
            );
        }
        // ---- RHYTHM amp (default bank) — UNCHANGED, bit-identical ------
        // 30 = distortion (scooped chug), 29 = overdrive (mid-push lead).
        // Two gentler stages replace v1's single hot tanh.
        //
        // Round 2 ("clean, dark sustain"): g1 raised 2.5→9.0 / 4.5→8.0 and
        // the DRIVE preset now feeds the insert ~7 dB hotter (voices.rs
        // DRIVE: amp 0.7→1.5, sustain 0.5→0.7, bright 4800→9000), so the
        // e-bow-held tail keeps audible harmonic edge
        // (driven_sustain_stays_distorted). Measured ceiling: the hold's
        // clipping depth is structurally capped by the §2.6 sag-catcher
        // (o_attack_sustained_plucks_no_late_bloom) — a deeply squared hold
        // out-RMSes the broadband attack window (crest-factor inversion,
        // measured at DRIVE.amp ≥ 2.0), so the hold sits at the tanh knee,
        // not in hard clip. `post` re-matched end-to-end (o_attack_held_note
        // _probe early window, key 45 vel 100: 29 0.0368, 30 0.0423 — the
        // pre-round-2 levels).
        let (g1, g2, post, bias) = if program == 30 {
            (8.0, 3.0, 0.145, 0.9)
        } else {
            // bias raised with g1 (0.45→0.9): at the hotter swing the old
            // bias point washed out of the curvature and the even-harmonic
            // warmth vanished (drive_asymmetry_and_dc's 2nd-vs-3rd floor)
            (9.0, 2.0, 0.12, 0.9)
        };
        let (voice, tilt) = if program == 30 {
            (
                (650.0, 0.9, -5.0),
                // deepen the scoop between the stages: stage 2 re-saturates
                // the mids the voicing pulled, so pull again where it counts
                Biquad::peak(700.0, 0.9, -4.0, sr_os),
            )
        } else {
            (
                (800.0, 0.8, 4.0),
                // upper-mid push into stage 2: the singing lead bite
                Biquad::peak(1200.0, 0.8, 2.0, sr_os),
            )
        };
        Drive::from_stages(
            program,
            alt,
            sr_os,
            90.0,
            voice,
            g1,
            bias,
            tilt,
            g2,
            post,
            cab_biquads(sr_os),
            cab_spec(),
        )
    }

    /// Shared field construction for the program-gated `new` (both banks) and
    /// the XG `amp_sim` insert: the pre-HPF, the post-shaper DC blocker and the
    /// interpolation state are identical; the voicing EQ, gain staging and
    /// CABINET differ. `program` is stored but DSP-irrelevant
    /// (`chain`/`process` never read it).
    ///
    /// `cab` must keep [`cab_biquads`]' 3-peaks-then-2-lowpasses topology —
    /// [`CAB_CLIFF`] splits it for the `MicroCab` insert, and the last two
    /// elements are the anti-alias decimation cliff.
    ///
    /// `pre_hz` is the PRE-shaper high-pass corner. It is a voicing parameter,
    /// not hygiene: low end that reaches the clipper eats headroom and smears
    /// intermodulation across the harmonics, so raising it is how a lead
    /// channel buys focus (90 Hz for the rhythm amps and the XG sim, 120 Hz
    /// for the lead — see `Drive::new`).
    #[allow(clippy::too_many_arguments)]
    fn from_stages(
        program: u8,
        alt: bool,
        sr_os: f32,
        pre_hz: f32,
        voice: (f32, f32, f32),
        g1: f32,
        bias: f32,
        tilt: Biquad,
        g2: f32,
        post: f32,
        cab: [Biquad; 5],
        cab_base: CabSpec,
    ) -> Self {
        let (peaks, cliff) = cab_base;
        Drive {
            program,
            alt,
            pre: Biquad::highpass(pre_hz, 0.7, sr_os),
            voice: Biquad::peak(voice.0, voice.1, voice.2, sr_os),
            g1,
            bias,
            tilt,
            g2,
            post,
            // a real DC blocker after the shapers: the biased tanh produces
            // large signal-dependent DC that the cab's unity-at-DC biquads
            // cannot remove (V4/CORR-1)
            dcb: Biquad::highpass(20.0, 0.7, sr_os),
            cab,
            micro: MicroCab::with_depth(sr_os, if alt { MICRO_CAB_LEAD_DEPTH } else { 1.0 }),
            prev: 0.0,
            // Base voicing for the score-authored offsets; all inert until the
            // strip authors an amp NRPN (`apply_params` sets `active`).
            base: DriveBase {
                pre_hz,
                voice,
                g1,
                g2,
                post,
                cab1: peaks[1],
                cab2: peaks[2],
                cliff,
            },
            sr_os,
            g1_target: g1,
            g2_target: g2,
            post_target: post,
            // one-pole scalar slew at the shared 20 ms controller time constant
            // (base rate: process() steps once per base-rate sample)
            slew: 1.0 - (-(DRIVE_OVERSAMPLE as f32) / (WAH_SLEW_S * sr_os)).exp(),
            active: false,
        }
    }

    /// XG Amp Simulator (Variation) as a per-part insert: the same amp+cabinet
    /// DSP as `new`, with the two gain stages scaled by the XG Drive parameter
    /// (0..127). Voiced as an overdriven-guitar amp (the reference file targets
    /// the electric-guitar channel); the cabinet is the shared 5-biquad
    /// decimation filter — exactly ONE cabinet, since the insert REPLACES the
    /// program drive rather than stacking after it. `post` trims the hotter
    /// settings so the wet stage stays near unity for the apply-site dry/wet
    /// blend; Arthur's ear is the final tuning (oracles check direction).
    fn amp_sim(sr: f32, drive_0_127: u8) -> Self {
        let sr_os = sr * DRIVE_OVERSAMPLE as f32;
        let d = drive_0_127 as f32 / 127.0;
        // Quadratic drive curve: nearly clean at low settings, hot at full, so
        // the knob is expressive across its range (a linear map saturates the
        // first stage too early and Drive barely moves the tone). The file's
        // Drive 24 (d ~= 0.19) sits in gentle overdrive.
        let g1 = 1.0 + d * d * 16.0;
        let g2 = 1.5 + d * 1.5;
        let bias = 0.7;
        // more drive compresses harder, so trim output as gain rises to hold a
        // roughly constant wet level for the blend.
        let post = 0.28 / (1.0 + d * 1.5);
        let voice = (800.0, 0.8, 4.0);
        let tilt = Biquad::peak(1200.0, 0.8, 2.0, sr_os);
        // The XG insert is an amp simulator, not a bank voicing: full ripple,
        // and the shared rhythm cabinet (the lead cab belongs to the CC0 bank).
        Drive::from_stages(
            0,
            false,
            sr_os,
            90.0,
            voice,
            g1,
            bias,
            tilt,
            g2,
            post,
            cab_biquads(sr_os),
            cab_spec(),
        )
    }

    #[inline]
    fn chain(&mut self, x: f32) -> f32 {
        let v = self.voice.process(self.pre.process(x));
        // stage 1: biased tanh referenced to its bias point — the curvature
        // asymmetry (even harmonics) stays, but silence maps to exactly zero
        let s1 = (v * self.g1 + self.bias).tanh() - self.bias.tanh();
        // interstage tilt, then the gentler symmetric second stage
        let s2 = (self.tilt.process(s1) * self.g2).tanh();
        let mut y = self.dcb.process(s2);
        // voicing biquads, then the fine structure, then the lowpass cliff
        // LAST (it is the decimation filter — review I5/D6)
        for c in &mut self.cab[..CAB_CLIFF] {
            y = c.process(y);
        }
        y = self.micro.process(y);
        for c in &mut self.cab[CAB_CLIFF..] {
            y = c.process(y);
        }
        y
    }

    /// Run one base-rate sample through the `DRIVE_OVERSAMPLE`x shaper.
    ///
    /// The input is linearly upsampled from the previous sample; the intermediate
    /// steps are evaluated purely to keep the nonlinearity's state advancing at
    /// the internal rate, and only the sample-aligned output is kept. The
    /// cabinet's lowpass cliff (the last two `cab` biquads) is the decimation
    /// filter, so there is no separate downsampler.
    #[inline]
    fn step(&mut self, x: f32) -> f32 {
        let prev = self.prev;
        self.prev = x;
        for i in 1..DRIVE_OVERSAMPLE {
            let t = i as f32 / DRIVE_OVERSAMPLE as f32;
            let _ = self.chain(prev + (x - prev) * t);
        }
        self.chain(x) * self.post
    }

    /// Per-block denormal flush (MM-BUG-KILN-00027) for the insert's IIR stages.
    /// The insert runs on every block of a program-29/30 or XG amp channel,
    /// voices or not, so after the last note its biquads park and churn
    /// subnormals for the rest of the render; this is the strip-owned analogue
    /// of the bus flushes. The `MicroCab` is a feed-forward FIR: it drains to
    /// exact zero on its own once these stages do.
    fn flush(&mut self) {
        self.pre.flush();
        self.voice.flush();
        self.tilt.flush();
        self.dcb.flush();
        for c in &mut self.cab {
            c.flush();
        }
    }

    /// Test-only: visit every filter state and stored sample of the insert.
    #[cfg(test)]
    fn visit_state(&self, visit: &mut dyn FnMut(&'static str, f32)) {
        for bq in [&self.pre, &self.voice, &self.tilt, &self.dcb]
            .into_iter()
            .chain(&self.cab)
        {
            for x in bq.debug_state() {
                visit("drive biquad", x);
            }
        }
        for &x in &self.micro.buf {
            visit("drive micro-cab line", x);
        }
        visit("drive upsampler", self.prev);
    }

    fn process(&mut self, buf: &mut [f32]) {
        self.flush();
        if !self.active {
            // No amp NRPN authored on this channel: no slew, no branches — the
            // inertness invariant is that an unauthored channel takes exactly the
            // program-drive path.
            for x in buf.iter_mut() {
                *x = self.step(*x);
            }
            return;
        }
        // Authored: the scalar knobs (Drive -> g1/g2/post) slew PER SAMPLE
        // toward this block's target, so a swept Drive cannot staircase at the
        // block frequency. The filter knobs are retuned per block in
        // `apply_params` (the biquad's own state smooths the small steps).
        for x in buf.iter_mut() {
            self.g1 += self.slew * (self.g1_target - self.g1);
            self.g2 += self.slew * (self.g2_target - self.g2);
            self.post += self.slew * (self.post_target - self.post);
            *x = self.step(*x);
        }
    }

    /// Apply the strip's slewed amp-knob positions (`cur`, each 0..127 with
    /// 64 = neutral) as signed offsets from `self.base`, in place — no rebuild,
    /// no allocation. Called once per block for an authored channel, and once
    /// with `snap = true` right after a rebuild so the fresh insert starts at
    /// the authored rig instead of slewing up from its base voicing.
    fn apply_params(&mut self, cur: &[f32; AMP_PARAM_COUNT], snap: bool) {
        let sr_os = self.sr_os;
        let n = |i: usize| (cur[i] - AMP_NEUTRAL as f32) / AMP_NEUTRAL as f32; // in [-1, +0.984]

        // Drive (idx 0): gain, with a strictly-positive makeup trim on post.
        let nd = n(AMP_DRIVE);
        self.g1_target = self.base.g1 * 2f32.powf(AMP_DRIVE_K * nd);
        self.g2_target = self.base.g2 * 2f32.powf(0.5 * AMP_DRIVE_K * nd);
        self.post_target = self.base.post * 2f32.powf(-AMP_DRIVE_POST_C * nd);

        // Tone (idx 1): pre-clip voice EQ gain.
        let (vh, vq, vdb) = self.base.voice;
        self.voice
            .retune_peak(vh, vq, vdb + AMP_TONE_DB * n(AMP_TONE), sr_os);

        // Tightness (idx 2): pre-shaper high-pass corner, capped.
        let pre_hz =
            (self.base.pre_hz * 2f32.powf(AMP_TIGHT_OCT * n(AMP_TIGHT))).min(AMP_TIGHT_MAX_HZ);
        self.pre.retune_highpass(pre_hz, 0.7, sr_os);

        // Body (idx 3) and Presence (idx 4): cabinet peak gains.
        let (b1h, b1q, b1db) = self.base.cab1;
        self.cab[1].retune_peak(b1h, b1q, b1db + AMP_EQ_DB * n(AMP_BODY), sr_os);
        let (b2h, b2q, b2db) = self.base.cab2;
        self.cab[2].retune_peak(b2h, b2q, b2db + AMP_EQ_DB * n(AMP_PRES), sr_os);

        // Cab Tone (idx 5): the anti-alias cliff corner, DOWNWARD only, so it
        // can only ever strengthen alias rejection (never trade it for brightness).
        let f = 2f32.powf(AMP_CABTONE_OCT * n(AMP_CABTONE).min(0.0));
        self.cab[3].retune_lowpass(self.base.cliff[0].0 * f, self.base.cliff[0].1, sr_os);
        self.cab[4].retune_lowpass(self.base.cliff[1].0 * f, self.base.cliff[1].1, sr_os);

        // Snap the scalars to target on the first application (so a rig authored
        // at t=0 is in effect on the first sample) and after a rebuild; slew
        // otherwise.
        if snap || !self.active {
            self.g1 = self.g1_target;
            self.g2 = self.g2_target;
            self.post = self.post_target;
        }
        self.active = true;
    }

    /// Test-only: neutralise the pre-voicing EQ (oracle 5's gain-matched
    /// reference — a 0 dB peak is an identity biquad).
    #[cfg(test)]
    fn with_flat_voice(mut self) -> Self {
        self.voice = Biquad::peak(800.0, 0.8, 0.0, 88_200.0);
        self
    }
}

/// Per-program bus sends (chorus, echo). Reverb stays CC91-authored.
fn fx_profile(program: u8, bank: u8) -> (f32, f32) {
    match program {
        19 if bank == 2 => (0.0, 0.0), // cathedral organ (CC0=2): the case/room supplies width
        16..=23 => (0.20, 0.0),        // legacy organs/free reeds: gentle ensemble
        24 | 25 => (0.12, 0.08),       // acoustic guitars: a touch of both
        26..=31 => (0.10, 0.30),       // electric guitars: the delayed-lead sound
        42 | 43 => (0.0, 0.06), // solo cello/contrabass: dry & forward, no ensemble chorus to smear the single-voice identity, only a trace of slap
        40..=45 | 110 => (0.10, 0.10), // fiddle + other bowed strings (40 == 110 kept for the gm110 oracle)
        46 => (0.15, 0.0),             // harp
        48..=51 => (0.35, 0.0),        // string ensembles
        52..=54 => (0.30, 0.0),        // choir
        56..=60 => (0.0, 0.0),         // solo brass: hall (CC91) is the space, no ensemble fake
        61..=63 => (0.25, 0.0),        // brass section / synth brass: section-width chorus
        64..=67 => (0.06, 0.10),       // saxes: lead voice, a touch of width and slap echo
        109 => (0.06, 0.0),            // bagpipe: small width, no slap echo on the drone
        111 => (0.04, 0.08),           // shanai: dry forward reed with a trace of slap
        72..=79 => (0.0, 0.22),        // flute / whistle
        80..=87 => (0.15, 0.25),       // synth leads: focused, with the delayed-lead echo
        88..=95 => (0.45, 0.0),        // pads
        // Synth FX (Stage 3): split per preset. 98 (crystal) keeps its pre-split
        // values — part of the 7-album freeze. 102 (echoes) gets a LOW bus-echo
        // send: its repeats are INTERNAL to the voice, so a bus echo would double
        // them. The rest are gut-feel (chorus shimmer + a little bus echo).
        96 => (0.30, 0.20),  // rain: droplets are internal; light shimmer
        97 => (0.35, 0.25),  // soundtrack: wide swell
        98 => (0.30, 0.35),  // crystal: FROZEN — unchanged from the pre-split arm
        99 => (0.30, 0.25),  // atmosphere: wash
        100 => (0.30, 0.30), // brightness: shimmer as it blooms
        101 => (0.25, 0.30), // goblins: a touch less width, more echo scatter
        102 => (0.30, 0.05), // echoes: internal repeats — starve the bus echo
        103 => (0.20, 0.30), // sci-fi: focused zap, echoed
        // Mallets (2026.07.24): the old shared 0.15 was too much echo for a
        // BRIGHT, FAST line. The bus time is a dotted quaver, so on a metronomic
        // quaver ostinato every repeat lands 1.5 slots late — dead on the
        // off-beat, carrying the wrong pitch for its position, ping-ponged hard
        // L/R. That reads as a strange shimmer rather than as space. Heard on
        // the Tubular Bells glockenspiel entry (200 ms quavers at 150 bpm vs a
        // 300 ms echo), where GM 9 is also the ONLY echoed voice in the opening.
        // Celesta/music box are sprinkled, not run, so they keep a trace.
        8 | 10 => (0.0, 0.06), // celesta / music box: a trace of slap
        9 => (0.0, 0.0),       // glockenspiel: brightest and fastest — no bus echo
        14 => (0.0, 0.08),     // tubular bells
        15 => (0.10, 0.0),     // hammered dulcimer: sub-beat width, no echo
        _ => (0.0, 0.0),
    }
}

/// SC-55-referenced per-program loudness trim (dB), applied at the melodic
/// channel strip. `0.0` = untouched.
///
/// ferrosintesis has no per-instrument loudness normalisation — each voice
/// carries its own hand-tuned gain, and only the whole *mix* is normalised to
/// −18 LUFS. That leaves the raw instrument-to-instrument balance uneven (e.g.
/// solo strings/brass and flutes run hot; string sections and choir run quiet).
/// This table nudges the sustained families toward the balance a Roland
/// SC-55mkII produces for the same GM programs, measured at equal note/velocity
/// (see `wrk_docs/2026.07.17 - CR - instrument level audit + SC-55 trim.md`).
///
/// It is deliberately CONSERVATIVE: sustained voices only (whole-note RMS is a
/// fair loudness proxy there), 0.70× the measured delta, clamped to ±6 dB, with
/// a 1 dB dead-band. Struck/plucked/percussive voices (piano, guitar, mallets,
/// drums) and noise/FX are left at 0.0 — their apparent "deficit" is usually a
/// faster decay envelope, not a level error, so trimming them would misfire.
/// That 0.0 is a MEASURED VERDICT, not a pending TODO. This comment used to
/// promise that an M-CAL v2 pass "will calibrate the percussive families". That
/// pass was built and run (2026.07.22), and it returned the opposite answer: 37
/// programs failed its shape/short guards, concentrated in exactly those families
/// (Guitar 8/8, Percussive 6, Bass 5, Ethnic 5), because ferrosintesis's plucked
/// decays are 2–4× faster than the SC-55's and no scalar reconciles a gap that
/// grows ~30 dB over 900 ms. The verdict was "this is voice work, not trim work",
/// and the per-family voice fixes are tracked in the bug ledger (MM-BUG-KILN-00045
/// bass, 00043 GM7 clavinet, 00039 GM107 koto) rather than here. Reaching for the
/// trim table again on these families is measuring a decay envelope, not a level.
/// See `wrk_docs/2026.07.22 - M-CAL v3 certified derivation report.md`; the
/// superseded plan is `2026.07.21 - HLD - M-CAL v2 envelope-guarded metric.md`.
/// (The earlier 21-Jul max-momentary derivation was rejected for the same reason:
/// it is a temporal-envelope artifact for short voices, not a level reading.)
///
/// GM6 harpsichord is the ONE documented plucked exception (+6 dB): the audit
/// used the fair EARLY-window RMS (0–150 ms, immune to the decay-artifact trap)
/// and still measured it ~10 dB under the SC-55 balance against the piano anchor;
/// its too-fast decay is fixed independently in the `HARPSICHORD` preset, so the
/// "deficit is only a decay artifact" objection does not apply here. The trim is
/// the right lever because it lifts the sampled quill onset and the modeled body
/// UNIFORMLY post-wrap (raising the model `amp` alone would shift the attack/
/// sustain balance). See the 2026.07.18 holds audit.
///
/// Timbre-neutral: it scales the dry voice and all its FX sends together (the
/// strip gain `g` feeds both), preserving each channel's wet/dry ratio.
///
/// **GM5 +1, GM8 +2, GM14 -6, GM110 -5, GM119 +1 are M-CAL v3 PANEL entries**
/// (2026.07.22). A single reference cannot tell you whether IT or ferro is the
/// outlier, so these are gated on TWO independent references agreeing with each
/// other — the Roland SC-55mkII and the Yamaha S-YXG50 (different vendor, era and
/// synthesis, so their patch quirks are uncorrelated). Each of these five agreed
/// within 0.3–2.9 dB. Programs where the references disagree are deliberately NOT
/// trimmed and go to a listening decision: GM11 vibraphone, for instance, splits
/// 10.8 dB (SC-55 wants +6, S-YXG50 wants -2), and single-reference evidence would
/// have shipped a 6 dB boost the panel does not support. The run is certified — the
/// master bus compressor is proven inert over the probe, so the differential is
/// linear where it was measured. See
/// `wrk_docs/2026.07.22 - M-CAL v3 certified derivation report.md`.
///
/// Arthur's 2026.07.29 direct left/right audition found GM48 slightly quieter
/// than both references, so its +5.5 dB trim moved to the existing +6 dB ceiling.
/// GM50/51 stayed put because their differences were small or tonal. GM56/57
/// stayed put because only their loud-note sustains ran hotter; a global scalar
/// would make their already-matched quiet notes wrong. GM67 stayed put pending
/// MM-BUG-KILN-00176 because its sampled-sustain artifacts contaminate the level
/// comparison.
#[rustfmt::skip] // keep the 8-per-row GM grid aligned for readability
pub(crate) const PROGRAM_TRIM_DB: [f32; 128] = [
     0.0,  0.0,  0.0,  0.0,  0.0,  1.0,  6.0,  0.0, //   0-7   Piano (5 +1, 6 harpsichord +6dB)
     3.0,  0.0,  0.0,  0.0,  0.0,  0.0, -6.0,  0.0, //   8-15  ChromPerc (8 celesta +3, 14 bells -6)
    -4.5, -3.0, -1.5, -6.0, -3.0, -5.0, -1.0, -4.5, //  16-23  Organ
     0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0, //  24-31  Guitar     (untouched)
     0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0, //  32-39  Bass       (untouched)
    -4.0, -4.0, -3.5, -6.0, -4.0,  0.0,  0.0,  0.0, //  40-47  Strings (bowed; pizz/harp/timpani=0)
     6.0,  1.5,  6.0,  5.0,  2.5,  6.0,  5.0,  0.0, //  48-55  Ensemble (sections/choir; orch-hit=0)
    -6.0, -6.0, -6.0, -2.0, -3.0, -2.0,  0.0,  5.0, //  56-63  Brass
     0.0, -2.5, -3.0, -3.0,  2.0,  1.5,  0.0,  0.0, //  64-71  Reed
    -4.0, -4.0, -2.0, -5.0, -6.0, -6.0,  0.0,  0.0, //  72-79  Pipe
    -4.0,  0.0,  0.0,  0.0, -2.0,  5.5,  1.0,  1.0, //  80-87  SynthLead
     4.0,  0.0,  2.0,  5.0,  3.0, -5.0,  0.0,  0.0, //  88-95  SynthPad
     0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0, //  96-103 SynthFX    (untouched)
     0.0,  0.0,  0.0,  0.0,  0.0,  0.0, -6.0,  0.0, // 104-111 Ethnic     (110 fiddle -6)
     0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  1.0, // 112-119 Percussive (119 rev-cymbal +1)
     0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0, // 120-127 SoundFX    (untouched)
];

/// Linear gain for the SC-55-referenced per-program loudness trim (see
/// `PROGRAM_TRIM_DB`). Returns exactly `1.0` for untouched programs.
#[inline]
pub(crate) fn program_trim_lin(program: u8) -> f32 {
    let db = PROGRAM_TRIM_DB[program as usize];
    if db == 0.0 {
        1.0
    } else {
        10f32.powf(db / 20.0)
    }
}

/// Stereo chorus bus: one modulated delay line, quadrature taps L/R.
struct Chorus {
    dl: DelayLine,
    phase: f32,
    rate: f32,
    base: f32,
    depth: f32,
    sr: f32,
}

impl Chorus {
    fn new(sr: f32) -> Self {
        Chorus {
            dl: DelayLine::new((0.040 * sr) as usize),
            phase: 0.0,
            rate: 0.35,
            base: 0.018 * sr,
            depth: 0.005 * sr,
            sr,
        }
    }

    fn process(&mut self, send: &[f32], l: &mut [f32], r: &mut [f32]) {
        for i in 0..send.len() {
            self.dl.push(send[i]);
            self.phase += TAU * self.rate / self.sr;
            if self.phase > TAU {
                self.phase -= TAU;
            }
            let tl = self.dl.tap(self.base + self.depth * self.phase.sin());
            let tr = self
                .dl
                .tap(self.base + self.depth * (self.phase + FRAC_PI_2).sin());
            l[i] += tl * 0.55;
            r[i] += tr * 0.55;
        }
    }

    /// Re-tune the LFO in place (the XG Chorus Type mapping). `base_s + depth_s`
    /// must fit inside the 40 ms delay line so the modulated tap never reads
    /// past the buffer (asserted). Rate is the LFO frequency in Hz. Delay-line
    /// length and phase are unchanged, so reconfiguring to the current values is
    /// an exact no-op.
    fn reconfigure(&mut self, rate_hz: f32, base_s: f32, depth_s: f32) {
        assert!(
            base_s + depth_s <= 0.040,
            "chorus sweep {base_s}+{depth_s}s exceeds the 40 ms line"
        );
        self.rate = rate_hz;
        self.base = base_s * self.sr;
        self.depth = depth_s * self.sr;
    }
}

/// Ping-pong echo bus: repeats alternate sides, darkening as they fade.
struct PingPong {
    left: DelayLine,
    right: DelayLine,
    time: f32,
    feedback: f32,
    lp_l: OnePole,
    lp_r: OnePole,
}

impl PingPong {
    fn new(sr: f32, time_s: f32) -> Self {
        let samples = (time_s * sr).max(64.0);
        PingPong {
            left: DelayLine::new(samples as usize + 4),
            right: DelayLine::new(samples as usize + 4),
            time: samples,
            feedback: 0.34,
            lp_l: OnePole::lowpass(3200.0, sr),
            lp_r: OnePole::lowpass(3200.0, sr),
        }
    }

    fn process(&mut self, send: &[f32], l: &mut [f32], r: &mut [f32]) {
        // Per-block denormal flush (MM-BUG-KILN-00027).
        self.lp_l.flush();
        self.lp_r.flush();
        for i in 0..send.len() {
            let out_l = self.left.tap(self.time);
            let out_r = self.right.tap(self.time);
            self.left.push(crate::dsp::flush_denormal(
                send[i] + self.lp_r.process(out_r) * self.feedback,
            ));
            self.right.push(crate::dsp::flush_denormal(
                self.lp_l.process(out_l) * self.feedback,
            ));
            l[i] += out_l * 0.8;
            r[i] += out_r * 0.8;
        }
    }
}

/// Sympathetic resonance: lightly-damped comb resonators fed by a send and
/// returned quietly. Parameterized (G5/V4): the piano instance rings one
/// comb per pitch class C3..B3; the guitar instance rings the six open
/// strings of acoustic guitars (prog 24|25 only).
struct Sympathetic {
    combs: Vec<(DelayLine, f32, OnePole)>,
    hp: Biquad,
    feedback: f32,
    input: f32,
    ret: f32,
}

impl Sympathetic {
    fn new(
        sr: f32,
        freqs: &[f32],
        damp_hz: f32,
        feedback: f32,
        hp_hz: f32,
        input: f32,
        ret: f32,
    ) -> Self {
        let combs = freqs
            .iter()
            .map(|&f| {
                let d = sr / f;
                (
                    DelayLine::new(d as usize + 4),
                    d,
                    OnePole::lowpass(damp_hz, sr),
                )
            })
            .collect();
        Sympathetic {
            combs,
            hp: Biquad::highpass(hp_hz, 0.7, sr),
            feedback,
            input,
            ret,
        }
    }

    /// The piano's undamped strings (the original v0.5 instance).
    fn piano(sr: f32) -> Self {
        let freqs: Vec<f32> = (0..12)
            .map(|k| 130.81 * 2f32.powf(k as f32 / 12.0))
            .collect();
        Self::new(sr, &freqs, 2600.0, 0.85, 170.0, 0.05, 0.55)
    }

    /// The acoustic guitar's open strings E2 A2 D3 G3 B3 E4 (GTR-3/KS-6).
    fn guitar(sr: f32) -> Self {
        Self::new(
            sr,
            &[82.41, 110.0, 146.83, 196.0, 246.94, 329.63],
            3400.0,
            0.85,
            120.0,
            0.03,
            0.30,
        )
    }

    /// The sitar's tarab strings (GM 104, v0.16): thirteen sympathetic
    /// strings under the frets. Tuned chromatically C4..C5 — the same
    /// raga-agnostic trick as the piano instance — with a brighter damper
    /// and a higher feedback than the guitar bus, so the halo shimmers and
    /// briefly outlasts the plucked string (per-trip 0.955 keeps every comb
    /// a strict contraction).
    fn sitar(sr: f32) -> Self {
        let freqs: Vec<f32> = (0..13)
            .map(|k| 261.63 * 2f32.powf(k as f32 / 12.0))
            .collect();
        let damp_hz = 5200.0;
        let mut s = Self::new(sr, &freqs, damp_hz, 0.955, 200.0, 0.035, 0.35);
        // At feedback 0.955 each comb's resonance is only a few Hz wide, so
        // the in-loop damper's phase delay (plus the write→read sample)
        // detunes the peak right off the played pitch — compensate the
        // delay exactly as KsLoop::delay_for does. The wider piano/guitar
        // instances (fb 0.85) stay untouched and bit-identical.
        let a = 1.0 - (-2.0 * std::f32::consts::PI * (damp_hz / sr).min(0.49)).exp();
        let b = 1.0 - a;
        for ((_, d, _), &f) in s.combs.iter_mut().zip(freqs.iter()) {
            let w = 2.0 * std::f32::consts::PI * f / sr;
            let d1p = ((b * w.sin()) / (1.0 - b * w.cos())).atan() / w;
            *d = (sr / f - d1p - 1.0).max(2.0);
        }
        s
    }

    fn process(&mut self, send: &[f32], l: &mut [f32], r: &mut [f32]) {
        // Per-block denormal flush (MM-BUG-KILN-00027): the damp one-poles and
        // the input HP otherwise park below the floor when the send goes quiet.
        self.hp.flush();
        for (_, _, damp) in &mut self.combs {
            damp.flush();
        }
        for i in 0..send.len() {
            let x = self.hp.process(send[i]) * self.input;
            let mut sum = 0.0;
            for (dl, d, damp) in &mut self.combs {
                // Per-sample tap flush. Routed through `dsp::flush_denormal` so the
                // floor lives in ONE place: this site used to hard-code `1e-20`, the
                // value that function's doc comment argues at length is wrong, and it
                // survived the MM-BUG-KILN-00027 fix that corrected the per-block
                // flushes eight lines above (MM-BUG-KILN-00100).
                let y = crate::dsp::flush_denormal(dl.tap(*d));
                dl.push(x + damp.process(y) * self.feedback);
                sum += y;
            }
            let w = sum * self.ret;
            l[i] += w;
            r[i] += w;
        }
    }
}

/// Master-bus glue: a slow 2:1 compressor (a dB or two of gentle movement)
/// and a whisper of saturation, so the mix couples like a record instead of
/// arithmetic.
struct BusGlue {
    env: f32,
    gain: f32,
    atk: f32,
    rel: f32,
    thr: f32,
    shelf_l: Biquad,
    shelf_r: Biquad,
}

impl BusGlue {
    fn new(sr: f32) -> Self {
        BusGlue {
            env: 0.0,
            gain: 1.0,
            atk: 1.0 - (-1.0 / (0.015 * sr)).exp(),
            rel: 1.0 - (-1.0 / (0.250 * sr)).exp(),
            thr: 0.32,
            shelf_l: Biquad::peak(95.0, 0.7, 1.5, sr),
            shelf_r: Biquad::peak(95.0, 0.7, 1.5, sr),
        }
    }

    fn process(&mut self, l: &mut [f32], r: &mut [f32]) {
        // Per-block denormal flush (MM-BUG-KILN-00027).
        self.shelf_l.flush();
        self.shelf_r.flush();
        for i in 0..l.len() {
            let xl = self.shelf_l.process(l[i]);
            let xr = self.shelf_r.process(r[i]);
            let level = xl.abs().max(xr.abs());
            let k = if level > self.env { self.atk } else { self.rel };
            self.env = crate::dsp::flush_denormal(self.env + k * (level - self.env));
            let target = if self.env > self.thr {
                (self.thr / self.env).sqrt() // 2:1 above threshold
            } else {
                1.0
            };
            let kg = if target < self.gain {
                self.atk
            } else {
                self.rel
            };
            self.gain += kg * (target - self.gain);
            // gentle tape-ish saturation on the glued signal
            let gl = xl * self.gain;
            let gr = xr * self.gain;
            l[i] = gl + 0.12 * ((gl * 1.4).tanh() / 1.4 - gl);
            r[i] = gr + 0.12 * ((gr * 1.4).tanh() / 1.4 - gr);
        }
    }
}

struct Strip {
    program: u8,
    kit: drums::Kit,    // channel-10 kit version; V3 by default
    alt_bank: bool,     // CC0 != 0 selects the alt orchestral voicings (altbank::make)
    alt_bank_value: u8, // raw CC0 value: 0 default, 1 legacy alt, 2 GM19 cathedral organ
    xg_drum: bool,      // CC0 == 127: XG drum-kit bank — route this channel to the drum path
    gs_drum: bool,      // GS "Use for Rhythm Part" SysEx — same routing, separate origin
    // (a GS rhythm part still sends CC0=0, so it cannot share xg_drum)
    volume: f32, // CC7 as amplitude (squared curve); slewed current value
    pan: f32,    // 0..1; slewed current value
    // CC7 volume / CC10 pan controller slew (prime-on-first-block). The handler
    // sets only `*_target` + `*_authored`; the per-block mix loop snaps the current
    // value to the target on the first block after authoring (reproducing MIDI
    // last-write-wins for a same-tick burst), then one-pole slews toward the target
    // thereafter — so a foreign GM fade or pan sweep ramps instead of stepping at
    // block boundaries. A channel that never authors CC7/CC10 keeps its default.
    volume_target: f32,
    volume_authored: bool,
    volume_primed: bool,
    pan_target: f32,
    pan_authored: bool,
    pan_primed: bool,
    bend: f32,     // channel pitch multiplier: wheel × range × fine-tune
    legato: bool,  // CC68: new notes slur into the ringing voice
    sustain: bool, // CC64: NoteOffs are held until the pedal lifts
    // v0.7 authored controllers (all inert until first touched)
    bend_wheel: f32, // last wheel position in ±2-normalised semitones
    bend_range: f32, // RPN 0: bend range in semitones (GM default 2)
    fine: f32,       // RPN 1: fine tune as a frequency multiplier
    rpn_msb: u8,     // CC101/CC100 select; 127/127 = null
    rpn_lsb: u8,
    data_msb: u8, // last CC6 under the RPN latch, so CC38 can refine it
    // NRPN latch (CC99/CC98 select; 127/127 = null), mutually exclusive with
    // the RPN latch — the most recent select wins and nulls the other, so a
    // Data Entry can never write into a stale selector (MM-BUG-KILN-00034).
    // `nrpn_data_msb` is the NRPN-domain CC6, kept separate from `data_msb` so
    // an amp Data Entry cannot leak into the RPN bend range.
    nrpn_msb: u8,
    nrpn_lsb: u8,
    nrpn_data_msb: u8,
    porta_on: bool,
    porta_time: f32,        // CC5 glide time in seconds
    last_freq: Option<f32>, // most recent NoteOn pitch (portamento origin)
    // CC32 bank-select LSB: selects an XG variation voice via make_variation.
    // Persists across Reset All Controllers (bank select is not a RAC controller).
    bank_lsb: u8,
    // CC84 portamento control: a pending one-shot glide source key, consumed by
    // the next NoteOn (glides regardless of CC65 porta-on). Cleared by RAC.
    porta_control: Option<u8>,
    bagpipe_drone_holds: u8, // low GM109 notes currently holding the synthetic drone
    bagpipe_drone_live: bool, // a channel drone is sounding — gates the latch tick
    bagpipe_drone_hang: u32, // blocks of chanter silence so far (drone release countdown)
    soft: bool,              // CC67 una corda
    sost_down: bool,         // CC66 sostenuto pedal position
    vowel_authored: bool,    // CC70 selects a static vowel on choir programs
    vowel_target: f32,       // CC70 value 0..127
    vowel_cur: f32,          // slewed per block
    at_authored: bool,       // channel aftertouch seen on this channel
    at_target: f32,          // pressure 0..1, smoothed like CC11
    at_cur: f32,
    at_phase: f32, // aftertouch vibrato LFO phase
    at_gain: f32,  // pressure gain lift (1.0 = none)
    vib_mult: f32, // this block's CC1 vibrato factor, for composition
    res: f32,      // CC71 resonance: current filter Q, slewed
    res_target: f32,
    expr_target: f32,
    expr: f32,
    // CC11 has been authored at least once (opt-in / authored-channel
    // invariant: `expr` defaults to 1.0).
    expr_authored: bool,
    // CC2 breath: a second expression lane (squared, smoothed like CC11)
    // aimed at sustained-excitation voices. NEUTRAL (1.0) until first
    // authored — deliberately NOT the GM power-on default of 0, which would
    // silence every channel that never sends CC2 (authored-channel invariant).
    breath_authored: bool,
    breath_target: f32,
    breath: f32,
    mod_target: f32, // CC1, smoothed into mod_cur like expression
    mod_cur: f32,
    mod_engaged: bool,  // mod machinery active (stays on through spin-down)
    mod_authored: bool, // CC1 has been sent at least once on this channel
    vib_phase: f32,
    leslie_rate: f32, // current tremulant rate/depth, slewed with inertia
    leslie_depth: f32,
    reverb_send: f32,
    reverb_authored: bool,
    chorus_send: f32,
    chorus_authored: bool,
    delay_send: f32,
    delay_authored: bool,
    organ_wind: f32,
    organ_trem_phase: f32,
    drive: Option<Drive>,
    // Score-authored amp parameters (MM-REQ-KILN-00028): six per-channel knobs
    // offset from the program voicing, 64 = as-shipped. `amp_authored` gates the
    // whole path — false keeps the driven render bit-identical. `amp_cur` slews
    // toward `amp_params` at block rate; `amp_primed` snaps each knob on its
    // first authoring so a t=0 rig is in effect immediately. All PERSIST across
    // Program Change / CC0 / CC121 (they are channel state, not program state);
    // only GM System On clears them (via Strip::new).
    amp_params: [u8; AMP_PARAM_COUNT],
    amp_cur: [f32; AMP_PARAM_COUNT],
    amp_primed: [bool; AMP_PARAM_COUNT],
    amp_authored: bool,
    // XG Variation Amp-Simulator insertion: an amp/cab insert that REPLACES the
    // program `drive` on this channel, paired with its dry/wet weight (0..1).
    // Set ONLY by XG effect SysEx (`resolve_variation`); program_change /
    // needs_drive / rederive_program_defaults never touch it — so an album,
    // which sends no SysEx, never installs one and stays byte-identical.
    xg_insert: Option<(Drive, f32)>,
    wah: Option<Biquad>, // CC74 brightness filter; None = true bypass
    wah_legacy: Option<Biquad>,
    wah_cathedral: Option<Biquad>,
    // second wah instance for channel 9's stereo drum pair (D9 strip
    // parity: an authored ch-9 CC74/71 keeps filtering the whole kit)
    wah_r: Option<Biquad>,
    cutoff: f32, // current wah cutoff Hz, slewed toward cutoff_target
    cutoff_target: f32,
    haas: DelayLine,
    haas_delay: f32, // samples of far-side delay; 0 disables
}

impl Strip {
    /// Drum-room send for this channel. An unauthored CC91 takes the exact
    /// historical constant; once authored, CC91 owns the full dry-to-room
    /// range just as it owns the shared-hall send.
    #[inline]
    fn drum_room_send(&self) -> f32 {
        if self.reverb_authored {
            ROOM_SEND * self.reverb_send
        } else {
            ROOM_SEND
        }
    }

    /// Snap any not-yet-primed amp knob to its authored value. Called right
    /// before a `Drive` rebuild re-applies the rig, so a rebuild that fires
    /// AFTER the channel authored a knob but BEFORE its first audio block starts
    /// the rig at the authored value rather than ramping up from neutral (the
    /// per-block priming would otherwise not have run yet).
    fn amp_prime_all(&mut self) {
        for i in 0..AMP_PARAM_COUNT {
            if !self.amp_primed[i] {
                self.amp_cur[i] = self.amp_params[i] as f32;
                self.amp_primed[i] = true;
            }
        }
    }

    fn new(sr: f32) -> Self {
        Strip {
            program: 0,
            kit: drums::Kit::V3,
            alt_bank: false,
            alt_bank_value: 0,
            xg_drum: false,
            gs_drum: false,
            volume: (100.0f32 / 127.0).powi(2),
            pan: 0.5,
            // Targets equal the current defaults, so the slew is a bit-exact no-op
            // until the first CC7/CC10 is authored (D6: the SAME expression, not a
            // rounded literal).
            volume_target: (100.0f32 / 127.0).powi(2),
            volume_authored: false,
            volume_primed: false,
            pan_target: 0.5,
            pan_authored: false,
            pan_primed: false,
            bend: 1.0,
            legato: false,
            sustain: false,
            bend_wheel: 0.0,
            bend_range: 2.0,
            fine: 1.0,
            rpn_msb: 127,
            rpn_lsb: 127,
            data_msb: 0,
            nrpn_msb: 127,
            nrpn_lsb: 127,
            nrpn_data_msb: 0,
            porta_on: false,
            porta_time: PORTA_MIN_S,
            last_freq: None,
            bank_lsb: 0,
            porta_control: None,
            bagpipe_drone_holds: 0,
            bagpipe_drone_live: false,
            bagpipe_drone_hang: 0,
            soft: false,
            sost_down: false,
            vowel_authored: false,
            vowel_target: 0.0,
            vowel_cur: 0.0,
            at_authored: false,
            at_target: 0.0,
            at_cur: 0.0,
            at_phase: 0.0,
            at_gain: 1.0,
            vib_mult: 1.0,
            res: WAH_Q,
            res_target: WAH_Q,
            expr_target: 1.0,
            expr: 1.0,
            expr_authored: false,
            breath_authored: false,
            breath_target: 1.0,
            breath: 1.0,
            mod_target: 0.0,
            mod_cur: 0.0,
            mod_engaged: false,
            mod_authored: false,
            vib_phase: 0.0,
            leslie_rate: 0.0,
            leslie_depth: 0.0,
            reverb_send: 0.3,
            reverb_authored: false,
            chorus_send: 0.0,
            chorus_authored: false,
            delay_send: 0.0,
            delay_authored: false,
            organ_wind: 0.0,
            organ_trem_phase: 0.0,
            drive: None,
            amp_params: [AMP_NEUTRAL; AMP_PARAM_COUNT],
            amp_cur: [AMP_NEUTRAL as f32; AMP_PARAM_COUNT],
            amp_primed: [false; AMP_PARAM_COUNT],
            amp_authored: false,
            xg_insert: None,
            wah: None,
            wah_legacy: None,
            wah_cathedral: None,
            wah_r: None,
            cutoff: WAH_MAX_HZ,
            cutoff_target: WAH_MAX_HZ,
            haas: DelayLine::new((0.006 * sr) as usize + 4),
            haas_delay: 0.0,
        }
    }
}

/// Lowest supported output sample rate, in Hz.
pub(crate) const MIN_SAMPLE_RATE: u32 = 8_000;
/// Highest supported output sample rate, in Hz — above every rate real hardware offers.
pub(crate) const MAX_SAMPLE_RATE: u32 = 384_000;
/// Longest supported reverb tail, in seconds.
pub(crate) const MAX_TAIL_S: f32 = 3_600.0;
/// Longest supported echo time, in seconds. The echo bus sizes two power-of-two delay
/// lines from this, so it is the knob that turns a typo into a multi-GiB allocation.
pub(crate) const MAX_ECHO_S: f32 = 10.0;
/// Highest supported realtime master gain.
pub(crate) const MAX_MASTER_GAIN: f32 = 8.0;

/// Bring one render knob into its supported range before anything sizes a buffer
/// from it (MM-BUG-CRUCIBLE-00026).
///
/// Finite values clamp; non-finite ones fall back to `fallback`, because there is no
/// sensible clamp for NaN and `f32::clamp` propagates it. Clamping rather than
/// rejecting is what keeps this non-breaking: `Options` and `RealtimeOptions` are
/// sealed, so the builders are the ONLY way a value reaches the DSP, and
/// `offline::render` and `RealtimeSynth::new` are both infallible — turning them
/// fallible would break every caller. The accessors report the clamped value, so a
/// caller that cares can see what it actually got.
///
/// In-range values pass through untouched, so no render this repo produces moves a
/// bit: the catalog's own echo is already clamped to 0.20-0.62 s upstream, and every
/// other value in the workspace sits far inside these bounds.
pub(crate) fn sanitize_knob(value: f32, lo: f32, hi: f32, fallback: f32) -> f32 {
    if value.is_finite() {
        value.clamp(lo, hi)
    } else {
        fallback
    }
}

/// Bring a requested sample rate into the supported range.
pub(crate) fn sanitize_sample_rate(rate: u32) -> u32 {
    rate.clamp(MIN_SAMPLE_RATE, MAX_SAMPLE_RATE)
}

/// How to render a [`Song`](crate::offline::Song).
///
/// Start from [`Options::default`] and refine with the `with_*` builders. The fields
/// are private on purpose: that is what lets a future minor release add a render knob,
/// or rename one, without breaking your code. Read them back with the accessors.
///
/// # Supported ranges
///
/// Every builder clamps its argument into the range its own documentation states, and
/// a non-finite argument falls back to the default. Sizing a DSP buffer from an
/// unchecked value is how a single typed call used to abort in the allocator —
/// `with_echo(100_000.0)` asked for about 64 GiB of delay line
/// (MM-BUG-CRUCIBLE-00026). Read a value back with its accessor to see what was kept.
///
/// ```
/// use ferrosintesis::offline::Options;
///
/// let opt = Options::default()
///     .with_sample_rate(48_000)
///     .with_echo(0.0); // no echo bus
///
/// assert_eq!(opt.sample_rate(), 48_000);
/// assert_eq!(opt.echo(), 0.0);
/// ```
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Options {
    /// Output sample rate, held as `f32` because that is what every DSP site wants:
    /// `sr` appears in ~130 voice/filter/envelope constructors and is divided into
    /// coefficients on the render path. The PUBLIC type is `u32` (see
    /// [`Options::with_sample_rate`] and [`Options::sample_rate`]) — sample rates are
    /// integers, and `write_wav` and `RealtimeOptions` have always taken `u32`.
    ///
    /// Do NOT "finish the job" by making this field `u32` and converting at each use:
    /// the conversion points are the render path, and moving them changes the order of
    /// float operations. Renders are byte-identical only while this stays `f32`.
    pub(crate) sr: f32,
    pub(crate) wet: f32,
    pub(crate) tail: f32,
    pub(crate) delay_s: f32,
    pub(crate) samples: bool,
    pub(crate) solo: u16,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            sr: 44_100.0,
            wet: 0.32,
            tail: 6.0,
            delay_s: 0.375,
            samples: true,
            solo: 0xFFFF,
        }
    }
}

impl Options {
    /// Set the output sample rate in Hz. Default 44100, clamped to 8000..=384000.
    pub fn with_sample_rate(mut self, sr: u32) -> Self {
        self.sr = sanitize_sample_rate(sr) as f32;
        self
    }

    /// Set the reverb send, 0.0 (dry) to 1.0. Default 0.32. Clamped to that range;
    /// a non-finite value falls back to the default.
    pub fn with_reverb(mut self, wet: f32) -> Self {
        self.wet = sanitize_knob(wet, 0.0, 1.0, Self::default().wet);
        self
    }

    /// Set how many seconds of reverb tail are rendered past the last note-off.
    /// Default 6.0, clamped to 0.0..=3600.0; a non-finite value falls back to the
    /// default.
    pub fn with_tail(mut self, tail: f32) -> Self {
        self.tail = sanitize_knob(tail, 0.0, MAX_TAIL_S, Self::default().tail);
        self
    }

    /// Enable or disable the embedded PCM attack-sample layer. Default true. Has no
    /// effect when the crate is built without the `embedded-samples` feature.
    pub fn with_samples(mut self, samples: bool) -> Self {
        self.samples = samples;
        self
    }

    /// Set the echo time in seconds. Pass 0.0 to disable the echo bus. Default 0.375,
    /// clamped to 0.0..=10.0; a non-finite value falls back to the default. The echo
    /// bus sizes two power-of-two delay lines from this, so the clamp is what stops a
    /// mistyped value asking the allocator for tens of GiB.
    pub fn with_echo(mut self, delay_s: f32) -> Self {
        self.delay_s = sanitize_knob(delay_s, 0.0, MAX_ECHO_S, Self::default().delay_s);
        self
    }

    /// Set the channel bitmask: bit *n* enables MIDI channel *n*. Notes on masked-out
    /// channels are dropped, which is how you render a single-instrument stem. The
    /// tempo map is unaffected, so a stem lines up with the full mix. Default `0xFFFF`.
    pub fn with_solo(mut self, solo: u16) -> Self {
        self.solo = solo;
        self
    }

    /// The output sample rate in Hz.
    pub fn sample_rate(&self) -> u32 {
        self.sr as u32
    }

    /// The reverb send, 0.0 (dry) to 1.0.
    pub fn reverb(&self) -> f32 {
        self.wet
    }

    /// Seconds of reverb tail rendered past the last note-off.
    pub fn tail(&self) -> f32 {
        self.tail
    }

    /// The echo time in seconds; 0.0 means the echo bus is disabled.
    pub fn echo(&self) -> f32 {
        self.delay_s
    }

    /// Whether the embedded PCM attack-sample layer is enabled. Always renders as
    /// disabled when the crate is built without the `embedded-samples` feature.
    pub fn samples(&self) -> bool {
        self.samples
    }

    /// The channel bitmask: bit *n* enables MIDI channel *n*.
    pub fn solo(&self) -> u16 {
        self.solo
    }
}

/// What a render cost, returned alongside the audio.
///
/// `#[non_exhaustive]`: new counters may be added in a minor release.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Stats {
    /// Total voices allocated over the whole render.
    pub voices_spawned: u64,
    /// Largest absolute sample value in the returned buffer, before any normalization.
    pub peak: f32,
    /// The most voices alive at once.
    pub max_polyphony: usize,
    #[cfg(test)]
    pub(crate) cathedral_return_peak: f32,
}

impl Default for Stats {
    fn default() -> Self {
        Self {
            voices_spawned: 0,
            peak: 0.0,
            max_polyphony: 0,
            #[cfg(test)]
            cathedral_return_peak: 0.0,
        }
    }
}

/// A progress report, passed to the callback given to
/// [`render_with_progress`](crate::offline::render_with_progress).
///
/// `#[non_exhaustive]`: new fields may be added in a minor release.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Progress {
    /// Seconds of audio rendered so far.
    pub rendered_seconds: f64,
    /// Total seconds this render will produce, including the reverb tail.
    pub total_seconds: f64,
    /// Voices alive at this instant.
    pub active_voices: usize,
}

impl Progress {
    /// Fraction of the render completed, in `0.0..=1.0`.
    pub fn fraction(&self) -> f64 {
        if self.total_seconds <= 0.0 {
            return 1.0;
        }
        (self.rendered_seconds / self.total_seconds).clamp(0.0, 1.0)
    }
}

struct Active {
    ch: u8,
    key: u8,
    program: u8,     // spawn-time program: program changes affect future notes
    held: bool,      // NoteOff arrived while the sustain pedal was down
    sost: bool,      // CC66: was ringing when the sostenuto pedal went down
    sost_held: bool, // NoteOff deferred by the sostenuto pedal
    // CC5/CC65 portamento: (semitone offset from the target, per-block slew)
    glide: Option<(f32, f32)>,
    alt: bool, // spawn-time bank: this voice is an alt-bank voicing (per-voice CC1 routing)
    alt_bank_value: u8, // spawn-time raw CC0 value (2 = GM19 cathedral organ routing)
    // spawn-time CC32 bank LSB: which VARIATION voice this is (25+96 is the mandolin,
    // 25+0 the steel guitar). Frozen at spawn like `alt`, and part of the routing
    // identity the tremolo-restrike path matches on (MM-BUG-KILN-00087).
    bank_lsb: u8,
    // spawn-time routing: this voice goes to the drum path (ch9, or an XG-drum
    // channel that had CC0==127). Frozen at spawn like `alt`, so a mid-note CC0
    // change only affects later notes. Gates both mix passes.
    is_drum: bool,
    // Poly (key) aftertouch (0xAn): a per-note pressure lane mirroring the
    // channel lane (same smoothing, LFO rate and depths). Channel and key
    // pressure COMPOSE: the dB gain lifts add and the vibrato factors
    // multiply — matching how CC7 x CC11 x channel-AT gain already stack in
    // the strip. All defaults are exact no-ops (multiply by 1.0), so a note
    // that never receives 0xAn renders bit-identically.
    poly_authored: bool,
    poly_target: f32, // pressure 0..1
    poly_cur: f32,    // smoothed like the channel at_cur
    poly_phase: f32,  // per-note pressure-vibrato LFO phase
    poly_mult: f32,   // this block's pitch factor (1.0 = none)
    poly_gain: f32,   // per-note gain lift (1.0 = none)
    voice: Box<dyn voices::Voice>,
}

#[derive(Clone, Copy)]
pub(crate) struct CoreOptions {
    pub sr: f32,
    pub wet: f32,
    pub delay_s: f32,
    pub samples: bool,
    pub solo: u16,
    pub gtr_symp_on: bool,
    pub drum_room_on: bool,
    pub sitar_symp_on: bool,
}

impl CoreOptions {
    fn from_options(
        opt: &Options,
        gtr_symp_on: bool,
        drum_room_on: bool,
        sitar_symp_on: bool,
    ) -> Self {
        Self {
            sr: opt.sr,
            wet: opt.wet,
            delay_s: opt.delay_s,
            samples: opt.samples,
            solo: opt.solo,
            gtr_symp_on,
            drum_room_on,
            sitar_symp_on,
        }
    }
}

/// The shared hall's default tuning (Freeverb comb feedback / damping). Single
/// source of truth for `EngineCore::new` and the XG System On reset, so the two
/// can never drift apart.
const DEFAULT_HALL_ROOM: f32 = 0.86;
const DEFAULT_HALL_DAMP: f32 = 0.35;

/// XG Reverb Type Hall 1 = type word (0x01, 0x00). Re-tuned (Arthur's "faithful"
/// steer) as a larger, brighter concert hall than the engine default: more comb
/// feedback (longer RT) and less damping (brighter tail). Applied only when a
/// file requests it; oracles check DIRECTION, not XG-exact numbers.
const HALL1_TYPE: [u8; 2] = [0x01, 0x00];
const HALL1_ROOM: f32 = 0.92;
const HALL1_DAMP: f32 = 0.22;

/// XG Chorus Type Chorus 1 = type word (0x41, 0x00). Faithful moderate chorus:
/// a touch faster and deeper than the engine default. Params are (LFO rate Hz,
/// base delay s, sweep depth s); `base + depth` stays inside the 40 ms line.
const CHORUS1_TYPE: [u8; 2] = [0x41, 0x00];
const CHORUS1_RATE: f32 = 0.8;
const CHORUS1_BASE_S: f32 = 0.018;
const CHORUS1_DEPTH_S: f32 = 0.006;

/// The engine chorus defaults — MIRROR `Chorus::new` (guarded by the
/// reconfigure-to-defaults-is-a-no-op test). Single source for the System On
/// reset.
const DEFAULT_CHORUS_RATE: f32 = 0.35;
const DEFAULT_CHORUS_BASE_S: f32 = 0.018;
const DEFAULT_CHORUS_DEPTH_S: f32 = 0.005;

/// XG Variation Type MSB for the Amp Simulator (the only variation type we
/// model). The LSB (0x11 in the reference file) is undocumented in the MU100/
/// MU128 map and ignored — treated as the basic Amp Sim.
const AMP_SIM_TYPE_MSB: u8 = 0x4B;
/// XG Variation Connection: 0 = INSERTION (a per-part insert), 1 = SYSTEM (a
/// global send bus — a non-goal; SYSTEM installs no insert).
const XG_VAR_INSERTION: u8 = 0x00;

/// XG effect-block state (Effect1): the pending variation-insertion config,
/// mutated ONLY by XG effect SysEx (`EvKind::XgEffectParam` / `XgReset`). No
/// album sends any SysEx, so every field's default leaves the render
/// bit-identical: `var_part = 127` (OFF) installs no insert, and the reverb /
/// chorus recognizers only fire on the exact Hall 1 / Chorus 1 type words. The
/// reverb/chorus *type* changes act on the live `Reverb`/`Chorus` in place, so
/// no state is duplicated here — only the variation, which is resolved into a
/// per-strip `xg_insert` after each parameter update.
#[derive(Clone, Copy)]
struct XgEffects {
    var_type_msb: u8,   // Variation Type MSB (Amp Simulator = 0x4B)
    var_type_lsb: u8,   // Variation Type LSB (0x11 undocumented -> basic Amp Sim)
    var_connection: u8, // 0 = INSERTION, 1 = SYSTEM
    var_part: u8,       // target Part 0..63; 127 = OFF (no insert)
    var_drive: u8,      // Variation Param1 = Drive (0..127)
    var_drywet: u8,     // Variation Param10 = Dry/Wet (1..127; 127 = full wet)
}

impl XgEffects {
    fn new() -> Self {
        // Defaults chosen so the resolve is a no-op: part OFF => no insert.
        XgEffects {
            var_type_msb: 0,
            var_type_lsb: 0,
            var_connection: 0,
            var_part: 127,
            var_drive: 0,
            var_drywet: 127,
        }
    }
}

pub(crate) struct EngineCore {
    opt: CoreOptions,
    strips: Vec<Strip>,
    active: Vec<Active>,
    // Per-channel index buckets into `active`, rebuilt once per block by
    // `rebuild_voice_buckets`. The control-lane phases each want "every active
    // voice on channel N"; without this they rescan the whole voice vector once
    // per (phase, channel) — 100+ full passes per block. Preallocated and only
    // ever `clear()`ed, so the render path never allocates.
    voice_by_ch: [Vec<usize>; 16],
    reverb: Reverb,
    cathedral: CathedralReverb,
    rev_hp: Biquad,
    #[cfg(test)]
    cathedral_send_hp: Biquad,
    #[cfg(test)]
    cathedral_send_hpf_on: bool,
    chorus: Chorus,
    echo: Option<PingPong>,
    symp: Sympathetic,
    gtr_symp: Sympathetic,
    sitar_symp: Sympathetic,
    // set the first time a strip sounds program 104; until then the tarab
    // bus is never processed, so sitar-less renders stay bit-identical
    sitar_seen: bool,
    drum_room: Reverb,
    glue: BusGlue,
    stats: Stats,
    // Deterministic voice-seed position. Usually advances with voices_spawned,
    // but GM System On resets synthesis state while public Stats stay cumulative.
    voice_seed_index: u64,
    ch_buf: Vec<[f32; BLOCK]>,
    legacy_buf: Vec<[f32; BLOCK]>,
    cathedral_buf: Vec<[f32; BLOCK]>,
    scratch: [f32; BLOCK],
    send_rev: [f32; BLOCK],
    send_cathedral: [f32; BLOCK],
    send_cho: [f32; BLOCK],
    send_del: [f32; BLOCK],
    send_sym: [f32; BLOCK],
    send_sym_gtr: [f32; BLOCK],
    send_sym_sitar: [f32; BLOCK],
    send_room: [f32; BLOCK],
    drum_l: [f32; BLOCK],
    drum_r: [f32; BLOCK],
    mix_l: [f32; BLOCK],
    mix_r: [f32; BLOCK],
    expr_smooth: f32,
    leslie_k: f32,
    wah_smooth: f32,
    // Per-key channel-10 hit counter (wraps): the sampled cymbals cycle their
    // round-robin takes from it, so consecutive hits of the SAME key step
    // 0→1→2→3→0… deterministically no matter what other drums interleave.
    // (A seed-modulo pick would immediate-repeat ~1/rr of the time — the
    // machine-gun artifact.)
    drum_rr: [u8; 128],
    // Per-channel GM120 fret-noise phase. The bank is pitchless, so written
    // keys share one canonical 0→1→…→11 cycle on a channel; another channel
    // owns an independent cycle. Advancing here, at the accepted fresh-spawn
    // seam, prevents unrelated global seed slots from replaying a take.
    fret_noise_rr: [usize; 16],
    // TREM1 (tremolo restrike): the running sample clock (advanced per
    // rendered block; events are block-quantised, so this is exactly their
    // resolution) and the per-(channel, key) time of the previous NoteOn —
    // together they give the same-key inter-onset interval that gates the
    // tremolo-restrike path in note_on.
    now: u64,
    key_on_at: Vec<[u64; 128]>,
    // Per-(channel, key) strike counter for PITCHED round-robin banks (today:
    // the mandolin at GM 25 + bank-LSB 96). Same guarantee as `drum_rr`, and for
    // the same reason: consecutive strikes of the SAME key step 0→1→2→3→0…
    // deterministically, so the takes cycle in the order they were recorded —
    // which for the mandolin encodes the player's down/up pick alternation — no
    // matter what other notes interleave. Per-CHANNEL as well as per-key, unlike
    // drum_rr, because pitched voices are not confined to one channel.
    // Deliberately NOT `seed % n`: the seed counter is global and advances on
    // every voice spawn, so it only decorrelates — two same-key strikes with
    // other notes between them can draw the same take.
    pitched_rr: Vec<[u8; 128]>,
    // XG effect-block state (variation insertion + the reverb/chorus type
    // recognizers). Defaults are inert; only XG SysEx mutates it.
    xg: XgEffects,
}

/// TREM1: a same-key NoteOn this close (in seconds) to the previous one on
/// the same channel is a tremolo stroke — re-excite the still-ringing
/// plucked voice instead of spawning a fresh one from silence. 100 ms
/// (10 strokes/s) separates genuine tremolo (mandolin/guitar tremolo is
/// 10–16 strokes/s, IOI ≤ 100 ms) from intentional same-note picking
/// (5–7 notes/s, IOI ≥ 143 ms, 43% above the gate), which must keep its
/// full per-note articulation.
const TREM_IOI_MAX_S: f32 = 0.10;
const NOTE_VOICE_SEED_XOR: u32 = 0x9E37;
const VOICE_SEED_STEP: u32 = 2_654_435_761;

pub(crate) fn note_voice_seed(index: u64) -> u32 {
    NOTE_VOICE_SEED_XOR ^ (index as u32).wrapping_mul(VOICE_SEED_STEP)
}

impl EngineCore {
    pub(crate) fn new(opt: CoreOptions) -> Self {
        let opt = CoreOptions {
            samples: opt.samples && crate::embedded_samples_available(),
            ..opt
        };
        let sr = opt.sr;
        Self {
            opt,
            strips: (0..16).map(|_| Strip::new(sr)).collect(),
            active: Vec::new(),
            voice_by_ch: std::array::from_fn(|_| Vec::with_capacity(64)),
            reverb: Reverb::new(sr, DEFAULT_HALL_ROOM, DEFAULT_HALL_DAMP, opt.wet),
            cathedral: CathedralReverb::new(sr, opt.wet * CATHEDRAL_WET_SCALE),
            rev_hp: Biquad::highpass(150.0, 0.7, sr),
            #[cfg(test)]
            cathedral_send_hp: Biquad::highpass(150.0, 0.7, sr),
            #[cfg(test)]
            cathedral_send_hpf_on: false,
            chorus: Chorus::new(sr),
            echo: (opt.delay_s > 0.0).then(|| PingPong::new(sr, opt.delay_s)),
            symp: Sympathetic::piano(sr),
            gtr_symp: Sympathetic::guitar(sr),
            sitar_symp: Sympathetic::sitar(sr),
            sitar_seen: false,
            drum_room: Reverb::with_predelay(sr, 0.42, 0.55, opt.wet * 0.9, 0.003),
            glue: BusGlue::new(sr),
            stats: Stats::default(),
            voice_seed_index: 0,
            ch_buf: vec![[0f32; BLOCK]; 16],
            legacy_buf: vec![[0f32; BLOCK]; 16],
            cathedral_buf: vec![[0f32; BLOCK]; 16],
            scratch: [0f32; BLOCK],
            send_rev: [0f32; BLOCK],
            send_cathedral: [0f32; BLOCK],
            send_cho: [0f32; BLOCK],
            send_del: [0f32; BLOCK],
            send_sym: [0f32; BLOCK],
            send_sym_gtr: [0f32; BLOCK],
            send_sym_sitar: [0f32; BLOCK],
            send_room: [0f32; BLOCK],
            drum_l: [0f32; BLOCK],
            drum_r: [0f32; BLOCK],
            mix_l: [0f32; BLOCK],
            mix_r: [0f32; BLOCK],
            expr_smooth: 1.0 - (-(BLOCK as f32) / (0.03 * sr)).exp(),
            leslie_k: 1.0 - (-(BLOCK as f32) / (LESLIE_INERTIA_S * sr)).exp(),
            wah_smooth: 1.0 - (-(BLOCK as f32) / (WAH_SLEW_S * sr)).exp(),
            drum_rr: [0; 128],
            fret_noise_rr: [0; 16],
            now: 0,
            key_on_at: vec![[u64::MAX; 128]; 16],
            pitched_rr: vec![[0u8; 128]; 16],
            xg: XgEffects::new(),
        }
    }

    pub(crate) fn hard_reset(&mut self) {
        let opt = self.opt;
        *self = Self::new(opt);
    }

    /// Restore fresh GM synthesis/channel state while whole-render diagnostics
    /// remain cumulative for the offline API.
    fn gm_system_on(&mut self) {
        let stats = self.stats;
        self.hard_reset();
        self.stats = stats;
    }

    pub(crate) fn active_voice_count(&self) -> usize {
        self.active.len()
    }

    pub(crate) fn stats(&self) -> Stats {
        self.stats
    }

    fn is_bagpipe_drone(a: &Active, ch: u8) -> bool {
        a.ch == ch && a.program == 109 && a.key == BAGPIPE_DRONE_KEY
    }

    fn ensure_bagpipe_drone(&mut self, ch: u8, key: u8, vel: u8) {
        if self
            .active
            .iter()
            .any(|a| Self::is_bagpipe_drone(a, ch) && !a.voice.released())
        {
            return;
        }
        let seed = 0xBA60 ^ (self.voice_seed_index as u32).wrapping_mul(VOICE_SEED_STEP);
        // Sampled drone by default; modeled when samples are off or on the CC0
        // alt bank — the same rule the chanter uses in voices::make, so the two
        // paths agree (HLD 2026.07.17 §5). `opt.samples` already folds in
        // embedded-availability.
        let sampled = self.opt.samples && !self.strips[ch as usize].alt_bank;
        let voice: Box<dyn voices::Voice> = if sampled {
            Box::new(voices::bagpipe_drone_sampled(key, self.opt.sr))
        } else {
            Box::new(voices::bagpipe_drone(key, vel, self.opt.sr, seed))
        };
        self.active.push(Active {
            ch,
            key: BAGPIPE_DRONE_KEY,
            program: 109,
            held: false,
            sost: false,
            sost_held: false,
            glide: None,
            alt: false,
            alt_bank_value: 0,
            bank_lsb: 0,    // the drone is not a bank variation
            is_drum: false, // the bagpipe drone is a melodic voice, never a drum
            poly_authored: false,
            poly_target: 0.0,
            poly_cur: 0.0,
            poly_phase: 0.0,
            poly_mult: 1.0,
            poly_gain: 1.0,
            voice,
        });
        self.stats.voices_spawned += 1;
        self.voice_seed_index += 1;
        self.strips[ch as usize].bagpipe_drone_live = true;
        self.strips[ch as usize].bagpipe_drone_hang = 0;
    }

    fn release_bagpipe_drone_if_idle(&mut self, ch: u8) {
        if self.strips[ch as usize].bagpipe_drone_holds > 0 {
            return;
        }
        let has_chant = self.active.iter().any(|a| {
            a.ch == ch && a.program == 109 && a.key != BAGPIPE_DRONE_KEY && !a.voice.released()
        });
        if has_chant {
            return;
        }
        for a in self
            .active
            .iter_mut()
            .filter(|a| Self::is_bagpipe_drone(a, ch) && !a.voice.released())
        {
            a.voice.note_off();
        }
        self.strips[ch as usize].bagpipe_drone_live = false;
        self.strips[ch as usize].bagpipe_drone_hang = 0;
    }

    /// Bagpipe drone latch (block rate). One CONTINUOUS drone per channel: a
    /// chanter gap must not release it — a real set of pipes never stops its
    /// drones between melody notes. The drone releases only after
    /// [`BAGPIPE_DRONE_HANG_S`] of chanter silence with no drone-control
    /// hold: the bag emptying at the end of the tune. Gated on
    /// `bagpipe_drone_live`, so every channel that never spawned a drone
    /// (every non-GM109 channel, hence every existing album) does no work —
    /// and sees no behaviour change — here.
    fn tick_bagpipe_drone_latch(&mut self) {
        let hang_blocks = (BAGPIPE_DRONE_HANG_S * self.opt.sr / BLOCK as f32) as u32;
        for ci in 0..self.strips.len() {
            if !self.strips[ci].bagpipe_drone_live {
                continue;
            }
            let ch = ci as u8;
            let has_drone = self
                .active
                .iter()
                .any(|a| Self::is_bagpipe_drone(a, ch) && !a.voice.released());
            if !has_drone {
                // released/choked elsewhere (CC120/123, authored stop)
                self.strips[ci].bagpipe_drone_live = false;
                self.strips[ci].bagpipe_drone_hang = 0;
                continue;
            }
            let holding = self.strips[ci].bagpipe_drone_holds > 0
                || self.active.iter().any(|a| {
                    a.ch == ch
                        && a.program == 109
                        && a.key != BAGPIPE_DRONE_KEY
                        && !a.voice.released()
                });
            if holding {
                self.strips[ci].bagpipe_drone_hang = 0;
            } else {
                self.strips[ci].bagpipe_drone_hang += 1;
                if self.strips[ci].bagpipe_drone_hang >= hang_blocks {
                    for a in self
                        .active
                        .iter_mut()
                        .filter(|a| Self::is_bagpipe_drone(a, ch) && !a.voice.released())
                    {
                        a.voice.note_off();
                    }
                    self.strips[ci].bagpipe_drone_live = false;
                    self.strips[ci].bagpipe_drone_hang = 0;
                }
            }
        }
    }

    fn make_room_for_driven_guitar(&mut self, ch: u8) {
        let active = self
            .active
            .iter()
            .filter(|a| a.ch == ch && needs_drive(a.program) && !a.voice.released())
            .count();
        let release_count = active.saturating_sub(DRIVEN_GUITAR_VOICE_LIMIT - 1);
        for a in self
            .active
            .iter_mut()
            .filter(|a| a.ch == ch && needs_drive(a.program) && !a.voice.released())
            .take(release_count)
        {
            // Voice stealing is a hard safety boundary: it overrides both pedal
            // deferrals and drops Pluck's e-bow driver through note_off().
            a.held = false;
            a.sost = false;
            a.sost_held = false;
            a.voice.note_off();
        }
    }

    /// Bound total polyphony to `cap`, stealing the oldest/quietest voices until
    /// the count is back at `cap`. Called ONLY from the realtime wrapper
    /// (`live::RealtimeSynth`), which has an audio-callback deadline a dense
    /// stream of un-released voices could otherwise blow. The offline path never
    /// calls this — it has no deadline, so its polyphony stays unbounded and its
    /// renders bit-identical.
    ///
    /// Victim choice: the oldest **released** voice (already decaying, so the
    /// quietest available proxy — the `Voice` trait exposes no level query),
    /// else the oldest voice overall (`active` is push-ordered, so index 0 is
    /// oldest — and the longest-ringing voice is the most decayed). Stealing is
    /// a hard cut, so it can click under genuine overload; that is the safety
    /// valve's cost versus xruns/dropouts.
    /// Reserve voice and per-channel index storage up front, so a NoteOn or the next
    /// bucket rebuild inside the audio callback never grows a vector
    /// (MM-BUG-KILN-00082, MM-BUG-CRUCIBLE-00006).
    ///
    /// Realtime-only: the offline renderer is unbounded by design and pays nothing for
    /// growth amortised over a whole render, so it does not call this.
    pub(crate) fn reserve_voices(&mut self, cap: usize) {
        self.active.reserve(cap.saturating_sub(self.active.len()));
        for bucket in &mut self.voice_by_ch {
            bucket.reserve(cap.saturating_sub(bucket.len()));
        }
    }

    /// Steal voices until at most `cap` remain: released ones first (in age order),
    /// then the oldest un-released ones.
    ///
    /// One pass, not one pass per stolen voice. The loop this replaces re-scanned
    /// from the front and `Vec::remove`d for every single voice over the cap, which
    /// is quadratic in the excess — and a live stream can put the excess in the
    /// hundreds within one block, on the deadline-bearing audio thread
    /// (MM-BUG-CRUCIBLE-00025). Removing a released voice cannot change any other
    /// voice's released state, so the victims can be chosen up front and dropped in
    /// a single `retain`; `retain` visits in index order, which is what preserves
    /// the released-first-then-oldest order the old loop produced.
    pub(crate) fn enforce_voice_cap(&mut self, cap: usize) {
        let len = self.active.len();
        if len <= cap {
            return;
        }
        let excess = len - cap;
        let released = self.active.iter().filter(|a| a.voice.released()).count();
        let mut released_budget = excess.min(released);
        let mut unreleased_budget = excess - released_budget;
        self.active.retain(|a| {
            if a.voice.released() {
                if released_budget > 0 {
                    released_budget -= 1;
                    return false;
                }
            } else if unreleased_budget > 0 {
                unreleased_budget -= 1;
                return false;
            }
            true
        });
    }

    pub(crate) fn handle_event(&mut self, kind: EvKind) {
        match kind {
            // --solo: muted channels keep their CCs but lose their notes
            EvKind::NoteOn { ch, .. } | EvKind::NoteOff { ch, .. }
                if self.opt.solo & (1u16 << ch) == 0 => {}
            EvKind::NoteOn { ch, key, vel } => self.note_on(ch, key, vel),
            EvKind::NoteOff { ch, key } => self.note_off(ch, key),
            EvKind::Cc { ch, num, val } => self.cc(ch, num, val),
            EvKind::Bend { ch, semis } => self.bend(ch, semis),
            EvKind::Aftertouch { ch, val } => {
                let s = &mut self.strips[ch as usize];
                s.at_target = val as f32 / 127.0;
                s.at_authored = true;
            }
            // Poly (key) aftertouch targets only the ringing voice(s) on that
            // key. Same family gate as the channel lane (drums stay out) —
            // gated at event time so unaffected notes never engage the lane.
            EvKind::PolyAftertouch { ch, key, val } => {
                if ch != 9 {
                    let p = val as f32 / 127.0;
                    for a in self.active.iter_mut().filter(|a| {
                        a.ch == ch
                            && a.key == key
                            && !a.voice.released()
                            && aftertouch_family(a.program)
                    }) {
                        a.poly_target = p;
                        a.poly_authored = true;
                    }
                }
            }
            EvKind::Prog { ch, prog } => self.program_change(ch, prog),
            // GS "Use for Rhythm Part": flag/unflag the channel a drum part. Frozen
            // into each voice's `is_drum` at spawn, so only later notes are affected.
            EvKind::DrumMode { ch, on } => {
                // Re-derive only on a real change, and only for the channel that
                // changed: re-running the derivation is idempotent for an unchanged
                // routing, but doing it needlessly would widen this event's blast
                // radius for no reason (MM-BUG-CRUCIBLE-00030).
                if self.strips[ch as usize].gs_drum != on {
                    self.strips[ch as usize].gs_drum = on;
                    self.rederive_routing_derived_state(ch);
                }
            }
            // GS Reset: revert part modes — clear every GS-declared rhythm part (ch9
            // stays drums via the ch==9 rule; the other GS reset effects aren't modeled).
            EvKind::GsReset => {
                for ch in 0..self.strips.len() {
                    if self.strips[ch].gs_drum {
                        self.strips[ch].gs_drum = false;
                        self.rederive_routing_derived_state(ch as u8);
                    }
                }
            }
            EvKind::GmReset => self.gm_system_on(),
            // XG effect SysEx (reverb/chorus type + the variation Amp-Sim
            // insertion). Byte-inert for every album (0 send any SysEx): the
            // reverb/chorus recognizers only fire on the exact Hall 1 / Chorus 1
            // words, and the variation resolves to an insert only when a real
            // Part (< 64) is targeted — default part is OFF.
            EvKind::XgReset => self.xg_reset(),
            EvKind::XgEffectParam { addr_lo, data, len } => {
                self.handle_xg_effect_param(addr_lo, data, len)
            }
        }
    }

    /// XG System On resets the XG effect block to defaults only. Unlike GM
    /// System On, it leaves voices and channel state untouched. Reverb/chorus
    /// return to constructor tuning and every variation insert is cleared.
    fn xg_reset(&mut self) {
        self.xg = XgEffects::new();
        // Restore the hall and chorus to their construction tuning (a no-op
        // unless a prior XG type event moved them). Only the shared hall — never
        // the cathedral or the drum room.
        self.reverb
            .reconfigure(DEFAULT_HALL_ROOM, DEFAULT_HALL_DAMP);
        self.chorus.reconfigure(
            DEFAULT_CHORUS_RATE,
            DEFAULT_CHORUS_BASE_S,
            DEFAULT_CHORUS_DEPTH_S,
        );
        self.resolve_variation();
    }

    /// Apply one XG Effect1 parameter. Semantics live here (the parser stays a
    /// dumb decoder, per the GS idiom): reverb/chorus *type* recognizers act on
    /// the live buses in place; variation params accumulate into `self.xg` and
    /// re-resolve the insert idempotently, so the t=0 message order is
    /// irrelevant. Unrecognized offsets (returns at 0x0C/0x2C/0x56, unknown
    /// types) are parsed-and-ignored by design.
    fn handle_xg_effect_param(&mut self, addr_lo: u8, data: [u8; 2], len: u8) {
        // XG data words are 7-bit halves; a value <= 127 lives in the LSB.
        let value14 = ((data[0] as u16) << 7) | (data[1] as u16);
        let value7 = value14.min(127) as u8;
        match addr_lo {
            // Reverb Type: Hall 1 re-tunes the shared hall; every other type
            // keeps the current bus (falls through to `_`). Reverb Return (0x0C)
            // is parsed-and-ignored — returns are unity here.
            0x00 if data == HALL1_TYPE => self.reverb.reconfigure(HALL1_ROOM, HALL1_DAMP),
            // Chorus Type: Chorus 1 re-tunes the chorus LFO; every other type
            // keeps the current bus. Chorus Return (0x2C) parsed-and-ignored.
            0x20 if data == CHORUS1_TYPE => {
                self.chorus
                    .reconfigure(CHORUS1_RATE, CHORUS1_BASE_S, CHORUS1_DEPTH_S)
            }
            // Variation Type (MSB,LSB). Amp Simulator = 0x4B; LSB ignored.
            0x40 => {
                self.xg.var_type_msb = data[0];
                self.xg.var_type_lsb = if len >= 2 { data[1] } else { 0 };
                self.resolve_variation();
            }
            // Variation Param 1 = Drive (0..127).
            0x42 => {
                self.xg.var_drive = value7;
                self.resolve_variation();
            }
            // Variation Param 10 = Dry/Wet (1..127; 127 = full wet).
            0x54 => {
                self.xg.var_drywet = value7;
                self.resolve_variation();
            }
            // Variation Connection: 0 = INSERTION, 1 = SYSTEM.
            0x5A => {
                self.xg.var_connection = data[0];
                self.resolve_variation();
            }
            // Variation Part: 0..63 target part; 127 = OFF.
            0x5B => {
                self.xg.var_part = data[0];
                self.resolve_variation();
            }
            _ => {}
        }
    }

    /// (Re)resolve the variation config into the per-strip insert. Idempotent —
    /// re-run after every parameter update, so the t=0 message order is
    /// irrelevant and a later part/connection/type change moves or removes the
    /// insert. At most one insert exists at a time (XG has a single variation
    /// block): clear every strip, then install on the target iff it is an Amp
    /// Simulator, INSERTION-connected, and aimed at a real part.
    fn resolve_variation(&mut self) {
        for s in &mut self.strips {
            s.xg_insert = None;
        }
        let is_amp_sim = self.xg.var_type_msb == AMP_SIM_TYPE_MSB;
        let insertion = self.xg.var_connection == XG_VAR_INSERTION;
        let part = self.xg.var_part as usize;
        if is_amp_sim && insertion && part < self.strips.len() {
            // Dry/Wet 1..127 -> weight 0..1 (127 = full wet). Blended at the
            // apply site; the Drive itself carries no blend.
            let wet = f32::from(self.xg.var_drywet.saturating_sub(1)) / 126.0;
            let insert = Drive::amp_sim(self.opt.sr, self.xg.var_drive);
            self.strips[part].xg_insert = Some((insert, wet.clamp(0.0, 1.0)));
        }
    }

    fn note_on(&mut self, ch: u8, key: u8, vel: u8) {
        let sr = self.opt.sr;
        let ci = ch as usize;
        let porta_from = self.strips[ci].last_freq;
        let program = self.strips[ci].program;
        let bagpipe_drone_control =
            ch != 9 && program == 109 && key <= voices::BAGPIPE_DRONE_CONTROL_MAX;
        // TREM1: same-key inter-onset interval (in samples) against the
        // previous NoteOn of this (channel, key); the clock updates on EVERY
        // melodic NoteOn so a slow passage keeps re-arming a long IOI.
        let trem_prev = if ch != 9 {
            let prev = self.key_on_at[ci][key as usize];
            self.key_on_at[ci][key as usize] = self.now;
            prev
        } else {
            u64::MAX
        };
        let trem_restrike =
            trem_prev != u64::MAX && (self.now - trem_prev) as f32 <= TREM_IOI_MAX_S * sr;
        if ch != 9 && !bagpipe_drone_control {
            self.strips[ci].last_freq = Some(key_freq(key));
        }
        if bagpipe_drone_control {
            self.strips[ci].bagpipe_drone_holds =
                self.strips[ci].bagpipe_drone_holds.saturating_add(1);
            self.ensure_bagpipe_drone(ch, key, vel);
            return;
        }
        if ch != 9 && program == 109 {
            self.ensure_bagpipe_drone(ch, key, vel);
        }
        if ch != 9 && self.strips[ci].legato {
            let mut ringing = self.active.iter_mut().filter(|a| {
                a.ch == ch
                    && a.key != BAGPIPE_DRONE_KEY
                    && !a.held
                    && !a.sost_held
                    && !a.voice.released()
            });
            if let (Some(a), None) = (ringing.next(), ringing.next()) {
                if a.voice.legato_to(key, vel) {
                    a.key = key;
                    return;
                }
            }
        }
        // Current drum routing, resolved BEFORE the tremolo path rather than at
        // spawn: the restrike predicate below is a routing-identity check, and it
        // cannot compare against a value that has not been computed yet
        // (MM-BUG-KILN-00087). Reading it here changes nothing else — no code
        // between here and the spawn mutates `xg_drum` / `gs_drum`.
        let is_drum = ch == 9 || self.strips[ci].xg_drum || self.strips[ci].gs_drum;
        // TREM1: a fast same-key restrike (IOI ≤ 100 ms — a tremolo stroke)
        // re-picks the still-ringing plucked voice instead of spawning a new
        // one from silence: a fresh spawn is a broadband restart transient,
        // and 10–16 of those per second read as a click train, not a
        // tremolo. Scoped by CAPABILITY: only Pluck implements retrigger()
        // (a plucked string physically IS re-struck while ringing); winds /
        // bowed / reeds / brass return the default false and keep full
        // per-note re-articulation — their legato_to (a slur) must never be
        // conscripted for this. The explicit CC68 legato path above still
        // wins where authored.
        //
        // The predicate is the voice's COMPLETE spawn-time routing identity, not a
        // subset of it: program, CC0 alt bank AND its raw value (1 legacy alt vs 2
        // cathedral organ are different voices), CC32 bank LSB (steel guitar 25 vs
        // mandolin 25+96), and melodic-vs-drum routing. A partial match let a bank
        // change inside the 100 ms window re-pick the PREVIOUS bank's voice, so the
        // newly selected one never spawned (MM-BUG-KILN-00087).
        if ch != 9 && trem_restrike && !is_drum {
            let prog = self.strips[ci].program;
            let alt = self.strips[ci].alt_bank;
            let alt_value = self.strips[ci].alt_bank_value;
            let bank_lsb = self.strips[ci].bank_lsb;
            if let Some(a) = self.active.iter_mut().rev().find(|a| {
                a.ch == ch
                    && a.key == key
                    && a.program == prog
                    && a.alt == alt
                    && a.alt_bank_value == alt_value
                    && a.bank_lsb == bank_lsb
                    && !a.is_drum
            }) {
                if a.voice.retrigger(key, vel) {
                    // the stroke re-opens the voice's gate: its NoteOff (and
                    // the pedal state at that time) now governs it afresh
                    a.held = false;
                    a.sost_held = false;
                    // A retriggered round-robin voice rotated its OWN take, so the
                    // engine counter must resume from where the voice actually is,
                    // not from the count it had when the voice spawned. Mirroring
                    // the sounding take (rather than adding 1 per stroke) is what
                    // keeps a declined rotation — a next take that would repitch out
                    // of window holds its take — from desyncing the two
                    // (MM-BUG-KILN-00088).
                    if let Some(sounding) = a.voice.rr_phase() {
                        self.pitched_rr[ci][key as usize] = (sounding as u8).wrapping_add(1);
                    }
                    // consume this stroke's seed slot so every LATER spawn
                    // draws exactly the seed it would have pre-change — the
                    // render diff stays confined to the tremolo itself
                    self.stats.voices_spawned += 1;
                    self.voice_seed_index += 1;
                    return;
                }
            }
        }

        // CC84 (portamento control): consume the pending one-shot glide source
        // now that every early-return path (bagpipe / legato / tremolo restrike)
        // is past and a fresh voice will actually spawn.
        let porta_ctrl = self.strips[ci].porta_control.take();

        let vel = if ch != 9
            && self.strips[ci].soft
            && voices::is_acoustic_piano(self.strips[ci].program)
        {
            ((vel as f32 * 0.75).round() as u8).max(1)
        } else {
            vel
        };

        // Hi-hat choke group. Keyed on `is_drum`, not `ch == 9`, so a channel declared
        // a drum part by XG or GS chokes its hats like channel 10 does — and on
        // `a.ch == ch`, because a choke group belongs to ONE kit: an open hat on ch10
        // must not be silenced by a pedal hat on some other declared drum channel. For
        // ch9 both forms are identical, so this cannot move a committed render.
        if is_drum && matches!(key, 42 | 44 | 46) {
            for a in self
                .active
                .iter_mut()
                .filter(|a| a.ch == ch && matches!(a.key, 42 | 44 | 46))
            {
                a.voice.choke();
            }
        }

        if !is_drum && needs_drive(program) {
            self.make_room_for_driven_guitar(ch);
        }

        let seed = note_voice_seed(self.voice_seed_index);
        // ch9 is always drums; a channel declared a drum part by XG (CC0==127) or GS
        // ("Use for Rhythm Part" SysEx) joins the drum path. `strips[ci].kit` is
        // that channel's own kit: since 2026-07-26 a declared drum channel honours the
        // ch-10 kit ladder too, so its program change selects a KIT rather than being
        // read as a melodic instrument. `is_drum` is resolved above, before the
        // tremolo-restrike predicate that also needs it.
        let voice = if is_drum {
            let rr = self.drum_rr[key as usize];
            self.drum_rr[key as usize] = rr.wrapping_add(1);
            drums::make(
                key,
                vel,
                sr,
                seed,
                self.strips[ci].kit,
                self.opt.samples,
                rr,
            )
        } else if program == 120 && self.opt.samples {
            // GM120 is an ordered, pitchless twelve-take bank. Select it at
            // the engine seam so every accepted sampled event advances once,
            // independently per channel; the global note seed still advances
            // below for every later voice exactly as before.
            let takes = crate::sampler::fret_noise_round_robins();
            let phase = &mut self.fret_noise_rr[ci];
            let rr = *phase;
            *phase = (rr + 1) % takes.max(1);
            Some(
                crate::sampler::sampled_fret_noise(vel, sr, rr)
                    .unwrap_or_else(|| voices::make(program, key, vel, sr, seed, false)),
            )
        } else {
            let prog = self.strips[ci].program;
            Some(if self.strips[ci].alt_bank {
                crate::altbank::make(
                    prog,
                    self.strips[ci].alt_bank_value,
                    key,
                    vel,
                    sr,
                    seed,
                    self.opt.samples,
                )
            } else {
                // XG bank-LSB variation, else base GM. Same `seed` on both paths,
                // so an undefined (prog, bank_lsb) is bit-identical to base.
                //
                // Read-and-advance this (channel, key)'s strike counter, but ONLY for
                // a variation that actually rotates takes. It used to advance on every
                // melodic spawn on the theory that the counter is inert elsewhere —
                // which is true of the voice it builds, and false of the phase: a base
                // steel or unrelated-LSB note on the same channel and key ate the
                // mandolin's next take, so the recorded down/up pick order broke at
                // the phrase boundary (MM-BUG-KILN-00088).
                let rr = if voices::variation_round_robins(prog, self.strips[ci].bank_lsb).is_some()
                {
                    let c = &mut self.pitched_rr[ci][key as usize];
                    let r = *c;
                    *c = c.wrapping_add(1);
                    r
                } else {
                    0
                };
                voices::make_variation(
                    prog,
                    self.strips[ci].bank_lsb,
                    key,
                    vel,
                    sr,
                    seed,
                    self.opt.samples,
                    rr,
                )
                .unwrap_or_else(|| voices::make(prog, key, vel, sr, seed, self.opt.samples))
            })
        };

        if let Some(mut voice) = voice {
            let s = &self.strips[ci];
            if s.bend != 1.0 {
                voice.set_pitch(s.bend);
            }
            if s.vowel_authored && vowel_family(s.program) {
                let (f, q, g) = vowel_at(s.vowel_cur);
                voice.set_vowel(f, q, g);
            }
            // BR9: brass opens its timbre with breath (CC11 expression). Seed
            // the new voice at the channel's current pressure so a note born
            // mid-swell starts open, not from silence.
            if matches!(s.program, 56..=63) {
                voice.set_breath((s.expr * s.breath).sqrt().min(1.3), 0.0);
            }
            // RD9 (§2.8.3): reeds open their timbre from the same CC2/CC11
            // lanes — but only once AUTHORED, so a channel that never sends
            // them renders controller-identically to before (§2.8.2; brass
            // predates that invariant and keeps its unconditional seed).
            if matches!(s.program, 64..=71 | 109 | 111)
                && (s.expr_authored || s.breath_authored || s.at_authored)
            {
                voice.set_breath((s.expr * s.breath).sqrt().min(1.0), 0.0);
            }
            // WD9 (§2.8.5.3): the flue arm of the same authored-only seam —
            // a note born mid-swell starts at the channel's pressure.
            if matches!(s.program, 72..=79)
                && (s.expr_authored || s.breath_authored || s.at_authored)
            {
                voice.set_breath((s.expr * s.breath).sqrt().min(1.0), 0.0);
            }
            // Glide source: CC84 (an explicit one-shot source key that glides
            // regardless of CC65 porta-on) takes precedence; otherwise the CC65
            // legato-portamento path from the previous NoteOn pitch.
            let glide = if ch != 9 {
                let src = porta_ctrl
                    .map(key_freq)
                    .or(if s.porta_on { porta_from } else { None });
                src.and_then(|from| {
                    let semis = 12.0 * (from / key_freq(key)).log2();
                    (semis.abs() > 1e-3).then(|| {
                        let k = 1.0 - (-(BLOCK as f32) / (s.porta_time.max(1e-3) * sr)).exp();
                        voice.set_pitch(s.bend * 2f32.powf(semis / 12.0));
                        (semis, k)
                    })
                })
            } else {
                None
            };
            self.active.push(Active {
                ch,
                key,
                program: if is_drum {
                    128
                } else {
                    self.strips[ci].program
                },
                held: false,
                sost: false,
                sost_held: false,
                glide,
                alt: self.strips[ci].alt_bank,
                alt_bank_value: self.strips[ci].alt_bank_value,
                bank_lsb: self.strips[ci].bank_lsb,
                is_drum,
                poly_authored: false,
                poly_target: 0.0,
                poly_cur: 0.0,
                poly_phase: 0.0,
                poly_mult: 1.0,
                poly_gain: 1.0,
                voice,
            });
            self.stats.voices_spawned += 1;
            self.voice_seed_index += 1;
        }
    }

    fn note_off(&mut self, ch: u8, key: u8) {
        let mut drone_stop = false;
        if ch != 9 && key <= voices::BAGPIPE_DRONE_CONTROL_MAX {
            let holds = &mut self.strips[ch as usize].bagpipe_drone_holds;
            drone_stop = *holds == 1; // this NoteOff ends the last authored hold
            *holds = holds.saturating_sub(1);
        }
        if let Some(a) = self
            .active
            .iter_mut()
            .find(|a| a.ch == ch && a.key == key && !a.held && !a.sost_held && !a.voice.released())
        {
            let s = &self.strips[ch as usize];
            if ch != 9 && s.sustain {
                a.held = true;
            } else if ch != 9 && a.sost {
                a.sost_held = true;
            } else {
                a.voice.note_off();
            }
        }
        // Chanter NoteOffs no longer release the channel drone — the old
        // per-note release/re-spawn made the "continuous" drone pump at every
        // note boundary (and re-strike at the NEW note's pitch). The drone
        // latches; only an AUTHORED stop (the last low drone-control note
        // ending) releases it here, and otherwise the block-rate hang timer
        // in `tick_bagpipe_drone_latch` releases it after sustained silence.
        if drone_stop {
            self.release_bagpipe_drone_if_idle(ch);
        }
    }

    fn cc(&mut self, ch: u8, num: u8, val: u8) {
        let sr = self.opt.sr;
        let s = &mut self.strips[ch as usize];
        let v = val as f32 / 127.0;
        match num {
            0 => {
                // XG: bank MSB 127 selects a drum kit on this channel — route it to
                // the drum path, not the alt orchestral bank. Every other value keeps
                // the existing bank behavior (1/2 = alt voicings, 0 = default), so a
                // channel that never sends 127 is byte-identical to before.
                if val == 127 {
                    s.xg_drum = true;
                    s.alt_bank = false;
                    s.alt_bank_value = 0;
                } else {
                    s.xg_drum = false;
                    s.alt_bank = val != 0; // CC0 bank select: non-zero = alt voicings
                    s.alt_bank_value = val; // raw value: 1 = legacy alt, 2 = GM19 cathedral organ
                }
                // The bank selects the driven cabinet's fine-structure depth
                // (MICRO_CAB_LEAD_DEPTH), so a CC0 that arrives AFTER the
                // program change must rebuild the insert — our albums order
                // bank-select first, but a foreign GM file need not.
                //
                // Routed through the shared derivation since MM-BUG-CRUCIBLE-00030.
                // This arm used to apply `fx_profile` unconditionally, so CC0 = 127 —
                // which DECLARES the channel a drum part on the line above — went on to
                // give it a melodic program's chorus/delay defaults and, for programs
                // 29/30, a guitar amp insert. That is the same defect as the GS side,
                // in the opposite direction.
                //
                // Byte-identical for every non-127 bank select, which is all the
                // catalog sends: for a melodic channel the shared path computes the
                // same `fx_profile(program, alt_bank_value)` under the same
                // `*_authored` guards, and its drive predicate
                // `(d.program, d.alt) != (program, alt_bank)` agrees with the old
                // `d.alt != alt_bank` because `drive` is only ever built from
                // `s.program`, so `d.program == s.program` always holds here.
                self.rederive_routing_derived_state(ch);
            }
            1 => {
                s.mod_target = v;
                s.mod_authored = true;
            }
            2 => {
                // Breath controller: same squared taper as CC11 expression.
                s.breath_target = v * v;
                s.breath_authored = true;
            }
            5 => s.porta_time = PORTA_MIN_S * (PORTA_MAX_S / PORTA_MIN_S).powf(v),
            6 | 38 => {
                // Data Entry is scoped to whichever latch is live. The two are
                // mutually exclusive (the select arms below null the other), so
                // a CC6/CC38 with NO live selector is meaningless MIDI and is
                // dropped — never stored — closing the KILN-00034 stale-MSB path
                // in every direction, including from the initial null/null state.
                if s.rpn_msb != 127 || s.rpn_lsb != 127 {
                    // ---- RPN Data Entry (bend range / fine tune) — unchanged ----
                    if num == 6 {
                        s.data_msb = val;
                    }
                    let (msb, lsb) = if num == 6 {
                        (val, 0)
                    } else {
                        (s.data_msb, val)
                    };
                    match (s.rpn_msb, s.rpn_lsb) {
                        (0, 0) => s.bend_range = msb.clamp(1, 24) as f32 + lsb as f32 / 100.0,
                        (0, 1) => {
                            let raw = ((msb as i32) << 7 | lsb as i32) - 8192;
                            let cents = raw as f32 * (100.0 / 8192.0);
                            s.fine = 2f32.powf(cents / 1200.0);
                        }
                        _ => {}
                    }
                    if matches!((s.rpn_msb, s.rpn_lsb), (0, 0) | (0, 1)) {
                        s.bend = 2f32.powf(s.bend_wheel * (s.bend_range * 0.5) / 12.0) * s.fine;
                        let mult = s.bend;
                        for a in self.active.iter_mut().filter(|a| a.ch == ch) {
                            a.voice.set_pitch(mult);
                        }
                    }
                } else if s.nrpn_msb != 127 || s.nrpn_lsb != 127 {
                    // ---- NRPN Data Entry — the ferrosintesis amp block ----
                    // Only the amp block (MSB 0x30) is modeled; every other NRPN
                    // is inert (the latch still absorbs the Data Entry so it
                    // cannot fall through to the RPN path). The 0..127 value is
                    // the Data Entry MSB (CC6); the LSB (CC38) is ignored.
                    if num == 6 {
                        s.nrpn_data_msb = val;
                        if s.nrpn_msb == AMP_NRPN_MSB && (s.nrpn_lsb as usize) < AMP_PARAM_COUNT {
                            s.amp_params[s.nrpn_lsb as usize] = val;
                            s.amp_authored = true;
                        }
                    }
                }
            }
            // CC7 volume / CC10 pan: author the target only; the per-block mix loop
            // primes-then-slews the current value (and derives haas_delay from the
            // slewed pan). See Strip's controller-slew fields.
            7 => {
                s.volume_target = v * v;
                s.volume_authored = true;
            }
            10 => {
                s.pan_target = v;
                s.pan_authored = true;
            }
            11 => {
                s.expr_target = v * v;
                s.expr_authored = true;
            }
            32 => s.bank_lsb = val, // XG bank-select LSB: selects a variation voice at note-on
            64 => {
                s.sustain = val >= 64;
                if !s.sustain {
                    for a in self.active.iter_mut().filter(|a| a.ch == ch && a.held) {
                        a.held = false;
                        if a.sost {
                            a.sost_held = true;
                        } else {
                            a.voice.note_off();
                        }
                    }
                }
            }
            65 => s.porta_on = val >= 64,
            66 => {
                let down = val >= 64;
                if down && !s.sost_down {
                    for a in self
                        .active
                        .iter_mut()
                        .filter(|a| a.ch == ch && !a.voice.released())
                    {
                        a.sost = true;
                    }
                } else if !down && s.sost_down {
                    for a in self.active.iter_mut().filter(|a| a.ch == ch && a.sost) {
                        a.sost = false;
                        if a.sost_held {
                            a.sost_held = false;
                            if s.sustain {
                                a.held = true;
                            } else {
                                a.voice.note_off();
                            }
                        }
                    }
                }
                s.sost_down = down;
            }
            67 => s.soft = val >= 64,
            68 => s.legato = val >= 64,
            70 => {
                if !s.vowel_authored {
                    s.vowel_cur = val as f32;
                }
                s.vowel_target = val as f32;
                s.vowel_authored = true;
            }
            71 => {
                s.res_target = RES_MIN_Q * (RES_MAX_Q / RES_MIN_Q).powf(v);
                if s.wah.is_none() {
                    s.wah = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    s.wah_legacy = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    s.wah_cathedral = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    if ch == 9 {
                        s.wah_r = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    }
                }
            }
            74 => {
                s.cutoff_target = WAH_MIN_HZ * (WAH_MAX_HZ / WAH_MIN_HZ).powf(v);
                if val < 127 && s.wah.is_none() {
                    s.wah = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    s.wah_legacy = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    s.wah_cathedral = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    if ch == 9 {
                        s.wah_r = Some(Biquad::lowpass(WAH_MAX_HZ, WAH_Q, sr));
                    }
                }
            }
            84 => s.porta_control = Some(val), // portamento control: one-shot glide source key
            91 => {
                s.reverb_send = v;
                s.reverb_authored = true;
            }
            93 => {
                s.chorus_send = v;
                s.chorus_authored = true;
            }
            94 => {
                s.delay_send = v;
                s.delay_authored = true;
            }
            // NRPN and RPN selects are mutually exclusive: the most recent one
            // wins and NULLS the other. This is correct MIDI semantics AND makes
            // the KILN-00034 stale-latch corruption impossible in both
            // directions — a Data Entry can only ever reach the selector the file
            // most recently chose. ferrosintesis models one NRPN block (the amp,
            // MSB 0x30); the latch is real either way so an unmodeled NRPN still
            // absorbs its Data Entry rather than leaking to the RPN path.
            98 => {
                s.nrpn_lsb = val;
                s.rpn_msb = 127;
                s.rpn_lsb = 127;
            }
            99 => {
                s.nrpn_msb = val;
                s.rpn_msb = 127;
                s.rpn_lsb = 127;
            }
            100 => {
                s.rpn_lsb = val;
                s.nrpn_msb = 127;
                s.nrpn_lsb = 127;
            }
            101 => {
                s.rpn_msb = val;
                s.nrpn_msb = 127;
                s.nrpn_lsb = 127;
            }
            120 => self.all_sound_off(ch),
            121 => self.reset_all_controllers(ch),
            123 => self.all_notes_off(ch),
            _ => {}
        }
    }

    fn bend(&mut self, ch: u8, semis: f32) {
        let s = &mut self.strips[ch as usize];
        s.bend_wheel = semis;
        let mult = 2f32.powf(semis * (s.bend_range * 0.5) / 12.0) * s.fine;
        s.bend = mult;
        for a in self.active.iter_mut().filter(|a| a.ch == ch) {
            a.voice.set_pitch(mult);
        }
    }

    fn program_change(&mut self, ch: u8, prog: u8) {
        self.strips[ch as usize].program = prog;
        self.rederive_routing_derived_state(ch);
    }

    /// Re-derive everything that depends on the channel's **drum routing**: the kit,
    /// the unauthored effect sends, and the `Drive` insert.
    ///
    /// Program Change is not the only thing that changes that routing. A GS "Use for
    /// Rhythm Part" SysEx and a GS Reset change it too, and until MM-BUG-CRUCIBLE-00030
    /// they flipped the `gs_drum` flag and nothing else — so the derived state stayed
    /// as whatever the LAST Program Change had computed under the OLD routing. Declare
    /// channel 11 a rhythm part, select program 29, then GS Reset and play: the note is
    /// melodic again, but keeps the zeroed sends and absent drive it was given as a
    /// drum part. The inverse holds too: a newly declared drum part kept melodic sends
    /// and a guitar amp insert.
    ///
    /// Both directions now route through here, so the invariant is stated once:
    /// **after any routing change, the derived state matches the routing.** Authored
    /// controller values are still preserved — the `*_authored` guards are what make
    /// this safe to re-run, since RP-015 keeps CC91/93/94 across these transitions.
    fn rederive_routing_derived_state(&mut self, ch: u8) {
        let s = &mut self.strips[ch as usize];
        let prog = s.program;
        // Drums use the best current kit by default. GM/GM2 Program Changes on
        // channel 10 are retained as authored metadata, not a compatibility
        // downgrade path — with three GM2 exceptions, a small "kit bank" ladder:
        //   40 EXACTLY — the GM2 brush kit (v0.12).
        //   24 EXACTLY — the GM2 Electronic slot (v0.18): the modeled "synth
        //                kit", V3 voices with the sampled replacement layer off.
        //   25 EXACTLY — the ORIGINAL kit (v0.19): `V1`, the pre-"kit-v2" drum
        //                voices from before the 9-10 Jul 2026 realism overhaul
        //                (no DR3 open-hat sizzle, original crash). Three-Sixty-One
        //                asks for it by name; V1 is held byte-stable by
        //                `v1_drum_render_signatures_are_stable`.
        // Any other program keeps selecting V3 (the committed showcase demo
        // authors prog 8 and must stay V3).
        //
        // A channel is a drum part if it is channel 10, OR was declared one by an XG
        // bank select (CC0 = 127) or a GS "Use for Rhythm Part" SysEx. Until 2026-07-26
        // all three decisions below keyed on `ch == 9` alone, so a declared drum channel
        // was stuck on the default kit AND read its program change as if it named a
        // MELODIC instrument — inheriting that program's chorus/delay defaults and, for
        // programs 29/30, a guitar amp insert. On a drum part the program number selects
        // a KIT; it is not an instrument at all.
        let is_drum_part = ch == 9 || s.xg_drum || s.gs_drum;
        if is_drum_part {
            s.kit = match prog {
                40 => drums::Kit::Brush,
                25 => drums::Kit::V1,
                24 => drums::Kit::Synth,
                _ => drums::Kit::V3,
            };
        }
        // Effect send levels are persistent CHANNEL state, not program state: GM /
        // MMA RP-015 keeps CC91/93/94 across a Program Change. So the program's
        // fx_profile is only a DEFAULT — it may fill a send the file never authored,
        // but it must not overwrite one the file did. This mirrors the CC0 bank arm
        // above, which already guards on the same flags; Program Change used to
        // clobber both the value and the authored flag, so a foreign file that set
        // CC93/CC94 and then changed program mid-song lost its sends
        // (MM-BUG-KILN-00033).
        let (cho, del) = if is_drum_part {
            (0.0, 0.0)
        } else {
            fx_profile(prog, s.alt_bank_value)
        };
        if !s.chorus_authored {
            s.chorus_send = cho;
        }
        if !s.delay_authored {
            s.delay_send = del;
        }
        // `!is_drum_part`: a kit-select program number must not build a guitar amp.
        // Verified safe for channel 10 by census — no album MIDI sends program 29 or 30
        // on ch 10 (the catalogue uses only 0, 1, 16, 25 and 40 there), so this cannot
        // change a committed render; it only stops a foreign XG/GS drum part from
        // picking up a Drive insert it never asked for.
        if needs_drive(prog) && !is_drum_part {
            // rebuild on a program CHANGE too: 29<->30 mid-song choreography
            // is an authored idiom, and the two programs differ in voicing,
            // stage gains and sag target (review C3). The BANK is part of the
            // identity as well — it picks the cabinet fine-structure depth —
            // so a bank change must rebuild just as a program change does.
            let alt = s.alt_bank;
            if s.drive.as_ref().map(|d| (d.program, d.alt)) != Some((prog, alt)) {
                let mut d = Drive::new(prog, alt, self.opt.sr);
                // Authored amp params are channel state (RP-015 / KILN-00033):
                // re-apply them to the rebuilt insert, seeded from the persisted
                // slew position so the rig does not ramp up from base.
                if s.amp_authored {
                    s.amp_prime_all();
                    d.apply_params(&s.amp_cur, true);
                }
                s.drive = Some(d);
            }
        } else {
            s.drive = None;
        }
    }

    /// Rebuild the program-derived drive insert after CC121.
    ///
    /// CC121 changes neither program nor bank, so the insert's *configuration* is
    /// unchanged — this only returns its internal sag/filter memory to spawn state,
    /// which is what CC121 has always done here. It no longer re-derives the effect
    /// sends: those are persistent channel state RP-015 preserves, and resetting
    /// them discarded an authored CC93/CC94 (MM-BUG-KILN-00033).
    fn rederive_program_drive(&mut self, ch: u8) {
        let ci = ch as usize;
        let prog = self.strips[ci].program;
        let bank = self.strips[ci].alt_bank_value;
        let mut drive = needs_drive(prog).then(|| Drive::new(prog, bank != 0, self.opt.sr));
        // CC121 preserves authored amp params (RP-015 nulls the selector, not the
        // values it wrote), so re-apply them to the fresh insert.
        if let Some(d) = drive.as_mut() {
            let s = &mut self.strips[ci];
            if s.amp_authored {
                s.amp_prime_all();
                d.apply_params(&s.amp_cur, true);
            }
        }
        self.strips[ci].drive = drive;
    }

    fn all_sound_off(&mut self, ch: u8) {
        if ch != 9 {
            self.strips[ch as usize].bagpipe_drone_holds = 0;
            self.strips[ch as usize].bagpipe_drone_live = false;
            self.strips[ch as usize].bagpipe_drone_hang = 0;
        }
        self.active.retain_mut(|a| {
            if a.ch == ch {
                a.voice.choke();
                false
            } else {
                true
            }
        });
    }

    fn all_notes_off(&mut self, ch: u8) {
        if ch != 9 {
            self.strips[ch as usize].bagpipe_drone_holds = 0;
        }
        let sustain = self.strips[ch as usize].sustain;
        for a in self
            .active
            .iter_mut()
            .filter(|a| a.ch == ch && !a.voice.released())
        {
            if ch != 9 && sustain {
                a.held = true;
            } else if ch != 9 && a.sost {
                a.sost_held = true;
            } else {
                a.voice.note_off();
            }
        }
    }

    /// CC121 Reset All Controllers.
    ///
    /// MMA RP-015 enumerates a SHORT list: modulation, expression, the four pedals,
    /// portamento control's pending source key, the RPN/NRPN selector (→ Null),
    /// pitch-bend position (→ centre) and channel/poly pressure. Everything else on
    /// the channel is explicitly preserved — volume, pan, program, bank, the effect
    /// sends, the CC70-79 sound controllers, and the VALUES an RPN wrote. That last
    /// one is the subtle part: RAC nulls the RPN *selector*, it does not revert what
    /// the selector set, so the pitch-bend range and fine tuning survive
    /// (MM-BUG-KILN-00033).
    fn reset_all_controllers(&mut self, ch: u8) {
        let ci = ch as usize;
        let s = &mut self.strips[ci];
        // Pitch bend returns to CENTRE — which is the channel's fine tuning, not
        // 1.0. `fine` (RPN 0,1) and `bend_range` (RPN 0,0) are RPN-set values and
        // survive, so a later bend still spans the range the file asked for.
        s.bend_wheel = 0.0;
        s.bend = s.fine;
        s.rpn_msb = 127;
        s.rpn_lsb = 127;
        s.data_msb = 0;
        // RP-015's "RPN/NRPN selector" is both latches; the NRPN half exists now
        // (the amp block), so null it too. The amp PARAMETER VALUES are preserved
        // — RAC nulls the selector, not what a selector wrote.
        s.nrpn_msb = 127;
        s.nrpn_lsb = 127;
        s.nrpn_data_msb = 0;
        s.porta_on = false;
        s.last_freq = None;
        s.porta_control = None; // pending CC84 source is cleared; bank_lsb persists (not a RAC controller)
        s.sustain = false;
        s.sost_down = false;
        s.soft = false;
        s.legato = false;
        s.at_authored = false;
        s.at_target = 0.0;
        s.at_cur = 0.0;
        s.at_gain = 1.0;
        s.mod_target = 0.0;
        s.mod_cur = 0.0;
        s.mod_engaged = false;
        s.mod_authored = false;
        s.vib_mult = 1.0;
        s.organ_trem_phase = 0.0;
        s.expr_target = 1.0;
        s.expr = 1.0;
        s.expr_authored = false;
        s.breath_authored = false;
        s.breath_target = 1.0;
        s.breath = 1.0;
        // Deliberately NOT reset, because RP-015 preserves them: the CC5 portamento
        // TIME (only the CC65 switch resets), the CC70 vowel / CC71 resonance /
        // CC74 cutoff sound controllers together with the wah filters that realise
        // them, and the CC93/94 effect sends.
        self.rederive_program_drive(ch);

        let program = self.strips[ci].program;
        let bend = self.strips[ci].bend;
        let vowel = self.strips[ci].vowel_cur;
        let choir_vowel = matches!(program, 52..=54).then(|| vowel_at(vowel));
        for a in self.active.iter_mut().filter(|a| a.ch == ch) {
            if a.held || a.sost_held {
                a.voice.note_off();
            }
            a.held = false;
            a.sost = false;
            a.sost_held = false;
            a.glide = None;
            // CC121 also drops any per-note key-pressure lane back to its
            // exact spawn defaults (all no-ops).
            a.poly_authored = false;
            a.poly_target = 0.0;
            a.poly_cur = 0.0;
            a.poly_phase = 0.0;
            a.poly_mult = 1.0;
            a.poly_gain = 1.0;
            // Centred bend, but still scaled by the preserved fine tuning.
            a.voice.set_pitch(bend);
            if organ_leslie_family(a.program, a.alt_bank_value) {
                let (rate, depth) = voices::organ_trem_base(a.program);
                a.voice.set_trem(rate, depth);
            }
            if let Some((freqs, qs, gains)) = choir_vowel {
                a.voice.set_vowel(freqs, qs, gains);
            }
        }
    }

    pub(crate) fn render_block_add(&mut self, n: usize, out: &mut [f32]) {
        debug_assert!(n <= BLOCK);
        debug_assert!(out.len() >= n * 2);
        // TREM1 sample clock: events for this block were already applied at
        // now == block start; advance for the next block's events.
        self.now += n as u64;
        let sr = self.opt.sr;

        self.tick_bagpipe_drone_latch();
        self.rebuild_voice_buckets();
        self.apply_mod_wheel_leslie_and_vibrato(n, sr);
        self.apply_cathedral_organ_wind(n, sr);
        self.apply_vowel_aftertouch_breath_and_glide(n, sr);
        self.render_melodic_voices(n);
        self.mix_channel_strips(n, sr);
        self.render_and_mix_drums(n, sr);
        self.apply_master_buses(n);
        self.accumulate_output(n, out);
    }

    /// Rebuild the per-channel voice index buckets for this block.
    ///
    /// Filled by scanning `self.active` FRONT TO BACK, so each bucket lists its
    /// channel's voices in `active` index order — exactly the order the
    /// `active.iter_mut().filter(|a| a.ch == ch)` scans these buckets replace
    /// used to yield. That is what keeps the render bit-identical: the visit
    /// order (and hence every summation order downstream) is unchanged.
    ///
    /// Valid for the whole control prologue that follows: `self.active` is
    /// neither pushed to (note-on handling runs outside `render_block_add`) nor
    /// retained (`render_melodic_voices` and the drum pass both run after)
    /// between here and the end of the last control phase — so one build per
    /// block is correct and no phase may rebuild.
    ///
    /// Allocation-free on the render path: `clear()` keeps each bucket's
    /// capacity, so after the first blocks nothing here touches the allocator.
    fn rebuild_voice_buckets(&mut self) {
        for bucket in self.voice_by_ch.iter_mut() {
            bucket.clear();
        }
        for (i, a) in self.active.iter().enumerate() {
            self.voice_by_ch[a.ch as usize].push(i);
        }
    }

    /// Advance the CC1 modulation lane on every melodic strip: Leslie
    /// rate/depth for the organ family, coherent pitch vibrato for the
    /// vibrato family.
    fn apply_mod_wheel_leslie_and_vibrato(&mut self, n: usize, sr: f32) {
        for (ci, strip) in self.strips.iter_mut().enumerate() {
            strip.mod_cur += self.expr_smooth * (strip.mod_target - strip.mod_cur);
            let on = strip.mod_cur > 1e-3;
            let leslie_program = self.voice_by_ch[ci]
                .iter()
                .map(|&i| &self.active[i])
                .find(|a| organ_leslie_family(a.program, a.alt_bank_value))
                .map(|a| a.program)
                .or_else(|| {
                    (strip.mod_authored && organ_leslie_family(strip.program, strip.alt_bank_value))
                        .then_some(strip.program)
                });
            let active_pitch_vibrato = self.voice_by_ch[ci]
                .iter()
                .map(|&i| &self.active[i])
                .any(|a| cc1_pitch_vibrato_target(a.program, a.alt));
            let pending_pitch_vibrato = vibrato_family(strip.program);
            if ci == 9 || (!on && !strip.mod_engaged && leslie_program.is_none()) {
                continue;
            }
            let m = if on { strip.mod_cur } else { 0.0 };
            let mut engaged = false;
            if let Some(program) = leslie_program {
                let (base_rate, base_depth) = voices::organ_trem_base(program);
                if !strip.mod_engaged || strip.leslie_depth <= 0.0 {
                    strip.leslie_rate = if strip.mod_authored {
                        LESLIE_SLOW_HZ
                    } else {
                        base_rate
                    };
                    strip.leslie_depth = base_depth;
                }
                let target_rate = if strip.mod_authored {
                    LESLIE_SLOW_HZ + (LESLIE_FAST_HZ - LESLIE_SLOW_HZ) * m
                } else {
                    base_rate
                };
                let target_depth = base_depth + LESLIE_DEPTH_ADD * m;
                strip.leslie_rate += self.leslie_k * (target_rate - strip.leslie_rate);
                strip.leslie_depth += self.leslie_k * (target_depth - strip.leslie_depth);
                for &i in &self.voice_by_ch[ci] {
                    let a = &mut self.active[i];
                    if !organ_leslie_family(a.program, a.alt_bank_value) {
                        continue;
                    }
                    a.voice.set_trem(strip.leslie_rate, strip.leslie_depth);
                }
                engaged |= strip.mod_authored || on || (strip.leslie_rate - base_rate).abs() > 0.01;
            }
            if (on || strip.mod_engaged) && (active_pitch_vibrato || pending_pitch_vibrato) {
                strip.vib_phase += TAU * VIB_RATE_HZ * n as f32 / sr;
                if strip.vib_phase > TAU {
                    strip.vib_phase -= TAU;
                }
                let factor = 2f32.powf(m * VIB_DEPTH_CENTS / 1200.0 * strip.vib_phase.sin());
                strip.vib_mult = factor;
                let mult = strip.bend * factor;
                for &i in &self.voice_by_ch[ci] {
                    let a = &mut self.active[i];
                    // Alt-bank strings/choir restore v0.9 CC1 semantics PER HELD
                    // voice (a.alt is the spawn-time bank): strings deepen their
                    // own decorrelated per-layer vibrato via set_vib (not the
                    // coherent set_pitch warble); choir gets no CC1. Every default
                    // voice takes the identical set_pitch path, so a channel with
                    // no alt voices is byte-for-byte unchanged.
                    if a.alt && matches!(a.program, 48..=51) {
                        let base = crate::altbank::strings_vib_base(a.program);
                        a.voice.set_vib(base + (ST_CC1_VIB_DEPTH - base) * m);
                    } else if a.alt && matches!(a.program, 52..=54) {
                        // alt-bank choir: no CC1 pitch vibrato (v0.9)
                    } else if a.alt && a.program == 22 {
                        // alt-bank 22 delegates to the default voice, but keeps
                        // the alt bank's spawn-time CC1 semantics.
                    } else if vibrato_family(a.program) {
                        a.voice.set_pitch(mult);
                    }
                }
                engaged |= on;
            } else if !active_pitch_vibrato {
                strip.vib_mult = 1.0;
            }
            strip.mod_engaged = engaged;
        }
    }

    /// Drive the cathedral-organ wind chest for every melodic strip.
    ///
    /// The cathedral organ breathes as one wind chest. Pressure and the
    /// signed tremulant sample are channel-global, while each rank applies
    /// its own sensitivity inside the voice. Legacy GM19 remains on the
    /// Leslie path above.
    fn apply_cathedral_organ_wind(&mut self, n: usize, sr: f32) {
        for (ci, strip) in self.strips.iter_mut().enumerate() {
            if ci == 9 {
                continue;
            }
            let cat_notes = self.voice_by_ch[ci]
                .iter()
                .map(|&i| &self.active[i])
                .filter(|a| cathedral_organ(a.program, a.alt_bank_value))
                .count();
            let load = cat_notes.saturating_sub(1).min(9) as f32 / 9.0;
            let target = load;
            let tau = if target > strip.organ_wind {
                0.35
            } else {
                1.20
            };
            let k = 1.0 - (-(BLOCK as f32) / (tau * sr)).exp();
            strip.organ_wind += k * (target - strip.organ_wind);
            let trem = if cat_notes > 0 && strip.mod_cur > 1e-4 {
                strip.organ_trem_phase += TAU * 5.5 * n as f32 / sr;
                if strip.organ_trem_phase > TAU {
                    strip.organ_trem_phase -= TAU;
                }
                strip.organ_trem_phase.sin() * strip.mod_cur
            } else {
                0.0
            };
            // Reed-rasp drive from the swell (CC11). Opt-in: 0 unless CC11 authored.
            let drive = if strip.expr_authored {
                ((strip.expr - ORGAN_SWELL_KNEE) / (1.0 - ORGAN_SWELL_KNEE))
                    .clamp(0.0, 1.0)
                    .powf(ORGAN_SWELL_GAMMA)
            } else {
                0.0
            };
            for &i in &self.voice_by_ch[ci] {
                let a = &mut self.active[i];
                if !cathedral_organ(a.program, a.alt_bank_value) {
                    continue;
                }
                a.voice.set_organ_pressure(strip.organ_wind, trem);
                a.voice.set_organ_swell(drive);
            }
        }
    }

    /// Advance the per-strip expression lanes that reach into held notes:
    /// CC70 vowel, poly (key) and channel aftertouch, the brass/reed/flue
    /// breath seams, and portamento glides.
    fn apply_vowel_aftertouch_breath_and_glide(&mut self, n: usize, sr: f32) {
        for (ci, strip) in self.strips.iter_mut().enumerate() {
            if ci == 9 {
                continue;
            }
            if strip.vowel_authored && vowel_family(strip.program) {
                strip.vowel_cur += self.expr_smooth * (strip.vowel_target - strip.vowel_cur);
                let (f, q, g) = vowel_at(strip.vowel_cur);
                for &i in &self.voice_by_ch[ci] {
                    self.active[i].voice.set_vowel(f, q, g);
                }
            }
            // Poly (key) aftertouch: advance each authored note's private
            // pressure lane first, so the channel-AT and glide sites below can
            // compose its factor in. Unauthored notes keep poly_mult/poly_gain
            // at exactly 1.0 (a bit-exact no-op).
            let mut any_poly = false;
            for &i in &self.voice_by_ch[ci] {
                let a = &mut self.active[i];
                if !a.poly_authored {
                    continue;
                }
                a.poly_cur += self.expr_smooth * (a.poly_target - a.poly_cur);
                a.poly_gain = 10f32.powf(a.poly_cur * AT_GAIN_DB / 20.0);
                a.poly_phase += TAU * AT_VIB_RATE_HZ * n as f32 / sr;
                if a.poly_phase > TAU {
                    a.poly_phase -= TAU;
                }
                a.poly_mult = 2f32.powf(a.poly_cur * AT_VIB_CENTS / 1200.0 * a.poly_phase.sin());
                any_poly = true;
            }
            let channel_at = strip.at_authored && aftertouch_family(strip.program);
            let mut at_vib = 1.0f32;
            if channel_at {
                strip.at_cur += self.expr_smooth * (strip.at_target - strip.at_cur);
                strip.at_gain = 10f32.powf(strip.at_cur * AT_GAIN_DB / 20.0);
                strip.at_phase += TAU * AT_VIB_RATE_HZ * n as f32 / sr;
                if strip.at_phase > TAU {
                    strip.at_phase -= TAU;
                }
                at_vib = 2f32.powf(strip.at_cur * AT_VIB_CENTS / 1200.0 * strip.at_phase.sin());
                // `!a.is_drum`: an XG/GS drum channel on this strip keeps its at_gain
                // (computed above) but its percussion voices must not be pitch-bent —
                // the same reason ch9 skips this whole block (ci==9 continues earlier).
                for &i in &self.voice_by_ch[ci] {
                    let a = &mut self.active[i];
                    if a.is_drum {
                        continue;
                    }
                    // Alt strings/choir take CC1 via set_vib, so the coherent
                    // vib_mult factor must not compose into their aftertouch
                    // pitch (v0.9 kept 48-54 out of vibrato_family; aftertouch
                    // still applies). Default voices are byte-for-byte unchanged.
                    let vm = if a.alt && (matches!(a.program, 48..=54) || a.program == 22) {
                        1.0
                    } else {
                        strip.vib_mult
                    };
                    a.voice.set_pitch(strip.bend * vm * at_vib * a.poly_mult);
                }
            }
            // Poly-only channels: no channel-AT loop ran, so authored notes
            // apply their own pitch factor here (glides are handled below).
            if any_poly && !channel_at {
                for &i in &self.voice_by_ch[ci] {
                    let a = &mut self.active[i];
                    if !(a.poly_authored && a.glide.is_none()) {
                        continue;
                    }
                    let vm = if a.alt && (matches!(a.program, 48..=54) || a.program == 22) {
                        1.0
                    } else {
                        strip.vib_mult
                    };
                    a.voice.set_pitch(strip.bend * vm * a.poly_mult);
                }
            }
            // BR9: brass breath — CC11 expression opens the timbre, channel
            // aftertouch adds flutter growl. A no-op on every 56-63 channel that
            // authors neither (only The Iron Tide uses brass, waived §4.3).
            if matches!(strip.program, 56..=63) {
                // CC2 breath composes into the pressure (1.0 = no-op) so a
                // breath-authored brass line also opens/closes its timbre.
                let p = (strip.expr * strip.breath).sqrt().min(1.3);
                let g = if strip.at_authored { strip.at_cur } else { 0.0 };
                for &i in &self.voice_by_ch[ci] {
                    self.active[i].voice.set_breath(p, g);
                }
            }
            // RD9 (§2.8.3): the reed breath seam, AUTHORED-only (§2.8.2 — an
            // unauthored reed channel must render exactly as before; contrast
            // the unconditional brass site above). Aftertouch rides along as
            // the growl arg, reserved for the §2.8.4 rasp stage.
            if matches!(strip.program, 64..=71 | 109 | 111)
                && (strip.expr_authored || strip.breath_authored || strip.at_authored)
            {
                let p = (strip.expr * strip.breath).sqrt().min(1.0);
                let g = if strip.at_authored { strip.at_cur } else { 0.0 };
                for &i in &self.voice_by_ch[ci] {
                    self.active[i].voice.set_breath(p, g);
                }
            }
            // WD9 (§2.8.5.3): the flue breath seam — same authored-only gate,
            // same lanes. `Wind` has no growl consumer, so nothing rides the
            // second arg. An unauthored flue channel never reaches here and
            // renders controller-identically to before.
            if matches!(strip.program, 72..=79)
                && (strip.expr_authored || strip.breath_authored || strip.at_authored)
            {
                let p = (strip.expr * strip.breath).sqrt().min(1.0);
                for &i in &self.voice_by_ch[ci] {
                    self.active[i].voice.set_breath(p, 0.0);
                }
            }
            for &i in &self.voice_by_ch[ci] {
                let a = &mut self.active[i];
                if let Some((semis, k)) = &mut a.glide {
                    *semis -= *k * *semis;
                    let done = semis.abs() < 0.005;
                    let gm = if done { 1.0 } else { 2f32.powf(*semis / 12.0) };
                    // Same alt-orchestral CC1 exclusion as the aftertouch site.
                    let vm = if a.alt && (matches!(a.program, 48..=54) || a.program == 22) {
                        1.0
                    } else {
                        strip.vib_mult
                    };
                    a.voice
                        .set_pitch(strip.bend * vm * at_vib * a.poly_mult * gm);
                    if done {
                        a.glide = None;
                    }
                }
            }
        }
    }

    /// Clear the per-channel accumulation buffers and render every melodic
    /// (non-drum) voice into them, retiring the voices that have finished.
    fn render_melodic_voices(&mut self, n: usize) {
        for buf in self.ch_buf.iter_mut() {
            buf[..n].fill(0.0);
        }
        for buf in self.legacy_buf.iter_mut() {
            buf[..n].fill(0.0);
        }
        for buf in self.cathedral_buf.iter_mut() {
            buf[..n].fill(0.0);
        }
        self.stats.max_polyphony = self.stats.max_polyphony.max(self.active.len());
        self.active.retain_mut(|a| {
            if a.is_drum {
                return true; // drums render in the dedicated pass below
            }
            self.scratch[..n].fill(0.0);
            let alive = a.voice.render(&mut self.scratch[..n]);
            // Per-note poly-AT gain lift; multiplies UNDER the strip's channel
            // at_gain so channel and key pressure add in dB. Skipped entirely
            // (1.0) for notes that never authored poly AT.
            if a.poly_gain != 1.0 {
                for x in self.scratch[..n].iter_mut() {
                    *x *= a.poly_gain;
                }
            }
            let buf = if cathedral_organ(a.program, a.alt_bank_value) {
                &mut self.cathedral_buf[a.ch as usize]
            } else if a.program == 19 && a.alt {
                &mut self.legacy_buf[a.ch as usize]
            } else {
                &mut self.ch_buf[a.ch as usize]
            };
            for (dst, src) in buf[..n].iter_mut().zip(self.scratch[..n].iter()) {
                *dst += *src;
            }
            alive
        });
    }

    /// Clear the master mix and the effect sends, then run each channel
    /// strip: insert effects, wah, CC7/CC10 slew, and the pan/level/send
    /// matrix into the mix and the send buses.
    fn mix_channel_strips(&mut self, n: usize, sr: f32) {
        self.mix_l[..n].fill(0.0);
        self.mix_r[..n].fill(0.0);
        self.send_rev[..n].fill(0.0);
        self.send_cathedral[..n].fill(0.0);
        self.send_cho[..n].fill(0.0);
        self.send_del[..n].fill(0.0);
        self.send_sym[..n].fill(0.0);
        self.send_sym_gtr[..n].fill(0.0);
        self.send_sym_sitar[..n].fill(0.0);
        self.send_room[..n].fill(0.0);
        for (ci, strip) in self.strips.iter_mut().enumerate() {
            let buf = &mut self.ch_buf[ci];
            let legacy = &mut self.legacy_buf[ci];
            let cathedral = &mut self.cathedral_buf[ci];
            // Per-block denormal flush (MM-BUG-KILN-00027) for the strip-owned
            // CC74 filters: once authored they run every block, voices or not,
            // and park below the floor after the last note. `wah_r` is the ch-9
            // drum pair's second filter, run later in `render_and_mix_drums`.
            for wah in [
                &mut strip.wah,
                &mut strip.wah_legacy,
                &mut strip.wah_cathedral,
                &mut strip.wah_r,
            ]
            .into_iter()
            .flatten()
            {
                wah.flush();
            }
            if let Some((xg, wet)) = &mut strip.xg_insert {
                // XG Amp-Simulator insertion REPLACES the program drive on this
                // channel (one amp+cabinet, never two in series). Dry/Wet blend
                // at BASE rate — outside Drive's internal 2x — so Drive::process
                // stays byte-for-byte the program-drive path: copy the dry
                // block, process 100% wet, then interpolate by the weight.
                let wet = *wet;
                if wet >= 1.0 {
                    xg.process(&mut buf[..n]);
                } else {
                    let mut dry = [0f32; BLOCK];
                    dry[..n].copy_from_slice(&buf[..n]);
                    xg.process(&mut buf[..n]);
                    for (b, d) in buf[..n].iter_mut().zip(&dry[..n]) {
                        *b = *d * (1.0 - wet) + *b * wet;
                    }
                }
            } else if let Some(drive) = &mut strip.drive {
                if strip.amp_authored {
                    // Advance each knob toward its authored target at block rate
                    // (snap on first authoring), then apply the offsets in place.
                    for i in 0..AMP_PARAM_COUNT {
                        let target = strip.amp_params[i] as f32;
                        if strip.amp_primed[i] {
                            strip.amp_cur[i] += self.wah_smooth * (target - strip.amp_cur[i]);
                        } else {
                            strip.amp_cur[i] = target;
                            strip.amp_primed[i] = true;
                        }
                    }
                    drive.apply_params(&strip.amp_cur, false);
                }
                drive.process(&mut buf[..n]);
            }
            if let Some(wah) = &mut strip.wah {
                strip.cutoff += self.wah_smooth * (strip.cutoff_target - strip.cutoff);
                strip.res += self.wah_smooth * (strip.res_target - strip.res);
                wah.retune_lowpass(strip.cutoff, strip.res, sr);
                if ci != 9 {
                    for x in buf[..n].iter_mut() {
                        *x = wah.process(*x);
                    }
                }
            }
            if let Some(wah) = &mut strip.wah_legacy {
                wah.retune_lowpass(strip.cutoff, strip.res, sr);
                for x in legacy[..n].iter_mut() {
                    *x = wah.process(*x);
                }
            }
            if let Some(wah) = &mut strip.wah_cathedral {
                wah.retune_lowpass(strip.cutoff, strip.res, sr);
                for x in cathedral[..n].iter_mut() {
                    *x = wah.process(*x);
                }
            }
            // CC7 volume / CC10 pan (prime-on-first-block): snap to the authored
            // target on the first block after authoring — reproducing MIDI
            // last-write-wins for a same-tick burst and the old instant set — then
            // one-pole slew toward it thereafter, so a fade or pan sweep ramps rather
            // than stepping at block boundaries. haas_delay is derived once per block
            // from the slewed pan (single source of truth; tracks the sweep). A
            // channel that never authors CC7/CC10 keeps its default byte-for-byte.
            if strip.volume_authored {
                if strip.volume_primed {
                    strip.volume += self.expr_smooth * (strip.volume_target - strip.volume);
                } else {
                    strip.volume = strip.volume_target;
                    strip.volume_primed = true;
                }
            }
            if strip.pan_authored {
                if strip.pan_primed {
                    strip.pan += self.expr_smooth * (strip.pan_target - strip.pan);
                } else {
                    strip.pan = strip.pan_target;
                    strip.pan_primed = true;
                }
                strip.haas_delay = 0.005 * sr * (strip.pan - 0.5).abs() * 2.0;
            }
            strip.expr += self.expr_smooth * (strip.expr_target - strip.expr);
            if strip.breath_authored {
                strip.breath += self.expr_smooth * (strip.breath_target - strip.breath);
            }
            // SC-55-referenced per-program loudness trim (melodic channels only;
            // ch9 drums are key-indexed and levelled by kit_balance()). `g` feeds
            // both the dry mix and every FX send below, so this scales the whole
            // voice together — pure level, timbre- and wet/dry-neutral.
            let trim = if ci != 9 {
                program_trim_lin(strip.program)
            } else {
                1.0
            };
            let g = strip.volume * strip.expr * strip.at_gain * strip.breath * trim;
            if g < 1e-6 {
                continue;
            }
            let theta = strip.pan * FRAC_PI_2;
            let (gl, gr) = (g * theta.cos(), g * theta.sin());
            let rs = strip.reverb_send * 0.9;
            let is_piano = ci != 9 && voices::is_acoustic_piano(strip.program);
            let is_ac_gtr = ci != 9 && matches!(strip.program, 24 | 25);
            let is_sitar = ci != 9 && strip.program == 104;
            if is_sitar {
                self.sitar_seen = true;
            }
            let haas = strip.haas_delay;
            let legacy_cho = if strip.chorus_authored {
                strip.chorus_send
            } else {
                0.20
            };
            let legacy_del = if strip.delay_authored {
                strip.delay_send
            } else {
                0.0
            };
            let cathedral_cho = if strip.chorus_authored {
                strip.chorus_send
            } else {
                0.0
            };
            let cathedral_del = if strip.delay_authored {
                strip.delay_send
            } else {
                0.0
            };
            for i in 0..n {
                let (ordinary_x, legacy_x, cathedral_x) = (buf[i], legacy[i], cathedral[i]);
                let x = ordinary_x + legacy_x + cathedral_x;
                strip.haas.push(x);
                let (xl, xr) = if haas < 1.0 {
                    (x, x)
                } else if strip.pan < 0.5 {
                    (x, strip.haas.tap(haas))
                } else {
                    (strip.haas.tap(haas), x)
                };
                self.mix_l[i] += xl * gl;
                self.mix_r[i] += xr * gr;
                let (ordinary_s, legacy_s, cathedral_s) =
                    (ordinary_x * g, legacy_x * g, cathedral_x * g);
                let xs = ordinary_s + legacy_s + cathedral_s;
                self.send_rev[i] += (ordinary_s + legacy_s) * rs;
                self.send_cathedral[i] += cathedral_s * rs;
                self.send_cho[i] += ordinary_s * strip.chorus_send
                    + legacy_s * legacy_cho
                    + cathedral_s * cathedral_cho;
                self.send_del[i] += ordinary_s * strip.delay_send
                    + legacy_s * legacy_del
                    + cathedral_s * cathedral_del;
                if is_piano {
                    self.send_sym[i] += xs;
                }
                if is_ac_gtr {
                    self.send_sym_gtr[i] += xs;
                }
                if is_sitar {
                    self.send_sym_sitar[i] += xs;
                }
            }
        }
    }

    /// Render the drum voices - ch9's main kit and any XG/GS drum channel -
    /// and fold the main drum bus through its wah pair and master gain into
    /// the mix.
    fn render_and_mix_drums(&mut self, n: usize, sr: f32) {
        self.drum_l[..n].fill(0.0);
        self.drum_r[..n].fill(0.0);
        self.active.retain_mut(|a| {
            if !a.is_drum {
                return true;
            }
            self.scratch[..n].fill(0.0);
            let alive = a.voice.render(&mut self.scratch[..n]);
            // Per-key placement, shared by both drum paths: the channel's own
            // pan offset (strips[9] for the main kit, since a.ch == 9 there) plus
            // the per-key kit map and balance.
            let s = &self.strips[a.ch as usize];
            let pan = (drum_pan(a.key) + (s.pan - 0.5)).clamp(0.0, 1.0);
            let theta = pan * FRAC_PI_2;
            let bal = kit_balance(a.key);
            let (ul, ur) = (theta.cos() * bal, theta.sin() * bal);
            if a.ch == 9 {
                // Main kit: accumulate raw into the drum bus; the shared wah +
                // bus master g9 are applied after the closure (path unchanged).
                for i in 0..n {
                    self.drum_l[i] += self.scratch[i] * ul;
                    self.drum_r[i] += self.scratch[i] * ur;
                }
            } else {
                // XG/GS drum channel: scaled by its OWN gain straight into the master
                // mix — bypassing ch9's bus master and wah — with its own CC91
                // reverb and a room send controlled by its own authored CC91.
                // The `(scratch*ul)*gc` association mirrors the ch9 path, so a
                // single hit is byte-equal to the same hit on ch9 (gc == g9 when
                // the strips match).
                let gc = s.volume * s.expr * s.at_gain * s.breath * DRUM_FORWARD;
                if gc >= 1e-6 {
                    let rs = s.reverb_send * 0.9;
                    let room_send = s.drum_room_send();
                    for i in 0..n {
                        let xl = (self.scratch[i] * ul) * gc;
                        let xr = (self.scratch[i] * ur) * gc;
                        self.mix_l[i] += xl;
                        self.mix_r[i] += xr;
                        let mono = 0.5 * (xl + xr);
                        self.send_rev[i] += mono * rs;
                        self.send_room[i] += mono * room_send;
                    }
                }
            }
            alive
        });
        let s9 = &mut self.strips[9];
        if let Some(wl) = &mut s9.wah {
            for x in self.drum_l[..n].iter_mut() {
                *x = wl.process(*x);
            }
        }
        if let Some(wr) = &mut s9.wah_r {
            wr.retune_lowpass(s9.cutoff, s9.res, sr);
            for x in self.drum_r[..n].iter_mut() {
                *x = wr.process(*x);
            }
        }
        let g9 = s9.volume * s9.expr * s9.at_gain * s9.breath * DRUM_FORWARD;
        if g9 >= 1e-6 {
            let rs = s9.reverb_send * 0.9;
            let room_send = s9.drum_room_send();
            for i in 0..n {
                let (xl, xr) = (self.drum_l[i] * g9, self.drum_r[i] * g9);
                self.mix_l[i] += xl;
                self.mix_r[i] += xr;
                let mono = 0.5 * (xl + xr);
                self.send_rev[i] += mono * rs;
                self.send_room[i] += mono * room_send;
            }
        }
    }

    /// Run the shared buses - sympathetic resonance, chorus, echo, drum
    /// room, reverb, cathedral - and the bus-glue compressor.
    fn apply_master_buses(&mut self, n: usize) {
        self.symp.process(
            &self.send_sym[..n],
            &mut self.mix_l[..n],
            &mut self.mix_r[..n],
        );
        if self.opt.gtr_symp_on {
            self.gtr_symp.process(
                &self.send_sym_gtr[..n],
                &mut self.mix_l[..n],
                &mut self.mix_r[..n],
            );
        }
        // tarab bus: gated on `sitar_seen` (not just the option) so a render
        // with no program 104 anywhere never even touches the combs
        if self.opt.sitar_symp_on && self.sitar_seen {
            self.sitar_symp.process(
                &self.send_sym_sitar[..n],
                &mut self.mix_l[..n],
                &mut self.mix_r[..n],
            );
        }
        self.chorus.process(
            &self.send_cho[..n],
            &mut self.mix_l[..n],
            &mut self.mix_r[..n],
        );
        if let Some(echo) = &mut self.echo {
            echo.process(
                &self.send_del[..n],
                &mut self.mix_l[..n],
                &mut self.mix_r[..n],
            );
        }
        if self.opt.drum_room_on {
            self.drum_room.process(
                &self.send_room[..n],
                &mut self.mix_l[..n],
                &mut self.mix_r[..n],
            );
        }
        // Per-block denormal flush (MM-BUG-KILN-00027). The hall's own tanks
        // flush, but this send high-pass sits in front of them: left unflushed
        // it parked after every song and fed a subnormal stream into the
        // pre-delay line and early-reflection taps for the rest of the session.
        self.rev_hp.flush();
        for x in self.send_rev[..n].iter_mut() {
            *x = self.rev_hp.process(*x);
        }
        self.reverb.process(
            &self.send_rev[..n],
            &mut self.mix_l[..n],
            &mut self.mix_r[..n],
        );
        #[cfg(test)]
        if self.cathedral_send_hpf_on {
            for x in self.send_cathedral[..n].iter_mut() {
                *x = self.cathedral_send_hp.process(*x);
            }
        }
        self.cathedral.process(
            &self.send_cathedral[..n],
            &mut self.mix_l[..n],
            &mut self.mix_r[..n],
        );
        #[cfg(test)]
        {
            self.stats.cathedral_return_peak = self
                .stats
                .cathedral_return_peak
                .max(self.cathedral.debug_return_peak());
        }
        self.glue
            .process(&mut self.mix_l[..n], &mut self.mix_r[..n]);
    }

    /// Test-only: visit the state of everything that runs on every block
    /// whether or not a voice is sounding — the master buses and each strip's
    /// inserts and filters. Voices are excluded: they die and are dropped.
    #[cfg(test)]
    fn visit_always_running_state(&self, visit: &mut dyn FnMut(&'static str, f32)) {
        for x in self.rev_hp.debug_state() {
            visit("reverb send high-pass", x);
        }
        self.reverb.visit_state(visit);
        self.drum_room.visit_state(visit);
        self.cathedral.visit_state(visit);
        for &x in self.chorus.dl.debug_buf() {
            visit("chorus line", x);
        }
        if let Some(echo) = &self.echo {
            for &x in echo.left.debug_buf().iter().chain(echo.right.debug_buf()) {
                visit("echo line", x);
            }
            visit("echo damp", echo.lp_l.debug_state());
            visit("echo damp", echo.lp_r.debug_state());
        }
        for symp in [&self.symp, &self.gtr_symp, &self.sitar_symp] {
            for x in symp.hp.debug_state() {
                visit("sympathetic high-pass", x);
            }
            for (line, _, damp) in &symp.combs {
                visit("sympathetic damp", damp.debug_state());
                for &x in line.debug_buf() {
                    visit("sympathetic comb line", x);
                }
            }
        }
        visit("glue envelope", self.glue.env);
        for x in self
            .glue
            .shelf_l
            .debug_state()
            .into_iter()
            .chain(self.glue.shelf_r.debug_state())
        {
            visit("glue shelf", x);
        }
        for strip in &self.strips {
            if let Some(drive) = &strip.drive {
                drive.visit_state(visit);
            }
            if let Some((drive, _)) = &strip.xg_insert {
                drive.visit_state(visit);
            }
            for wah in [
                &strip.wah,
                &strip.wah_legacy,
                &strip.wah_cathedral,
                &strip.wah_r,
            ]
            .into_iter()
            .flatten()
            {
                for x in wah.debug_state() {
                    visit("strip CC74 filter", x);
                }
            }
            for &x in strip.haas.debug_buf() {
                visit("strip Haas line", x);
            }
        }
    }

    /// Add the finished stereo mix into the caller's output buffer and
    /// track the render peak.
    fn accumulate_output(&mut self, n: usize, out: &mut [f32]) {
        for i in 0..n {
            out[i * 2] += self.mix_l[i];
            out[i * 2 + 1] += self.mix_r[i];
            let m = self.mix_l[i].abs().max(self.mix_r[i].abs());
            if m > self.stats.peak {
                self.stats.peak = m;
            }
        }
    }
}

pub fn render(song: &Song, opt: &Options) -> (Vec<f32>, Stats) {
    render_buses_with_progress(song, opt, true, true, true, &mut |_| {})
}

pub fn render_with_progress(
    song: &Song,
    opt: &Options,
    on_progress: &mut dyn FnMut(Progress),
) -> (Vec<f32>, Stats) {
    render_buses_with_progress(song, opt, true, true, true, on_progress)
}

/// The A/B oracle entry point (19, 32a): render the same song with the
/// guitar-sympathetic, drum-room, or sitar-tarab bus disabled. The public
/// `render` always enables all three — no shipped knob — so this is
/// test-only.
#[cfg(test)]
pub(crate) fn render_buses(
    song: &Song,
    opt: &Options,
    gtr_symp_on: bool,
    drum_room_on: bool,
    sitar_symp_on: bool,
) -> (Vec<f32>, Stats) {
    render_buses_with_progress(
        song,
        opt,
        gtr_symp_on,
        drum_room_on,
        sitar_symp_on,
        &mut |_| {},
    )
}

pub(crate) fn render_buses_with_progress(
    song: &Song,
    opt: &Options,
    gtr_symp_on: bool,
    drum_room_on: bool,
    sitar_symp_on: bool,
    on_progress: &mut dyn FnMut(Progress),
) -> (Vec<f32>, Stats) {
    let total = render_sample_count(song, opt);
    let mut out = vec![0f32; total * 2]; // interleaved stereo
    let stats = drive_render(
        song,
        opt,
        gtr_symp_on,
        drum_room_on,
        sitar_symp_on,
        on_progress,
        |core, block_start, n| {
            core.render_block_add(n, &mut out[block_start * 2..(block_start + n) * 2]);
            Ok::<(), std::convert::Infallible>(())
        },
    )
    .expect("an infallible render sink cannot fail");
    (out, stats)
}

pub(crate) fn render_sample_count(song: &Song, opt: &Options) -> usize {
    ((song.seconds + opt.tail as f64) * opt.sr as f64) as usize
}

pub(crate) fn render_stream_with_progress(
    song: &Song,
    opt: &Options,
    on_progress: &mut dyn FnMut(Progress),
    emit: &mut dyn FnMut(&[f32]) -> std::io::Result<()>,
) -> std::io::Result<Stats> {
    let mut block = [0.0f32; BLOCK * 2];
    drive_render(song, opt, true, true, true, on_progress, |core, _, n| {
        block[..n * 2].fill(0.0);
        core.render_block_add(n, &mut block[..n * 2]);
        emit(&block[..n * 2])
    })
}

fn drive_render<E>(
    song: &Song,
    opt: &Options,
    gtr_symp_on: bool,
    drum_room_on: bool,
    sitar_symp_on: bool,
    on_progress: &mut dyn FnMut(Progress),
    mut emit_block: impl FnMut(&mut EngineCore, usize, usize) -> Result<(), E>,
) -> Result<Stats, E> {
    let sr = opt.sr;
    let total = render_sample_count(song, opt);
    let mut core = EngineCore::new(CoreOptions::from_options(
        opt,
        gtr_symp_on,
        drum_room_on,
        sitar_symp_on,
    ));

    let events: Vec<(usize, EvKind)> = song
        .events
        .iter()
        .map(|e| ((e.sec * sr as f64) as usize, e.kind))
        .collect();
    let mut ev_i = 0;

    let mut next_report = total / 10;

    let mut block_start = 0usize;
    while block_start < total {
        let n = BLOCK.min(total - block_start);

        // apply events that fall inside this block (quantised to block start)
        while ev_i < events.len() && events[ev_i].0 < block_start + n {
            let (_, kind) = events[ev_i];
            ev_i += 1;

            core.handle_event(kind);
        }

        emit_block(&mut core, block_start, n)?;

        block_start += n;
        if block_start >= next_report {
            on_progress(Progress {
                rendered_seconds: block_start as f64 / sr as f64,
                total_seconds: total as f64 / sr as f64,
                active_voices: core.active_voice_count(),
            });
            next_report += total / 10;
        }
    }
    Ok(core.stats())
}

/// Scale by `scale`, TPDF-dither, and quantise to interleaved i16. Shared by the
/// peak- and loudness-normalisation paths so both dither identically.
fn dither_quantize(samples: &[f32], scale: f32) -> Vec<i16> {
    let mut quantizer = DitherQuantizer::new();
    samples
        .iter()
        .map(|&x| quantizer.quantize(x, scale))
        .collect()
}

pub(crate) struct DitherQuantizer {
    rng: Rng,
}

impl DitherQuantizer {
    pub(crate) fn new() -> Self {
        Self {
            rng: Rng::new(0xD17E),
        }
    }

    pub(crate) fn quantize(&mut self, sample: f32, scale: f32) -> i16 {
        let dither = (self.rng.white() + self.rng.white()) * 0.5;
        ((sample * scale).clamp(-1.0, 1.0) * 32767.0 + dither)
            .round()
            .clamp(-32768.0, 32767.0) as i16
    }
}

/// Peak-normalise to `target` and convert to interleaved i16 with TPDF dither.
pub fn normalize_to_i16(samples: &[f32], peak: f32, target: f32) -> Vec<i16> {
    let scale = if peak > 1e-9 { target / peak } else { 1.0 };
    dither_quantize(samples, scale)
}

/// Max loudness-recovery iterations and the LUFS tolerance for "on target".
pub(crate) const LOUDNESS_MAX_ITERS: usize = 6;
pub(crate) const LOUDNESS_TOL_DB: f32 = 0.3;

/// Loudness-normalise: bring integrated loudness (BS.1770-4) to `target_lufs`,
/// true-peak-limit to `ceiling_dbtp`, then TPDF-dither to interleaved i16.
///
/// The gain is a single scalar, so every composed within-track dynamic (and every
/// `analyze.py` ratio oracle) is preserved exactly; only over-ceiling transients
/// are touched, by the limiter. On a high-crest track a low ceiling removes enough
/// peak energy to drop the loudness below target, so we iterate: re-measure and
/// re-apply the residual makeup, re-limit, until on target. Because limiting only
/// ever removes energy, loudness approaches the target from below and never
/// overshoots — so this converges (or, for a track that genuinely cannot reach the
/// target without over-limiting, lands as close as the ceiling allows). Silence
/// (no gated blocks) passes through ungained.
///
/// A non-finite `target_lufs` or `ceiling_dbtp` also passes through ungained. This
/// function cannot report an error, so leaving the audio alone is the one answer that
/// neither destroys it nor pretends the setting was honoured; use
/// [`render_to_wav`](crate::offline::render_to_wav) if you want the setting validated
/// and rejected instead.
pub fn normalize_loudness(
    samples: &[f32],
    sr: u32,
    target_lufs: f32,
    ceiling_dbtp: f32,
) -> Vec<i16> {
    let mut buf: Vec<f32> = samples.to_vec();
    // This helper is infallible, so it cannot report a bad setting the way
    // `render_to_wav` does — its documented behaviour for a non-finite target or
    // ceiling is therefore to leave the audio ALONE (MM-BUG-CRUCIBLE-00032). It used
    // to compute a NaN gain, fill the buffer with NaN, and hand that to the quantizer,
    // which casts NaN to zero: a silent result returned as if it had succeeded.
    // Passing the samples through unchanged is the honest infallible answer — the
    // caller still has its audio, and `render_to_wav` is there when a diagnostic is
    // wanted instead.

    if !target_lufs.is_finite() || !ceiling_dbtp.is_finite() {
        return dither_quantize(&buf, 1.0);
    }

    for _ in 0..LOUDNESS_MAX_ITERS {
        let measured = crate::loudness::integrated_lufs(&buf, sr);
        if !measured.is_finite() {
            break; // silence — leave ungained
        }
        let delta = target_lufs - measured;
        let on_target = delta.abs() < LOUDNESS_TOL_DB;
        if !on_target {
            let g = 10f32.powf(delta / 20.0);
            for x in buf.iter_mut() {
                *x *= g;
            }
        }
        // The ceiling applies whether or not the loudness needed gain
        // (MM-BUG-CRUCIBLE-00031). This `break` used to sit ABOVE the limiter, so a
        // high-crest signal that arrived already on target was returned unlimited —
        // contradicting the documented promise to constrain transients. Loudness is a
        // TARGET; the true-peak ceiling is a CONSTRAINT, and a constraint cannot be
        // skipped because a target happens to be met.
        //
        // Costs nothing when it is not needed: `limit_true_peak` writes the samples
        // back unchanged if its first pass finds nothing above the ceiling, so a
        // signal already under it is bit-identical to before this change.
        crate::loudness::limit_true_peak(&mut buf, sr, ceiling_dbtp);
        if on_target {
            break;
        }
    }
    dither_quantize(&buf, 1.0)
}

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

    /// After a song ends, nothing that runs on every block may keep churning
    /// subnormals (the mdem sound-cost survey: a post-song realtime tail cost
    /// 3-6x idle until the CPU was put in flush-to-zero). Play a short phrase
    /// through every always-running path — the hall's send high-pass, authored
    /// CC74 filters (melodic and the ch-9 drum pair), a program-29 drive
    /// insert, the three sympathetic buses, chorus, echo, drum room and
    /// cathedral — then all-sound-off and render silence. Every state must end
    /// exactly zero or normal. Red without the per-block flushes of `rev_hp`,
    /// the strip CC74 filters, and `Drive`: each parks for good, not briefly.
    #[test]
    fn silent_session_state_never_parks_subnormal() {
        let sr = 44_100.0;
        let mut core = EngineCore::new(CoreOptions {
            sr,
            wet: 0.32,
            delay_s: 0.375,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        });
        let cc = |ch, num, val| EvKind::Cc { ch, num, val };
        for (ch, prog) in [(0, 0), (1, 29), (2, 24), (3, 104), (4, 19), (5, 48)] {
            core.handle_event(EvKind::Prog { ch, prog });
        }
        for ch in 0..16 {
            core.handle_event(cc(ch, 91, 100));
            core.handle_event(cc(ch, 93, 80));
            core.handle_event(cc(ch, 94, 60));
        }
        for ch in [0, 1, 9] {
            core.handle_event(cc(ch, 74, 50));
            core.handle_event(cc(ch, 71, 90));
        }
        for ch in 0..6 {
            core.note_on(ch, 60 + ch, 100);
        }
        for key in [36, 38, 42] {
            core.note_on(9, key, 110);
        }
        let mut out = vec![0.0f32; BLOCK * 2];
        let mut render = |core: &mut EngineCore, seconds: f32| {
            for _ in 0..(seconds * sr) as usize / BLOCK {
                out.fill(0.0);
                core.render_block_add(BLOCK, &mut out);
            }
        };
        render(&mut core, 1.0);
        for ch in 0..16 {
            core.handle_event(cc(ch, 120, 0));
        }
        render(&mut core, 10.0);

        assert!(core.active.is_empty(), "every voice must be gone");
        let mut parked = std::collections::BTreeMap::<&str, usize>::new();
        core.visit_always_running_state(&mut |site, x| {
            if x.is_subnormal() {
                *parked.entry(site).or_default() += 1;
            }
        });
        assert!(
            parked.is_empty(),
            "always-running state still holds subnormals 10 s after all-sound-off \
             (site: count): {parked:?}"
        );
    }

    /// `PROGRAM_TRIM_DB` is CONSERVATIVE by design, and this oracle pins its scope
    /// so a future edit cannot silently trim piano, guitar or drums — plus the
    /// flagship calibrated anchors and the dB→linear mapping.
    ///
    /// The scope is the sustained families, the documented GM6 plucked exception,
    /// AND (since 2026.07.22) a small set of percussive entries admitted by the
    /// M-CAL v3 reference PANEL. The panel deliberately widened the scope: a single
    /// reference cannot tell you whether it or ferro is the outlier, so an entry is
    /// only admitted when TWO independent references (Roland SC-55mkII and Yamaha
    /// S-YXG50 — uncorrelated vendor/era/synthesis) agree with each other about it.
    /// Percussive programs where they disagree stay untouched by design, so the
    /// "struck voices are untrimmed" intent still holds everywhere it was not
    /// positively measured. Their values are pinned below for the same reason the
    /// sustained anchors are.
    fn amp_protocol_readme_rows(readme: &str) -> Vec<(usize, String)> {
        let amp_section = readme
            .split("### Score-authored amp (driven guitars 29/30)")
            .nth(1)
            .expect("README score-authored amp section")
            .split("\n### ")
            .next()
            .expect("README score-authored amp section body");
        amp_section
            .lines()
            .filter_map(|line| {
                let mut cells = line.trim().strip_prefix('|')?.split('|');
                let index = cells.next()?.trim().parse().ok()?;
                Some((index, cells.next()?.trim().to_string()))
            })
            .filter(|(index, _)| *index < AMP_PARAM_COUNT)
            .collect()
    }

    /// MM-REQ-KILN-00030: the amp-control protocol has THREE independent
    /// statements — this crate's constants, `amp-lab`'s published `amp::KNOBS`
    /// table, and the README's NRPN table — and nothing forced them to agree.
    /// Each crate's own tests pass whichever way they drift, so a knob renamed
    /// or renumbered in one place stays green everywhere.
    ///
    /// This is the repo's standing defect (hand-maintained lists that drift), so
    /// the oracle DERIVES all three sides from source text rather than checking
    /// them against a fourth copied table — a guard that is itself hand-written
    /// inherits the defect it exists to catch.
    ///
    /// It lives in `ferrosintesis`, not `amp-lab`, deliberately: `amp-lab` is
    /// excluded from the integration gate (`.deltic-integrate.toml` — it drags
    /// in egui + cpal, ~200 crates), so a parity test living there would not run
    /// when it matters. Reading amp-lab's source as TEXT keeps the check on the
    /// gated side without taking the dependency.
    ///
    /// Names are compared by prefix after normalising to uppercase letters only,
    /// because this crate's identifiers are abbreviations of the published names
    /// (`AMP_TIGHT` / "Tightness", `AMP_PRES` / "Presence", `AMP_CABTONE` /
    /// "Cab Tone"). That is a derived relationship, not a mapping table.
    #[cfg(ferrosintesis_repository_tests)]
    #[test]
    fn amp_protocol_has_one_definition() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .expect("crates/")
            .parent()
            .expect("repo root")
            .to_path_buf();
        let read = |rel: &str| {
            std::fs::read_to_string(root.join(rel))
                .unwrap_or_else(|e| panic!("cannot read {rel}: {e}"))
        };
        let lab = read("crates/amp-lab/src/amp.rs");
        let readme = read("crates/ferrosintesis/README.md");
        let norm = |s: &str| -> String {
            s.chars()
                .filter(|c| c.is_ascii_alphabetic())
                .collect::<String>()
                .to_uppercase()
        };
        let prefix_match = |a: &str, b: &str| {
            let (a, b) = (norm(a), norm(b));
            !a.is_empty() && (a.starts_with(&b) || b.starts_with(&a))
        };

        // ---- MSB: this crate vs amp-lab vs the README ----
        let lab_msb = u8::from_str_radix(
            lab.split("pub const AMP_NRPN_MSB: u8 = 0x")
                .nth(1)
                .expect("amp-lab AMP_NRPN_MSB")
                .split(';')
                .next()
                .unwrap()
                .trim(),
            16,
        )
        .expect("amp-lab MSB hex");
        assert_eq!(
            lab_msb, AMP_NRPN_MSB,
            "amp-lab publishes NRPN MSB 0x{lab_msb:02X} but the synth uses 0x{AMP_NRPN_MSB:02X} \
             — a file authored against amp-lab would address a different block"
        );
        let readme_msb = u8::from_str_radix(
            readme
                .split("MSB (CC99) = `0x")
                .nth(1)
                .expect("README NRPN MSB")
                .split('`')
                .next()
                .unwrap()
                .trim(),
            16,
        )
        .expect("README MSB hex");
        assert_eq!(
            readme_msb, AMP_NRPN_MSB,
            "the README documents NRPN MSB 0x{readme_msb:02X}, the synth uses \
             0x{AMP_NRPN_MSB:02X}"
        );

        // ---- neutral value ----
        let lab_neutral: u8 = lab
            .split("pub const NEUTRAL: u8 = ")
            .nth(1)
            .expect("amp-lab NEUTRAL")
            .split(';')
            .next()
            .unwrap()
            .trim()
            .parse()
            .expect("amp-lab NEUTRAL value");
        assert_eq!(
            lab_neutral, AMP_NEUTRAL,
            "amp-lab's neutral is {lab_neutral}, the synth's is {AMP_NEUTRAL} — every \
             knob would be offset from a different origin"
        );
        assert!(
            readme.contains(&format!("{AMP_NEUTRAL} = as-shipped")),
            "the README no longer states `{AMP_NEUTRAL} = as-shipped` as the neutral"
        );

        // ---- this crate's index constants, read from ITS OWN source ----
        let engine_src = read("crates/ferrosintesis/src/engine.rs");
        let mut mine: Vec<(usize, String)> = Vec::new();
        for line in engine_src.lines() {
            let t = line.trim();
            if let Some(rest) = t.strip_prefix("const AMP_") {
                if let Some((name, tail)) = rest.split_once(": usize = ") {
                    // the declaration carries a trailing `// ...` comment
                    if let Ok(idx) = tail.split(';').next().unwrap_or("").trim().parse::<usize>() {
                        if name != "PARAM_COUNT" {
                            mine.push((idx, name.to_string()));
                        }
                    }
                }
            }
        }
        mine.sort();
        assert_eq!(
            mine.len(),
            AMP_PARAM_COUNT,
            "found {} AMP_* index constants in engine.rs but AMP_PARAM_COUNT is \
             {AMP_PARAM_COUNT} — the protocol gained or lost a knob without the count \
             following: {mine:?}",
            mine.len()
        );
        for (i, (idx, name)) in mine.iter().enumerate() {
            assert_eq!(
                *idx, i,
                "engine.rs AMP_{name} sits at index {idx}, breaking the contiguous \
                 0..{AMP_PARAM_COUNT} block the NRPN LSB addresses"
            );
        }

        // ---- amp-lab's KNOBS table ----
        let knobs: Vec<(usize, String)> = lab
            .split("Knob {")
            .skip(1)
            .filter_map(|b| {
                let idx = b
                    .split("idx:")
                    .nth(1)?
                    .split(',')
                    .next()?
                    .trim()
                    .parse()
                    .ok()?;
                let name = b.split("name: \"").nth(1)?.split('"').next()?.to_string();
                Some((idx, name))
            })
            .collect();
        assert_eq!(
            knobs.len(),
            AMP_PARAM_COUNT,
            "amp-lab publishes {} knobs, the synth implements {AMP_PARAM_COUNT}",
            knobs.len()
        );

        // ---- the README's NRPN table ----
        let rows = amp_protocol_readme_rows(&readme);
        assert_eq!(
            rows.len(),
            AMP_PARAM_COUNT,
            "the README's NRPN table documents {} of {AMP_PARAM_COUNT} knobs",
            rows.len()
        );

        // ---- all three agree, knob by knob ----
        for (i, (_, mine_name)) in mine.iter().enumerate() {
            let (_, lab_name) = knobs.iter().find(|(k, _)| *k == i).expect("amp-lab knob");
            let (_, doc_name) = rows.iter().find(|(k, _)| *k == i).expect("README row");
            assert!(
                prefix_match(mine_name, lab_name),
                "LSB {i}: the synth calls it AMP_{mine_name}, amp-lab calls it \
                 \"{lab_name}\" — the same index means two different knobs"
            );
            assert!(
                prefix_match(lab_name, doc_name),
                "LSB {i}: amp-lab calls it \"{lab_name}\", the README documents \
                 \"{doc_name}\""
            );
        }
    }

    #[test]
    fn amp_protocol_readme_scan_ignores_other_numbered_tables() {
        let readme = r#"
### Unrelated table
| 0 | Wrong before |

### Score-authored amp (driven guitars 29/30)
| LSB | knob |
|-----|------|
| 0 | Drive |
| 1 | Tone |

### Later table
| 2 | Wrong after |
"#;
        assert_eq!(
            amp_protocol_readme_rows(readme),
            [(0, "Drive".to_string()), (1, "Tone".to_string())]
        );
    }

    #[test]
    fn program_trim_scope_and_calibration() {
        // The corrected set = the sustained ranges (bowed strings only;
        // pizz/harp/timpani and the orchestra-hit stab stay out) PLUS the one
        // documented plucked exception, GM6 harpsichord (measured ~10 dB low by
        // the fair early-window RMS — see PROGRAM_TRIM_DB). Its complement MUST be
        // untouched (0.0 dB, unity gain).
        let is_corrected = |p: u8| {
            matches!(p,
                6          // harpsichord (documented plucked exception)
                // M-CAL v3 panel-admitted percussive entries (both references agreed):
                | 5        // Electric Piano 2
                | 8        // Celesta
                | 14       // Tubular Bells
                | 110      // Fiddle
                | 119      // Reverse Cymbal
                | 16..=23  // Organ
                | 40..=44  // bowed strings (pizz 45 / harp 46 / timpani 47 excluded)
                | 48..=54  // string & synth sections + choir (orch-hit 55 excluded)
                | 56..=63  // Brass
                | 64..=71  // Reed
                | 72..=79  // Pipe
                | 80..=87  // SynthLead
                | 88..=95) // SynthPad
        };
        for p in 0u8..128 {
            if !is_corrected(p) {
                assert_eq!(
                    PROGRAM_TRIM_DB[p as usize], 0.0,
                    "program {p} is outside the conservative scope and must stay at 0.0 dB"
                );
                assert_eq!(
                    program_trim_lin(p),
                    1.0,
                    "untouched program {p} must be unity gain"
                );
            }
        }

        // Flagship corrections: sections/choir lifted, solo strings/brass/flutes/
        // organ trimmed.
        assert_eq!(PROGRAM_TRIM_DB[48], 6.0); // StringEnsemble1 — direct L/R audition
        assert_eq!(PROGRAM_TRIM_DB[50], 6.0); // SynthStrings1 — lifted
        assert_eq!(PROGRAM_TRIM_DB[53], 6.0); // VoiceOohs     — lifted
        assert_eq!(PROGRAM_TRIM_DB[56], -6.0); // Trumpet      — trimmed
        assert_eq!(PROGRAM_TRIM_DB[58], -6.0); // Tuba         — trimmed
        assert_eq!(PROGRAM_TRIM_DB[43], -6.0); // Contrabass   — trimmed
        assert_eq!(PROGRAM_TRIM_DB[73], -4.0); // Flute        — trimmed
        assert_eq!(PROGRAM_TRIM_DB[19], -6.0); // ChurchOrgan  — trimmed
        assert_eq!(PROGRAM_TRIM_DB[6], 6.0); // Harpsichord   — plucked exception, lifted

        // M-CAL v3 panel entries, pinned with the reference agreement that admitted them.
        assert_eq!(PROGRAM_TRIM_DB[5], 1.0); // ElecPiano2   — refs agreed to 0.7 dB
        assert_eq!(PROGRAM_TRIM_DB[8], 3.0); // Celesta      — 2nd damped iteration, 2026.07.25
        assert_eq!(PROGRAM_TRIM_DB[14], -6.0); // TubularBell — refs agreed to 0.3 dB
        assert_eq!(PROGRAM_TRIM_DB[110], -6.0); // Fiddle    — 2nd damped iteration, 2026.07.25
        assert_eq!(PROGRAM_TRIM_DB[119], 1.0); // RevCymbal   — refs agreed to 2.9 dB

        // Deliberate ZEROS. These are recorded decisions, not merely-untouched programs, so
        // they are pinned to stop a future derivation silently re-litigating them.
        //
        // GM11 vibraphone: the references split 10.8 dB (SC-55 +6 vs S-YXG50 -2), so there
        // is no consensus target; awaiting a listening call.
        assert_eq!(PROGRAM_TRIM_DB[11], 0.0);
        // GM0/1/3 pianos: BOTH references place their pianos well below their own median
        // (GM0: SC-55 -8.9, S-YXG50 -3.4) and would pull ferro's down with them. Arthur's
        // ear ruled on 2026.07.22 that ferro's pianos are right at ferro's median and that
        // both modules are wrong here — the acoustic grand is the most-played program in GM
        // and a 4-6 dB cut on module authority alone is not a trade worth making. All three
        // are also pitch-tilt excluded on both references, so no single number was reliable
        // for them anyway.
        assert_eq!(PROGRAM_TRIM_DB[0], 0.0);
        assert_eq!(PROGRAM_TRIM_DB[1], 0.0);
        assert_eq!(PROGRAM_TRIM_DB[3], 0.0);

        // Every entry within the ±6 dB clamp.
        for (p, &db) in PROGRAM_TRIM_DB.iter().enumerate() {
            assert!(
                (-6.0..=6.0).contains(&db),
                "program {p} trim {db} dB is outside the ±6 dB clamp"
            );
        }

        // dB → linear mapping.
        assert!(
            (program_trim_lin(56) - 0.5012).abs() < 1e-3,
            "-6 dB ≈ 0.501×"
        );
        assert!(
            (program_trim_lin(53) - 1.9953).abs() < 1e-3,
            "+6 dB ≈ 1.995×"
        );
        assert_eq!(
            program_trim_lin(0),
            1.0,
            "untouched program must be exactly unity"
        );
    }

    /// `render_with_progress` must be a pure observer: attaching a progress callback
    /// cannot move a single sample.
    ///
    /// This pins the property the v0.17 API pass claimed and would otherwise only have
    /// asserted. It matters because the callback path is now the ONLY path — `render`
    /// delegates to it with a no-op closure — so a future change that let the callback
    /// (or the counter that fires it) touch engine state would silently re-voice every
    /// album in this repo. A bit-exact compare inside one build is a valid oracle here:
    /// both renders run in the same binary, so there is no cross-profile float-reorder
    /// trap (see lessons_learnt.md).
    #[test]
    fn render_with_progress_is_bit_identical_to_render() {
        // Something with a bit of everything: pitched voices, a program change, a
        // controller, and a drum hit on channel 10.
        let mut events = Vec::new();
        for (sec, kind) in [
            (0.0, EvKind::Prog { ch: 0, prog: 46 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 91,
                    val: 80,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 9,
                    key: 38,
                    vel: 110,
                },
            ),
            (
                0.40,
                EvKind::NoteOn {
                    ch: 0,
                    key: 67,
                    vel: 90,
                },
            ),
            (0.90, EvKind::NoteOff { ch: 0, key: 60 }),
            (1.20, EvKind::NoteOff { ch: 0, key: 67 }),
        ] {
            events.push(Ev { sec, kind });
        }
        let song = Song {
            events,
            seconds: 1.5,
            markers: Vec::new(),
            title: String::new(),
            initial_bpm: 120.0,
        };
        let opt = Options::default().with_tail(0.5);

        let (plain, plain_stats) = render(&song, &opt);

        let mut seen = Vec::new();
        let (observed, observed_stats) = render_with_progress(&song, &opt, &mut |p| seen.push(p));
        let mut streamed = Vec::new();
        let streamed_stats = render_stream_with_progress(&song, &opt, &mut |_| {}, &mut |block| {
            streamed.extend_from_slice(block);
            Ok(())
        })
        .unwrap();

        assert_eq!(
            plain, observed,
            "attaching a progress callback changed the rendered audio"
        );
        assert_eq!(
            plain, streamed,
            "streaming blocks changed the rendered audio"
        );
        assert_eq!(plain_stats, streamed_stats);
        assert_eq!(plain_stats.peak, observed_stats.peak);
        assert_eq!(plain_stats.voices_spawned, observed_stats.voices_spawned);

        // And the callback must actually have fired, or the test proves nothing.
        assert!(!seen.is_empty(), "progress callback never fired");
        assert!(seen.iter().all(|p| (0.0..=1.0).contains(&p.fraction())));
        // Monotonic, and it reaches the end.
        assert!(seen
            .windows(2)
            .all(|w| w[1].rendered_seconds >= w[0].rendered_seconds));
    }

    /// MM-BUG-CRUCIBLE-00031: the true-peak ceiling is a CONSTRAINT, not something
    /// skipped because the loudness TARGET happens to be met.
    ///
    /// Constructed by measuring first and then asking for exactly that loudness, so
    /// `delta` is zero and the normalizer takes its already-on-target path on the very
    /// first iteration — where the `break` used to sit above the limiter. The ceiling
    /// is set below the signal's real intersample peak, and the test asserts that
    /// premise before it asserts anything else, so it cannot pass because the input
    /// was already quiet enough.
    ///
    /// Both properties are checked on the OUTPUT, independently: the true peak must
    /// respect the ceiling, and the loudness must not overshoot the target. Limiting
    /// only removes energy, so a signal that has to be limited lands below its target
    /// — "as close as the ceiling allows" — which is why the loudness assertion is
    /// one-sided.
    #[test]
    fn loudness_normalization_applies_the_ceiling_when_already_on_target() {
        let sr = 44_100u32;
        let ceiling = -6.0f32;
        // 997 Hz is the standard test tone precisely because it does not land on
        // sample points, so it has genuine intersample peaks.
        let samples: Vec<f32> = (0..sr as usize * 2)
            .flat_map(|i| {
                let s = 0.9 * (2.0 * std::f32::consts::PI * 997.0 * i as f32 / sr as f32).sin();
                [s, s]
            })
            .collect();

        let target = crate::loudness::integrated_lufs(&samples, sr);
        let peak_in = crate::loudness::true_peak_dbtp(&samples, sr);
        assert!(
            peak_in > ceiling + 1.0,
            "premise: the input must exceed the ceiling, but it is {peak_in:.2} dBTP"
        );

        let out = normalize_loudness(&samples, sr, target, ceiling);
        let back: Vec<f32> = out.iter().map(|&s| s as f32 / 32768.0).collect();

        let peak_out = crate::loudness::true_peak_dbtp(&back, sr);
        assert!(
            peak_out <= ceiling + 0.3,
            "already-on-target signal was returned unlimited: {peak_out:.2} dBTP \
             against a {ceiling:.1} dBTP ceiling"
        );
        let loudness_out = crate::loudness::integrated_lufs(&back, sr);
        assert!(
            loudness_out <= target + 0.3,
            "loudness overshot the target: {loudness_out:.2} LUFS against {target:.2}"
        );
    }

    /// U4 full-chain oracle: loudness-normalising an arbitrary-level stereo tone
    /// must land the decoded i16 at the target LUFS and under the true-peak ceiling.
    #[test]
    fn normalize_loudness_hits_target_and_ceiling() {
        let fs = 44100.0;
        // A −30 dBFS-ish 1 kHz stereo sine (needs boosting toward −18).
        let n = (fs * 5.0) as usize;
        let mut sig = Vec::with_capacity(n * 2);
        for i in 0..n {
            let s = 0.03 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / fs).sin();
            sig.push(s);
            sig.push(s);
        }
        let pcm = normalize_loudness(&sig, fs as u32, -18.0, -1.0);
        let dec: Vec<f32> = pcm.iter().map(|&s| s as f32 / 32768.0).collect();
        let lufs = crate::loudness::integrated_lufs(&dec, fs as u32);
        let tp = crate::loudness::true_peak_dbtp(&dec, fs as u32);
        assert!(
            (lufs - (-18.0)).abs() < 0.5,
            "decoded loudness should be ~-18 LUFS, got {lufs}"
        );
        assert!(
            tp <= -0.8,
            "decoded true peak should be <= ceiling, got {tp}"
        );
    }

    /// When the loudness gain leaves the signal under the ceiling, the path is a
    /// pure scalar: output must equal input×gain to within the dither (±1 LSB).
    #[test]
    fn normalize_loudness_is_pure_scalar_under_ceiling() {
        let fs = 44100.0;
        let n = (fs * 5.0) as usize;
        let mut sig = Vec::with_capacity(n * 2);
        for i in 0..n {
            let s = 0.05 * (2.0 * std::f32::consts::PI * 440.0 * i as f32 / fs).sin();
            sig.push(s);
            sig.push(s);
        }
        // Target the signal's own loudness → gain ≈ 1, no limiting.
        let measured = crate::loudness::integrated_lufs(&sig, fs as u32);
        let pcm = normalize_loudness(&sig, fs as u32, measured, 0.0);
        // Reference: same dither/quantise with unity scale, no gain, no limiter.
        let reference = normalize_to_i16(&sig, 1.0, 1.0);
        let max_lsb = pcm
            .iter()
            .zip(&reference)
            .map(|(a, b)| (a - b).unsigned_abs())
            .max()
            .unwrap();
        assert!(max_lsb <= 1, "pure-scalar path drifted by {max_lsb} LSB");
    }

    /// High-crest recovery: a quiet body with sparse loud transients, normalised
    /// under an aggressive ceiling. Single-pass gain+limit lands well below target
    /// (the limiter eats the transient energy); the recovery loop must lift it back
    /// to the target by raising the body, while the true peak stays at the ceiling.
    #[test]
    fn normalize_loudness_recovers_on_high_crest() {
        let fs = 44100.0;
        let n = (fs * 6.0) as usize;
        let burst_period = fs as usize / 3; // a burst ~every 0.33 s
        let burst_len = fs as usize / 200; // ~5 ms bursts
        let mut sig = Vec::with_capacity(n * 2);
        for i in 0..n {
            let t = i as f32 / fs;
            let mut s = 0.05 * (2.0 * std::f32::consts::PI * 180.0 * t).sin(); // quiet body
            if i % burst_period < burst_len {
                s += 0.55 * (2.0 * std::f32::consts::PI * 1200.0 * t).sin(); // loud transient
            }
            sig.push(s);
            sig.push(s);
        }
        // Single-pass reference (what the old code did): gain to target, limit once.
        let raw = crate::loudness::integrated_lufs(&sig, fs as u32);
        let g = 10f32.powf((-18.0 - raw) / 20.0);
        let mut once: Vec<f32> = sig.iter().map(|&x| x * g).collect();
        crate::loudness::limit_true_peak(&mut once, fs as u32, -6.0);
        let single = crate::loudness::integrated_lufs(&once, fs as u32);
        assert!(
            single < -18.0 - 0.5,
            "test signal must under-shoot single-pass (got {single}) or it proves nothing"
        );

        // Full path with the recovery loop.
        let pcm = normalize_loudness(&sig, fs as u32, -18.0, -6.0);
        let dec: Vec<f32> = pcm.iter().map(|&s| s as f32 / 32768.0).collect();
        let lufs = crate::loudness::integrated_lufs(&dec, fs as u32);
        let tp = crate::loudness::true_peak_dbtp(&dec, fs as u32);
        assert!(
            (lufs - (-18.0)).abs() < 0.4,
            "recovery loop should reach ~-18 LUFS, got {lufs} (single-pass was {single})"
        );
        assert!(
            tp <= -5.8,
            "true peak must respect the -6 dBTP ceiling, got {tp}"
        );
    }

    fn test_song(events: Vec<(f64, EvKind)>, seconds: f64) -> Song {
        Song {
            events: events
                .into_iter()
                .map(|(sec, kind)| Ev { sec, kind })
                .collect(),
            seconds,
            markers: Vec::new(),
            title: String::new(),
            initial_bpm: 120.0,
        }
    }

    /// Dry options: no reverb, no echo, no LA samples — the tests below
    /// measure the voices themselves, not the room.
    fn test_opts(sr: f32) -> Options {
        Options {
            sr,
            wet: 0.0,
            tail: 0.5,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
        }
    }

    fn left(stereo: &[f32]) -> Vec<f32> {
        stereo.iter().step_by(2).copied().collect()
    }

    fn rms(seg: &[f32]) -> f32 {
        (seg.iter().map(|&x| (x * x) as f64).sum::<f64>() / seg.len() as f64).sqrt() as f32
    }

    #[test]
    fn gm0_fra_phrase_keeps_energy_through_short_key_up_gaps() {
        let sr = 44100.0;
        let onsets = [0.100f64, 0.475, 0.850];
        let keys = [62u8, 66, 69];
        let mut events = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 0 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 91,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 94,
                    val: 0,
                },
            ),
        ];
        for (&onset, &key) in onsets.iter().zip(keys.iter()) {
            events.push((
                onset,
                EvKind::NoteOn {
                    ch: 0,
                    key,
                    vel: 104,
                },
            ));
            events.push((onset + 0.3125, EvKind::NoteOff { ch: 0, key }));
        }
        events.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());

        let mut opts = test_opts(sr);
        opts.samples = true;
        let rendered = left(&render(&test_song(events, 1.35), &opts).0);
        let window = (0.020 * sr) as usize;
        let mut drops = Vec::new();
        for &onset in &onsets {
            let note_off = onset + 0.3125;
            let pre_end = (note_off * sr as f64) as usize;
            let gap_end = ((note_off + 0.0625) * sr as f64) as usize;
            let before = rms(&rendered[pre_end - window..pre_end]);
            let after = rms(&rendered[gap_end - window..gap_end]);
            drops.push(20.0 * (before / after.max(1e-9)).log10());
        }

        // Bars DERIVED from the felt damper curve, not a flat dB constant.
        //
        // This is the engine-side twin of `sampler::tests::gm0_fra_gap_release_bridges
        // _then_clears`, which MM-BUG-KILN-00104 already converted from a flat band to
        // ratios of the damper's own prediction — because a flat bar "assumed every key
        // shared one release, which is the thing the felt damper models away". That
        // conversion was never applied here, and the leftover flat 10 dB bar sat within
        // 0.1 dB of what the damper itself prescribes at key 66 (9.91 dB). Any voice
        // that follows its own damper faithfully therefore passed by luck; the bar was
        // really measuring "does the sampled layer over-sustain the gap", which the
        // outgoing conditioned bank did heavily (it bridged key 69 to 0.43x) and the B1
        // does not.
        //
        // Same constants as the twin, same meaning: MAX catches a note that is cut
        // rather than damped, MIN catches one that never damps at all.
        for (index, (&drop, &key)) in drops.iter().zip(keys.iter()).enumerate() {
            let (t60, _) = voices::PianoDamper::Felt.t60_for(key);
            let expect = 60.0 * 0.0625 / t60;
            assert!(
                drop <= expect * 1.10,
                "FRA note {} (key {key}) gap drop {drop:.2} dB exceeds 1.10x the \
                 {expect:.2} dB its {t60:.3}s damper predicts — the note is cut, not \
                 damped: {drops:?}",
                index + 1,
            );
            assert!(
                drop >= expect * 0.40,
                "FRA note {} (key {key}) gap drop {drop:.2} dB is under 0.40x the \
                 {expect:.2} dB its {t60:.3}s damper predicts — the note is not \
                 damping between repeats: {drops:?}",
                index + 1,
            );
        }
    }

    /// A same-key repeated-note figure on one channel: `n` NoteOn/NoteOff
    /// pairs, `ioi` seconds apart, each gated `gate` seconds — the tremolo
    /// (and, at slow ioi, picked-repeat) test figure.
    fn repeat_song(prog: u8, key: u8, n: usize, ioi: f64, gate: f64, secs: f64) -> Song {
        let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog })];
        for i in 0..n {
            let t = 0.1 + i as f64 * ioi;
            ev.push((
                t,
                EvKind::NoteOn {
                    ch: 0,
                    key,
                    vel: 55,
                },
            ));
            ev.push((t + gate, EvKind::NoteOff { ch: 0, key }));
        }
        test_song(ev, secs)
    }

    /// p10/p90 ratio of the f0-carrier magnitude track (Goertzel per 10 ms
    /// frame) over [t0, t1] — the "does the TONE persist between strokes"
    /// scalar. A ratio, so the −18 LUFS single-scalar loudness normalisation
    /// (and any other pure gain) cannot move it.
    fn carrier_p10_over_p90(out: &[f32], sr: f32, f0: f32, t0: f64, t1: f64) -> f32 {
        let hop = (0.010 * sr) as usize;
        let (a, b) = (
            (t0 * sr as f64) as usize / hop,
            (t1 * sr as f64) as usize / hop,
        );
        let mut mags: Vec<f32> = (a..b)
            .map(|k| crate::testutil::mag_at(&out[k * hop..(k + 1) * hop], sr, f0))
            .collect();
        mags.sort_by(|x, y| x.partial_cmp(y).unwrap());
        mags[mags.len() / 10] / mags[mags.len() * 9 / 10].max(1e-12)
    }

    /// TREM1 oracle: a fast same-key repeated figure on the steel guitar
    /// (GM 25) — 40 strokes at 75 ms IOI, 45 ms gate, the measured shape of
    /// the reported defect — must render as a TREMOLO (one string whose
    /// fundamental persists between strokes, re-picked per stroke), not as
    /// 13 fresh-voice restarts per second (a click train).
    ///
    /// Clause (a) is the perceptual defect itself: the f0 CARRIER's
    /// trough/peak ratio across the steady run. Fresh spawns + the hard
    /// 0.15 s release + G6 release-darkening leave nothing ringing between
    /// strokes (measured 0.03), and — the HFfrac lesson — gross-band
    /// metrics can't see that (overlapping released twins fill the gaps
    /// with broadband hash; broadband p10/p90 moved the WRONG way on an
    /// intermediate fix). The carrier ratio tracks exactly the thing the
    /// ear streams into "one continuous note": tonal energy at f0 in the
    /// gaps. With the restrike path it measures 0.22.
    ///
    /// Clause (b) rejects the opposite degeneracy: the strokes must still
    /// ARTICULATE (broadband 20 ms-frame ripple ≥ 4 dB) — a fix that slurs
    /// the run into one flat held note fails here.
    ///
    /// Clause (c) pins the IOI gate: the same figure at 200 ms IOI is
    /// intentional picking and must keep dying between notes (carrier ratio
    /// stays at the articulated floor, measured 0.006). If the gate ever
    /// widens into picking territory, this clause reds.
    #[test]
    fn fast_same_key_restrikes_shimmer_not_click_train() {
        let sr = 44100.0;
        let key = 83u8; // B5 — treble worst case: fundamental t60 ~130 ms
        let f0 = crate::dsp::key_freq(key);

        // (a) + (b): the defect figure — 40 strokes, 13.3/s
        let song = repeat_song(25, key, 40, 0.075, 0.045, 3.6);
        let out = left(&render(&song, &test_opts(sr)).0);
        let carrier = carrier_p10_over_p90(&out, sr, f0, 0.6, 2.9);
        assert!(
            carrier > 0.10,
            "tremolo carrier collapses between strokes: f0 p10/p90 = {carrier:.3} \
             (fresh-spawn click train ≈ 0.03, restrike shimmer ≈ 0.22)"
        );
        let frame = (0.020 * sr) as usize;
        let a = (0.6 * sr) as usize / frame;
        let b = (2.9 * sr) as usize / frame;
        let mut frames: Vec<f32> = (a..b)
            .map(|k| rms(&out[k * frame..(k + 1) * frame]))
            .collect();
        frames.sort_by(|x, y| x.partial_cmp(y).unwrap());
        let ripple = frames[frames.len() / 10] / frames[frames.len() * 9 / 10].max(1e-12);
        assert!(
            ripple < 0.63,
            "strokes no longer articulate (broadband ripple {ripple:.3} ≥ 0.63 \
             ≈ under 4 dB): the tremolo degenerated into a slur"
        );

        // (c): 200 ms IOI is PICKING — each note must still die away
        let slow = repeat_song(25, key, 12, 0.200, 0.045, 3.6);
        let out = left(&render(&slow, &test_opts(sr)).0);
        let slow_carrier = carrier_p10_over_p90(&out, sr, f0, 0.6, 2.4);
        assert!(
            slow_carrier < 0.05,
            "slow same-note picking lost its articulation: f0 p10/p90 = \
             {slow_carrier:.3} (articulated ≈ 0.006) — the tremolo IOI gate \
             has widened into picking territory"
        );
    }

    /// MM-BUG-KILN-00087: a bank change inside the tremolo window must spawn the
    /// NEWLY selected voice, never re-pick the previous bank's still-ringing one.
    ///
    /// The restrike path (TREM1) matched only channel, key, program and the CC0-alt
    /// *boolean*, so a voice whose routing had since changed still satisfied it: a
    /// steel-guitar voice was re-picked for a mandolin note (and the reverse), one
    /// nonzero CC0 bank stood in for another, and a melodic voice could be re-picked
    /// on a channel that had become an XG drum part. The requested voice then never
    /// spawned at all — the wrong instrument sounds, for as long as the tremolo runs.
    ///
    /// Observable: whether a SECOND voice appears. A retrigger re-excites the one
    /// ringing voice (`active.len() == 1`); a correct spawn leaves the old voice
    /// ringing and adds the new one (`== 2`), carrying the routing now selected.
    /// The final clause is the positive control — an UNCHANGED bank must still take
    /// the retrigger path, or this fix would have silently disabled TREM1.
    // Sampled-bank routing: the mandolin variation is an embedded-samples bank, and a
    // modeled-only build panics on the first sample request.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn a_routing_change_inside_the_tremolo_window_spawns_the_new_voice() {
        let sr = 44100.0;
        let opts = || CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: true,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        };
        const KEY: u8 = 74;
        // Well inside TREM_IOI_MAX_S (0.10 s) — the reported 75 ms tremolo stroke.
        let ioi = (0.075 * sr) as u64;

        // (channel setup, second-stroke setup, description) — each pair is a routing
        // change, so each must spawn rather than retrigger.
        let cc = |ch: u8, num: u8, val: u8| EvKind::Cc { ch, num, val };
        #[allow(clippy::type_complexity)]
        let cases: Vec<(&str, Vec<EvKind>, Vec<EvKind>)> = vec![
            (
                "steel guitar -> mandolin (CC32 0 -> 96)",
                vec![EvKind::Prog { ch: 0, prog: 25 }, cc(0, 32, 0)],
                vec![cc(0, 32, 96), EvKind::Prog { ch: 0, prog: 25 }],
            ),
            (
                "mandolin -> steel guitar (CC32 96 -> 0)",
                vec![EvKind::Prog { ch: 0, prog: 25 }, cc(0, 32, 96)],
                vec![cc(0, 32, 0), EvKind::Prog { ch: 0, prog: 25 }],
            ),
            (
                "alt bank 1 -> alt bank 2 (both CC0 nonzero, on a plucked program)",
                vec![EvKind::Prog { ch: 0, prog: 25 }, cc(0, 0, 1)],
                vec![cc(0, 0, 2)],
            ),
            (
                "melodic -> XG drum part (CC0 -> 127)",
                vec![EvKind::Prog { ch: 0, prog: 25 }, cc(0, 0, 0)],
                vec![cc(0, 0, 127)],
            ),
        ];

        // Collected, not short-circuited: a partial fix that handles one transition
        // must not hide behind the first assertion.
        let mut wrong: Vec<&str> = Vec::new();
        for (what, setup, change) in cases {
            let mut core = EngineCore::new(opts());
            for ev in setup {
                core.handle_event(ev);
            }
            core.note_on(0, KEY, 100);
            assert_eq!(core.active.len(), 1, "{what}: the first note did not spawn");

            core.now += ioi;
            for ev in change {
                core.handle_event(ev);
            }
            core.note_on(0, KEY, 100);
            if core.active.len() != 2 {
                wrong.push(what);
            }
        }
        assert!(
            wrong.is_empty(),
            "{} routing change(s) re-picked the PREVIOUS bank's voice instead of \
             spawning the newly selected one — the requested voice never sounds:\n  {}",
            wrong.len(),
            wrong.join("\n  ")
        );

        // Positive control: no routing change, so TREM1 still re-picks the voice.
        let mut core = EngineCore::new(opts());
        core.handle_event(EvKind::Prog { ch: 0, prog: 25 });
        core.handle_event(cc(0, 32, 96));
        core.note_on(0, KEY, 100);
        core.now += ioi;
        core.handle_event(cc(0, 32, 96)); // re-sent, same value
        core.note_on(0, KEY, 100);
        assert_eq!(
            core.active.len(),
            1,
            "an UNCHANGED bank stopped taking the tremolo-restrike path — TREM1 is \
             disabled and a fast repeated figure is back to a click train"
        );

        // And the spawned voice carries the routing that was selected, not the old one.
        let mut core = EngineCore::new(opts());
        core.handle_event(EvKind::Prog { ch: 0, prog: 25 });
        core.handle_event(cc(0, 32, 0));
        core.note_on(0, KEY, 100);
        core.now += ioi;
        core.handle_event(cc(0, 32, 96));
        core.note_on(0, KEY, 100);
        let spawned = core.active.last().expect("the new voice");
        assert_eq!(
            spawned.bank_lsb, 96,
            "the spawned voice froze the OLD bank LSB — its routing identity is wrong \
             and the next restrike would match on a lie"
        );
    }

    /// MM-BUG-KILN-00088: the mandolin's strike phase advances exactly once per
    /// accepted stroke, and only for the bank that owns it.
    ///
    /// The takes encode the player's alternating pick direction, so a phase that
    /// slips replays a take and reads as down/up/up with identical onset PCM. Two
    /// ownership defects did that:
    ///   (a) a fast stroke retriggered the voice, which rotated its PRIVATE index
    ///       while the engine counter stood still — so the next fresh voice after
    ///       the gap replayed the take just heard;
    ///   (b) the engine advanced its counter on EVERY melodic spawn, so a base
    ///       steel or unrelated-LSB note on the same channel and key ate the
    ///       mandolin's next take.
    ///
    /// Asserted on the SOUNDING take (`Voice::rr_phase`), not on the counter, so
    /// the test measures what a listener would hear.
    // Sampled-bank routing: `rr_phase` exists only on the LA voice, so the round-robin
    // this pins is not present in a modeled-only build.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn the_mandolin_strike_phase_is_bank_scoped_and_survives_a_retrigger() {
        let sr = 44100.0;
        let opts = || CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: true,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        };
        const KEY: u8 = 74;
        let takes = voices::variation_round_robins(25, 96).expect("the mandolin rotates takes");
        let fast = (0.075 * sr) as u64; // inside TREM_IOI_MAX_S
        let gap = (0.400 * sr) as u64; // well outside it
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
        let mandolin = |core: &mut EngineCore| {
            core.handle_event(EvKind::Prog { ch: 0, prog: 25 });
            core.handle_event(cc(32, 96));
        };
        // The take the newest voice is sounding.
        let sounding = |core: &EngineCore| {
            core.active
                .last()
                .expect("a voice")
                .voice
                .rr_phase()
                .expect("the mandolin voice owns a round-robin phase")
        };

        // (a) fresh 0 -> fast retrigger 1 -> gap -> fresh 2: one continuous sequence
        // across the spawn/retrigger boundary.
        let mut core = EngineCore::new(opts());
        mandolin(&mut core);
        core.note_on(0, KEY, 100);
        assert_eq!(sounding(&core), 0, "the first stroke is not take 0");
        core.now += fast;
        core.note_on(0, KEY, 100);
        assert_eq!(
            sounding(&core),
            1,
            "the fast stroke did not rotate to the next take"
        );
        core.now += gap;
        core.note_on(0, KEY, 100);
        assert_eq!(
            sounding(&core),
            2,
            "the fresh voice after the gap replayed a take the retrigger already \
             played — the engine counter did not follow the voice's rotation, so the \
             recorded down/up pick order breaks at every phrase boundary"
        );

        // (b) several fast strokes, then a fresh phrase — and the wrap past the last
        // take is continuous, not a reset.
        let mut core = EngineCore::new(opts());
        mandolin(&mut core);
        core.note_on(0, KEY, 100);
        for _ in 0..takes {
            core.now += fast;
            core.note_on(0, KEY, 100);
        }
        // takes+1 strokes total: 0,1,..,takes-1,0 — the last wrapped back to 0.
        assert_eq!(sounding(&core), 0, "the take sequence did not wrap");
        core.now += gap;
        core.note_on(0, KEY, 100);
        assert_eq!(
            sounding(&core),
            1,
            "the phrase after a wrapped tremolo run restarted the sequence instead of \
             continuing it"
        );

        // (c) unrelated voices on the SAME channel and key must not consume phase.
        for (what, setup) in [
            ("base steel guitar (LSB 0)", 0u8),
            ("an undefined LSB variation", 7u8),
        ] {
            let mut core = EngineCore::new(opts());
            core.handle_event(EvKind::Prog { ch: 0, prog: 25 });
            core.handle_event(cc(32, setup));
            for _ in 0..3 {
                core.now += gap;
                core.note_on(0, KEY, 100);
            }
            core.now += gap;
            mandolin(&mut core);
            core.note_on(0, KEY, 100);
            assert_eq!(
                sounding(&core),
                0,
                "{what} consumed the mandolin's strike phase: its first stroke is not \
                 take 0"
            );
        }
    }

    /// MM-BUG-KILN-00094: sampled GM120 owns one deterministic phase per
    /// channel. Other voices, written keys, and another channel cannot consume
    /// that phase, and a run longer than the old 64-seed probe cycles all twelve
    /// takes without an adjacent repeat.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn sampled_fret_noise_cycles_per_channel_across_interleaved_events() {
        let mut core = EngineCore::new(CoreOptions {
            sr: 44_100.0,
            wet: 0.0,
            delay_s: 0.0,
            samples: true,
            solo: 0xFFFF,
            gtr_symp_on: false,
            drum_room_on: false,
            sitar_symp_on: false,
        });
        for ch in [0, 1] {
            core.handle_event(EvKind::Prog { ch, prog: 120 });
        }
        core.handle_event(EvKind::Prog { ch: 2, prog: 0 });

        let takes = ferrosintesis_samples_fretnoise::ROUND_ROBINS;
        let mut next = [0usize; 2];
        let mut seen = [
            std::collections::BTreeSet::new(),
            std::collections::BTreeSet::new(),
        ];
        // 528 events means 264 GM120 events on each channel: 22 complete
        // twelve-take cycles and far enough to cross a naive u8 counter's
        // boundary. This proves the phase wraps at the BANK, not at an integer.
        for event in 0..528usize {
            let ch = (event % 2) as u8;
            core.handle_event(EvKind::NoteOn {
                ch,
                key: 48 + (event % 25) as u8,
                vel: 100,
            });
            let sounding = core
                .active
                .last()
                .expect("GM120 spawned a voice")
                .voice
                .rr_phase()
                .expect("the sampled fret-noise voice reports its take");
            assert_eq!(
                sounding,
                next[ch as usize] % takes,
                "channel {ch} event {} did not take the next canonical round robin",
                next[ch as usize]
            );
            seen[ch as usize].insert(sounding);
            next[ch as usize] += 1;

            // Unrelated accepted voices still consume global seed slots, but
            // must not perturb either channel's GM120 phase.
            if event % 4 == 0 {
                core.handle_event(EvKind::NoteOn {
                    ch: 2,
                    key: 60 + (event % 12) as u8,
                    vel: 80,
                });
            }
            if event % 11 == 0 {
                core.handle_event(EvKind::Prog { ch, prog: 0 });
                core.handle_event(EvKind::NoteOn {
                    ch,
                    key: 36 + (event % 24) as u8,
                    vel: 80,
                });
                core.handle_event(EvKind::Prog { ch, prog: 120 });
            }
        }

        for (ch, phases) in seen.iter().enumerate() {
            assert_eq!(
                phases.len(),
                takes,
                "channel {ch} did not reach all {takes} fret-noise takes"
            );
        }
    }

    fn drum_song(hits: &[(f64, u8, u8)], secs: f64, ccs: &[(u8, u8)]) -> Song {
        let mut ev: Vec<(f64, EvKind)> = ccs
            .iter()
            .map(|&(num, val)| (0.0, EvKind::Cc { ch: 9, num, val }))
            .collect();
        for &(t, key, vel) in hits {
            ev.push((t, EvKind::NoteOn { ch: 9, key, vel }));
        }
        ev.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        test_song(ev, secs)
    }

    fn drum_prog_song(prog: Option<u8>) -> Song {
        let mut ev = Vec::new();
        if let Some(prog) = prog {
            ev.push((0.0, EvKind::Prog { ch: 9, prog }));
        }
        for (t, key, vel) in [
            (0.05, 36, 110),
            (0.30, 38, 104),
            (0.55, 46, 96),
            (0.85, 49, 108),
            (1.30, 51, 102),
        ] {
            ev.push((t, EvKind::NoteOn { ch: 9, key, vel }));
        }
        test_song(ev, 2.0)
    }

    fn right(stereo: &[f32]) -> Vec<f32> {
        stereo.iter().skip(1).step_by(2).copied().collect()
    }

    #[test]
    fn channel_10_program_change_keeps_v3_default_kit() {
        let sr = 44100.0;
        let opts = test_opts(sr);
        let no_pc = render(&drum_prog_song(None), &opts).0;
        assert!(rms(&no_pc) > 1e-4, "default drum kit should sound");
        for prog in [0u8, 8, 16] {
            let got = render(&drum_prog_song(Some(prog)), &opts).0;
            assert_eq!(
                got, no_pc,
                "channel-10 Program Change {prog} changed the V3 kit"
            );
        }
    }

    /// Channel-10 Program Change 24 (the GM2 Electronic slot) selects the
    /// modeled "synth kit": with samples ON it must NOT take the realistic
    /// sampled drum kit the default V3 does, and it must render exactly as the
    /// samples-OFF modeled path (the synth kit is inert to the global samples
    /// flag). This is the seam Three-Sixty-One rides back onto the synth drums.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn channel_10_program_24_selects_the_synth_kit() {
        let sr = 44100.0;
        let sampled = Options {
            samples: true,
            ..test_opts(sr)
        };
        // Samples ON: the default V3 kit plays the realistic sampled kit...
        let default_kit = render(&drum_prog_song(None), &sampled).0;
        // ...but PC 24 switches to the modeled synth kit, which must differ.
        let synth = render(&drum_prog_song(Some(24)), &sampled).0;
        assert_ne!(
            synth, default_kit,
            "channel-10 PC 24 did not switch off the sampled kit"
        );
        // The synth kit ignores the samples flag — identical to samples-off.
        let modeled = render(&drum_prog_song(Some(24)), &test_opts(sr)).0;
        assert_eq!(
            synth, modeled,
            "synth kit differs from the samples-off modeled path"
        );
    }

    /// Channel-10 Program Change 25 selects the ORIGINAL kit (`Kit::V1`) — the
    /// drum voices from before the 9-10 Jul 2026 "kit-v2"/realism overhaul, which
    /// Three-Sixty-One asks for. It must be a genuinely distinct kit from both the
    /// sampled default and the PC-24 synth kit. V1's *sound* is pinned separately
    /// (and byte-exactly) by `v1_drum_render_signatures_are_stable`; this test
    /// pins the ch-10 selection wiring that makes it reachable.
    #[test]
    fn channel_10_program_25_selects_the_original_v1_kit() {
        let sr = 44100.0;
        let sampled = Options {
            samples: true,
            ..test_opts(sr)
        };
        let default_kit = render(&drum_prog_song(None), &sampled).0;
        let original = render(&drum_prog_song(Some(25)), &sampled).0;
        let synth = render(&drum_prog_song(Some(24)), &sampled).0;
        assert!(rms(&original) > 1e-4, "PC 25 original kit should sound");
        assert_ne!(
            original, default_kit,
            "channel-10 PC 25 did not leave the sampled default kit"
        );
        assert_ne!(
            original, synth,
            "channel-10 PC 25 selected the synth kit, not the original V1 kit"
        );
        // V1 predates the sampled layer entirely, so the samples flag is inert.
        let dry = render(&drum_prog_song(Some(25)), &test_opts(sr)).0;
        assert_eq!(
            original, dry,
            "the original V1 kit must ignore the samples flag"
        );
    }

    /// XG drum-kit bank routing (CC0=127). Yamaha XG declares a drum kit on ANY
    /// channel via bank MSB 127; the Incantations Part IV reference uses ch14 for a
    /// conga part that way, which before this fix misrendered as a GM Drawbar Organ
    /// (program 16) hammering the D4/Eb4/E4 conga keys. Three fresh-engine renders,
    /// dry (`test_opts` wet=0):
    ///   drum9  — key 62 on ch9 (the built-in drum channel)
    ///   xg13   — key 62 on ch13 with CC0=127 + program 16  → must take the drum path
    ///   organ  — key 62 on ch13 with program 16 but NO CC0=127 → the old behaviour
    /// A SINGLE isolated hit, so the compared paths can't diverge on FP associativity
    /// or voice overlap; the XG parallel path mirrors ch9's `(scratch*ul)*g`
    /// association, so byte-equality with the ch9 hit holds exactly. Do NOT fold that
    /// association, and do NOT extend this equality to overlapping voices.
    #[test]
    fn xg_bank_127_routes_channel_to_drums() {
        let sr = 44100.0;
        let opt = test_opts(sr);
        let key = 62u8; // GM/XG "mute hi conga"; as GM program 16 it is D4 ≈ 293.66 Hz

        let hit = |ch: u8, xg: bool| -> Vec<f32> {
            let mut ev = Vec::new();
            if xg {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch,
                        num: 0,
                        val: 127,
                    },
                )); // XG drum-kit bank
            }
            ev.push((0.0, EvKind::Prog { ch, prog: 16 })); // XG Rock kit / GM Drawbar Organ
            ev.push((0.05, EvKind::NoteOn { ch, key, vel: 100 }));
            render(&test_song(ev, 1.5), &opt).0
        };

        let drum9 = hit(9, true); // ch9: CC0=127 is inert (already drums)
        let xg13 = hit(13, true); // ch14 XG-drum: the fix routes this to the drum path
        let organ = hit(13, false); // ch14 without CC0=127: the pre-fix Drawbar Organ

        // The XG-drum hit takes the drum path — byte-identical to the same hit on ch9.
        assert_eq!(
            xg13, drum9,
            "CC0=127 on ch13 must render key {key} as a drum, identical to ch9"
        );
        // ...and is NOT the melodic organ it produced before.
        assert_ne!(
            xg13, organ,
            "CC0=127 must route away from the melodic Drawbar Organ"
        );

        // Bug-proof: the organ SUSTAINS the conga-key pitch (D4); a drum decays. Compare
        // late-tail energy at D4 (1.0–1.4 s, long after the 0.05 s onset) — the organ's
        // is far larger. (Raw onset magnitude is weaker: a conga has some D4 attack too.)
        let f0 = crate::dsp::key_freq(key); // D4
        let tail = |out: &[f32]| {
            let m = left(out);
            let a = sr as usize; // 1.0 s
            let b = (1.4 * sr as f64) as usize;
            crate::testutil::mag_at(&m[a..b], sr, f0)
        };
        assert!(
            tail(&xg13) < 0.1 * tail(&organ),
            "drum tail at D4 ({}) must be far below the sustained organ ({})",
            tail(&xg13),
            tail(&organ)
        );
    }

    /// A channel declared a drum part by XG bank select or GS SysEx must honour the
    /// ch-10 kit ladder, exactly as channel 10 does.
    ///
    /// Before 2026-07-26 the ladder was gated on `ch == 9`, so such a channel was
    /// permanently the default V3 kit however its program change was written — the
    /// program was read as naming a melodic instrument instead of selecting a kit.
    ///
    /// Fail-first shape: each declared channel is compared against the SAME song on
    /// channel 10. Under the old gate the brush cases rendered as V3 and these
    /// assertions failed; the `assert_ne` against the default kit is what stops the
    /// test passing vacuously if the ladder ever stops selecting anything at all.
    ///
    /// Keys 38 and 42 are chosen because `Kit::Brush` intercepts them with its own
    /// voices, so V3-vs-Brush is a large difference rather than a subtle one.
    #[test]
    fn declared_drum_channels_honour_the_kit_ladder() {
        let sr = 44100.0;
        let opt = Options {
            samples: true,
            ..test_opts(sr)
        };
        let hits = |ch: u8| {
            [
                (
                    0.05,
                    EvKind::NoteOn {
                        ch,
                        key: 38,
                        vel: 108,
                    },
                ),
                (
                    0.40,
                    EvKind::NoteOn {
                        ch,
                        key: 42,
                        vel: 96,
                    },
                ),
                (
                    0.75,
                    EvKind::NoteOn {
                        ch,
                        key: 38,
                        vel: 120,
                    },
                ),
            ]
        };
        // Channel 10 is the reference: no declaration needed, the ladder always applied.
        let ch10 = |prog: u8| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 9, prog })];
            ev.extend(hits(9));
            render(&test_song(ev, 2.0), &opt).0
        };
        // An XG-declared drum channel: CC0 = 127, then the kit program.
        let xg = |ch: u8, prog: u8| {
            let mut ev = vec![
                (
                    0.0,
                    EvKind::Cc {
                        ch,
                        num: 0,
                        val: 127,
                    },
                ),
                (0.0, EvKind::Prog { ch, prog }),
            ];
            ev.extend(hits(ch));
            render(&test_song(ev, 2.0), &opt).0
        };
        // A GS-declared rhythm part: the SysEx, then the kit program. Note a GS part
        // still sends CC0 = 0, which is why it cannot share the XG flag.
        let gs = |ch: u8, prog: u8| {
            let mut ev = vec![
                (0.0, EvKind::DrumMode { ch, on: true }),
                (0.0, EvKind::Prog { ch, prog }),
            ];
            ev.extend(hits(ch));
            render(&test_song(ev, 2.0), &opt).0
        };

        let default_kit = ch10(0);
        let brush_ch10 = ch10(40);
        assert_ne!(
            brush_ch10, default_kit,
            "PC 40 must select the brush kit on ch10 — the reference itself is broken"
        );
        assert!(rms(&brush_ch10) > 1e-4, "the brush reference must sound");

        // Compared with a TOLERANCE, not byte-equality. A declared drum channel sums
        // into the master by a slightly different path from ch9, so identical voices
        // land with a different float rounding order: measured max|diff| 3.8e-5
        // (~-88 dBFS) with RMS equal to six decimals. That is summation order, not a
        // behavioural difference, and asserting byte-equality here would be pinning the
        // adder. The kit difference we DO care about is orders of magnitude larger,
        // which the selectivity assertion below states rather than assumes.
        let maxdiff = |a: &[f32], b: &[f32]| {
            a.iter()
                .zip(b)
                .map(|(x, y)| (x - y).abs())
                .fold(0f32, f32::max)
        };
        const SAME: f32 = 1e-3;

        for (label, got) in [("XG", xg(13, 40)), ("GS", gs(11, 40))] {
            let d = maxdiff(&got, &brush_ch10);
            assert!(
                d < SAME,
                "{label}-declared drum channel ignored PC 40 (max|diff| vs the ch10 \
                 brush kit = {d:.5}); it must select the brush kit as channel 10 does"
            );
        }
        for (label, got) in [("XG", xg(13, 0)), ("GS", gs(11, 0))] {
            let d = maxdiff(&got, &default_kit);
            assert!(
                d < SAME,
                "{label}-declared drum channel with PC 0 is not the default kit \
                 (max|diff| = {d:.5})"
            );
        }
        // The ladder must actually SELECT. Without this, both checks above would pass
        // if the kit were ignored entirely and everything rendered identically.
        let kit_delta = maxdiff(&brush_ch10, &default_kit);
        assert!(
            kit_delta > 50.0 * SAME,
            "brush and default kits are barely distinguishable (max|diff| = \
             {kit_delta:.5}); the checks above would be passing vacuously"
        );
    }

    /// GS "Use for Rhythm Part" routes a non-drum channel to the drum path — the GS
    /// counterpart of the XG test above. A GS rhythm hit on ch11 is byte-identical to
    /// the same hit on ch9 (single hit; the parallel drum path mirrors ch9's
    /// association, and a fresh ch11 strip shares ch9's default gain/pan), and differs
    /// from the same note played as a melodic voice.
    #[test]
    fn gs_rhythm_part_routes_channel_to_drums() {
        let sr = 44100.0;
        let opt = test_opts(sr);
        let key = 62u8;
        let render_ev = |ev: Vec<(f64, EvKind)>| render(&test_song(ev, 1.5), &opt).0;

        let gs = render_ev(vec![
            (0.0, EvKind::DrumMode { ch: 11, on: true }), // GS: ch11 is a rhythm part
            (
                0.05,
                EvKind::NoteOn {
                    ch: 11,
                    key,
                    vel: 100,
                },
            ),
        ]);
        let drum9 = render_ev(vec![(
            0.05,
            EvKind::NoteOn {
                ch: 9,
                key,
                vel: 100,
            },
        )]);
        let melodic = render_ev(vec![
            (0.0, EvKind::Prog { ch: 11, prog: 0 }), // grand piano, no rhythm-part flag
            (
                0.05,
                EvKind::NoteOn {
                    ch: 11,
                    key,
                    vel: 100,
                },
            ),
        ]);

        assert_eq!(
            gs, drum9,
            "GS rhythm part (ch11) must render as a drum, identical to ch9"
        );
        assert_ne!(
            gs, melodic,
            "GS rhythm part must not render as a melodic voice"
        );
    }

    /// The GS flag is separate from the XG flag: an ordinary `CC0=0` bank select (which
    /// a real GS rhythm part still sends) must NOT clear it, and a GS Reset MUST. These
    /// guard the two-flag decision and the reset handling.
    #[test]
    fn gs_rhythm_survives_bank_select_but_not_reset() {
        let sr = 44100.0;
        let opt = test_opts(sr);
        let key = 62u8;
        let render_ev = |ev: Vec<(f64, EvKind)>| render(&test_song(ev, 1.5), &opt).0;

        let drum9 = render_ev(vec![(
            0.05,
            EvKind::NoteOn {
                ch: 9,
                key,
                vel: 100,
            },
        )]);
        let melodic = render_ev(vec![
            (0.0, EvKind::Prog { ch: 11, prog: 0 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 11,
                    key,
                    vel: 100,
                },
            ),
        ]);

        // GS rhythm part, then the ordinary bank-select + program a real GS file sends
        // to pick the kit — still drums (gs_drum is immune to CC0, unlike xg_drum).
        let after_bank = render_ev(vec![
            (0.0, EvKind::DrumMode { ch: 11, on: true }),
            (
                0.01,
                EvKind::Cc {
                    ch: 11,
                    num: 0,
                    val: 0,
                },
            ), // bank select MSB 0
            (
                0.02,
                EvKind::Cc {
                    ch: 11,
                    num: 32,
                    val: 0,
                },
            ), // bank select LSB 0
            (0.03, EvKind::Prog { ch: 11, prog: 0 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 11,
                    key,
                    vel: 100,
                },
            ),
        ]);
        assert_eq!(
            after_bank, drum9,
            "GS rhythm part must survive CC0=0 + PC (proves gs_drum is not the CC0-driven xg_drum)"
        );

        // GS Reset reverts the part mode → the same note is melodic again.
        let after_reset = render_ev(vec![
            (0.0, EvKind::DrumMode { ch: 11, on: true }),
            (0.02, EvKind::GsReset),
            (0.03, EvKind::Prog { ch: 11, prog: 0 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 11,
                    key,
                    vel: 100,
                },
            ),
        ]);
        assert_eq!(
            after_reset, melodic,
            "GS Reset must clear the rhythm part (renders melodic, identical to a plain ch11 note)"
        );
    }

    /// MM-BUG-CRUCIBLE-00030: a routing change must re-derive the state that depends
    /// on it, WITHOUT a following Program Change to paper over it.
    ///
    /// The routing flag flipped immediately but the kit, the unauthored effect sends
    /// and the `Drive` insert were only recomputed by `program_change`. So a channel
    /// declared a rhythm part and given program 29 kept that drum-derived state — zero
    /// sends, no drive — after a GS Reset made it melodic again. The test above misses
    /// this precisely because it issues `Prog` after the reset; every case here omits
    /// it, which is the whole point.
    ///
    /// Both directions and both kinds of program: 29 (a `needs_drive` guitar, where
    /// the `Drive` insert is the audible difference) and 52 (choir aahs, an ordinary
    /// program whose `fx_profile` sends are nonzero). The reference for each case is a
    /// render that reaches the same routing by the path that always worked, so a
    /// failure means the two paths disagree — not merely that something changed.
    #[test]
    fn gs_routing_changes_rederive_program_state_without_a_program_change() {
        let sr = 44100.0;
        let opt = test_opts(sr);
        let key = 62u8;
        let render_ev = |ev: Vec<(f64, EvKind)>| render(&test_song(ev, 1.5), &opt).0;
        let note = |ch: u8| (0.9, EvKind::NoteOn { ch, key, vel: 100 });

        for prog in [29u8, 52] {
            // Melodic reference: program selected while the channel is melodic.
            let melodic = render_ev(vec![(0.0, EvKind::Prog { ch: 11, prog }), note(11)]);
            // Drum reference: program selected while the channel is a rhythm part.
            let drum = render_ev(vec![
                (0.0, EvKind::DrumMode { ch: 11, on: true }),
                (0.1, EvKind::Prog { ch: 11, prog }),
                note(11),
            ]);
            assert_ne!(
                melodic, drum,
                "prog {prog}: the two references are identical, so this test cannot \
                 distinguish anything"
            );

            // Declared a rhythm part, program selected there, then GS Reset — and NO
            // further Program Change. Must match the melodic reference.
            let reset_no_pc = render_ev(vec![
                (0.0, EvKind::DrumMode { ch: 11, on: true }),
                (0.1, EvKind::Prog { ch: 11, prog }),
                (0.2, EvKind::GsReset),
                note(11),
            ]);
            assert_eq!(
                reset_no_pc, melodic,
                "prog {prog}: after GS Reset the channel is melodic again but kept \
                 drum-derived sends/drive — a Program Change should not be required to \
                 repair it"
            );

            // The inverse: program selected while melodic, THEN declared a rhythm
            // part, with no further Program Change. Must match the drum reference.
            let declared_no_pc = render_ev(vec![
                (0.0, EvKind::Prog { ch: 11, prog }),
                (0.2, EvKind::DrumMode { ch: 11, on: true }),
                note(11),
            ]);
            assert_eq!(
                declared_no_pc, drum,
                "prog {prog}: a newly declared rhythm part kept melodic sends/drive"
            );
        }
    }

    /// Oracle (D10d, kit internal balance): the kit voicing was cymbal-heavy and
    /// hat-light — measured on the Hey Jude reference the hi-hats sat ~19 dB under
    /// the kick and the crash only ~2 dB under, so a standard beat lost its hats
    /// and the cymbals dominated. The `kit_balance` trim corrects it. This locks in
    /// the corrected balance on the DEFAULT (sampled) kit: the hi-hats must be
    /// audible against the kick (not buried), the crash must sit below the kick (an
    /// accent, not the loudest voice), and the snare/toms must be forward (near the
    /// kick). Isolated equal-velocity hits, dry (wet=0), so it measures the
    /// voices + trim, not the room; each level is taken relative to the kick, so
    /// the shape survives the renderer's normalization.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn kit_internal_balance_hats_audible_crash_an_accent() {
        let sr = 44100.0;
        let mut opt = test_opts(sr);
        opt.samples = true;
        // one hit each, 1 s apart: kick, snare, closed hat, crash, tom.
        let hits = [
            (0.0, 36, 100),
            (1.0, 38, 100),
            (2.0, 42, 100),
            (3.0, 49, 100),
            (4.0, 45, 100),
        ];
        let out = render(&drum_song(&hits, 5.0, &[]), &opt).0;
        let mono = left(&out);
        let db = |t: f64| {
            let a = (t * sr as f64) as usize;
            let b = ((t + 0.4) * sr as f64) as usize;
            20.0 * rms(&mono[a..b.min(mono.len())]).max(1e-9).log10()
        };
        let (kick, snare, hat, crash, tom) = (db(0.0), db(1.0), db(2.0), db(3.0), db(4.0));
        // Measured margins at the shipped trim: hat-kick ~-11.7, crash-kick ~-11.9,
        // snare-kick ~-6.2, tom-kick ~-4.4 dB. Reverting the hat trim drops hat-kick
        // to ~-24.8 and trips the first assert (fail-first verified).
        // hi-hats must be audible against the kick (they were ~19-26 dB under before)
        assert!(
            hat - kick > -16.0,
            "hi-hats buried vs kick: {:.1} dB",
            hat - kick
        );
        // crash sits below the kick — an accent, not the loudest voice
        assert!(crash < kick, "crash not below kick: {:.1} dB", crash - kick);
        // snare and toms are forward (within ~9 dB of the kick)
        assert!(
            snare - kick > -9.0,
            "snare too far back: {:.1} dB",
            snare - kick
        );
        assert!(tom - kick > -9.0, "toms too far back: {:.1} dB", tom - kick);
    }

    #[cfg(feature = "embedded-samples")]
    #[test]
    fn samples_option_reaches_channel_10_drums() {
        let sr = 44100.0;
        let song = drum_prog_song(None);
        let off = render(&song, &test_opts(sr)).0;
        let mut on_opts = test_opts(sr);
        on_opts.samples = true;
        let on = render(&song, &on_opts).0;
        assert_ne!(off, on, "samples=true did not alter channel-10 drums");
        assert!(
            on.iter().all(|x| x.is_finite()),
            "sampled drum render produced non-finite samples"
        );
        let db = 20.0 * (rms(&on) / rms(&off).max(1e-12)).log10();
        assert!(
            db.abs() <= 6.0,
            "samples changed drum render level by {db:+.2} dB"
        );
    }

    /// Oracle 32b (D9, §5.3): the kit images across the stereo field —
    /// decorrelated L/R with real placement — without any Haas trickery
    /// (mono sum loses < 1 dB), and kick/snare stay centred.
    #[test]
    fn kit_images_in_stereo_without_mono_loss() {
        let sr = 44100.0;
        let mut hits = Vec::new();
        for i in 0..8 {
            hits.push((i as f64 * 0.25, 42u8, 90u8)); // hats left
        }
        // ride right — matched in density and level to the (now hat-forward) kit so
        // the pattern actually exercises the L/R spread. Since the D10d rebalance
        // trims the ride and lifts the hats, a sparse quiet ride would let the
        // dominant left-panned hats correlate the field; a present ride keeps both
        // sides live (the point of the oracle), while a real mono collapse would
        // still peg corr near 1.0.
        for i in 0..8 {
            hits.push((0.125 + i as f64 * 0.25, 51, 120)); // ride right
        }
        let song = drum_song(&hits, 2.2, &[]);
        let out = render(&song, &test_opts(sr)).0;
        let (l, r) = (left(&out), right(&out));
        let corr = crate::testutil::inter_corr(&l, &r);
        assert!(
            corr < 0.93,
            "kit stereo field collapsed toward a mono point source: corr {corr}"
        );
        // placement: hats-only song leans left, and the mono sum holds up
        let hat_song = drum_song(
            &(0..8)
                .map(|i| (i as f64 * 0.25, 42, 90))
                .collect::<Vec<_>>(),
            2.2,
            &[],
        );
        let hout = render(&hat_song, &test_opts(sr)).0;
        let (hl, hr) = (left(&hout), right(&hout));
        assert!(
            rms(&hl) > 1.2 * rms(&hr),
            "hats not left: L {} R {}",
            rms(&hl),
            rms(&hr)
        );
        let mono: Vec<f32> = hl.iter().zip(&hr).map(|(a, b)| 0.5 * (a + b)).collect();
        let mid = ((rms(&hl).powi(2) + rms(&hr).powi(2)) / 2.0).sqrt();
        let loss_db = 20.0 * (rms(&mono) / mid.max(1e-12)).log10();
        assert!(loss_db > -1.0, "mono collapse: {loss_db:.2} dB");
        // kick/snare centred
        let kick_song = drum_song(&[(0.05, 36, 110), (0.55, 38, 105)], 1.2, &[]);
        let kout = render(&kick_song, &test_opts(sr)).0;
        let (kl, kr) = (left(&kout), right(&kout));
        let bal = rms(&kl) / rms(&kr).max(1e-12);
        assert!((0.95..=1.05).contains(&bal), "kick/snare off centre: {bal}");
    }

    /// Oracle 42 (D9 strip parity — the review's converged CRITICAL):
    /// CC7 silences the kit, CC74 darkens it, CC91 still reaches the hall,
    /// and authored CC10 shifts the whole image.
    #[test]
    fn drum_strip_parity_preserved() {
        let sr = 44100.0;
        let hits: Vec<(f64, u8, u8)> = (0..6).map(|i| (0.05 + i as f64 * 0.2, 42, 100)).collect();
        // CC7 = 0 silences
        let silent = render(&drum_song(&hits, 1.6, &[(7, 0)]), &test_opts(sr)).0;
        assert!(
            rms(&silent) < 1e-6,
            "CC7=0 drums still audible: {}",
            rms(&silent)
        );
        // CC74 = 20 darkens
        let plain = render(&drum_song(&hits, 1.6, &[]), &test_opts(sr)).0;
        let dark = render(&drum_song(&hits, 1.6, &[(74, 20)]), &test_opts(sr)).0;
        let cent = |s: &[f32]| {
            let m: Vec<f32> = s.chunks_exact(2).map(|p| 0.5 * (p[0] + p[1])).collect();
            crate::testutil::centroid(&m, sr)
        };
        assert!(
            cent(&dark) < 0.8 * cent(&plain),
            "ch-9 wah dead: dark {} vs plain {}",
            cent(&dark),
            cent(&plain)
        );
        // CC91 still reaches the hall: wet render, tail after the last hit
        let wet_opts = || Options {
            wet: 0.32,
            ..test_opts(sr)
        };
        let kick = |cc91: u8| {
            let song = drum_song(&[(0.05, 36, 115)], 2.0, &[(91, cc91)]);
            render(&song, &wet_opts()).0
        };
        let tail =
            |s: &[f32], t0: f32, t1: f32| rms(&left(s)[(t0 * sr) as usize..(t1 * sr) as usize]);
        assert!(
            tail(&kick(127), 1.2, 1.9) > 2.0 * tail(&kick(0), 1.2, 1.9),
            "drum hall send lost"
        );
        // authored CC10 shifts the kit image (hats table-left → pushed right)
        let panned = render(&drum_song(&hits, 1.6, &[(10, 127)]), &test_opts(sr)).0;
        let (pl, pr) = (left(&panned), right(&panned));
        assert!(
            rms(&pr) > 1.2 * rms(&pl),
            "CC10 ignored on ch 9: L {} R {}",
            rms(&pl),
            rms(&pr)
        );
    }

    #[test]
    fn cc121_resets_controllers_but_preserves_mix_state() {
        let sr = 44100.0;
        let mut core = EngineCore::new(CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        });
        core.handle_event(EvKind::Prog { ch: 0, prog: 30 });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 7,
            val: 80,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 10,
            val: 20,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 64,
            val: 127,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 1,
            val: 100,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 74,
            val: 20,
        });
        // Effect sends, an RPN-set bend range, and a portamento TIME. RP-015
        // preserves every one of these across CC121 (MM-BUG-KILN-00033).
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 91,
            val: 50,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 93,
            val: 100,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 94,
            val: 40,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 5,
            val: 90,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 101,
            val: 0,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 100,
            val: 0,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 6,
            val: 12,
        });
        let porta_time_before = core.strips[0].porta_time;
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 121,
            val: 0,
        });

        // CC7/CC10 now prime at block rate (prime-on-first-block), so advance one
        // block to snap volume/pan to their authored targets. CC121 does not reset
        // volume or pan (correct GM semantics), so the block preserves them.
        let mut sink = [0f32; BLOCK * 2];
        core.render_block_add(BLOCK, &mut sink);

        let s = &core.strips[0];

        // --- RP-015 RESETS these ---
        assert!(!s.sustain, "CC64 must reset");
        assert!(!s.mod_authored, "CC1 must reset");
        assert_eq!(s.expr, 1.0, "CC11 must reset to full");
        assert_eq!(s.expr_target, 1.0);
        assert_eq!(s.rpn_msb, 127, "RPN selector must park at Null");
        assert_eq!(s.rpn_lsb, 127);
        assert_eq!(s.bend_wheel, 0.0, "pitch bend must return to centre");

        // --- RP-015 PRESERVES these ---
        assert!((s.volume - (80.0f32 / 127.0).powi(2)).abs() < 1e-6);
        assert!((s.pan - 20.0 / 127.0).abs() < 1e-6);
        assert!(
            s.drive.is_some(),
            "program-derived drive should be restored"
        );
        // Effect sends are persistent channel state, not program state.
        assert_eq!(
            s.reverb_send,
            50.0 / 127.0,
            "CC121 discarded the authored CC91 reverb send"
        );
        assert_eq!(
            s.chorus_send,
            100.0 / 127.0,
            "CC121 discarded the authored CC93 chorus send"
        );
        assert_eq!(
            s.delay_send,
            40.0 / 127.0,
            "CC121 discarded the authored CC94 delay send"
        );
        assert!(s.reverb_authored && s.chorus_authored && s.delay_authored);
        // CC121 nulls the RPN SELECTOR; it does not revert what the selector set.
        assert_eq!(
            s.bend_range, 12.0,
            "CC121 reverted the RPN-set pitch-bend range"
        );
        assert_eq!(s.fine, 1.0);
        // Bend is centred, but centre is scaled by the preserved fine tuning.
        assert_eq!(s.bend, s.fine);
        // CC70-79 sound controllers survive, and so must the filters realising them.
        assert!(
            s.wah.is_some(),
            "CC121 tore down the CC74 filter — CC74 is a preserved sound controller"
        );
        assert!(
            s.cutoff_target < WAH_MAX_HZ,
            "CC121 reverted the authored CC74 cutoff"
        );
        assert_eq!(s.res_target, WAH_Q, "CC71 was never authored here");
        // Only the CC65 portamento SWITCH resets; the CC5 TIME is setup state.
        assert!(!s.porta_on, "CC65 must reset");
        assert_eq!(
            s.porta_time, porta_time_before,
            "CC121 reverted the authored CC5 portamento time"
        );
    }

    /// MM-BUG-KILN-00035: GM System On is a full synthesis/channel reset, but
    /// public diagnostics still describe the complete offline render.
    #[test]
    fn gm_system_on_restores_fresh_state_and_preserves_stats() {
        let mut core = slew_test_core(44_100.0);
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
        for kind in [
            EvKind::Prog { ch: 0, prog: 30 },
            cc(7, 80),
            cc(101, 0),
            cc(100, 0),
            cc(6, 12),
            EvKind::DrumMode { ch: 0, on: true },
            EvKind::XgEffectParam {
                addr_lo: 0x40,
                data: [0x4B, 0x11],
                len: 2,
            },
            EvKind::NoteOn {
                ch: 0,
                key: 60,
                vel: 100,
            },
            EvKind::NoteOn {
                ch: 1,
                key: 64,
                vel: 100,
            },
        ] {
            core.handle_event(kind);
        }
        let mut audio = [0.0; BLOCK * 2];
        core.render_block_add(BLOCK, &mut audio);
        let before = core.stats();
        assert_eq!(before.voices_spawned, 2);
        assert_eq!(before.max_polyphony, 2);
        assert!(before.peak > 0.0);
        assert_eq!(core.voice_seed_index, 2);
        assert_eq!(core.strips[0].program, 30);
        assert_eq!(core.strips[0].bend_range, 12.0);
        assert!(core.strips[0].gs_drum);
        assert_eq!(core.xg.var_type_msb, 0x4B);

        core.handle_event(EvKind::GmReset);

        let strip = &core.strips[0];
        assert_eq!(core.active_voice_count(), 0);
        assert_eq!(strip.program, 0);
        assert_eq!(strip.volume, (100.0f32 / 127.0).powi(2));
        assert!(!strip.volume_authored);
        assert_eq!(strip.bend_range, 2.0);
        assert_eq!((strip.rpn_msb, strip.rpn_lsb), (127, 127));
        assert!(!strip.gs_drum);
        assert_eq!(core.xg.var_type_msb, 0);
        assert_eq!(core.xg.var_part, 127);
        assert_eq!(core.stats(), before);
        assert_eq!(core.voice_seed_index, 0);
    }

    /// MM-BUG-KILN-00034: an NRPN select (CC98/99) must invalidate the RPN latch,
    /// so a later Data-Entry cannot corrupt the RPN-set pitch-bend range. Without
    /// the guard, CC6 after an NRPN select is still interpreted against the
    /// latched RPN 0,0 (a common GS/XG sequence: set bend range, then use an NRPN
    /// without an RPN-Null).
    #[test]
    fn nrpn_select_does_not_corrupt_the_rpn_bend_range() {
        let sr = 44100.0;
        let mut core = EngineCore::new(CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        });
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };

        // Select RPN 0,0 and set the pitch-bend range to 2 semitones.
        core.handle_event(cc(101, 0)); // RPN MSB = 0
        core.handle_event(cc(100, 0)); // RPN LSB = 0
        core.handle_event(cc(6, 2)); // data entry → bend range 2
        assert_eq!(core.strips[0].bend_range, 2.0);

        // Select an NRPN (no intervening RPN-Null) then send Data-Entry. The NRPN
        // select must have parked the RPN latch, so this CC6 is inert — it must
        // NOT be re-interpreted as the bend range (which would clamp to 24).
        core.handle_event(cc(99, 1)); // NRPN MSB
        core.handle_event(cc(98, 8)); // NRPN LSB
        core.handle_event(cc(6, 80)); // would set bend range 24 without the guard

        assert_eq!(
            core.strips[0].bend_range, 2.0,
            "NRPN select failed to invalidate the RPN latch — bend range corrupted"
        );
        // The latch sits at null, so a genuine RPN can still be re-selected later.
        assert_eq!(core.strips[0].rpn_msb, 127);
        assert_eq!(core.strips[0].rpn_lsb, 127);
    }

    /// MM-BUG-KILN-00033: effect sends are persistent CHANNEL state (GM / RP-015),
    /// so a Program Change must not discard a send the file authored with CC93 /
    /// CC94. The program's `fx_profile` is a default that fills an UNauthored send
    /// only — exactly the rule the CC0 bank arm already followed.
    #[test]
    fn program_change_preserves_authored_effect_sends() {
        let sr = 44100.0;
        let core_opts = || CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        };

        // A channel that AUTHORS its sends keeps them across a Program Change.
        let mut core = EngineCore::new(core_opts());
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
        core.handle_event(EvKind::Prog { ch: 0, prog: 30 });
        core.handle_event(cc(93, 100));
        core.handle_event(cc(94, 20));
        let (authored_cho, authored_del) = (100.0 / 127.0, 20.0 / 127.0);
        assert_eq!(core.strips[0].chorus_send, authored_cho);
        assert_eq!(core.strips[0].delay_send, authored_del);

        // Program 48 (string ensemble) profiles to (0.35, 0.0) — it must NOT
        // overwrite the authored values, and the authored flags must survive:
        // the mix reads them to pick the legacy/cathedral bus feeds.
        core.handle_event(EvKind::Prog { ch: 0, prog: 48 });
        assert_eq!(
            core.strips[0].chorus_send, authored_cho,
            "Program Change discarded the authored CC93 chorus send"
        );
        assert_eq!(
            core.strips[0].delay_send, authored_del,
            "Program Change discarded the authored CC94 delay send"
        );
        assert!(core.strips[0].chorus_authored);
        assert!(core.strips[0].delay_authored);

        // A channel that authors NOTHING still tracks the program's profile — the
        // default path is unchanged, so silent files render exactly as before.
        let mut bare = EngineCore::new(core_opts());
        bare.handle_event(EvKind::Prog { ch: 0, prog: 30 });
        assert_eq!(bare.strips[0].chorus_send, 0.10);
        assert_eq!(bare.strips[0].delay_send, 0.30);
        bare.handle_event(EvKind::Prog { ch: 0, prog: 48 });
        assert_eq!(bare.strips[0].chorus_send, 0.35);
        assert_eq!(bare.strips[0].delay_send, 0.0);

        // Authoring only ONE of the pair leaves the other on the program default.
        let mut half = EngineCore::new(core_opts());
        half.handle_event(EvKind::Cc {
            ch: 0,
            num: 93,
            val: 64,
        });
        half.handle_event(EvKind::Prog { ch: 0, prog: 48 });
        assert_eq!(half.strips[0].chorus_send, 64.0 / 127.0);
        assert_eq!(half.strips[0].delay_send, 0.0);
    }

    // ---- MM-BUG-KILN-00011: CC7 volume / CC10 pan controller slew ----

    fn slew_test_core(sr: f32) -> EngineCore {
        EngineCore::new(CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        })
    }

    fn advance_blocks(core: &mut EngineCore, blocks: usize) {
        let mut sink = [0f32; BLOCK * 2];
        for _ in 0..blocks {
            core.render_block_add(BLOCK, &mut sink);
        }
    }

    /// AC1 (confinement) + AC3 (prime): a channel that never authors CC7/CC10 keeps
    /// its defaults byte-for-byte across many blocks; authoring latches but does not
    /// change the current value until a block primes it.
    #[test]
    fn cc7_cc10_unauthored_channel_is_unchanged() {
        let sr = 44100.0;
        let default_vol = (100.0f32 / 127.0).powi(2);
        let mut core = slew_test_core(sr);
        advance_blocks(&mut core, 50);
        let s = &core.strips[0];
        assert_eq!(s.volume, default_vol);
        assert_eq!(s.pan, 0.5);
        assert_eq!(s.haas_delay, 0.0);
        assert!(!s.volume_authored && !s.pan_authored);
        assert!(!s.volume_primed && !s.pan_primed);
    }

    /// AC3: the first block after authoring snaps volume/pan to the *last* value
    /// authored before that block (MIDI last-write-wins for a same-tick burst), with
    /// no glide from the default; haas_delay derives from the snapped pan.
    #[test]
    fn cc7_cc10_prime_on_first_block_is_last_write_wins() {
        let sr = 44100.0;
        let default_vol = (100.0f32 / 127.0).powi(2);
        let mut core = slew_test_core(sr);
        // ch0: a single set at t0 (volume 80, pan 96).
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 7,
            val: 80,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 10,
            val: 96,
        });
        // ch1: a same-tick pan burst 54 then 64 — the last write must win.
        core.handle_event(EvKind::Cc {
            ch: 1,
            num: 10,
            val: 54,
        });
        core.handle_event(EvKind::Cc {
            ch: 1,
            num: 10,
            val: 64,
        });

        // Authored but not yet primed: current values are still the defaults.
        assert!(core.strips[0].volume_authored && !core.strips[0].volume_primed);
        assert_eq!(core.strips[0].volume, default_vol);
        assert_eq!(core.strips[0].pan, 0.5);

        advance_blocks(&mut core, 1);

        // Snapped to the authored targets (no glide from the default).
        assert!((core.strips[0].volume - (80.0f32 / 127.0).powi(2)).abs() < 1e-9);
        assert!((core.strips[0].pan - 96.0 / 127.0).abs() < 1e-9);
        assert!(core.strips[0].volume_primed && core.strips[0].pan_primed);
        // Same-tick burst resolved to the LAST value (64/127), not the first (54/127).
        assert!(
            (core.strips[1].pan - 64.0 / 127.0).abs() < 1e-9,
            "same-tick burst must snap to the last authored value; got {}",
            core.strips[1].pan
        );
        // haas_delay follows the snapped pan.
        let want_haas = 0.005 * sr * (96.0f32 / 127.0 - 0.5).abs() * 2.0;
        assert!((core.strips[0].haas_delay - want_haas).abs() < 1e-6);
    }

    /// AC2 + AC6: a post-prime CC7/CC10 change slews as the CC11 one-pole (exact
    /// step), moving a fraction per block, monotonically, without overshoot, and
    /// converging to the target. haas_delay tracks the slewed pan.
    #[test]
    fn cc7_cc10_post_prime_change_slews_one_pole_monotone() {
        let sr = 44100.0;
        let smooth = 1.0 - (-(BLOCK as f32) / (0.03 * sr)).exp();
        let mut core = slew_test_core(sr);
        // Prime: volume to full, pan hard-left.
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 7,
            val: 127,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 10,
            val: 0,
        });
        advance_blocks(&mut core, 1);
        assert!(
            core.strips[0].pan.abs() < 1e-9,
            "pan primed to hard-left (0)"
        );
        assert!(
            (core.strips[0].volume - 1.0).abs() < 1e-9,
            "volume primed to full"
        );

        // Post-prime change: volume -> 0 (fade), pan -> hard-right (sweep).
        let v0 = core.strips[0].volume; // 1.0
        let p0 = core.strips[0].pan; // 0.0
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 7,
            val: 0,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 10,
            val: 127,
        });
        advance_blocks(&mut core, 1);

        // Exact one-pole step, not a jump.
        let want_v = v0 + smooth * (0.0 - v0);
        let want_p = p0 + smooth * (1.0 - p0);
        assert!(
            (core.strips[0].volume - want_v).abs() < 1e-6,
            "volume one-pole step"
        );
        assert!(
            (core.strips[0].pan - want_p).abs() < 1e-6,
            "pan one-pole step"
        );
        assert!(core.strips[0].volume < v0 && core.strips[0].volume > 0.0);
        assert!(core.strips[0].pan > p0 && core.strips[0].pan < 1.0);

        // Monotone, no overshoot, converges.
        let mut prev_v = core.strips[0].volume;
        let mut prev_p = core.strips[0].pan;
        for _ in 0..500 {
            advance_blocks(&mut core, 1);
            let (v, p) = (core.strips[0].volume, core.strips[0].pan);
            assert!(
                v <= prev_v + 1e-7 && v >= -1e-6,
                "volume monotone down, no undershoot"
            );
            assert!(
                p >= prev_p - 1e-7 && p <= 1.0 + 1e-6,
                "pan monotone up, no overshoot"
            );
            prev_v = v;
            prev_p = p;
        }
        assert!(core.strips[0].volume.abs() < 1e-3, "volume converges to 0");
        assert!(
            (core.strips[0].pan - 1.0).abs() < 1e-3,
            "pan converges to 1"
        );
        // haas tracks the slewed pan each block.
        let want_haas = 0.005 * sr * (core.strips[0].pan - 0.5).abs() * 2.0;
        assert!((core.strips[0].haas_delay - want_haas).abs() < 1e-6);
    }

    /// AC7: during a realistic incremental auto-pan the Haas tap advances in small
    /// per-block steps (no click), unlike the old instant retune which flipped the
    /// whole ~220-sample delay to the other channel at each CC event.
    #[test]
    fn cc10_haas_tap_advances_smoothly_not_in_jumps() {
        let sr = 44100.0;
        let full_range = 0.005 * sr; // ~220 samples: hard-pan Haas delay
        let mut core = slew_test_core(sr);
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 10,
            val: 0,
        });
        advance_blocks(&mut core, 1); // prime hard-left

        // Fast auto-pan: bump the target one CC unit every 4 blocks, 0 -> 127.
        let mut prev = core.strips[0].haas_delay;
        let mut max_block_step = 0.0f32;
        let mut next_v = 1u8;
        for block in 0..700usize {
            if block % 4 == 0 && next_v <= 127 {
                core.handle_event(EvKind::Cc {
                    ch: 0,
                    num: 10,
                    val: next_v,
                });
                next_v += 1;
            }
            advance_blocks(&mut core, 1);
            let h = core.strips[0].haas_delay;
            max_block_step = max_block_step.max((h - prev).abs());
            prev = h;
        }
        // A smooth tap moves well under a sample per block here; the old instant
        // side-flip moved the full ~220-sample delay at once. Bound generously to
        // stay robust while still catching a regression to jump behaviour.
        assert!(
            max_block_step < 0.02 * full_range,
            "Haas tap should advance smoothly: max per-block step {:.3} samples (range {:.1})",
            max_block_step,
            full_range
        );
    }

    /// Oracle 32a (D10, §5.2/§5.3 A/B): the drum room adds early energy a
    /// room-less render lacks, and non-drum channels get no room at all.
    #[test]
    fn drum_room_early_reflections() {
        let sr = 44100.0;
        let song = drum_song(&[(0.05, 36, 115)], 1.0, &[]);
        let opts = Options {
            wet: 0.32,
            ..test_opts(sr)
        };
        let with = render_buses(&song, &opts, true, true, true).0;
        let without = render_buses(&song, &opts, true, false, true).0;
        // the room's first reflections: ~5-30 ms after the kick onset
        let win = |s: &[f32]| left(s)[(0.055 * sr) as usize..(0.085 * sr) as usize].to_vec();
        let diff: Vec<f32> = win(&with)
            .iter()
            .zip(win(&without))
            .map(|(a, b)| a - b)
            .collect();
        assert!(rms(&diff) > 1e-4, "no early room energy: {}", rms(&diff));
        // a piano note gets no room send
        let piano = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 0 }),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 60,
                        vel: 100,
                    },
                ),
                (0.8, EvKind::NoteOff { ch: 0, key: 60 }),
            ],
            1.2,
        );
        let a = render_buses(&piano, &opts, true, true, true).0;
        let b = render_buses(&piano, &opts, true, false, true).0;
        assert!(
            a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()),
            "non-ch9 audio leaked into the drum room"
        );
    }

    /// MM-BUG-KILN-00028: once channel 10 authors CC91, that controller owns
    /// both of its reverberant sends. CC91=0 must therefore make the kit
    /// bit-identical whether the private drum-room bus is enabled or disabled.
    #[test]
    fn authored_cc91_zero_dries_the_channel_10_room() {
        let sr = 44100.0;
        let song = drum_song(&[(0.05, 36, 115)], 1.0, &[(91, 0)]);
        let opts = Options {
            wet: 0.32,
            ..test_opts(sr)
        };
        let with_room = render_buses(&song, &opts, true, true, true).0;
        let without_room = render_buses(&song, &opts, true, false, true).0;
        assert!(
            with_room
                .iter()
                .zip(&without_room)
                .all(|(with, without)| with.to_bits() == without.to_bits()),
            "authored channel-10 CC91=0 left drum-room energy"
        );
    }

    #[test]
    fn authored_cc91_scales_the_drum_room_linearly() {
        let sr = 44100.0;
        let mut core = EngineCore::new(CoreOptions {
            sr,
            wet: 0.32,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        });
        assert_eq!(
            core.strips[9].drum_room_send(),
            ROOM_SEND,
            "unauthored CC91 must retain the exact historical room constant"
        );
        for &val in &[0u8, 32, 64, 96, 127] {
            core.handle_event(EvKind::Cc {
                ch: 9,
                num: 91,
                val,
            });
            assert_eq!(
                core.strips[9].drum_room_send(),
                ROOM_SEND * (val as f32 / 127.0),
                "CC91={val} did not scale the drum room linearly"
            );
        }
    }

    /// GS and XG rhythm parts share the secondary drum mix path. Their OWN
    /// authored CC91 must dry their room rather than consulting channel 10.
    #[test]
    fn authored_cc91_zero_dries_gs_and_xg_drum_rooms() {
        let sr = 44100.0;
        let opts = Options {
            wet: 0.32,
            ..test_opts(sr)
        };
        for (name, route) in [
            ("GS", EvKind::DrumMode { ch: 11, on: true }),
            (
                "XG",
                EvKind::Cc {
                    ch: 11,
                    num: 0,
                    val: 127,
                },
            ),
        ] {
            let song = test_song(
                vec![
                    (0.0, route),
                    (
                        0.01,
                        EvKind::Cc {
                            ch: 11,
                            num: 91,
                            val: 0,
                        },
                    ),
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 11,
                            key: 36,
                            vel: 115,
                        },
                    ),
                ],
                1.0,
            );
            let with_room = render_buses(&song, &opts, true, true, true).0;
            let without_room = render_buses(&song, &opts, true, false, true).0;
            assert!(
                with_room
                    .iter()
                    .zip(&without_room)
                    .all(|(with, without)| with.to_bits() == without.to_bits()),
                "authored {name} rhythm-part CC91=0 left drum-room energy"
            );
        }
    }

    /// Oracle 19 (G5, §5.3 difference signal): the guitar-sympathetic bus
    /// rings the open strings under an acoustic guitar, and stays silent
    /// for the driven electric.
    #[test]
    fn guitar_sympathetic_rings_open_strings() {
        let sr = 44100.0;
        let strum = |prog: u8| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog })];
            for (i, &key) in [40u8, 45, 50, 55, 59, 64].iter().enumerate() {
                let t = i as f64 * 0.012;
                ev.push((
                    t,
                    EvKind::NoteOn {
                        ch: 0,
                        key,
                        vel: 105,
                    },
                ));
                ev.push((1.2, EvKind::NoteOff { ch: 0, key }));
            }
            test_song(ev, 1.6)
        };
        let opts = test_opts(sr);
        let with = render_buses(&strum(24), &opts, true, true, true).0;
        let without = render_buses(&strum(24), &opts, false, true, true).0;
        let d: Vec<f32> = left(&with)
            .iter()
            .zip(left(&without))
            .map(|(a, b)| a - b)
            .collect();
        let tail = &d[(0.3 * sr) as usize..(0.8 * sr) as usize];
        let ring: f32 = [82.41f32, 110.0, 146.83]
            .iter()
            .map(|&f| crate::testutil::band_rms(tail, sr, f, 8.0))
            .sum();
        assert!(ring > 1e-5, "sympathetic strings silent: {ring}");
        // prog 30 (driven electric) must not feed the bus at all
        let e_with = render_buses(&strum(30), &opts, true, true, true).0;
        let e_without = render_buses(&strum(30), &opts, false, true, true).0;
        assert!(
            e_with
                .iter()
                .zip(&e_without)
                .all(|(x, y)| x.to_bits() == y.to_bits()),
            "electric guitar leaked into the sympathetic bus"
        );
    }

    /// Tarab oracle (GM 104, v0.16, §5.3 difference signal): the sitar's
    /// thirteen sympathetic strings ring under a sitar note — the bus-on
    /// minus bus-off difference is exactly the tarab return, comb-shaped
    /// around the resonating strings — and a banjo (or anything else)
    /// leaves the bus bit-identically silent.
    #[test]
    fn sitar_tarab_strings_ring_sympathetically() {
        let sr = 44100.0;
        let song = |prog: u8| {
            test_song(
                vec![
                    (0.0, EvKind::Prog { ch: 0, prog }),
                    (
                        0.02,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 62,
                            vel: 105,
                        },
                    ),
                    (1.0, EvKind::NoteOff { ch: 0, key: 62 }),
                ],
                1.8,
            )
        };
        let opts = test_opts(sr);
        let with = render_buses(&song(104), &opts, true, true, true).0;
        let without = render_buses(&song(104), &opts, true, true, false).0;
        let d: Vec<f32> = left(&with)
            .iter()
            .zip(left(&without))
            .map(|(a, b)| a - b)
            .collect();
        let (w0, w1) = ((0.20 * sr) as usize, (1.20 * sr) as usize);
        let ring = rms(&d[w0..w1]);
        let dry = rms(&left(&without)[w0..w1]);
        // the return is a real halo relative to the dry sitar, not dust
        assert!(
            ring > 1e-3 * dry,
            "tarab strings silent: return {ring} vs dry {dry}"
        );
        // …and it is comb-shaped: the D4 tarab string (the played pitch)
        // rings far above a probe BELOW the whole bank (261.63 Hz bottom
        // string; probes between combs are useless — thirteen strings'
        // overtone series blanket everything above)
        let played = crate::testutil::band_rms(&d[w0..w1], sr, 293.66, 8.0);
        let probe = crate::testutil::band_rms(&d[w0..w1], sr, 225.0, 8.0);
        assert!(
            played > 2.0 * probe,
            "tarab return not comb-shaped: D4 {played} vs 225 Hz {probe}"
        );
        // a banjo playing the same note must not feed the bus at all
        let b_with = render_buses(&song(105), &opts, true, true, true).0;
        let b_without = render_buses(&song(105), &opts, true, true, false).0;
        assert!(
            b_with
                .iter()
                .zip(&b_without)
                .all(|(x, y)| x.to_bits() == y.to_bits()),
            "banjo leaked into the tarab bus"
        );
    }

    /// Oracle 26 (D6, engine half): a closed-hat strike chokes the ringing
    /// open hat in the full render path.
    #[test]
    fn closed_hat_chokes_open_in_engine() {
        let sr = 44100.0;
        let open_only = drum_song(&[(0.05, 46, 110)], 1.0, &[]);
        let choked = drum_song(&[(0.05, 46, 110), (0.25, 42, 90)], 1.0, &[]);
        let a = render(&open_only, &test_opts(sr)).0;
        let b = render(&choked, &test_opts(sr)).0;
        let w = |s: &[f32]| rms(&left(s)[(0.32 * sr) as usize..(0.45 * sr) as usize]);
        assert!(
            w(&b) < 0.3 * w(&a),
            "open hat survived the choke: {} vs {}",
            w(&b),
            w(&a)
        );
    }

    /// Normalized cross-correlation of two equal windows, max |r| over
    /// ±`max_lag` samples — the anti-machine-gun similarity measure.
    #[cfg(feature = "embedded-samples")]
    fn ncc_max(a: &[f32], b: &[f32], max_lag: usize) -> f32 {
        fn ncc_at(a: &[f32], b: &[f32]) -> f32 {
            let (mut sab, mut saa, mut sbb) = (0f64, 0f64, 0f64);
            for (&x, &y) in a.iter().zip(b) {
                sab += (x * y) as f64;
                saa += (x * x) as f64;
                sbb += (y * y) as f64;
            }
            (sab / (saa.sqrt() * sbb.sqrt()).max(1e-30)) as f32
        }
        let n = a.len().min(b.len()) - max_lag;
        let mut best = 0f32;
        for lag in 0..=max_lag {
            best = best.max(ncc_at(&a[..n], &b[lag..lag + n]).abs());
            best = best.max(ncc_at(&a[lag..lag + n], &b[..n]).abs());
        }
        best
    }

    /// First sample above 5% of the window's peak — a hit's true onset,
    /// undoing the engine's block-quantized voice spawn.
    #[cfg(feature = "embedded-samples")]
    fn hit_onset(w: &[f32]) -> usize {
        let peak = w.iter().fold(0f32, |m, &x| m.max(x.abs()));
        w.iter().position(|&x| x.abs() > 0.05 * peak).unwrap_or(0)
    }

    /// Rate-warp-searching NCC: max correlation over playback-rate ratios
    /// ±5.5% (the jitter spread of two hits), warping `b` from its detected
    /// onset and comparing a 40 ms window that starts 30 ms in — past the
    /// stick transient every take of one cymbal shares, into the
    /// take-specific wash. A rate-jittered copy of the SAME take re-aligns
    /// near its true ratio and reads high; a different take stays low at
    /// every warp. Plain NCC cannot make this distinction — ±2.5% rate
    /// jitter alone already decorrelates the window (measured ~0.07-0.19 for
    /// the same take), which would let a seed-modulo repeat sail through.
    #[cfg(feature = "embedded-samples")]
    fn warp_ncc(a: &[f32], b: &[f32]) -> f32 {
        let (a, b) = (&a[hit_onset(a)..], &b[hit_onset(b)..]);
        let w0 = 1323usize; // window start: 30 ms
        let n = 1764usize; // window length: 40 ms
        let lag = 48usize; // residual onset-estimate error
        let steps = 220;
        // correlate FIRST DIFFERENCES: differencing tilts the measure toward
        // the high-frequency sizzle that is take-specific, away from the low
        // plate modes every take of one cymbal shares
        let da: Vec<f32> = a[w0..w0 + n + lag + 1]
            .windows(2)
            .map(|p| p[1] - p[0])
            .collect();
        let mut warped = vec![0f32; w0 + n + lag + 1];
        let mut best = 0f32;
        for s in 0..=steps {
            let r = 0.945 + 0.11 * s as f32 / steps as f32;
            for (i, w) in warped.iter_mut().enumerate() {
                let x = i as f32 * r;
                let j = x as usize;
                let frac = x - j as f32;
                *w = b[j] * (1.0 - frac) + b[j + 1] * frac;
            }
            let dw: Vec<f32> = warped[w0..].windows(2).map(|p| p[1] - p[0]).collect();
            best = best.max(ncc_max(&da, &dw, lag));
        }
        best
    }

    /// THE anti-machine-gun oracle (Stage C headline). Eight ride hits of the
    /// SAME key through the full engine path, so the per-key round-robin
    /// counter drives the take and the note seed drives the micro-variation:
    ///
    ///  * consecutive hits must be genuinely different TAKES: their
    ///    warp-searched NCC stays low. Seed-modulo rr picking repeats a take
    ///    back-to-back, the warp search re-aligns it through the rate jitter,
    ///    and this clause goes red (fail-first proven);
    ///  * NO pair of the eight may correlate like a clone (plain NCC ~1.0)
    ///    and no two hits may be bit-identical: dropping the rate/gain
    ///    micro-variation makes hits 0&4/1&5/… (same take after the 4-take
    ///    wrap) exact clones and this clause goes red (fail-first proven).
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn sampled_ride_hits_are_decorrelated() {
        let sr = 44100.0;
        let n_hits = 8usize;
        let spacing = 1.3f64; // ride takes are ~1.2 s: windows never overlap
        let hits: Vec<(f64, u8, u8)> = (0..n_hits)
            .map(|i| (0.05 + spacing * i as f64, 51u8, 100u8))
            .collect();
        // dry drum bus: zero the sends so hit windows hold only the voice
        let song = drum_song(
            &hits,
            0.05 + spacing * n_hits as f64,
            &[(91, 0), (93, 0), (94, 0)],
        );
        let opt = Options {
            samples: true,
            ..test_opts(sr)
        };
        let s = render(&song, &opt).0;
        let mono: Vec<f32> = s.chunks_exact(2).map(|p| p[0] + p[1]).collect();
        let win = |i: usize| {
            let at = ((0.05 + spacing * i as f64) * sr as f64) as usize;
            &mono[at..at + (0.20 * sr) as usize]
        };
        let mut worst_any = 0f32;
        for i in 0..n_hits {
            for j in (i + 1)..n_hits {
                assert_ne!(win(i), win(j), "hits {i} and {j} are bit-identical");
                let r = ncc_max(win(i), win(j), 128);
                if j == i + 1 || j == i + 4 {
                    println!("ride hits {i}-{j}: plain ncc {r:.3}");
                }
                worst_any = worst_any.max(r);
            }
        }
        // calibration visibility: same-take pairs (i, i+4) must read HIGH
        // under the warp search — that head-room is what lets the consecutive
        // clause catch a seed-modulo repeat
        for i in 0..n_hits - 4 {
            let r = warp_ncc(win(i), win(i + 4));
            println!("ride hits {i}-{} (same take): warp ncc {r:.3}", i + 4);
        }
        let mut worst_consecutive = 0f32;
        for i in 0..n_hits - 1 {
            let r = warp_ncc(win(i), win(i + 1));
            println!("ride hits {i}-{}: warp ncc {r:.3}", i + 1);
            worst_consecutive = worst_consecutive.max(r);
        }
        // Calibration (measured on this bank): distinct takes warp-NCC
        // 0.12-0.48; the same take under micro-variation re-aligns to
        // 0.70-0.86; a clone is 1.0. The 0.60 threshold sits ≥0.10 clear of
        // both populations.
        assert!(
            worst_consecutive < 0.60,
            "consecutive ride hits warp-correlate {worst_consecutive:.3} — round-robin repeat"
        );
        assert!(
            worst_any < 0.98,
            "some ride hit pair is a clone: ncc {worst_any:.3}"
        );
    }

    /// Stage E (engine half): the hi-hat choke group survives the sampled
    /// kit — a closed (42) or pedal (44) strike chokes the ringing SAMPLED
    /// open hat (46) within ~30 ms, exactly as the modeled hats behave
    /// (`closed_hat_chokes_open_in_engine`).
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn sampled_closed_or_pedal_hat_chokes_open_in_engine() {
        let sr = 44100.0;
        let opt = Options {
            samples: true,
            ..test_opts(sr)
        };
        let open_only = drum_song(&[(0.05, 46, 110)], 1.0, &[]);
        let a = render(&open_only, &opt).0;
        // 30 ms after the choking hit the open ring must be gone (the voice
        // fade is -60 dB in ~15 ms). The window also contains the choker's
        // OWN body (the pedal chick rings well past 200 ms), so the oracle
        // measures the RESIDUAL: choked-render energy minus the energy of
        // the choker played alone. An unchoked open hat leaves its full ring
        // in the residual; a choked one leaves almost nothing.
        let w = |s: &[f32]| rms(&left(s)[(0.28 * sr) as usize..(0.45 * sr) as usize]);
        for choker in [42u8, 44] {
            let choked = drum_song(&[(0.05, 46, 110), (0.25, choker, 90)], 1.0, &[]);
            let b = render(&choked, &opt).0;
            let solo = drum_song(&[(0.25, choker, 90)], 1.0, &[]);
            let c = render(&solo, &opt).0;
            let residual = (w(&b).powi(2) - w(&c).powi(2)).max(0.0).sqrt();
            println!(
                "choker {choker}: open-only {:.5}, choked {:.5}, choker-solo {:.5}, residual {:.5}",
                w(&a),
                w(&b),
                w(&c),
                residual
            );
            assert!(
                residual < 0.35 * w(&a),
                "sampled open hat survived the key-{choker} choke: residual {residual} vs open ring {}",
                w(&a)
            );
        }
    }

    /// THE Stage E anti-machine-gun oracle for the highest-stakes piece:
    /// hats play continuous 16ths. Sixteen closed-hat (42) hits at 16th-note
    /// spacing (120 bpm, 0.125 s) through the full engine path, so the
    /// per-key round-robin counter cycles the 4 takes and the note seed
    /// drives the per-hit rate/gain micro-variation:
    ///
    ///  * every hit window must be audible and NO pair bit-identical;
    ///  * NO pair — same-take or cross-take — may correlate above 0.35
    ///    (listener-verified: the pre-hat-profile kit read worst-pair 0.494
    ///    and Arthur heard it as machine-gunny). Uniform ±2.5% rate jitter
    ///    cannot reach this: over 16 hits some same-take pair always lands
    ///    within a fraction of a percent in rate, re-correlating the
    ///    transient (fail-first: threshold tightened before the hat jitter
    ///    profile landed — the old engine read 0.494 against this 0.35).
    ///    The hat profile answers with STRATIFIED rate offsets
    ///    (hit_index % 5 over ±7%, coprime with the 4-take round-robin, so
    ///    no two hits closer than 20 apart share take AND rate stratum)
    ///    plus onset jitter (U(0, 1 ms)) and wider gain jitter;
    ///  * the same-take pairs (i, i+4 after the 4-take wrap) must differ
    ///    SUBSTANTIALLY (normalized difference energy — the ride oracle's
    ///    diff/rms measure).
    ///
    /// The clone detector is calibrated FAIL-FIRST inside the test: two
    /// voices built with the same seed and same hit index (what a
    /// machine-gun engine would produce) render bit-identically and read
    /// NCC 1.0 — the reading the engine path must never approach.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn sampled_fast_closed_hats_do_not_machine_gun() {
        let sr = 44100.0;
        // fail-first calibration: same seed + same take == a true machine gun
        let clone_hat = || {
            let mut w = vec![0f32; (0.10 * sr) as usize];
            let mut v = drums::make(42, 100, sr, 0xBEEF, drums::Kit::V3, true, 3).unwrap();
            v.render(&mut w);
            w
        };
        let (c1, c2) = (clone_hat(), clone_hat());
        assert_eq!(c1, c2, "identical seed+take must render bit-identically");
        let clone_ncc = ncc_max(&c1, &c2, 128);
        assert!(
            clone_ncc > 0.999,
            "clone detector miscalibrated: {clone_ncc:.4}"
        );

        let n = 16usize;
        let dt = 0.125f64; // 16th notes at 120 bpm
        let hits: Vec<(f64, u8, u8)> = (0..n).map(|i| (0.05 + dt * i as f64, 42, 100)).collect();
        // dry drum bus: zero the sends so hit windows hold only the voice
        let song = drum_song(
            &hits,
            0.05 + dt * n as f64 + 0.3,
            &[(91, 0), (93, 0), (94, 0)],
        );
        let opt = Options {
            samples: true,
            ..test_opts(sr)
        };
        let s = render(&song, &opt).0;
        let mono: Vec<f32> = s.chunks_exact(2).map(|p| p[0] + p[1]).collect();
        let win = |i: usize| -> &[f32] {
            let at = ((0.05 + dt * i as f64) * sr as f64) as usize;
            &mono[at..at + (0.10 * sr) as usize]
        };
        for i in 0..n {
            assert!(
                rms(win(i)) > 1e-4,
                "hat hit {i} is silent — sampled hat not routed?"
            );
        }
        let mut worst_any = 0f32;
        for i in 0..n {
            for j in (i + 1)..n {
                assert_ne!(win(i), win(j), "hat hits {i} and {j} are bit-identical");
                worst_any = worst_any.max(ncc_max(win(i), win(j), 128));
            }
        }
        let mut worst_diff = f32::INFINITY;
        for i in 0..n - 4 {
            let (a, b) = (win(i), win(i + 4));
            let diff: Vec<f32> = a.iter().zip(b).map(|(x, y)| x - y).collect();
            worst_diff = worst_diff.min(rms(&diff) / rms(a).max(1e-9));
        }
        println!(
            "fast hats: max pairwise ncc {worst_any:.3} (clone reads {clone_ncc:.3}), \
             min same-take diff/rms {worst_diff:.3}"
        );
        assert!(
            worst_any < 0.35,
            "some hat pair correlates {worst_any:.3} (limit 0.35) — MACHINE-GUN: \
             the hat jitter profile is not decorrelating repeats"
        );
        assert!(
            worst_diff > 0.4,
            "same-take hats nearly identical (diff/rms {worst_diff:.3}) — \
             MACHINE-GUN: the micro-variation is not decorrelating repeats"
        );
    }

    /// Oracle 3 (§5.1/§5.3): the cabinet's magnitude response, measured on
    /// the linear cab chain alone at the 2× rate it runs at — presence peak,
    /// steep HF cliff, low-end resonance.
    #[test]
    fn cabinet_response_shape() {
        let sr2 = 88_200.0;
        let mut cab = cab_biquads(sr2);
        let mut ir = vec![0f32; 16384];
        ir[0] = 1.0;
        for x in ir.iter_mut() {
            let mut y = *x;
            for c in cab.iter_mut() {
                y = c.process(y);
            }
            *x = y;
        }
        let db = |f: f32| 20.0 * crate::testutil::mag_at(&ir, sr2, f).max(1e-12).log10();
        assert!(
            db(2600.0) - db(1000.0) >= 3.0,
            "presence: 2600 {:.1} dB vs 1000 {:.1} dB",
            db(2600.0),
            db(1000.0)
        );
        assert!(
            db(6000.0) - db(3000.0) <= -18.0,
            "cliff: 6000 {:.1} dB vs 3000 {:.1} dB",
            db(6000.0),
            db(3000.0)
        );
        assert!(
            db(100.0) - db(300.0) >= 2.0,
            "low resonance: 100 {:.1} dB vs 300 {:.1} dB",
            db(100.0),
            db(300.0)
        );
    }

    /// Guitar-realism HLD §5 / AC4 (bar recalibrated in-implementation, HLD
    /// §14 rider): MicroCab standalone puts genuine fine structure on the
    /// 900–3600 Hz band — ≥ 6 magnitude alternations of ≥ 1.5 dB (the
    /// drafted "≥ 2 dB" was physically over-spec'd for a ≤ 0.9 ms sparse
    /// FIR: a 250 k-candidate search found no tap set meeting it inside the
    /// cliff-tilt and low-band bounds) — while the band-average stays
    /// ~unity and the total swing stays musical. Whether it reads as "cab"
    /// vs "phaser" is the audition's call — this pins presence and level.
    #[test]
    fn micro_cab_ripple_fine_structure() {
        let sr2 = 88_200.0;
        let mut mc = MicroCab::with_depth(sr2, 1.0);
        let mut ir = vec![0f32; 4096];
        ir[0] = 1.0;
        for x in ir.iter_mut() {
            *x = mc.process(*x);
        }
        let db = |f: f32| 20.0 * crate::testutil::mag_at(&ir, sr2, f).max(1e-12).log10();
        let grid: Vec<f32> = (0..55).map(|k| 900.0 + k as f32 * 50.0).collect();
        let curve: Vec<f32> = grid.iter().map(|&f| db(f)).collect();
        // count direction reversals with >= 1.5 dB swing from the running
        // extreme (dir 0 = no run yet: track both extremes)
        const DEPTH: f32 = 1.5;
        let (mut alternations, mut dir) = (0usize, 0i8);
        let (mut mn, mut mx) = (curve[0], curve[0]);
        for &v in &curve[1..] {
            if dir >= 0 {
                mx = mx.max(v);
            }
            if dir <= 0 {
                mn = mn.min(v);
            }
            if dir >= 0 && mx - v >= DEPTH {
                alternations += 1;
                dir = -1;
                mn = v;
            } else if dir <= 0 && v - mn >= DEPTH {
                alternations += 1;
                dir = 1;
                mx = v;
            }
        }
        assert!(
            alternations >= 6,
            "fine structure too smooth: {alternations} alternations >= 1.5 dB in 900-3600 Hz ({curve:?})"
        );
        // band-average parity vs an identity (bare impulse) measured the
        // same way — mag_at carries a fixed impulse-scale offset, so the
        // contract is relative, not absolute
        let mut ident = vec![0f32; 4096];
        ident[0] = 1.0;
        let dbi = |f: f32| 20.0 * crate::testutil::mag_at(&ident, sr2, f).max(1e-12).log10();
        let avg: f32 = grid.iter().map(|&f| db(f) - dbi(f)).sum::<f32>() / grid.len() as f32;
        assert!(
            avg.abs() < 1.5,
            "band-average moved: {avg:.2} dB (normalization contract)"
        );
        let (lo, hi) = curve
            .iter()
            .fold((f32::MAX, f32::MIN), |(a, b), &v| (a.min(v), b.max(v)));
        assert!(
            hi - lo <= 10.0,
            "standalone ripple swing {:.1} dB — too deep to stay musical",
            hi - lo
        );
    }

    /// The cabinet ripple must not cost a SUSTAINING lead its money note.
    ///
    /// `MicroCab` normalizes to unity on the 900–3600 Hz band AVERAGE, which
    /// is level-neutral for broadband material but not for a voice holding
    /// ONE pitch: it keeps whatever the ripple does at that single frequency.
    /// At full depth the comb is coarse enough to swallow a held tone whole —
    /// measured on Three-Sixty-One's finale, C6 −2.08 dB and E6 −1.03 dB at
    /// the fundamental with their harmonics +2.8 dB, i.e. thin rather than
    /// merely quiet (2026.07.20 journal). [`MICRO_CAB_LEAD_DEPTH`] bounds
    /// that for the CC0 alt bank while keeping the ripple audible.
    ///
    /// RED if the lead depth is restored to full (worst-case deviation goes
    /// back over 3 dB), and RED the other way if someone zeroes the ripple
    /// instead of shallowing it (the lead would stop speaking through a cab).
    #[test]
    fn sustaining_lead_cab_ripple_is_bounded_at_every_held_pitch() {
        let sr2 = 88_200.0;
        let curve = |depth: f32| -> Vec<f32> {
            let mut mc = MicroCab::with_depth(sr2, depth);
            let mut ir = vec![0f32; 4096];
            ir[0] = 1.0;
            for x in ir.iter_mut() {
                *x = mc.process(*x);
            }
            let mut ident = vec![0f32; 4096];
            ident[0] = 1.0;
            (0..=270)
                .map(|k| {
                    let f = 900.0 + k as f32 * 10.0;
                    20.0 * (crate::testutil::mag_at(&ir, sr2, f).max(1e-12)
                        / crate::testutil::mag_at(&ident, sr2, f).max(1e-12))
                    .log10()
                })
                .collect()
        };
        let worst = |c: &[f32]| c.iter().fold(0f32, |m, v| m.max(v.abs()));
        let swing = |c: &[f32]| {
            let (lo, hi) = c
                .iter()
                .fold((f32::MAX, f32::MIN), |(a, b), &v| (a.min(v), b.max(v)));
            hi - lo
        };
        let (full, lead) = (curve(1.0), curve(MICRO_CAB_LEAD_DEPTH));

        // (1) the pathology is real at full depth — this is what the default
        // bank still carries, deliberately, for broadband rhythm work
        assert!(
            worst(&full) > 2.5,
            "full-depth ripple only {:.2} dB deep — the premise of this fix is gone",
            worst(&full)
        );
        // (2) ... and is bounded below audibility for a held tone on the lead
        assert!(
            worst(&lead) < 1.0,
            "sustaining lead can lose {:.2} dB on a held pitch (want < 1.0)",
            worst(&lead)
        );
        // (3) ... without deleting the cabinet: the ripple is still there
        assert!(
            swing(&lead) > 0.8,
            "lead ripple flattened to {:.2} dB swing — that is a DI, not a cab",
            swing(&lead)
        );
        // (4) the specific tones that provoked this: C6 and E6 recover
        let at = |c: &[f32], f: f32| c[((f - 900.0) / 10.0).round() as usize];
        for (name, f0, want) in [("C6", 1050.0, 1.0), ("E6", 1320.0, 0.5)] {
            let gain = at(&lead, f0) - at(&full, f0);
            assert!(
                gain >= want,
                "{name} ({f0} Hz) recovers only {gain:.2} dB (want >= {want})"
            );
        }
    }

    /// The bank is part of the driven insert's identity, so a CC0 that lands
    /// AFTER the program change must rebuild it. Our albums order bank-select
    /// first (`fix(albums): order bank select before program changes`), but a
    /// foreign GM file need not, and the two orderings must agree.
    #[test]
    fn cc0_bank_select_reaches_the_driven_cabinet_in_either_order() {
        let sr = 44100.0;
        let opts = test_opts(sr);
        let song = |bank_first: bool, bank: u8| {
            let mut ev = Vec::new();
            if bank_first {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: bank,
                    },
                ));
                ev.push((0.0, EvKind::Prog { ch: 0, prog: 29 }));
            } else {
                ev.push((0.0, EvKind::Prog { ch: 0, prog: 29 }));
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: bank,
                    },
                ));
            }
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 88,
                    vel: 104,
                },
            ));
            test_song(ev, 2.0)
        };
        let alt_first = render(&song(true, 1), &opts).0;
        let alt_after = render(&song(false, 1), &opts).0;
        let default_bank = render(&song(true, 0), &opts).0;

        assert!(rms(&alt_first) > 1e-4, "the driven lead should sound");
        assert_eq!(
            alt_first, alt_after,
            "CC0 after the program change did not reach the driven cabinet — \
             the insert was left on the default bank's ripple depth"
        );
        assert_ne!(
            alt_first, default_bank,
            "the alt bank renders identically to the default — the shallower \
             lead cabinet ripple is not wired up"
        );
    }

    /// Guitar-realism HLD §5 / AC4 (review C5) — the SHIPPED series response
    /// (MicroCab into the cab biquads) keeps the macro cabinet shape the
    /// coarse oracle pins on the biquads alone, bounds the ripple depth, and
    /// holds broadband level parity with the biquads-only cab.
    #[test]
    fn micro_cab_combined_keeps_macro_shape() {
        let sr2 = 88_200.0;
        let run = |with_micro: bool| {
            let mut cab = cab_biquads(sr2);
            let mut mc = MicroCab::with_depth(sr2, 1.0);
            let mut ir = vec![0f32; 16384];
            ir[0] = 1.0;
            for x in ir.iter_mut() {
                let mut y = *x;
                for c in &mut cab[..CAB_CLIFF] {
                    y = c.process(y);
                }
                if with_micro {
                    y = mc.process(y);
                }
                for c in &mut cab[CAB_CLIFF..] {
                    y = c.process(y);
                }
                *x = y;
            }
            ir
        };
        let ir = run(true);
        let db = |ir: &[f32], f: f32| 20.0 * crate::testutil::mag_at(ir, sr2, f).max(1e-12).log10();
        // the same three macro anchors cabinet_response_shape pins
        assert!(
            db(&ir, 2600.0) - db(&ir, 1000.0) >= 3.0,
            "presence lost: 2600 {:.1} vs 1000 {:.1}",
            db(&ir, 2600.0),
            db(&ir, 1000.0)
        );
        assert!(
            db(&ir, 6000.0) - db(&ir, 3000.0) <= -18.0,
            "cliff lost: 6000 {:.1} vs 3000 {:.1}",
            db(&ir, 6000.0),
            db(&ir, 3000.0)
        );
        assert!(
            db(&ir, 100.0) - db(&ir, 300.0) >= 2.0,
            "low resonance lost: 100 {:.1} vs 300 {:.1}",
            db(&ir, 100.0),
            db(&ir, 300.0)
        );
        // ripple depth bounded: within 900-3600 the swing stays musical
        let vals: Vec<f32> = (0..28).map(|k| db(&ir, 900.0 + k as f32 * 100.0)).collect();
        let (mn, mx) = vals
            .iter()
            .fold((f32::MAX, f32::MIN), |(a, b), &v| (a.min(v), b.max(v)));
        assert!(
            mx - mn <= 14.0,
            "ripple guts the band: {:.1} dB swing in 900-3600",
            mx - mn
        );
        // broadband level parity vs the biquads-only cab
        let base = run(false);
        let band_avg = |ir: &[f32]| {
            (0..28)
                .map(|k| db(ir, 300.0 + k as f32 * 100.0))
                .sum::<f32>()
                / 28.0
        };
        let delta = band_avg(&ir) - band_avg(&base);
        assert!(
            delta.abs() < 1.5,
            "combined cab level moved {delta:.2} dB vs biquads-only"
        );
    }

    /// Oracle 4 (§5.3): the biased shaper adds a real 2nd harmonic (a pure
    /// sine in, so 2f can only come from the new asymmetry) and the DC
    /// blocker holds the sustained output DC-free.
    ///
    /// Extended 2026.07.23 to both programs, both banks and two drive levels
    /// (16 points, up from 1). The lead bank runs a relaxed bias (0.85 vs the
    /// rhythm amps' 0.9), so this is the pin that it did not trade its
    /// even-harmonic warmth away.
    ///
    /// The extension exposed a physics fact worth recording, because it looks
    /// like a bug and is not: **at the LOUD operating point both banks are
    /// legitimately ODD-harmonic dominated.** A deeply clipped wave is nearly a
    /// square, and a square is odd. Measured H2−H3 at amp 0.5, f0 110 Hz:
    /// 29-main −14.4 dB, 30-main −15.6, 29-alt −22.6, 30-alt −23.7 — negative
    /// for the SHIPPED rhythm amps too. So "H2 must exceed a tenth of H3" is a
    /// meaningful test of the asymmetry mechanism only at moderate drive, where
    /// the bias — not the rail — is what breaks the waveform's symmetry. Do not
    /// "fix" a future loud-point failure by re-biasing; check the tail first.
    ///
    /// Hence three claims, each asserted where it is actually the design's:
    ///   1. DC-free at EVERY operating point (unconditional).
    ///   2. Real even-harmonic content present at every operating point
    ///      (H2 ≥ −40 dBc; worst measured −34.3 dBc).
    ///   3. Even harmonics DOMINATE the odd at the moderate/tail point, which
    ///      is where the "tube warmth" claim lives (worst measured +6.1 dB).
    ///
    /// Plus the original single-point pin, retained verbatim so nothing this
    /// oracle used to catch is lost.
    #[test]
    fn drive_asymmetry_and_dc() {
        let sr = 44100.0;
        let f0 = 110.0;
        let measure = |prog: u8, alt: bool, amp: f32| {
            let mut drive = Drive::new(prog, alt, sr);
            let mut buf: Vec<f32> = (0..(sr as usize))
                .map(|i| amp * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
                .collect();
            drive.process(&mut buf);
            // skip the DC-blocker settling (§5.3: window starts ≥50 ms in)
            let seg = &buf[(0.05 * sr) as usize..];
            let dc = seg.iter().map(|&x| x as f64).sum::<f64>() / seg.len() as f64;
            let m1 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
            let m2 = crate::testutil::mag_at(seg, sr, 2.0 * f0);
            let m3 = crate::testutil::mag_at(seg, sr, 3.0 * f0);
            (dc, m1, m2, m3)
        };

        // The ORIGINAL pin, unchanged: prog 29, default bank, loud, 110 Hz.
        let (dc, _, m2, m3) = measure(29, false, 0.5);
        assert!(dc.abs() < 1e-3, "sustained DC {dc}");
        assert!(m2 > 0.1 * m3, "2nd harmonic {m2} vs 3rd {m3}");

        for prog in [29u8, 30] {
            for alt in [false, true] {
                for amp in [0.5f32, 0.05] {
                    let (dc, m1, m2, m3) = measure(prog, alt, amp);
                    let bank = if alt { "alt " } else { "main" };

                    // (1) DC-free everywhere.
                    assert!(
                        dc.abs() < 1e-3,
                        "prog {prog} {bank} amp {amp}: sustained DC {dc}"
                    );

                    // (2) the asymmetry mechanism is alive everywhere.
                    let h2 = 20.0 * (m2 / m1).log10();
                    assert!(
                        h2 >= -40.0,
                        "prog {prog} {bank} amp {amp}: the biased shaper produced no real 2nd \
                         harmonic — H2 {h2:.1} dBc"
                    );

                    // (3) and it DOMINATES where the warmth claim lives.
                    if amp < 0.1 {
                        assert!(
                            m2 > 0.1 * m3,
                            "prog {prog} {bank} amp {amp}: the biased shaper lost its \
                             even-harmonic warmth at the tail operating point — \
                             2nd harmonic {m2} vs 3rd {m3}"
                        );
                    }
                }
            }
        }
    }

    /// Oracle 5 (§5.1 differential): the program-keyed pre-voicing shifts
    /// the 600 Hz : 2 kHz balance in the intended direction against a
    /// voice-bypassed reference — prog 30 scoops the mids, prog 29 pushes.
    #[test]
    fn drive_pre_voicing_direction() {
        let sr = 44100.0;
        let input: Vec<f32> = {
            let mut rng = crate::dsp::Rng::new(11);
            (0..(sr as usize)).map(|_| rng.white() * 0.3).collect()
        };
        let ratio = |prog: u8, flat: bool| {
            let mut d = Drive::new(prog, false, sr);
            if flat {
                d = d.with_flat_voice();
            }
            let mut buf = input.clone();
            d.process(&mut buf);
            crate::testutil::band_rms(&buf, sr, 600.0, 1.0)
                / crate::testutil::band_rms(&buf, sr, 2000.0, 1.0).max(1e-9)
        };
        assert!(
            ratio(30, false) < ratio(30, true),
            "prog 30 should scoop the mids"
        );
        assert!(
            ratio(29, false) > ratio(29, true),
            "prog 29 should push the mids"
        );
    }

    /// Small-signal response of the alt (LEAD) insert against the main
    /// (RHYTHM) insert, at named frequencies. Shared by the amp/cab oracles
    /// below; driven at 0.02 so the shapers stay near-linear and the numbers
    /// read as the DESIGNED EQ rather than as clipping products.
    #[cfg(test)]
    fn insert_band_db(prog: u8, alt: bool, sr: f32, freqs: &[f32]) -> Vec<f32> {
        let mut b: Vec<f32> = {
            let mut rng = crate::dsp::Rng::new(7);
            (0..(4.0 * sr) as usize)
                .map(|_| rng.white() * 0.02)
                .collect()
        };
        Drive::new(prog, alt, sr).process(&mut b);
        freqs
            .iter()
            .map(|&f| {
                20.0 * crate::testutil::band_rms(&b[(0.2 * sr) as usize..], sr, f, 4.0)
                    .max(1e-12)
                    .log10()
            })
            .collect()
    }

    #[cfg(test)]
    fn lead_minus_main_db(prog: u8, sr: f32, freqs: &[f32]) -> Vec<f32> {
        let m = insert_band_db(prog, false, sr, freqs);
        let a = insert_band_db(prog, true, sr, freqs);
        a.iter().zip(&m).map(|(x, y)| x - y).collect()
    }

    /// 2026.07.23 amp+cab HLD — THE core oracle: the CC0 alt bank is a
    /// genuinely different AMP, not the rhythm amp with a trim.
    ///
    /// Until this change `alt` moved only the `MicroCab` ripple depth, so main
    /// and alt ran identical gain staging, voicing EQ and cabinet — which is
    /// what Arthur heard ("GM029 main sounds the same as GM029 alt") and why
    /// the lead sounded thin. The string-side oracle
    /// (`voices::driven_main_and_alt_banks_diverge`) could not catch it: it
    /// renders the bare presets and never touches the insert. Its sustain-index
    /// gap is in fact LARGE and grows with pitch (14→60 dB over keys 45–69) —
    /// but a lead line's notes last a few hundred milliseconds, and over that
    /// span the two banks went through the same amp. Hence this pin.
    ///
    /// Every clause is a DIFFERENCE OF DIFFERENCES, so it is invariant to the
    /// `post` level-match: re-trimming `post` shifts all three named-frequency
    /// deltas equally and cancels here. That is deliberate — the contract is
    /// the voicing SHAPE, not a level. Each clause is BOUNDED both ways: the
    /// floor is roughly half the designed move (so it fails long before the
    /// contrast is inaudible) and the ceiling stops a future "more is better"
    /// tweak ratcheting the lead into a honking, fizzy caricature.
    #[test]
    fn alt_drive_is_a_distinct_lead_voicing() {
        let sr = 44100.0;
        // (100 Hz low, 800 Hz body, 2800 Hz presence, 6000 Hz fizz)
        for (prog, tilt_floor, low_floor) in [(29u8, 1.5f32, -2.5f32), (30, 2.5, -4.0)] {
            let d = lead_minus_main_db(prog, sr, &[100.0, 800.0, 2800.0, 6000.0]);
            let (low, body, pres, fizz) = (d[0], d[1], d[2], d[3]);

            // (1) BODY-vs-PRESENCE tilt — the cure for "thin". The lead must be
            // more mid-forward relative to its own presence than the rhythm amp
            // is. Measured: 29 +3.0 dB, 30 +7.1 dB.
            let tilt = body - pres;
            println!(
                "lead voicing prog {prog}: tilt(800-2800) {tilt:+.2} dB, \
                 low(100-800) {:+.2}, fizz(6000-800) {:+.2}",
                low - body,
                fizz - body
            );
            assert!(
                tilt >= tilt_floor,
                "prog {prog}: the lead amp is not more body-forward than the rhythm amp \
                 — tilt(800-2800) {tilt:+.2} dB < {tilt_floor:+.1}"
            );
            assert!(
                tilt <= 12.0,
                "prog {prog}: the lead amp has ratcheted into a mid honk — \
                 tilt(800-2800) {tilt:+.2} dB > +12"
            );

            // (2) LOW-END FOCUS — lows are cut relative to the body (the raised
            // pre-shaper high-pass plus the tighter cab resonance). Bounded
            // below so the lead never becomes a thin, bass-less buzz.
            let low_rel = low - body;
            assert!(
                low_rel <= low_floor,
                "prog {prog}: the lead amp did not tighten the low end — \
                 low(100-800) {low_rel:+.2} dB > {low_floor:+.1}"
            );
            assert!(
                low_rel >= -16.0,
                "prog {prog}: the lead amp gutted the low end — \
                 low(100-800) {low_rel:+.2} dB < -16"
            );

            // (3) NO FIZZ — presence is added in the CAB, after the shapers, so
            // the lead must not end up brighter-relative-to-body than the
            // rhythm amp. This is the clause that fails if someone "adds cut"
            // by boosting the interstage tilt into the clipper, or by raising
            // the cabinet's anti-alias cliff for "air".
            let fizz_rel = fizz - body;
            assert!(
                fizz_rel <= -1.0,
                "prog {prog}: the lead amp is fizzier than the rhythm amp — \
                 fizz(6000-800) {fizz_rel:+.2} dB > -1"
            );
        }
    }

    /// 2026.07.23 amp+cab HLD: 29 and 30 must stay DIFFERENT inside the alt
    /// bank, on the same push-vs-scoop axis their main banks use — otherwise
    /// fixing "main sounds like alt" just moves the collapse to "GM029 alt
    /// sounds like GM030 alt".
    ///
    /// Three axes, so a change has to defeat all three to erase the contrast.
    ///
    /// **A note on the constraint clash here, because it shaped the voicing.**
    /// 30's lead has two obligations that pull against each other on the mid
    /// axis: it must differ from 30's MAIN (which wants more mid body, since
    /// 30's main is mid-scooped) and from 29's LEAD (which on that axis wants
    /// less). A single shared lead cabinet could not serve both — it left 30's
    /// lead only 0.68 dB from its own main at some pitches. The resolution is
    /// the per-program lead cabinet (`cab_biquads_lead`): 30's puts back more
    /// body and less presence, 29's the reverse, so the two leads keep the
    /// push-vs-scoop relationship their mains have while each still separates
    /// cleanly from its own main.
    ///
    /// Clause (a) is direction-agnostic (a distance), so it states the real
    /// requirement — "these are two different amps" — without prescribing how.
    /// Clause (b) pins the direction, so the pair cannot drift into being
    /// different-but-backwards; it deliberately uses the same 600 Hz : 2 kHz
    /// axis `drive_pre_voicing_direction` uses for the main banks. Clause (c)
    /// is gain staging: a SMALLER loud-to-quiet span means more compression.
    #[test]
    fn alt_bank_leads_stay_distinct_from_each_other() {
        let sr = 44100.0;
        const F: [f32; 6] = [120.0, 300.0, 600.0, 1200.0, 2400.0, 3400.0];

        // (a) the two leads are different amps at all: level-normalised
        // spectral distance between the inserts, same input, no string in the
        // path. Direction-agnostic and immune to the per-program `post` match.
        let shape = |prog: u8, alt: bool| {
            let v = insert_band_db(prog, alt, sr, &F);
            let mean = v.iter().sum::<f32>() / v.len() as f32;
            v.into_iter().map(|x| x - mean).collect::<Vec<f32>>()
        };
        let dist = |a: &[f32], b: &[f32]| {
            (a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f32>() / a.len() as f32).sqrt()
        };
        let (l29, l30) = (shape(29, true), shape(30, true));
        let (m29, m30) = (shape(29, false), shape(30, false));
        let lead_d = dist(&l29, &l30);
        let main_d = dist(&m29, &m30);
        println!(
            "alt leads: 29-vs-30 spectral distance {lead_d:.2} dB (their mains: {main_d:.2} dB)"
        );
        assert!(
            lead_d >= 1.5,
            "the two alt leads have collapsed into one amp: spectral distance only \
             {lead_d:.2} dB (their mains differ by {main_d:.2} dB)"
        );

        // (b) and they differ in the RIGHT direction — the SAME direction their
        // main banks do: 29 is mid-pushed, 30 is mid-scooped. Measured on the
        // 600 Hz : 2 kHz axis, the same axis `drive_pre_voicing_direction` uses
        // for the mains, so the two oracles speak about one thing. Level-
        // invariant, and compared lead-to-lead rather than each to its own main.
        let mid = |prog: u8, alt: bool| {
            let v = insert_band_db(prog, alt, sr, &[600.0, 2000.0]);
            v[0] - v[1]
        };
        let (lead_gap, main_gap) = (
            mid(29, true) - mid(30, true),
            mid(29, false) - mid(30, false),
        );
        println!(
            "alt leads: 29-vs-30 600:2000 mid balance {lead_gap:+.2} dB \
             (their mains {main_gap:+.2} dB — same sign required)"
        );
        assert!(
            lead_gap >= 1.0,
            "the two alt leads no longer sit on the push-vs-scoop axis their mains use: \
             29's lead should be the mid-pushed one and 30's the mid-scooped one, \
             measured {lead_gap:+.2} dB (their mains differ by {main_gap:+.2} dB)"
        );

        // (c) compression: band-limited output span from a loud to a quiet input
        let span = |prog: u8| {
            let at = |amp: f32| {
                let mut d = Drive::new(prog, true, sr);
                let mut buf: Vec<f32> = (0..(sr as usize))
                    .map(|i| amp * (std::f32::consts::TAU * 220.0 * i as f32 / sr).sin())
                    .collect();
                d.process(&mut buf);
                20.0 * crate::testutil::spectral_band_rms(
                    &buf[(0.2 * sr) as usize..],
                    sr,
                    300.0,
                    3400.0,
                )
                .max(1e-12)
                .log10()
            };
            at(0.5) - at(0.05)
        };
        let (s29, s30) = (span(29), span(30));
        println!("alt leads: loud-quiet span — 29 {s29:.2} dB, 30 {s30:.2} dB (smaller = more compressed)");
        assert!(
            s30 <= s29 - 0.5,
            "the two alt leads share gain staging: 30-lead should compress harder than \
             29-lead, spans {s30:.2} vs {s29:.2} dB"
        );
    }

    /// V6b (guitar v2): the held-lead steady state stays HARMONIC through the
    /// engine — the sustainer converges toward the fundamental (by design;
    /// the damper's tilted loss stands), and the Drive's tanh re-harmonizes
    /// it. A naked-sine pass (the T16 "wooden glockenspiel" failure mode,
    /// which measures ≤ −50 dB here) fails the 2f0 pin.
    ///
    /// Floor provenance: −20 dB was calibrated when the sag boost ran the
    /// held tail ×4 hotter into the shapers; with the inverted sag deleted
    /// (§2.6) the level-matched static drive at the e-bow's hold level
    /// (DRIVE.sustain = 0.5) measures −24.9 dB, so the anti-naked-sine floor
    /// is re-pinned at −30 dB (5 dB margin, matching the old pin's margin).
    #[test]
    fn sustained_lead_stays_harmonic_through_drive() {
        let sr = 44100.0;
        // Round-3 U2: the held-lead idiom lives on the CC0 alt bank now —
        // the default DRIVE bank decays again (plan §3.6), so this pin
        // follows the sustainer to DRIVE_LEAD via bank-select 1.
        let events = vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 29 }),
            // silence the default echo send so the pin reads the dry voice
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 94,
                    val: 0,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 76,
                    vel: 100,
                },
            ),
        ];
        let out = left(&render(&test_song(events, 3.2), &test_opts(sr)).0);
        let seg = &out[(2.5 * sr) as usize..(3.0 * sr) as usize];
        let f0 = 659.26;
        let m1 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
        let m2 = crate::testutil::mag_at(seg, sr, 2.0 * f0);
        let rel = 20.0 * (m2 / m1).log10();
        println!("V6b: 2f0 at {rel:.1} dB rel f0 in the 2.5–3.0 s window");
        assert!(
            rel >= -30.0,
            "held lead lost its harmonics: 2f0 {rel:.1} dB rel f0"
        );
    }

    /// Round-2 GM029/030 ("clean, dark sustain"): the e-bow-held tail must
    /// keep an audible harmonic edge, not decay to a warm near-sine. The
    /// sustainer holds the string near a pure fundamental, so only the
    /// Drive's regeneration puts harmonics in the deep hold — THD of
    /// harmonics 2..=16 vs f0, through the full engine (dry: chorus/echo
    /// silenced), in the 5.5–6.0 s window of a held note (past the ~6 s
    /// e-bow climb, the pick's own partials long dead). Pre-round-2 the
    /// four rows measured −32.8/−35.8/−35.5/−35.4 dB (inaudible); the
    /// floors sit ~3 dB above those and ~3 dB below the shipped values.
    /// The depth is capped structurally: a harder-clipped hold turns
    /// square and its windowed RMS overtakes the broadband attack,
    /// tripping the §2.6 sag-catcher (o_attack_sustained_plucks_no_late_
    /// bloom) — so the hold rides the tanh knee, not the rail.
    #[test]
    fn driven_sustain_stays_distorted() {
        let sr = 44100.0;
        for (prog, key, floor) in [
            (29u8, 40u8, -29.0f32), // E2: low chug register
            (29, 45, -28.0),        // A2: open-string lead register
            (30, 40, -33.0),
            (30, 45, -29.0),
        ] {
            let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
            let events = vec![
                // Round-3 U2: the e-bow hold lives on the CC0 alt bank
                // (DRIVE_LEAD); the default bank decays, so a 5.5 s window
                // on it would read string remnants, not a held tail.
                (0.0, cc(0, 1)),
                (0.0, EvKind::Prog { ch: 0, prog }),
                (0.0, cc(93, 0)),
                (0.0, cc(94, 0)),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key,
                        vel: 100,
                    },
                ),
            ];
            let out = left(&render(&test_song(events, 6.2), &test_opts(sr)).0);
            let f0 = 440.0 * 2f32.powf((key as f32 - 69.0) / 12.0);
            let seg = &out[(5.5 * sr) as usize..(6.0 * sr) as usize];
            let m1 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
            let mut pow = 0.0f32;
            for n in 2..=16u32 {
                let m = crate::testutil::mag_at(seg, sr, n as f32 * f0);
                pow += m * m;
            }
            let thd = 20.0 * (pow.sqrt() / m1).log10();
            println!("driven sustain prog {prog} key {key}: THD(2..16) {thd:.1} dB rel f0");
            assert!(
                thd >= floor,
                "prog {prog} key {key}: held sustain went clean — THD {thd:.1} dB \
                 rel f0 (floor {floor})"
            );
            // CEILING added 2026.07.23 with the lead amp. The floors alone are
            // a one-sided contract, and every lever the lead voicing pulls
            // (more stage-2 gain, a raised pre-shaper high-pass that thins f0
            // at low keys) pushes THD UP — so the failure mode this change can
            // actually introduce is the opposite of "went clean": a hold that
            // has turned into a square-wave fuzz. −12 dB rel f0 is the
            // harshness ceiling both consults independently proposed; the
            // worst row today measures −15.7 dB (prog 29 key 40, where the
            // 120 Hz pre-HPF legitimately shrinks the 82 Hz fundamental).
            assert!(
                thd <= -12.0,
                "prog {prog} key {key}: held sustain turned to fuzz — THD {thd:.1} dB \
                 rel f0 exceeds the −12 dB harshness ceiling"
            );
        }
    }

    /// 2026.07.23 amp+cab HLD — the END-TO-END pin: through the whole engine,
    /// at the pitches Arthur actually listens to, the CC0 alt bank must read as
    /// a different instrument from the default bank.
    ///
    /// `alt_drive_is_a_distinct_lead_voicing` attributes the change to the amp
    /// by feeding both inserts the same input; this one asks the question the
    /// listener asks, with the real string, the real sends and the real mix in
    /// the path.
    ///
    /// **Read this as an INTEGRATION guard, not as the pin for the amp/cab
    /// change.** The two banks already differed here before that change — they
    /// play different strings (`DRIVE` vs `DRIVE_LEAD`) and the sample layer is
    /// disabled on the alt bank — so this oracle was green at HEAD too. What it
    /// protects is the wiring: that CC0 still reaches a genuinely different
    /// voice end-to-end. The fix-specific, observed-RED-at-HEAD evidence lives
    /// on `alt_drive_is_a_distinct_lead_voicing`, whose six clauses all fail on
    /// the unmodified baseline.
    ///
    /// Window choice matters and is the crux of the original complaint. The
    /// string-side sustain gap is enormous and grows with pitch (14→60 dB over
    /// keys 45–69, see `voices::driven_main_and_alt_banks_diverge`) — but a
    /// lead line's notes last a few hundred milliseconds, so almost nobody ever
    /// hears that tail. 0.15–0.55 s is past the onset transient and inside the
    /// span a real lead note occupies: exactly the region where the two banks
    /// used to be nearly identical, because they shared an amp.
    ///
    /// **Metric choice, and a trap worth recording.** The obvious end-to-end
    /// metric — a SIGNED body:presence band ratio, alt minus main — does not
    /// work here, and measuring it was how I found out. Its per-key values
    /// swung from −1.7 to +8.8 dB across adjacent keys for a fixed pair of
    /// amps, because at these fundamentals a two-band ratio is dominated by
    /// which harmonics happen to land in which band, and the two banks also
    /// play different STRINGS (`DRIVE` bright 9000 vs `DRIVE_LEAD` 11000). So
    /// it mostly measured the string's harmonic comb, not the amp.
    ///
    /// Instead this asserts a level-normalised multi-band spectral DISTANCE.
    /// Any real timbral difference accumulates into it whatever direction the
    /// individual bands moved, so it is robust to the comb; and normalising
    /// each vector by its own mean makes it invariant to level, so it cannot be
    /// passed by making the lead louder. The signed, bounded, amp-attributed
    /// claim lives in `alt_drive_is_a_distinct_lead_voicing`, which feeds both
    /// inserts the SAME input and so has no string in the path at all. Between
    /// them: that oracle says the amp changed in the designed direction, this
    /// one says the listener hears two different instruments.
    #[test]
    fn driven_banks_diverge_at_lead_pitches() {
        let sr = 44100.0;
        const BANDS: [(f32, f32); 6] = [
            (200.0, 400.0),
            (400.0, 800.0),
            (800.0, 1600.0),
            (1600.0, 2400.0),
            (2400.0, 3200.0),
            (3200.0, 4200.0),
        ];
        let render_bank = |prog: u8, key: u8, bank: u8| {
            let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
            let events = vec![
                (0.0, cc(0, bank)),
                (0.0, EvKind::Prog { ch: 0, prog }),
                // silence the sends so the pin reads the dry voice
                (0.0, cc(93, 0)),
                (0.0, cc(94, 0)),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key,
                        vel: 100,
                    },
                ),
            ];
            left(&render(&test_song(events, 1.2), &test_opts(sr)).0)
        };
        // per-band dB, then mean-removed => level-invariant spectral shape
        let shape = |b: &[f32]| {
            let s = &b[(0.15 * sr) as usize..(0.55 * sr) as usize];
            let mut v: Vec<f32> = BANDS
                .iter()
                .map(|&(lo, hi)| {
                    20.0 * crate::testutil::spectral_band_rms(s, sr, lo, hi)
                        .max(1e-12)
                        .log10()
                })
                .collect();
            let mean = v.iter().sum::<f32>() / v.len() as f32;
            for x in v.iter_mut() {
                *x -= mean;
            }
            v
        };
        let distance = |a: &[f32], b: &[f32]| {
            (a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f32>() / a.len() as f32).sqrt()
        };

        // Scored as a per-program MEAN over the register plus a per-key
        // non-collapse floor, rather than a flat per-key bar. Even this metric
        // varies with which harmonics land in which band at a given
        // fundamental (1.1–5.4 dB across these seven keys for a fixed pair of
        // amps), so a per-key bar tight enough to mean anything is brittle,
        // while the mean over the register is stable. The floor still catches a
        // single pitch at which the two banks fall together.
        let mut bad: Vec<String> = Vec::new();
        for prog in [29u8, 30] {
            let mut ds = Vec::new();
            for key in [57u8, 59, 61, 63, 65, 67, 69] {
                let main = shape(&render_bank(prog, key, 0));
                let alt = shape(&render_bank(prog, key, 1));
                let d = distance(&main, &alt);
                println!(
                    "lead-pitch divergence prog {prog} key {key}: spectral distance {d:.2} dB"
                );
                if d < 0.8 {
                    bad.push(format!("prog {prog} key {key} collapsed: {d:.2} dB"));
                }
                ds.push(d);
            }
            let mean = ds.iter().sum::<f32>() / ds.len() as f32;
            println!("lead-pitch divergence prog {prog}: MEAN {mean:.2} dB over the register");
            if mean < 2.0 {
                bad.push(format!("prog {prog} register mean {mean:.2} dB"));
            }
        }
        // Vacuity control: the metric must report ZERO for a bank against
        // itself, so a passing distance above can never be an artefact of the
        // measurement manufacturing difference out of nothing.
        let ctl = shape(&render_bank(29, 62, 0));
        assert!(
            distance(&ctl, &ctl) < 1e-6,
            "the spectral-distance metric is not self-consistent"
        );
        assert!(
            bad.is_empty(),
            "the alt bank still sounds like the default bank through the full engine \
             (per-key distance < 0.8 dB, or register mean < 2.0 dB) at: {bad:?}"
        );
    }

    /// V9 (guitar v2): aliasing floor — a pure steady sine fed DIRECTLY into
    /// the Drive (a rendered voice would confound legitimate string
    /// inharmonicity: detuned polarizations, coupling, noise excitation).
    /// Every predicted fold-back bin — the 2× nonlinear stage folds at
    /// 88.2 kHz, the sample-aligned decimation folds again at 44.1 kHz —
    /// must sit ≤ −40 dB below the fundamental.
    #[test]
    fn drive_alias_floor() {
        let sr = 44100.0;
        let fold = |f: f32, fs: f32| {
            let r = f % fs;
            if r > fs / 2.0 {
                fs - r
            } else {
                r
            }
        };
        // Extended 2026.07.23 to the LEAD bank across three fundamentals. This
        // is the load-bearing safety check for the alt amp: the cabinet's
        // lowpass cliff is the DECIMATION filter, but harmonics the 2× shapers
        // generate above 44.1 kHz fold back INSIDE the 2× domain and can land
        // anywhere in the audible passband, where no cliff can remove them.
        // Their level is the tanh harmonic tail at very high orders, which is
        // exponentially sensitive to drive — so raising the lead's g2 has to be
        // measured here, not reasoned about. Three fundamentals because the
        // fold-landing pattern is f0-dependent and one value can get lucky.
        for prog in [29u8, 30] {
            for alt in [false, true] {
                for f0 in [997.0f32, 1301.0, 1763.0] {
                    let mut d = Drive::new(prog, alt, sr);
                    let mut buf: Vec<f32> = (0..(sr as usize))
                        .map(|i| 0.5 * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
                        .collect();
                    d.process(&mut buf);
                    let seg = &buf[(0.2 * sr) as usize..];
                    let m0 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
                    let mut worst = -200.0f32;
                    let mut worst_bin = 0.0f32;
                    for n in 2..=80u32 {
                        let fh = n as f32 * f0;
                        if fh <= sr / 2.0 {
                            continue; // a true harmonic, not an alias
                        }
                        let alias = fold(fold(fh, sr * DRIVE_OVERSAMPLE as f32), sr);
                        if !(100.0..=20_000.0).contains(&alias) {
                            continue;
                        }
                        // skip bins that coincide with legitimate harmonics
                        if (alias / f0 - (alias / f0).round()).abs() * f0 < 8.0 {
                            continue;
                        }
                        let rel = 20.0 * (crate::testutil::mag_at(seg, sr, alias) / m0).log10();
                        if rel > worst {
                            worst = rel;
                            worst_bin = alias;
                        }
                    }
                    println!(
                "V9 prog {prog} {} f0 {f0:.0}: worst alias {worst:.1} dB rel f0 at {worst_bin:.0} Hz",
                if alt { "alt " } else { "main" }
            );
                    assert!(
                worst <= -40.0,
                "prog {prog} {} f0 {f0:.0}: alias at {worst_bin:.0} Hz is {worst:.1} dB rel f0",
                if alt { "alt" } else { "main" }
            );
                }
            }
        }
    }

    // ===== Score-authored amp parameters (MM-REQ-KILN-00028, part-A HLD) =====

    /// A settled authored render: snap the six knobs to `params` and process
    /// `input` through the resulting amp. Used by the steady-state oracles.
    fn amp_settled(
        prog: u8,
        alt: bool,
        sr: f32,
        params: [u8; AMP_PARAM_COUNT],
        input: &[f32],
    ) -> Vec<f32> {
        let mut d = Drive::new(prog, alt, sr);
        let cur = params.map(|v| v as f32);
        d.apply_params(&cur, true);
        let mut out = input.to_vec();
        d.process(&mut out);
        out
    }

    /// Block-accurate authored render: mirrors the engine's per-block handling
    /// exactly (prime-on-first-block, block-rate `amp_cur` slew, per-block
    /// `apply_params`, per-sample scalar slew inside `process`) so the zipper /
    /// click oracles see the real smoothing path.
    fn amp_blocks(
        prog: u8,
        alt: bool,
        sr: f32,
        input: &[f32],
        params: impl Fn(usize) -> [u8; AMP_PARAM_COUNT],
    ) -> Vec<f32> {
        let mut d = Drive::new(prog, alt, sr);
        let mut cur = [AMP_NEUTRAL as f32; AMP_PARAM_COUNT];
        let mut primed = [false; AMP_PARAM_COUNT];
        let smooth = 1.0 - (-(BLOCK as f32) / (WAH_SLEW_S * sr)).exp();
        let mut out = input.to_vec();
        for (bi, chunk) in out.chunks_mut(BLOCK).enumerate() {
            let p = params(bi);
            for i in 0..AMP_PARAM_COUNT {
                let t = p[i] as f32;
                if primed[i] {
                    cur[i] += smooth * (t - cur[i]);
                } else {
                    cur[i] = t;
                    primed[i] = true;
                }
            }
            d.apply_params(&cur, false);
            d.process(chunk);
        }
        out
    }

    fn noise(sr: f32, secs: f32, amp: f32, seed: u32) -> Vec<f32> {
        let mut rng = crate::dsp::Rng::new(seed);
        (0..(secs * sr) as usize)
            .map(|_| rng.white() * amp)
            .collect()
    }

    fn sine(sr: f32, secs: f32, f0: f32, amp: f32) -> Vec<f32> {
        (0..(secs * sr) as usize)
            .map(|i| amp * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
            .collect()
    }

    /// AC2/AC4: a channel authoring every knob at the neutral 64 renders
    /// BIT-IDENTICALLY to the unauthored path, for all four program × bank
    /// combinations. This is the inertness invariant at the sample level and
    /// simultaneously proves the offset math is an exact identity at n=0 (so a
    /// future base-value desync could not hide).
    #[test]
    fn amp_neutral_is_bit_identical() {
        let sr = 44100.0;
        let input = noise(sr, 1.0, 0.2, 0x0028_0001);
        for prog in [29u8, 30] {
            for alt in [false, true] {
                let mut d0 = Drive::new(prog, alt, sr);
                let mut base = input.clone();
                d0.process(&mut base); // unauthored path

                let authored =
                    amp_blocks(prog, alt, sr, &input, |_| [AMP_NEUTRAL; AMP_PARAM_COUNT]);
                assert_eq!(
                    base.len(),
                    authored.len(),
                    "prog {prog} alt {alt}: length mismatch"
                );
                for (i, (a, b)) in base.iter().zip(&authored).enumerate() {
                    assert_eq!(
                        a.to_bits(),
                        b.to_bits(),
                        "prog {prog} alt {alt} sample {i}: neutral render is not bit-identical ({a} vs {b})"
                    );
                }
            }
        }
    }

    /// AC4: each knob moves its OWN primary axis in the intended direction and
    /// by at least a pinned minimum, and reads exactly the neutral value at 64.
    /// The measured spread is well above the asserted floor — the floor exists
    /// so a `/63`-scaled or epsilon-sized knob would fail.
    #[test]
    fn amp_each_knob_moves_its_axis() {
        let sr = 44100.0;
        // The floor rules out an epsilon-sized or wrongly scaled knob; it is not
        // the effect size. The two PRE-CLIP knobs (Tone, Tightness) are
        // deliberately subtle — a pre-clip EQ is largely swallowed by the
        // saturator (§2.1), so they colour rather than transform, and move
        // ~1.7–4 dB. The three CABINET knobs are post-clip (linear) and move
        // 11–17 dB. Measured spreads are printed for the coupling report.
        struct Case {
            knob: usize,
            f0: f32,
            amp: f32,
            lo: f32,
            hi: f32,
            more: u8, // knob value producing MORE of the measured band
            less: u8,
            min_db: f32,
        }
        let c = |knob, f0, amp, lo, hi, more, less, min_db| Case {
            knob,
            f0,
            amp,
            lo,
            hi,
            more,
            less,
            min_db,
        };
        let cases = [
            c(AMP_TONE, 110.0, 0.02, 400.0, 1600.0, 127, 0, 2.4),
            c(AMP_TIGHT, 82.4, 0.30, 40.0, 110.0, 0, 127, 3.0), // more low end at value 0
            c(AMP_BODY, 150.0, 0.10, 350.0, 750.0, 127, 0, 22.0),
            c(AMP_PRES, 150.0, 0.10, 2000.0, 3400.0, 127, 0, 22.0),
            c(AMP_CABTONE, 150.0, 0.10, 2500.0, 3600.0, 127, 0, 13.0), // downward-only
        ];
        for prog in [29u8, 30] {
            for alt in [false, true] {
                for &Case {
                    knob,
                    f0,
                    amp,
                    lo,
                    hi,
                    more,
                    less,
                    min_db,
                } in &cases
                {
                    let input = sine(sr, 0.6, f0, amp);
                    let band = |v: u8| {
                        let mut p = [64u8; AMP_PARAM_COUNT];
                        p[knob] = v;
                        let out = amp_settled(prog, alt, sr, p, &input);
                        let seg = &out[(0.2 * sr) as usize..];
                        20.0 * crate::testutil::spectral_band_rms(seg, sr, lo, hi)
                            .max(1e-12)
                            .log10()
                    };
                    let hi_db = band(more);
                    let lo_db = band(less);
                    let spread = hi_db - lo_db;
                    println!(
                        "knob {knob} prog {prog} {}: spread {spread:.2} dB (more {hi_db:.2} less {lo_db:.2})",
                        if alt { "alt" } else { "main" }
                    );
                    // 64 is the neutral identity: authoring it equals not touching it.
                    let neutral = amp_settled(prog, alt, sr, [64; AMP_PARAM_COUNT], &input);
                    let mut plain = Drive::new(prog, alt, sr);
                    let mut plain_out = input.clone();
                    plain.process(&mut plain_out);
                    assert_eq!(
                        neutral.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
                        plain_out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
                        "prog {prog} alt {alt} knob {knob}: value 64 is not identity"
                    );
                    assert!(
                        spread >= min_db,
                        "prog {prog} alt {alt} knob {knob}: spread {spread:.2} dB < {min_db} \
                         (more={more} {hi_db:.2} less={less} {lo_db:.2})"
                    );
                }
            }
        }
    }

    /// Diagnostic (`--ignored --nocapture`): where is the Drive knob's REAL
    /// ceiling? `AMP_DRIVE_K` was first set to 1.2 on a review's *prediction*
    /// that 2.0 would breach the −40 dBc alias budget; that prediction was never
    /// measured. This sweeps candidate exponents through the same fold-bin logic
    /// `amp_drive_knob_holds_alias_floor` asserts, over both programs, both banks
    /// and three fundamentals, and reports the worst alias for each — so the
    /// shipped value is set by measurement instead of by inherited caution.
    #[test]
    #[ignore]
    fn amp_drive_ceiling_sweep() {
        let sr = 44100.0;
        let fold = |f: f32, fs: f32| {
            let r = f % fs;
            if r > fs / 2.0 {
                fs - r
            } else {
                r
            }
        };
        let n_max = (127.0 - 64.0) / 64.0; // the knob's top end
        println!("\n k     worst alias (dBc)   headroom vs -40   verdict");
        for k in [1.2f32, 1.5, 1.8, 2.0, 2.2, 2.5, 3.0] {
            let mut worst_all = -200.0f32;
            for prog in [29u8, 30] {
                for alt in [false, true] {
                    for f0 in [997.0f32, 1301.0, 1763.0] {
                        let mut d = Drive::new(prog, alt, sr);
                        // Apply the candidate curve directly (active stays false,
                        // so `process` reads these scalars on the original path).
                        d.g1 = d.base.g1 * 2f32.powf(k * n_max);
                        d.g2 = d.base.g2 * 2f32.powf(0.5 * k * n_max);
                        d.post = d.base.post * 2f32.powf(-AMP_DRIVE_POST_C * n_max);
                        let mut buf: Vec<f32> = (0..(sr as usize))
                            .map(|i| 0.5 * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
                            .collect();
                        d.process(&mut buf);
                        let seg = &buf[(0.2 * sr) as usize..];
                        let m0 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
                        for h in 2..=80u32 {
                            let fh = h as f32 * f0;
                            if fh <= sr / 2.0 {
                                continue;
                            }
                            let alias = fold(fold(fh, sr * DRIVE_OVERSAMPLE as f32), sr);
                            if !(100.0..=20_000.0).contains(&alias) {
                                continue;
                            }
                            if (alias / f0 - (alias / f0).round()).abs() * f0 < 8.0 {
                                continue;
                            }
                            let rel = 20.0 * (crate::testutil::mag_at(seg, sr, alias) / m0).log10();
                            worst_all = worst_all.max(rel);
                        }
                    }
                }
            }
            let g1x = 2f32.powf(k * n_max);
            println!(
                "{k:4.1}   {worst_all:8.1}          {:+6.1}          {}   (g1 x{g1x:.2} at 127)",
                -40.0 - worst_all,
                if worst_all <= -40.0 { "OK " } else { "OVER" }
            );
        }
    }

    /// Diagnostic (`--ignored --nocapture`): how much WIDER can the post-clip
    /// knobs go? Body/Presence/Tone are linear cabinet EQ and Cab Tone only ever
    /// darkens, so none of them is alias-bounded — the real limits are range
    /// safety (finite, DC-free, not pinned into clip) and musical usefulness.
    /// Reports the spread each candidate range buys, plus peak and DC.
    #[test]
    #[ignore]
    fn amp_range_headroom_sweep() {
        let sr = 44100.0;
        let n_max = (127.0 - 64.0) / 64.0;
        let probe = sine(sr, 0.6, 150.0, 0.10);

        println!("\n--- cabinet EQ swing (Body, cab[1]) ---");
        println!(" +/-dB   spread(dB)   peak    DC        verdict");
        for eq in [9.0f32, 12.0, 15.0, 18.0] {
            let mut spread_min = 999.0f32;
            let mut peak_max = 0.0f32;
            let mut dc_max = 0.0f32;
            for prog in [29u8, 30] {
                for alt in [false, true] {
                    let band = |sign: f32| {
                        let mut d = Drive::new(prog, alt, sr);
                        let (h, q, db) = d.base.cab1;
                        d.cab[1].retune_peak(h, q, db + eq * sign * n_max, d.sr_os);
                        let mut b = probe.clone();
                        d.process(&mut b);
                        let seg = &b[(0.2 * sr) as usize..];
                        (
                            20.0 * crate::testutil::spectral_band_rms(seg, sr, 350.0, 750.0)
                                .max(1e-12)
                                .log10(),
                            b.iter().fold(0.0f32, |m, x| m.max(x.abs())),
                            crate::testutil::dc_offset(seg).abs(),
                        )
                    };
                    let (hi, p1, d1) = band(1.0);
                    let (lo, p2, d2) = band(-1.0);
                    spread_min = spread_min.min(hi - lo);
                    peak_max = peak_max.max(p1.max(p2));
                    dc_max = dc_max.max(d1.max(d2));
                }
            }
            println!(
                "{eq:6.0}   {spread_min:8.1}   {peak_max:6.3}  {dc_max:.2e}   {}",
                if peak_max < 1.5 && dc_max < 1e-3 {
                    "safe"
                } else {
                    "CHECK"
                }
            );
        }

        println!("\n--- JOINT pre-clip ceiling: Tone swing at Drive 127 ---");
        println!(" toneDB   worst alias(dBc)   verdict   (both pre-clip knobs at max)");
        {
            let fold = |f: f32, fs: f32| {
                let r = f % fs;
                if r > fs / 2.0 {
                    fs - r
                } else {
                    r
                }
            };
            let n_max = (127.0 - 64.0) / 64.0;
            for tone_db in [4.0f32, 5.0, 6.0, 7.0, 8.0, 9.0] {
                let mut worst_all = -200.0f32;
                for prog in [29u8, 30] {
                    for alt in [false, true] {
                        for f0 in [997.0f32, 1301.0, 1763.0] {
                            let mut d = Drive::new(prog, alt, sr);
                            d.g1 = d.base.g1 * 2f32.powf(AMP_DRIVE_K * n_max);
                            d.g2 = d.base.g2 * 2f32.powf(0.5 * AMP_DRIVE_K * n_max);
                            d.post = d.base.post * 2f32.powf(-AMP_DRIVE_POST_C * n_max);
                            let (vh, vq, vdb) = d.base.voice;
                            d.voice.retune_peak(vh, vq, vdb + tone_db * n_max, d.sr_os);
                            let mut b: Vec<f32> = (0..(sr as usize))
                                .map(|i| 0.5 * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
                                .collect();
                            d.process(&mut b);
                            let seg = &b[(0.2 * sr) as usize..];
                            let m0 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
                            for h in 2..=80u32 {
                                let fh = h as f32 * f0;
                                if fh <= sr / 2.0 {
                                    continue;
                                }
                                let alias = fold(fold(fh, sr * DRIVE_OVERSAMPLE as f32), sr);
                                if !(100.0..=20_000.0).contains(&alias) {
                                    continue;
                                }
                                if (alias / f0 - (alias / f0).round()).abs() * f0 < 8.0 {
                                    continue;
                                }
                                worst_all = worst_all.max(
                                    20.0 * (crate::testutil::mag_at(seg, sr, alias) / m0).log10(),
                                );
                            }
                        }
                    }
                }
                println!(
                    "{tone_db:6.0}   {worst_all:12.1}       {}",
                    if worst_all <= -40.0 { "OK " } else { "OVER" }
                );
            }
        }

        println!("\n--- WORST CASE: Presence boost at Drive 127 + Tone boost max ---");
        println!(" presDB   worst alias(dBc)   verdict");
        {
            let fold = |f: f32, fs: f32| {
                let r = f % fs;
                if r > fs / 2.0 {
                    fs - r
                } else {
                    r
                }
            };
            let nm = (127.0 - 64.0) / 64.0;
            for pres_db in [3.0f32, 4.0, 5.0, 6.0, 9.0, 12.0, 15.0] {
                let mut worst_all = -200.0f32;
                for prog in [29u8, 30] {
                    for alt in [false, true] {
                        for f0 in [997.0f32, 1301.0, 1763.0] {
                            let mut d = Drive::new(prog, alt, sr);
                            d.g1 = d.base.g1 * 2f32.powf(AMP_DRIVE_K * nm);
                            d.g2 = d.base.g2 * 2f32.powf(0.5 * AMP_DRIVE_K * nm);
                            d.post = d.base.post * 2f32.powf(-AMP_DRIVE_POST_C * nm);
                            let (vh, vq, vdb) = d.base.voice;
                            d.voice.retune_peak(vh, vq, vdb + AMP_TONE_DB * nm, d.sr_os);
                            let (ph, pq, pdb) = d.base.cab2;
                            d.cab[2].retune_peak(ph, pq, pdb + pres_db * nm, d.sr_os);
                            let mut b: Vec<f32> = (0..(sr as usize))
                                .map(|i| 0.5 * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
                                .collect();
                            d.process(&mut b);
                            let seg = &b[(0.2 * sr) as usize..];
                            let m0 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
                            for h in 2..=80u32 {
                                let fh = h as f32 * f0;
                                if fh <= sr / 2.0 {
                                    continue;
                                }
                                let a = fold(fold(fh, sr * DRIVE_OVERSAMPLE as f32), sr);
                                if !(100.0..=20_000.0).contains(&a) {
                                    continue;
                                }
                                if (a / f0 - (a / f0).round()).abs() * f0 < 8.0 {
                                    continue;
                                }
                                worst_all = worst_all
                                    .max(20.0 * (crate::testutil::mag_at(seg, sr, a) / m0).log10());
                            }
                        }
                    }
                }
                println!(
                    "{pres_db:6.0}   {worst_all:12.1}       {}",
                    if worst_all <= -40.0 { "OK " } else { "OVER" }
                );
            }
        }

        println!("\n--- Cab Tone floor (cliff corner multiplier at knob 0) ---");
        println!(" floor   corner(Hz)   HF spread(dB)   peak    verdict");
        for floor in [0.5f32, 0.4, 0.3, 0.25] {
            let mut spread_min = 999.0f32;
            let mut peak_max = 0.0f32;
            for prog in [29u8, 30] {
                for alt in [false, true] {
                    let meas = |f: f32| {
                        let mut d = Drive::new(prog, alt, sr);
                        d.cab[3].retune_lowpass(d.base.cliff[0].0 * f, d.base.cliff[0].1, d.sr_os);
                        d.cab[4].retune_lowpass(d.base.cliff[1].0 * f, d.base.cliff[1].1, d.sr_os);
                        let mut b = probe.clone();
                        d.process(&mut b);
                        let seg = &b[(0.2 * sr) as usize..];
                        (
                            20.0 * crate::testutil::spectral_band_rms(seg, sr, 2500.0, 3600.0)
                                .max(1e-12)
                                .log10(),
                            b.iter().fold(0.0f32, |m, x| m.max(x.abs())),
                        )
                    };
                    let (bright, p1) = meas(1.0);
                    let (dark, p2) = meas(floor);
                    spread_min = spread_min.min(bright - dark);
                    peak_max = peak_max.max(p1.max(p2));
                }
            }
            println!(
                "{floor:6.2}   {:8.0}   {spread_min:11.1}   {peak_max:6.3}   {}",
                4000.0 * floor,
                if peak_max < 1.5 { "safe" } else { "CHECK" }
            );
        }
    }

    /// AC8: the Drive knob's TOP end is bounded by the alias floor, not taste.
    /// Runs `drive_alias_floor`'s exact fold-bin logic at Drive 0/64/127 across
    /// both programs, both banks and three fundamentals, and asserts the shipped
    /// -40 dBc budget holds — this is what pins `AMP_DRIVE_K`.
    #[test]
    fn amp_drive_knob_holds_alias_floor() {
        let sr = 44100.0;
        let fold = |f: f32, fs: f32| {
            let r = f % fs;
            if r > fs / 2.0 {
                fs - r
            } else {
                r
            }
        };
        // Sweep every knob that can move the fold-back floor, not just Drive.
        // Two mechanisms, both real:
        //  * PRE-clip (Drive, Tone boost) drives the shaper harder, generating
        //    more of the very-high-order harmonics that fold back.
        //  * POST-clip Presence is a boost centred at 2.6-2.8 kHz, which lifts
        //    whatever alias already sits in that band RELATIVE to a fundamental
        //    that sits below it — so it can breach the budget without creating a
        //    single new alias product.
        // The last row is the genuine worst case: everything that costs headroom
        // at maximum together.
        for (drive, tone, pres) in [
            (0u8, 64u8, 64u8),
            (64, 64, 64),
            (127, 64, 64),
            (64, 127, 64),
            (64, 0, 64),
            (64, 64, 127),
            (127, 127, 127),
        ] {
            for prog in [29u8, 30] {
                for alt in [false, true] {
                    for f0 in [997.0f32, 1301.0, 1763.0] {
                        let mut p = [64u8; AMP_PARAM_COUNT];
                        p[AMP_DRIVE] = drive;
                        p[AMP_TONE] = tone;
                        p[AMP_PRES] = pres;
                        let input = sine(sr, 1.0, f0, 0.5);
                        let buf = amp_settled(prog, alt, sr, p, &input);
                        let seg = &buf[(0.2 * sr) as usize..];
                        let m0 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
                        let mut worst = -200.0f32;
                        for n in 2..=80u32 {
                            let fh = n as f32 * f0;
                            if fh <= sr / 2.0 {
                                continue;
                            }
                            let alias = fold(fold(fh, sr * DRIVE_OVERSAMPLE as f32), sr);
                            if !(100.0..=20_000.0).contains(&alias) {
                                continue;
                            }
                            if (alias / f0 - (alias / f0).round()).abs() * f0 < 8.0 {
                                continue;
                            }
                            let rel = 20.0 * (crate::testutil::mag_at(seg, sr, alias) / m0).log10();
                            worst = worst.max(rel);
                        }
                        assert!(
                            worst <= -40.0,
                            "Drive {drive} Tone {tone} Pres {pres} prog {prog} {} f0 {f0:.0}: alias {worst:.1} dBc > -40",
                            if alt { "alt" } else { "main" }
                        );
                    }
                }
            }
        }
    }

    /// AC5 (diagnostic, `--ignored --nocapture`): the 6×6 cross-coupling matrix.
    /// Row = knob driven 64→127 (Tightness/Cab Tone 64→0, their "more" end);
    /// column = the change in each knob's OWN primary band-measure, in dB. The
    /// diagonal is a knob's own effect; off-diagonal is leakage. Pre-clip knobs
    /// (Tone, Tightness) share the mid path with Body, so some overlap is
    /// expected and by design (§residual risks) — the matrix documents it rather
    /// than pretending the six are orthogonal.
    #[test]
    #[ignore]
    fn amp_coupling_matrix() {
        let sr = 44100.0;
        // (knob, f0, amp, band lo, band hi, "more" value)
        let axes = [
            (AMP_DRIVE, 220.0f32, 0.30f32, 1500.0f32, 6000.0f32, 127u8),
            (AMP_TONE, 110.0, 0.02, 400.0, 1600.0, 127),
            (AMP_TIGHT, 82.4, 0.30, 40.0, 110.0, 0),
            (AMP_BODY, 150.0, 0.10, 350.0, 750.0, 127),
            (AMP_PRES, 150.0, 0.10, 2000.0, 3400.0, 127),
            (AMP_CABTONE, 150.0, 0.10, 2500.0, 3600.0, 0), // active end is DOWNWARD
        ];
        let names = ["Drive", "Tone", "Tight", "Body", "Pres", "CabTn"];
        for prog in [29u8, 30] {
            for alt in [false, true] {
                println!(
                    "\n=== coupling prog {prog} {} (row=driven knob, col=measured axis, dB) ===",
                    if alt { "alt" } else { "main" }
                );
                print!("{:8}", "");
                for n in names {
                    print!("{n:>8}");
                }
                println!();
                for &(rk, _, _, _, _, more) in &axes {
                    print!("{:8}", names[rk]);
                    for &(_, f0, amp, lo, hi, _) in &axes {
                        let input = sine(sr, 0.6, f0, amp);
                        let meas = |v: u8| {
                            let mut p = [64u8; AMP_PARAM_COUNT];
                            p[rk] = v;
                            let out = amp_settled(prog, alt, sr, p, &input);
                            let seg = &out[(0.2 * sr) as usize..];
                            20.0 * crate::testutil::spectral_band_rms(seg, sr, lo, hi)
                                .max(1e-12)
                                .log10()
                        };
                        print!("{:8.1}", meas(more) - meas(64));
                    }
                    println!();
                }
            }
        }
    }

    /// AC7: `post` is a partial makeup trim; the residual level change across
    /// the whole Drive range is BOUNDED and reported. This pins `AMP_DRIVE_POST_C`
    /// — not by asserting perfect compensation (no static law can), but by
    /// measuring the band RMS at Drive 0/64/127 and holding it inside a stated
    /// tolerance at two pitches and two input levels.
    #[test]
    fn amp_drive_level_residual_bounded() {
        let sr = 44100.0;
        // `post` is a PARTIAL makeup trim (§2.2): the level error depends on
        // input level and pitch, not the knob alone, so no static law flattens
        // it — loud input wants less trim, quiet input more.
        //
        // Re-baselined 6.0 -> 9.0 dB when the Drive span widened from x2.3 to
        // x3.9 (2026-07-23). This is NOT a check weakened to make a failure go
        // away: `AMP_DRIVE_POST_C` was re-swept and set to its measured minimax
        // (8.21 dB worst case, vs 9.40 dB either side of it), and the tolerance
        // then follows the wider knob it now has to cover. The check still does
        // its job — catching a GROSS regression such as compensation disabled or
        // inverted — and it still does not claim perfect level-matching, which
        // the design does not
        // promise. Reported, not asserted away — this is the honest residual.
        let tol_db = 9.0;
        for prog in [29u8, 30] {
            for alt in [false, true] {
                for f0 in [147.0f32, 330.0] {
                    for amp in [0.3f32, 0.05] {
                        let input = sine(sr, 0.6, f0, amp);
                        let level = |drive: u8| {
                            let mut p = [64u8; AMP_PARAM_COUNT];
                            p[AMP_DRIVE] = drive;
                            let out = amp_settled(prog, alt, sr, p, &input);
                            let seg = &out[(0.2 * sr) as usize..];
                            20.0 * crate::testutil::spectral_band_rms(seg, sr, 120.0, 6000.0)
                                .max(1e-12)
                                .log10()
                        };
                        let (l0, l64, l127) = (level(0), level(64), level(127));
                        let spread = (l0 - l64).abs().max((l127 - l64).abs());
                        println!(
                            "level prog {prog} {} f0 {f0:.0} amp {amp}: 0={l0:.2} 64={l64:.2} 127={l127:.2} spread {spread:.2}",
                            if alt { "alt" } else { "main" }
                        );
                        assert!(
                            spread <= tol_db,
                            "prog {prog} {} f0 {f0:.0} amp {amp}: level residual {spread:.2} dB > {tol_db}",
                            if alt { "alt" } else { "main" }
                        );
                    }
                }
            }
        }
    }

    /// AC6a: a knob swept mid-note must not add a spectral line at the block
    /// frequency (`sr/BLOCK`). This is the zipper a peak sample-difference
    /// detector cannot see, and the reason the scalar knobs slew PER SAMPLE.
    #[test]
    fn amp_sweep_has_no_block_rate_zipper() {
        let sr = 44100.0;
        let block_hz = sr / BLOCK as f32; // 689 Hz at 44.1k
        let f0 = 220.0;
        let input = sine(sr, 1.2, f0, 0.3);
        let nb = input.len().div_ceil(BLOCK);
        // Drive ramps 64 -> 127 across the middle third of the render.
        let swept = amp_blocks(29, false, sr, &input, |bi| {
            let mut p = [64u8; AMP_PARAM_COUNT];
            let frac = ((bi as f32 / nb as f32) - 0.33) / 0.34;
            p[AMP_DRIVE] = (64.0 + 63.0 * frac.clamp(0.0, 1.0)) as u8;
            p
        });
        let control = amp_blocks(29, false, sr, &input, |_| [96; AMP_PARAM_COUNT]);
        let seg = &swept[(0.1 * sr) as usize..];
        let ctl = &control[(0.1 * sr) as usize..];
        // Any block-rate sideband would sit at f0 +/- k*block_hz. Measure the
        // strongest such bin against the same bin in a steady control.
        let mut worst = -200.0f32;
        for k in 1..=3 {
            for side in [-1.0f32, 1.0] {
                let f = f0 + side * k as f32 * block_hz;
                if f < 40.0 || f > sr / 2.0 - 40.0 {
                    continue;
                }
                let s = 20.0 * crate::testutil::mag_at(seg, sr, f).max(1e-12).log10();
                let c = 20.0 * crate::testutil::mag_at(ctl, sr, f).max(1e-12).log10();
                worst = worst.max(s - c);
            }
        }
        println!("zipper: worst block-rate sideband {worst:.1} dB over control");
        assert!(
            worst <= 12.0,
            "swept Drive raised a block-rate ({block_hz:.0} Hz) sideband {worst:.1} dB above the steady control — zipper"
        );
    }

    /// AC6b: a single large knob step authored mid-note (after the rig is
    /// already primed) must not click. The block-rate `amp_cur` slew turns the
    /// jump into small coefficient steps; the per-sample scalar slew smooths the
    /// gain. Compared against a steady control's peak sample slew.
    #[test]
    fn amp_single_step_does_not_click() {
        let sr = 44100.0;
        let f0 = 196.0;
        let input = sine(sr, 1.0, f0, 0.3);
        let nb = input.len().div_ceil(BLOCK);
        let step_block = nb / 2;
        // Primed at neutral, then a hard Body+Drive jump at the half-way block.
        let stepped = amp_blocks(29, true, sr, &input, |bi| {
            if bi >= step_block {
                let mut p = [64u8; AMP_PARAM_COUNT];
                p[AMP_DRIVE] = 127;
                p[AMP_BODY] = 127;
                p
            } else {
                [64; AMP_PARAM_COUNT]
            }
        });
        let steady = amp_blocks(29, true, sr, &input, |_| [AMP_NEUTRAL; AMP_PARAM_COUNT]);
        let s_click = crate::testutil::max_slew_norm(&stepped);
        let base_click = crate::testutil::max_slew_norm(&steady);
        println!("step click {s_click:.4} vs steady {base_click:.4}");
        assert!(
            s_click <= base_click * 2.0 + 0.02,
            "single-step Body/Drive jump clicked: peak slew {s_click:.4} vs steady {base_click:.4}"
        );
    }

    /// AC10: authored amp params are CHANNEL state — they survive Program Change,
    /// CC0 bank select and CC121, and are cleared only by GM System On. Each row
    /// of the state table, exercised through the real event dispatch.
    #[test]
    fn amp_params_follow_the_state_table() {
        let sr = 44100.0;
        let opts = || CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        };
        let author = |core: &mut EngineCore| {
            core.handle_event(EvKind::Prog { ch: 0, prog: 29 });
            core.handle_event(EvKind::Cc {
                ch: 0,
                num: 99,
                val: AMP_NRPN_MSB,
            });
            core.handle_event(EvKind::Cc {
                ch: 0,
                num: 98,
                val: AMP_DRIVE as u8,
            });
            core.handle_event(EvKind::Cc {
                ch: 0,
                num: 6,
                val: 100,
            });
        };

        // Program Change preserves.
        let mut core = EngineCore::new(opts());
        author(&mut core);
        assert!(core.strips[0].amp_authored);
        assert_eq!(core.strips[0].amp_params[AMP_DRIVE], 100);
        core.handle_event(EvKind::Prog { ch: 0, prog: 30 });
        assert!(
            core.strips[0].amp_authored,
            "Program Change dropped amp authoring"
        );
        assert_eq!(
            core.strips[0].amp_params[AMP_DRIVE], 100,
            "Program Change reset an amp param"
        );
        assert!(
            core.strips[0].drive.as_ref().unwrap().active,
            "rebuilt Drive did not re-apply the rig"
        );

        // CC0 bank select preserves.
        let mut core = EngineCore::new(opts());
        author(&mut core);
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 0,
            val: 1,
        });
        assert_eq!(
            core.strips[0].amp_params[AMP_DRIVE], 100,
            "CC0 reset an amp param"
        );
        assert!(
            core.strips[0].drive.as_ref().unwrap().active,
            "CC0-rebuilt Drive did not re-apply the rig"
        );

        // CC121 Reset All Controllers preserves the VALUES (nulls only the selector).
        let mut core = EngineCore::new(opts());
        author(&mut core);
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 121,
            val: 0,
        });
        assert_eq!(
            core.strips[0].amp_params[AMP_DRIVE], 100,
            "CC121 reset an amp param value"
        );
        assert_eq!(
            core.strips[0].nrpn_msb, 127,
            "CC121 did not null the NRPN selector"
        );
        assert!(
            core.strips[0].drive.as_ref().unwrap().active,
            "CC121-rebuilt Drive did not re-apply the rig"
        );

        // GM System On clears everything.
        let mut core = EngineCore::new(opts());
        author(&mut core);
        core.handle_event(EvKind::GmReset);
        assert!(
            !core.strips[0].amp_authored,
            "GM System On did not clear amp authoring"
        );
        assert_eq!(
            core.strips[0].amp_params[AMP_DRIVE], 64,
            "GM System On did not reset amp params to neutral"
        );

        // A rebuild that fires AFTER authoring but BEFORE the channel's first
        // audio block must start the rig at the authored value, not ramp up from
        // neutral: the per-block priming has not run yet, so the reseed itself
        // primes the knobs (amp_prime_all). Author Drive=127, then a bank change
        // rebuilds — the rebuilt insert's g1 must already be the Drive=127 gain.
        let mut core = EngineCore::new(opts());
        core.handle_event(EvKind::Prog { ch: 0, prog: 29 });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 99,
            val: AMP_NRPN_MSB,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 98,
            val: AMP_DRIVE as u8,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 6,
            val: 127,
        });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 0,
            val: 1,
        }); // bank change -> rebuild
        let g1 = core.strips[0].drive.as_ref().unwrap().g1;
        let neutral_g1 = Drive::new(29, true, sr).g1;
        assert!(
            g1 > neutral_g1 * 1.5,
            "rebuild before first block left g1 at {g1} (neutral {neutral_g1}); the authored Drive=127 did not snap"
        );
    }

    /// AC11: the RPN⇄NRPN latch is mutually exclusive and Data Entry is scoped to
    /// the live selector, so the KILN-00034 bend-range corruption is impossible
    /// in every direction — including the amp-authoring direction this feature
    /// introduces, and the initial null/null state.
    #[test]
    fn amp_nrpn_never_corrupts_the_rpn_bend_range() {
        let sr = 44100.0;
        let opts = CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        };
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };

        // Direction A: amp NRPN then RPN select then a bare CC38 must not leak
        // the amp value into the bend range.
        let mut core = EngineCore::new(opts);
        core.handle_event(cc(99, AMP_NRPN_MSB));
        core.handle_event(cc(98, AMP_DRIVE as u8));
        core.handle_event(cc(6, 100)); // authors the amp; nrpn_data_msb = 100
        assert_eq!(core.strips[0].amp_params[AMP_DRIVE], 100);
        core.handle_event(cc(101, 0)); // select RPN 0,0 — nulls the NRPN latch
        core.handle_event(cc(100, 0));
        core.handle_event(cc(38, 0)); // LSB-only Data Entry
        assert_ne!(
            core.strips[0].bend_range, 24.0,
            "amp NRPN Data Entry leaked into the RPN bend range (KILN-00034 direction A)"
        );

        // Direction B (null/null): a Data Entry with no live selector is dropped,
        // so it cannot poison a later RPN write.
        let mut core = EngineCore::new(opts);
        core.handle_event(cc(6, 100)); // no selector live — must be ignored
        core.handle_event(cc(101, 0));
        core.handle_event(cc(100, 0));
        core.handle_event(cc(38, 0));
        assert_ne!(
            core.strips[0].bend_range, 24.0,
            "null-selector Data Entry leaked into the RPN bend range (KILN-00034 null path)"
        );

        // And the amp block still authors correctly when it IS the live selector.
        let mut core = EngineCore::new(opts);
        core.handle_event(cc(99, AMP_NRPN_MSB));
        core.handle_event(cc(98, AMP_PRES as u8));
        core.handle_event(cc(6, 120));
        assert_eq!(core.strips[0].amp_params[AMP_PRES], 120);
        assert!(core.strips[0].amp_authored);
    }

    /// Level-match probe (diagnostic, `--ignored --nocapture`): post-drive RMS
    /// of steady 220 Hz sines at a loud and a tail operating point, per
    /// program — the two-point loudness reference for re-matching `post`
    /// across Drive revisions (guitar v2 HLD §3.C).
    #[test]
    #[ignore]
    fn drive_level_probe() {
        let sr = 44100.0;
        // Both banks, so the LEAD amp's `post` can be re-matched to the rhythm
        // amp's the same way (2026.07.23 amp+cab HLD): the bank difference is
        // meant to be TIMBRE, so the two should read within ~1 dB here and the
        // A/B then isolates voicing rather than loudness.
        for prog in [29u8, 30] {
            for alt in [false, true] {
                for amp in [0.5f32, 0.05] {
                    let mut d = Drive::new(prog, alt, sr);
                    let mut buf: Vec<f32> = (0..(sr as usize))
                        .map(|i| amp * (std::f32::consts::TAU * 220.0 * i as f32 / sr).sin())
                        .collect();
                    d.process(&mut buf);
                    let seg = &buf[(0.2 * sr) as usize..];
                    let r = crate::testutil::rms(seg);
                    // Match `post` on the BAND, not the wideband RMS: the two
                    // cabinets differ at the low resonance (100 vs 120 Hz), and
                    // a 220 Hz source puts enough energy there to skew a
                    // wideband match by ~1 dB. 300–3400 Hz is where the ear
                    // places a driven guitar.
                    let b = crate::testutil::spectral_band_rms(seg, sr, 300.0, 3400.0);
                    println!(
                        "drive probe prog {prog} {} amp {amp}: wide {:.2} dBFS  band300-3400 {:.2} dBFS",
                        if alt { "alt " } else { "main" },
                        20.0 * r.max(1e-12).log10(),
                        20.0 * b.max(1e-12).log10()
                    );
                }
            }
        }
    }

    /// Voicing fingerprint (diagnostic, `--ignored --nocapture`): the LEAD
    /// bank's response against the RHYTHM bank's at named frequencies, plus
    /// the harmonic balance at a tail operating point. This is the tuning
    /// bench for `cab_biquads_lead` and the alt voicing EQ (2026.07.23 amp+cab
    /// HLD) — the oracles assert the DIRECTIONS, this prints the magnitudes.
    ///
    /// The sweep is driven small-signal (0.02) on purpose: the shapers stay
    /// near-linear, so the printed deltas read as the DESIGNED EQ rather than
    /// as clipping products.
    #[test]
    #[ignore]
    fn drive_voicing_fingerprint_probe() {
        let sr = 44100.0;
        let input: Vec<f32> = {
            let mut rng = crate::dsp::Rng::new(7);
            (0..(4.0 * sr) as usize)
                .map(|_| rng.white() * 0.02)
                .collect()
        };
        for prog in [29u8, 30] {
            let run = |alt: bool| {
                let mut d = Drive::new(prog, alt, sr);
                let mut b = input.clone();
                d.process(&mut b);
                b
            };
            let (m, a) = (run(false), run(true));
            let db = |b: &[f32], f: f32| {
                20.0 * crate::testutil::band_rms(&b[(0.2 * sr) as usize..], sr, f, 4.0)
                    .max(1e-12)
                    .log10()
            };
            print!("fingerprint prog {prog} (lead-main dB):");
            for f in [
                100.0f32, 250.0, 500.0, 800.0, 1400.0, 2500.0, 2800.0, 3000.0, 6000.0,
            ] {
                print!("  {f:.0}:{:+.2}", db(&a, f) - db(&m, f));
            }
            println!();
        }
        // Harmonic balance — the H2 (even-harmonic "warmth") the bias choice
        // trades against, swept over fundamental and drive so the
        // operating-point dependence is visible rather than sampled at one
        // lucky point.
        for prog in [29u8, 30] {
            for alt in [false, true] {
                for f0 in [110.0f32, 165.0, 220.0, 330.0] {
                    for amp in [0.5f32, 0.05] {
                        let mut d = Drive::new(prog, alt, sr);
                        let mut buf: Vec<f32> = (0..(sr as usize))
                            .map(|i| amp * (std::f32::consts::TAU * f0 * i as f32 / sr).sin())
                            .collect();
                        d.process(&mut buf);
                        let seg = &buf[(0.2 * sr) as usize..];
                        let m1 = crate::testutil::mag_at(seg, sr, f0).max(1e-12);
                        let h2 = 20.0 * (crate::testutil::mag_at(seg, sr, 2.0 * f0) / m1).log10();
                        let h3 = 20.0 * (crate::testutil::mag_at(seg, sr, 3.0 * f0) / m1).log10();
                        println!(
                            "harmonics prog {prog} {} f0 {f0:.0} amp {amp}: \
                             H2 {h2:+.1} dBc  H3 {h3:+.1} dBc  H2-H3 {:+.1}",
                            if alt { "alt " } else { "main" },
                            h2 - h3
                        );
                    }
                }
            }
        }
    }

    // -----------------------------------------------------------------
    // O-ATTACK (§3.1): "a struck/plucked voice's attack is its loudest
    // instant", measured on a windowed-RMS envelope through the FULL
    // engine — never a single global sample peak (noise/beating/body
    // resonance can nudge a raw peak; a 30 ms RMS window cannot).
    // -----------------------------------------------------------------

    /// Windowed-RMS envelope: 30 ms windows on a 10 ms hop, as
    /// (window-start seconds, rms) pairs.
    fn rms_env(sig: &[f32], sr: f32) -> Vec<(f32, f32)> {
        let win = (0.030 * sr) as usize;
        let hop = (0.010 * sr) as usize;
        let mut v = Vec::new();
        let mut a = 0usize;
        while a + win <= sig.len() {
            v.push((a as f32 / sr, rms(&sig[a..a + win])));
            a += hop;
        }
        v
    }

    /// One note through the engine, dry: reverb wet 0, echo bus disabled
    /// (`delay_s: 0`), chorus/echo/reverb sends zeroed so a bus tail cannot
    /// masquerade as a late bloom of the voice itself.
    fn o_attack_render(
        program: u8,
        key: u8,
        vel: u8,
        secs: f64,
        samples: bool,
        sr: f32,
    ) -> Vec<f32> {
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
        let events = vec![
            (
                0.0,
                EvKind::Prog {
                    ch: 0,
                    prog: program,
                },
            ),
            (0.0, cc(91, 0)),
            (0.0, cc(93, 0)),
            (0.0, cc(94, 0)),
            (0.05, EvKind::NoteOn { ch: 0, key, vel }),
        ];
        let mut opt = test_opts(sr);
        opt.samples = samples;
        left(&render(&test_song(events, secs), &opt).0)
    }

    /// The property: no post-attack window's RMS may exceed the attack
    /// window's loudest RMS. The attack window is per-class (`attack_s`),
    /// not a hard 80 ms constant — bar percussion speaks fast, timpani and
    /// tubular bells slower.
    fn assert_attack_dominates(sig: &[f32], sr: f32, note_s: f32, attack_s: f32, name: &str) {
        let env = rms_env(sig, sr);
        let attack = env
            .iter()
            .filter(|(t, _)| *t >= note_s - 0.005 && *t < note_s + attack_s)
            .map(|&(_, r)| r)
            .fold(0f32, f32::max);
        assert!(attack > 1e-5, "{name}: silent attack window");
        let (mut worst, mut worst_t) = (0f32, 0f32);
        for &(t, r) in env.iter().filter(|(t, _)| *t >= note_s + attack_s) {
            if r > worst {
                (worst, worst_t) = (r, t);
            }
        }
        assert!(
            worst <= attack,
            "{name}: late bloom — window at {worst_t:.2} s has rms {worst:.5} \
             above the attack's {attack:.5}"
        );
    }

    /// O-ATTACK, struck/plucked leg: Modal (piano/bells/mallets/timpani)
    /// and non-sustaining Pluck presets, model-only through the engine.
    #[test]
    fn o_attack_struck_attack_dominates() {
        let sr = 44100.0;
        for (program, key, attack_s, name) in [
            (0u8, 60u8, 0.15f32, "acoustic piano"),
            (6, 60, 0.12, "harpsichord"), // §2.10: guards the new Pluck route
            (9, 84, 0.12, "glockenspiel"),
            (12, 72, 0.10, "marimba"),
            (14, 65, 0.20, "tubular bells"),
            (47, 50, 0.20, "timpani"),
            (24, 52, 0.12, "nylon guitar"),
            (25, 52, 0.12, "steel guitar"),
            (45, 60, 0.10, "pizzicato"),
            (46, 60, 0.12, "harp"),
        ] {
            let sig = o_attack_render(program, key, 100, 3.0, false, sr);
            assert_attack_dominates(&sig, sr, 0.05, attack_s, name);
        }
    }

    /// O-ATTACK, sampled leg: the LA-wrapped struck voices with the sample
    /// layer on, through the engine (a pick quieter than the model's 200 ms
    /// sustain is upside-down for a plucked string). Under the pre-§2.7
    /// crossfade the model's own onset ran UNDER the sample (a doubled
    /// attack) and masked the GM-24 gain cut even here; once the contract
    /// gives the sample sole onset ownership, the 0.25 hack fails
    /// `la_level_continuity`'s attack-is-the-peak leg (measured: nylon key
    /// 45 inverts at 0.25), and this engine-level leg pins the fixed gain.
    #[test]
    fn o_attack_sampled_struck_attack_dominates() {
        if !crate::embedded_samples_available() {
            return;
        }
        let sr = 44100.0;
        for (program, key, attack_s, name) in [
            (0u8, 60u8, 0.20f32, "acoustic piano (LA)"),
            (24, 52, 0.12, "nylon guitar (LA)"),
            (24, 57, 0.12, "nylon guitar (LA), mid"),
            (24, 64, 0.12, "nylon guitar (LA), high"),
        ] {
            let sig = o_attack_render(program, key, 100, 3.0, true, sr);
            assert_attack_dominates(&sig, sr, 0.05, attack_s, name);
        }
    }

    /// O-ATTACK, sustaining-pluck leg (`sustain > 0`: the DRIVE e-bow):
    /// a held distorted note may HOLD, but no late window may exceed the
    /// pick — the §2.6 sag-inversion catcher. The deleted sag law's restore
    /// target was an ABSOLUTE level, so a quiet pick (vel 20-30) was boosted
    /// past its own attack ~0.2 s in, and at ff the sag's slow limit cycle
    /// grew past the pick by ~7 s (measured 1.00-1.04x pre-fix on every row
    /// here; the static two-stage cascade keeps all four well below 1).
    #[test]
    fn o_attack_sustained_plucks_no_late_bloom() {
        let sr = 44100.0;
        for (program, vel, secs, name) in [
            (29u8, 20u8, 4.0, "overdrive pp"),
            (29, 100, 4.0, "overdrive ff"),
            (30, 30, 4.0, "distortion p"),
            (30, 100, 8.0, "distortion ff, long hold"),
        ] {
            let sig = o_attack_render(program, 45, vel, secs, false, sr);
            assert_attack_dominates(&sig, sr, 0.05, 0.15, name);
        }
    }

    /// O-ATTACK, unit leg: the Drive insert itself on a known decaying
    /// input (−15 dB/s, 220 Hz), pinning recovery at the unit rather than
    /// only end-to-end. Two clauses: (a) windowed output RMS never RISES
    /// (0.5 dB tolerance) — a recovery gain law that outruns the decay
    /// fails; (b) the tail genuinely DECAYS — ≥ 12 dB from the 0.05-0.10 s
    /// window to the 1.80-1.95 s window. The deleted sag law held that
    /// decay to 5.6 dB (measured, prog 30) by slewing gain up to 4x as the
    /// envelope fell; the static two-stage cascade measures 16.6 dB.
    #[test]
    fn o_attack_drive_never_blooms_on_decay() {
        let sr = 44100.0;
        let n = (2.0 * sr) as usize;
        for prog in [29u8, 30] {
            let mut d = Drive::new(prog, false, sr);
            let mut buf: Vec<f32> = (0..n)
                .map(|i| {
                    let t = i as f32 / sr;
                    0.5 * 10f32.powf(-15.0 * t / 20.0) * (std::f32::consts::TAU * 220.0 * t).sin()
                })
                .collect();
            d.process(&mut buf);
            let win = (0.05 * sr) as usize;
            let env: Vec<f32> = buf.chunks_exact(win).map(rms).collect();
            // (a) skip the first pair: filter/DC-blocker settling
            for (k, pair) in env.windows(2).enumerate().skip(1) {
                assert!(
                    pair[1] <= pair[0] * 1.06,
                    "prog {prog}: output rose on a decaying input at window {k}: \
                     {:.5} -> {:.5}",
                    pair[0],
                    pair[1]
                );
            }
            // (b) the decay must pass through, not be recovered away
            let db = |a: f32, z: f32| {
                20.0 * rms(&buf[(a * sr) as usize..(z * sr) as usize])
                    .max(1e-12)
                    .log10()
            };
            let decay = db(0.05, 0.10) - db(1.80, 1.95);
            assert!(
                decay >= 12.0,
                "prog {prog}: tail held up — decay {decay:.1} dB < 12 \
                 (a sag-like envelope-inverse recovery gain)"
            );
        }
    }

    /// Diagnostic (`--ignored --nocapture`): held-note level through the
    /// engine for the driven guitars — the §2.6 loudness-risk probe. Prints
    /// the windowed RMS of a 3.5 s held note at 0.2–0.5 s vs 2.5–3.0 s so a
    /// sustain collapse after a Drive change is measured, not guessed.
    #[test]
    #[ignore = "diagnostic probe, not a gate"]
    fn o_attack_held_note_probe() {
        let sr = 44100.0;
        for prog in [29u8, 30] {
            let sig = o_attack_render(prog, 45, 100, 3.5, false, sr);
            let w = |a: f32, z: f32| rms(&sig[(a * sr) as usize..(z * sr) as usize]);
            let (early, late) = (w(0.2, 0.5), w(2.5, 3.0));
            println!(
                "prog {prog}: early {early:.5} ({:.1} dB), late {late:.5} ({:.1} dB), \
                 drop {:.1} dB",
                20.0 * early.max(1e-9).log10(),
                20.0 * late.max(1e-9).log10(),
                20.0 * (early.max(1e-9) / late.max(1e-9)).log10()
            );
        }
    }

    /// The bus glue must tame loud material, pass quiet material nearly
    /// unchanged, and never blow up.
    #[test]
    fn glue_compresses_and_stays_sane() {
        let sr = 44100.0;
        let mut glue = BusGlue::new(sr);
        let mut l: Vec<f32> = (0..44100)
            .map(|i| (i as f32 * 220.0 / sr * std::f32::consts::TAU).sin() * 0.8)
            .collect();
        let mut r = l.clone();
        glue.process(&mut l, &mut r);
        let out_peak = l[22050..].iter().fold(0f32, |m, &x| m.max(x.abs()));
        assert!(out_peak < 0.8, "no gain reduction: {out_peak}");
        assert!(out_peak > 0.3, "over-compressed: {out_peak}");
        assert!(l.iter().all(|x| x.is_finite()));

        let mut glue2 = BusGlue::new(sr);
        let mut ql: Vec<f32> = (0..44100)
            .map(|i| (i as f32 * 220.0 / sr * std::f32::consts::TAU).sin() * 0.05)
            .collect();
        let mut qr = ql.clone();
        glue2.process(&mut ql, &mut qr);
        let q_peak = ql[22050..].iter().fold(0f32, |m, &x| m.max(x.abs()));
        assert!(
            (q_peak - 0.05).abs() < 0.012,
            "quiet signal changed: {q_peak}"
        );
    }

    /// Isolate the fundamental, find interpolated rising zero-crossings,
    /// smooth the per-cycle frequency over 8 cycles, and report max − min:
    /// how far the pitch wanders inside the segment.
    fn cycle_freq_spread(seg: &[f32], sr: f32) -> f32 {
        let mut lp1 = OnePole::lowpass(700.0, sr);
        let mut lp2 = OnePole::lowpass(700.0, sr);
        let f: Vec<f32> = seg.iter().map(|&x| lp2.process(lp1.process(x))).collect();
        let mut times = Vec::new();
        for i in 1..f.len() {
            if f[i - 1] <= 0.0 && f[i] > 0.0 {
                times.push((i - 1) as f32 - f[i - 1] / (f[i] - f[i - 1]));
            }
        }
        let freqs: Vec<f32> = times.windows(2).map(|w| sr / (w[1] - w[0])).collect();
        let smooth: Vec<f32> = freqs
            .windows(8)
            .map(|w| w.iter().sum::<f32>() / 8.0)
            .collect();
        let hi = smooth.iter().fold(f32::MIN, |m, &x| m.max(x));
        let lo = smooth.iter().fold(f32::MAX, |m, &x| m.min(x));
        hi - lo
    }

    /// Like [`cycle_freq_spread`], but ZERO-PHASE band-limits around `f0` first
    /// so a sub-octave partial cannot leak into the fundamental's zero-crossing
    /// count and inflate the reading. GM19's 16' foundation adds a partial at
    /// `f0/2`; that sub-octave sits inside `cycle_freq_spread`'s 700 Hz passband
    /// and wanders its per-cycle frequency estimate. A single causal high/band-
    /// pass would RING and bias the spread further UP, so we apply a `Biquad`
    /// bandpass forward, reverse the buffer, filter again, and reverse back
    /// (filtfilt): the two passes cancel phase and ringing, leaving a real pitch
    /// vibrato (whose fundamental stays inside the [0.75·f0, 1.5·f0] band)
    /// untouched while rejecting the f0/2 sub-octave and 2·f0 harmonic.
    fn cycle_freq_spread_f0(seg: &[f32], sr: f32, f0: f32) -> f32 {
        // Q ≈ 1.3 puts the single-pass −3 dB skirts near [0.75·f0, 1.5·f0]; the
        // second (reverse) pass squares the magnitude, deepening sub-octave and
        // harmonic rejection without adding phase distortion.
        let q = 1.3;
        let mut fwd = Biquad::bandpass(f0, q, sr);
        let forward: Vec<f32> = seg.iter().map(|&x| fwd.process(x)).collect();
        let mut rev = Biquad::bandpass(f0, q, sr);
        let mut back: Vec<f32> = forward.iter().rev().map(|&x| rev.process(x)).collect();
        back.reverse();
        cycle_freq_spread(&back, sr)
    }

    fn render_cc1_program(program: u8, cc1: Option<u8>, cc1_before_note: bool) -> Vec<f32> {
        let mut events = Vec::new();
        if program == 19 {
            events.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ));
        }
        events.extend([
            (
                0.0,
                EvKind::Prog {
                    ch: 0,
                    prog: program,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
        ]);
        if cc1_before_note {
            if let Some(val) = cc1 {
                events.push((0.0, EvKind::Cc { ch: 0, num: 1, val }));
            }
        }
        events.push((
            0.05,
            EvKind::NoteOn {
                ch: 0,
                key: 69,
                vel: 100,
            },
        ));
        if !cc1_before_note {
            if let Some(val) = cc1 {
                events.push((0.60, EvKind::Cc { ch: 0, num: 1, val }));
            }
        }
        events.push((3.85, EvKind::NoteOff { ch: 0, key: 69 }));
        left(&render(&test_song(events, 4.0), &test_opts(44100.0)).0)
    }

    fn render_cc1_events(events: Vec<(f64, EvKind)>) -> Vec<f32> {
        left(&render(&test_song(events, 4.0), &test_opts(44100.0)).0)
    }

    fn am_rate(mono: &[f32], sr: f32, t0: f32, t1: f32) -> f32 {
        let mut env_lps = [OnePole::lowpass(12.0, sr); 4];
        let env: Vec<f32> = mono
            .iter()
            .map(|&x| {
                let mut y = x.abs();
                for lp in env_lps.iter_mut() {
                    y = lp.process(y);
                }
                y
            })
            .collect();
        let mut trend = OnePole::lowpass(1.2, sr);
        let det: Vec<f32> = env.iter().map(|&x| x - trend.process(x)).collect();
        let seg = &det[(t0 * sr) as usize..(t1 * sr) as usize];
        let crossings = seg.windows(2).filter(|w| w[0] <= 0.0 && w[1] > 0.0).count();
        crossings as f32 / (t1 - t0)
    }

    fn render_bowed_program_with_mod(program: u8, mod_val: u8) -> Vec<f32> {
        let song = test_song(
            vec![
                (
                    0.0,
                    EvKind::Prog {
                        ch: 0,
                        prog: program,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 93,
                        val: 0,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 1,
                        val: mod_val,
                    },
                ),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 69,
                        vel: 100,
                    },
                ),
                (2.4, EvKind::NoteOff { ch: 0, key: 69 }),
            ],
            2.5,
        );
        left(&render(&song, &test_opts(44100.0)).0)
    }

    fn render_bowed_controls(
        program: u8,
        key: u8,
        mod_val: u8,
        aftertouch: u8,
        samples: bool,
    ) -> Vec<f32> {
        let song = test_song(
            vec![
                (
                    0.0,
                    EvKind::Prog {
                        ch: 0,
                        prog: program,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 93,
                        val: 0,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 1,
                        val: mod_val,
                    },
                ),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key,
                        vel: 100,
                    },
                ),
                (
                    0.10,
                    EvKind::Aftertouch {
                        ch: 0,
                        val: aftertouch,
                    },
                ),
                (2.4, EvKind::NoteOff { ch: 0, key }),
            ],
            2.5,
        );
        let opt = Options {
            samples,
            ..test_opts(44100.0)
        };
        left(&render(&song, &opt).0)
    }

    /// Render GM44 through the engine so its authored CC1 path is exercised.
    fn render_bowed_with_mod(mod_val: u8) -> Vec<f32> {
        render_bowed_program_with_mod(44, mod_val)
    }

    /// CC1 = 127 on GM44 must deepen the waveguide's natural vibrato.
    ///
    /// Autocorrelation is required here: the strong low harmonics of a
    /// `BowedString` make zero-crossing counts look wildly unstable.
    #[test]
    fn cc1_mod_wheel_adds_vibrato() {
        let sr = 44100.0;
        let plain = render_bowed_with_mod(0);
        let modded = render_bowed_with_mod(127);
        let (a, b) = ((0.8 * sr) as usize, (2.2 * sr) as usize);
        let f0 = crate::dsp::key_freq(69);
        let spread_plain = autocorr_cents_spread(&plain[a..b], sr, f0);
        let spread_mod = autocorr_cents_spread(&modded[a..b], sr, f0);
        assert!(
            (3.0..=42.0).contains(&spread_plain),
            "GM44 autonomous excursion {spread_plain:.1} cents"
        );
        assert!(
            spread_mod > 2.0 * spread_plain,
            "GM44 CC1 {spread_mod:.1} vs natural {spread_plain:.1} cents"
        );
    }

    #[test]
    fn gm110_fiddle_routes_to_bowedstring_and_takes_mod_vibrato() {
        let sr = 44100.0;
        let routed = crate::voices::make(110, 69, 100, sr, 5, true);
        // Was "bowed" until 2026.07.26. The fiddle now plays the `BowedString`
        // waveguide like the rest of the solo bowed strings; the saw voice it
        // left behind is what made it read as synthy.
        assert_eq!(
            routed.kind(),
            "bowedstring",
            "GM 110 must use the bowed-waveguide/LA fiddle path"
        );
        assert!(vibrato_family(110), "GM 110 must take authored CC1 vibrato");
        assert_eq!(
            fx_profile(110, 0),
            fx_profile(40, 0),
            "GM 110 should use the fiddle bus profile"
        );

        // The CC1 depth assertions that used to live here measured GM110 with the
        // zero-crossing `cycle_freq_spread`, which cannot read a waveguide. They
        // are not dropped: `bowedstring_family_pitch_bounded` makes the same two
        // claims about GM110 (autonomous excursion bounded, CC1 at least doubles
        // it) by autocorrelation, at both sample settings.
    }

    /// Natural vibrato, CC1 and channel aftertouch compose without either
    /// cancelling into dropouts or exceeding the signed pitch bound.
    #[test]
    fn bowed_natural_cc1_aftertouch_composition_is_bounded() {
        let sr = 44100.0;
        let range = ((0.8 * sr) as usize, (2.2 * sr) as usize);
        // GM44 is now a `BowedString` waveguide. Its strong low partials fool
        // zero-crossing counts, so use the same autocorrelation measure as the
        // rest of the bowed-string family.
        for (program, key, samples) in [(44u8, 69u8, false), (44, 69, true)] {
            let plain = render_bowed_controls(program, key, 0, 0, samples);
            let modded = render_bowed_controls(program, key, 127, 0, samples);
            let composed = render_bowed_controls(program, key, 127, 127, samples);
            let f0 = crate::dsp::key_freq(key);
            let plain_c = autocorr_cents_spread(&plain[range.0..range.1], sr, f0);
            let mod_c = autocorr_cents_spread(&modded[range.0..range.1], sr, f0);
            let both_c = autocorr_cents_spread(&composed[range.0..range.1], sr, f0);
            assert!(
                (3.0..=42.0).contains(&plain_c),
                "GM{program} samples={samples}: autonomous excursion {plain_c:.1} cents"
            );
            assert!(
                mod_c >= 2.0 * plain_c,
                "GM{program} samples={samples}: CC1 {mod_c:.1} vs natural {plain_c:.1} cents"
            );
            assert!(
                both_c < 150.0,
                "GM{program} samples={samples}: composed excursion {both_c:.1} cents"
            );

            let seg = &composed[range.0..range.1];
            let win = (0.01 * sr) as usize;
            let levels: Vec<f32> = seg.chunks(win).map(rms).collect();
            let mut ordered = levels.clone();
            ordered.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let median = ordered[ordered.len() / 2];
            let floor = levels.iter().copied().fold(f32::INFINITY, f32::min);
            assert!(
                floor >= 0.25 * median,
                "GM{program} samples={samples}: controller beat dropout {floor:.5} vs median {median:.5}"
            );
        }
    }

    /// Robust fundamental-frequency spread (cents) via per-window
    /// autocorrelation with a parabolic peak refine. Unlike zero-crossing
    /// counting, autocorrelation locks to the fundamental *period* even when the
    /// low harmonics are strong (a bowed string's H2/H3 rival H1), so it does
    /// not mis-read a harmonic-rich waveguide's stable pitch as unstable.
    fn autocorr_cents_spread(seg: &[f32], sr: f32, f0: f32) -> f32 {
        let win = 2048usize;
        let hop = 2048usize;
        let lag_lo = (sr / (f0 * 1.5)).floor().max(2.0) as usize;
        let lag_hi = ((sr / (f0 * 0.67)).ceil() as usize).min(win - 2);
        let mut freqs = Vec::new();
        let mut start = 0;
        while start + win <= seg.len() {
            let w = &seg[start..start + win];
            let mean = w.iter().sum::<f32>() / win as f32;
            let acf = |lag: usize| -> f32 {
                let mut a = 0.0f32;
                for i in 0..(win - lag) {
                    a += (w[i] - mean) * (w[i + lag] - mean);
                }
                a
            };
            let mut best_lag = lag_lo;
            let mut best = f32::MIN;
            for lag in lag_lo..=lag_hi {
                let a = acf(lag);
                if a > best {
                    best = a;
                    best_lag = lag;
                }
            }
            // sub-lag parabolic refine for sub-cent resolution
            let refined = if best_lag > lag_lo && best_lag < lag_hi {
                let (y0, y1, y2) = (acf(best_lag - 1), best, acf(best_lag + 1));
                let d = y0 - 2.0 * y1 + y2;
                best_lag as f32 + if d != 0.0 { 0.5 * (y0 - y2) / d } else { 0.0 }
            } else {
                best_lag as f32
            };
            freqs.push(sr / refined);
            start += hop;
        }
        if freqs.len() < 2 {
            return 0.0;
        }
        let hi = freqs.iter().copied().fold(f32::MIN, f32::max);
        let lo = freqs.iter().copied().fold(f32::MAX, f32::min);
        1200.0 * (hi / lo).log2()
    }

    /// Every `BowedString` program: autonomous pitch is a gentle vibrato + human
    /// drift, CC1 deepens it, and CC1 + aftertouch compose without a runaway
    /// excursion or amplitude dropouts.
    ///
    /// Measured with autocorrelation, which is robust to the waveguide's strong
    /// low harmonics (H2/H3 rival H1). The zero-crossing `cycle_freq_spread`
    /// cannot count those correctly and reads a stable waveguide as wildly
    /// unstable — it once read a false ~1780 cents here.
    ///
    /// Covered GM43 alone until 2026.07.26, when GM 40/41/110 moved onto the same
    /// waveguide and inherited both the invariants and the measurement problem.
    /// GM44 followed on 2026.07.27 with its direction-reversing tremolo treatment.
    /// These entries replace the zero-crossing coverage that asserted the old saw
    /// voices' numbers.
    #[test]
    fn bowedstring_family_pitch_bounded() {
        let sr = 44100.0;
        let range = ((0.8 * sr) as usize, (2.2 * sr) as usize);
        for (program, key, samples) in [
            (43u8, 45u8, false),
            (43, 45, true),
            (43, 40, false),
            (40, 69, false),
            (40, 69, true),
            (41, 60, false),
            (42, 48, false),
            (44, 69, false),
            (44, 69, true),
            (110, 69, false),
            (110, 69, true),
        ] {
            let f0 = crate::dsp::key_freq(key);
            let plain = render_bowed_controls(program, key, 0, 0, samples);
            let modded = render_bowed_controls(program, key, 127, 0, samples);
            let composed = render_bowed_controls(program, key, 127, 127, samples);
            let plain_c = autocorr_cents_spread(&plain[range.0..range.1], sr, f0);
            let mod_c = autocorr_cents_spread(&modded[range.0..range.1], sr, f0);
            let both_c = autocorr_cents_spread(&composed[range.0..range.1], sr, f0);
            // autonomous pitch is the deepened natural arco vibrato + human drift.
            // Measured ~28-32 cents pk-pk since the bass vibrato was deepened to a
            // realistic depth (was ~10-12 when the vibrato ran ~5-10x too shallow) —
            // present and expressive, but bounded, never a runaway warble.
            assert!(
                (3.0..=42.0).contains(&plain_c),
                "GM{program} key={key} samples={samples}: autonomous excursion {plain_c:.1} cents"
            );
            // CC1 clearly deepens the vibrato
            assert!(
                mod_c >= 2.0 * plain_c,
                "GM{program} key={key} samples={samples}: CC1 {mod_c:.1} vs natural {plain_c:.1} cents"
            );
            // CC1 + aftertouch compose without a runaway (the zero-crossing
            // measure read a false ~1780 cents here; the true excursion is ~130
            // with the deepened natural vibrato underneath the maxed controllers)
            assert!(
                both_c < 150.0,
                "GM{program} key={key} samples={samples}: composed excursion {both_c:.1} cents"
            );
            // no controller-induced amplitude dropouts
            let seg = &composed[range.0..range.1];
            let win = (0.01 * sr) as usize;
            let levels: Vec<f32> = seg.chunks(win).map(rms).collect();
            let mut ordered = levels.clone();
            ordered.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let median = ordered[ordered.len() / 2];
            let floor = levels.iter().copied().fold(f32::INFINITY, f32::min);
            assert!(
                floor >= 0.25 * median,
                "GM{program} key={key} samples={samples}: controller beat dropout {floor:.5} vs median {median:.5}"
            );
        }
    }

    #[test]
    fn bagpipe_shanai_route_to_reed_engine_with_drone_or_double_reed() {
        let sr = 44100.0;
        assert_eq!(
            crate::voices::make(109, 67, 100, sr, 5, false).kind(),
            "reed",
            "GM109 bagpipe chanter must use the reed voice"
        );
        assert_eq!(
            crate::voices::make(111, 72, 100, sr, 5, false).kind(),
            "reed",
            "GM111 shanai must use the reed voice"
        );
        assert!(vibrato_family(109), "bagpipe should take authored reed CC1");
        assert!(vibrato_family(111), "shanai should take authored reed CC1");

        let bagpipe = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 109 }),
                (
                    0.0,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 43,
                        vel: 70,
                    },
                ),
                (
                    0.12,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 67,
                        vel: 104,
                    },
                ),
                (0.42, EvKind::NoteOff { ch: 0, key: 67 }),
                (
                    0.50,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 69,
                        vel: 104,
                    },
                ),
                (0.82, EvKind::NoteOff { ch: 0, key: 69 }),
                (1.10, EvKind::NoteOff { ch: 0, key: 43 }),
            ],
            1.45,
        );
        let (bagpipe_out, stats) = render(&bagpipe, &test_opts(sr));
        assert_eq!(
            stats.voices_spawned, 3,
            "one low drone control plus two chanters should spawn one channel drone and two reed chanters"
        );
        let bagpipe_l = left(&bagpipe_out);
        let root = key_freq(43);
        let fifth = root * 1.5;
        let drone_only = &bagpipe_l[(0.05 * sr) as usize..(0.11 * sr) as usize];
        let drone_root = crate::testutil::band_rms(drone_only, sr, root, 8.0);
        let drone_fifth = crate::testutil::band_rms(drone_only, sr, fifth, 8.0);
        let drone_level = rms(drone_only);
        assert!(
            drone_root > 0.18 * drone_level,
            "bagpipe drone root band weak: root/drone {:.3}",
            drone_root / drone_level.max(1e-9)
        );
        // Highland drones are OCTAVES (tenor pair + bass), never a dedicated
        // fifth oscillator. The bound allows the bass drone's own 3rd
        // harmonic (an odd-harmonic square at root/2 puts its 3rd exactly on
        // the twelfth, ≈0.41 of root here — physically real on any pipe) but
        // rejects the old fifth oscillator (measured 0.73 of root).
        assert!(
            drone_fifth < 0.55 * drone_root,
            "bagpipe drone carries a FIFTH ({:.3} of root) — Highland drones \
             are a tenor pair plus a bass octave",
            drone_fifth / drone_root.max(1e-9)
        );
        let body = &bagpipe_l[(0.20 * sr) as usize..(0.74 * sr) as usize];
        let body_rms = rms(body);
        let body_drone = crate::testutil::band_rms(body, sr, root, 8.0);
        let body_bass = crate::testutil::band_rms(body, sr, root * 0.5, 6.0);
        let chanter = crate::testutil::band_rms(body, sr, key_freq(67), 10.0)
            + crate::testutil::band_rms(body, sr, key_freq(69), 10.0);
        assert!(
            body_drone > 0.06 * body_rms && chanter > 0.10 * body_rms,
            "bagpipe needs drone plus chanter: drone/body {:.3}, chanter/body {:.3}",
            body_drone / body_rms.max(1e-9),
            chanter / body_rms.max(1e-9)
        );
        assert!(
            body_bass > 0.04 * body_rms,
            "bagpipe drone has no bass octave: bass/body {:.3}",
            body_bass / body_rms.max(1e-9)
        );
        assert!(
            body_rms < 0.12,
            "bagpipe drone+chanter level too hot before normalisation: {body_rms:.4}"
        );
        let release_tail = rms(&bagpipe_l[(1.30 * sr) as usize..(1.42 * sr) as usize]);
        assert!(
            release_tail < 0.25 * body_rms,
            "bagpipe drone did not release with the channel: tail/body {:.3}",
            release_tail / body_rms.max(1e-9)
        );

        let render_voice = |program: u8, key: u8, secs: f32| {
            let mut voice = crate::voices::make(program, key, 110, sr, 9, false);
            let mut buf = vec![0f32; (secs * sr) as usize];
            voice.render(&mut buf);
            buf
        };
        let shanai = render_voice(111, 72, 1.4);
        let clarinet = render_voice(71, 72, 1.4);
        let seg_start = (0.35 * sr) as usize;
        let seg_end = (1.20 * sr) as usize;
        let sh_seg = &shanai[seg_start..seg_end];
        let cl_seg = &clarinet[seg_start..seg_end];
        let prom = |s: &[f32], f: f32| crate::testutil::band_rms(s, sr, f, 2.5) / rms(s).max(1e-9);
        assert!(
            prom(sh_seg, 1200.0) > 1.25 * prom(cl_seg, 1200.0),
            "shanai nasal formant too weak vs clarinet: {:.3} vs {:.3}",
            prom(sh_seg, 1200.0),
            prom(cl_seg, 1200.0)
        );
        let f0 = key_freq(72);
        let sh_h1 = crate::testutil::band_rms(sh_seg, sr, f0, 12.0);
        let sh_h2 = crate::testutil::band_rms(sh_seg, sr, f0 * 2.0, 12.0);
        let cl_h1 = crate::testutil::band_rms(cl_seg, sr, f0, 12.0);
        let cl_h2 = crate::testutil::band_rms(cl_seg, sr, f0 * 2.0, 12.0);
        assert!(
            sh_h2 / sh_h1.max(1e-9) > 2.0 * (cl_h2 / cl_h1.max(1e-9)),
            "shanai should be even-rich like a double reed: shanai {:.3}, clarinet {:.3}",
            sh_h2 / sh_h1.max(1e-9),
            cl_h2 / cl_h1.max(1e-9)
        );

        let high = render_voice(111, 87, 0.24);
        let seg = &high[(0.06 * sr) as usize..(0.22 * sr) as usize];
        let f_alias = sr / 35.5;
        let fund = crate::testutil::mag_at(seg, sr, f_alias).max(1e-12);
        let mut acc = 0.0f64;
        let mut cnt = 0u32;
        let mut k = 1.5f32;
        while f_alias * k < 0.4 * sr {
            let r = crate::testutil::mag_at(seg, sr, f_alias * k) / fund;
            acc += (r as f64) * (r as f64);
            cnt += 1;
            k += 1.0;
        }
        let alias = (acc / cnt as f64).sqrt() as f32;
        assert!(
            alias < 0.03,
            "shanai fold-back alias floor too high: {alias:.4}"
        );
    }

    /// BP-O3: the channel drone is CONTINUOUS across chanter note boundaries.
    /// A real set of pipes never stops its drones between melody notes; the
    /// old engine released the drone at every chanter NoteOff (when no other
    /// chanter rang) and spawned a FRESH one — at the NEW note's pitch — on
    /// the next NoteOn: an amplitude notch plus a pitch lurch at every note
    /// boundary. One latched drone per channel, released only by an authored
    /// drone-control stop or the block-rate hang timer (the bag emptying).
    #[test]
    fn bagpipe_drone_is_continuous_across_chanter_note_boundaries() {
        let sr = 44100.0;
        // A plain chanter melody — NO low drone-control note (the shape of a
        // real-world GM 109 file): two notes with a 20 ms articulation gap.
        let song = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 109 }),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 67,
                        vel: 96,
                    },
                ),
                (0.60, EvKind::NoteOff { ch: 0, key: 67 }),
                (
                    0.62,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 69,
                        vel: 96,
                    },
                ),
                (1.20, EvKind::NoteOff { ch: 0, key: 69 }),
            ],
            1.30,
        );
        let (out, stats) = render(&song, &test_opts(sr));
        let l = left(&out);
        let win = |a: f32, b: f32| &l[(a * sr) as usize..(b * sr) as usize];
        // Tenor drones sit an octave below the FIRST chanter note (196 Hz)
        // and must still be there, at the SAME pitch, during the second note.
        let tenor_w1 = crate::testutil::band_rms(win(0.25, 0.55), sr, 196.0, 8.0);
        let tenor_w2 = crate::testutil::band_rms(win(0.70, 1.15), sr, 196.0, 8.0);
        let tenor_hold = tenor_w2 / tenor_w1.max(1e-9);
        // The bass drone (98 Hz — steady, no beat partner) must not notch at
        // the 0.60/0.62 boundary: 100 ms windows, 50 ms hop, min vs median.
        let mut env98: Vec<(f32, f32)> = Vec::new();
        let mut t = 0.20f32;
        while t + 0.10 <= 1.151 {
            env98.push((
                t,
                crate::testutil::band_rms(win(t, t + 0.10), sr, 98.0, 8.0),
            ));
            t += 0.05;
        }
        let mut all: Vec<f32> = env98.iter().map(|&(_, e)| e).collect();
        all.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let med = all[all.len() / 2];
        let dip = env98
            .iter()
            .filter(|&&(t0, _)| (0.40..=0.90).contains(&t0))
            .map(|&(_, e)| e)
            .fold(f32::INFINITY, f32::min)
            / med.max(1e-9);
        let body = rms(win(0.25, 1.15));
        println!(
            "BP-O3: voices {}, tenor hold {tenor_hold:.3}, bass med/body {:.3}, \
             bass dip {dip:.3}",
            stats.voices_spawned,
            med / body.max(1e-9)
        );
        // ONE drone for the whole channel: 2 chanters + 1 drone. The per-note
        // release/re-spawn bug spawned a second drone (4 voices).
        assert_eq!(
            stats.voices_spawned, 3,
            "two chanter notes must share ONE latched channel drone \
             (2 chanters + 1 drone); more means a re-spawn per note"
        );
        // The sharp presence discriminator: pre-fix the 98 Hz band was pure
        // leakage floor (0.023 of body); the real bass drone reads ~0.13.
        assert!(
            med > 0.06 * body,
            "the drone has no steady bass octave at 98 Hz (med/body {:.4})",
            med / body.max(1e-9)
        );
        // The tenor PAIR beats (~0.78 Hz), so this band's level swings with
        // beat phase across the two windows (deterministically 0.41 here);
        // the floor only requires the tenors to still be audibly present.
        assert!(
            tenor_hold >= 0.25,
            "tenor drone collapsed across the note boundary (note2/note1 \
             196 Hz band {tenor_hold:.3}) — released and re-spawned at the \
             new note's pitch"
        );
        assert!(
            dip >= 0.5,
            "bass drone notches at the chanter note boundary: min/median {dip:.3}"
        );
    }

    // --- GM 109 sampled bagpipe oracles (HLD 2026.07.17 §7) ------------------

    #[cfg(feature = "embedded-samples")]
    fn bp_opts(sr: f32, samples: bool) -> Options {
        Options {
            samples,
            ..test_opts(sr)
        }
    }

    /// A held note on ch0 program 109, optional alt-bank (CC0 = `bank`).
    #[cfg(feature = "embedded-samples")]
    fn bagpipe_song(key: u8, secs: f64, bank: Option<u8>) -> Song {
        let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog: 109 })];
        if let Some(v) = bank {
            ev.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: v,
                },
            ));
        }
        ev.push((
            0.05,
            EvKind::NoteOn {
                ch: 0,
                key,
                vel: 100,
            },
        ));
        ev.push((secs - 0.1, EvKind::NoteOff { ch: 0, key }));
        test_song(ev, secs)
    }

    /// Dispatch + the MANDATORY alt-bank arm (§7.2). Samples-on the default bank
    /// engages the SAMPLED bagpipe (differs from the model); the CC0 alt bank and
    /// samples-off both render the MODEL, byte-identical — proving the model
    /// stays reachable and that BOTH halves (chanter via altbank::make, drone via
    /// ensure_bagpipe_drone reading alt_bank) honour the bank.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn bagpipe_sampled_dispatch_and_alt_bank_are_coherent() {
        let sr = 44100.0;
        let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
        let (model, _) = render(&bagpipe_song(69, 1.0, None), &bp_opts(sr, false));
        let (sampled, _) = render(&bagpipe_song(69, 1.0, None), &bp_opts(sr, true));
        let (alt, _) = render(&bagpipe_song(69, 1.0, Some(1)), &bp_opts(sr, true));
        assert_ne!(
            bits(&model),
            bits(&sampled),
            "samples-on 109 did not engage the sampled bagpipe"
        );
        assert_eq!(
            bits(&alt),
            bits(&model),
            "alt-bank (CC0=1) 109 must render the byte-identical model — the \
             mandatory altbank arm is missing, or the drone ignored alt_bank"
        );
    }

    /// The sampled drone's octave stack AND the drone-control branch (§7.6b).
    /// A drone-control note (key <= 54) sounds the tenor AT its key pitch, with
    /// the bass an octave below. Key 43 (G2, ~98 Hz) must therefore show energy
    /// at ~98 (tenor at pitch) and ~49 (bass octave below). If the at-pitch
    /// branch were dropped, the tenor would sit at ~49 and 98 would be empty.
    /// Level stays near the modeled drone (§7.6c balance).
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn bagpipe_sampled_drone_octave_and_control_pitch() {
        let sr = 44100.0;
        // drone-control note only (no chanter): key 43 spawns the drone at pitch
        let song = {
            let ev = vec![
                (0.0, EvKind::Prog { ch: 0, prog: 109 }),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 43,
                        vel: 100,
                    },
                ),
                (1.4, EvKind::NoteOff { ch: 0, key: 43 }),
            ];
            test_song(ev, 1.5)
        };
        let (out, _) = render(&song, &bp_opts(sr, true));
        let l = left(&out);
        let win = &l[(0.4 * sr) as usize..(1.2 * sr) as usize];
        let tenor = crate::testutil::band_rms(win, sr, 98.0, 8.0);
        let bass = crate::testutil::band_rms(win, sr, 49.0, 6.0);
        let body = rms(win).max(1e-9);
        assert!(
            tenor > 0.06 * body,
            "no tenor at the control pitch (98 Hz {:.4} of body) — the \
             drone-control at-pitch branch is missing",
            tenor / body
        );
        assert!(
            bass > 0.04 * body,
            "no bass octave below (49 Hz {:.4} of body)",
            bass / body
        );
        // balance: within a factor of the modeled drone's level (not swamping)
        let (m, _) = render(&song, &bp_opts(sr, false));
        let (rs, rm) = (rms(&left(&out)), rms(&left(&m)).max(1e-9));
        assert!(
            (0.4..=2.5).contains(&(rs / rm)),
            "sampled drone level {rs:.4} is off the modeled {rm:.4} (x{:.2})",
            rs / rm
        );
    }

    /// Coverage extremes (§7.8): the step clamp and the ratio-then-SRC order.
    /// Spawn keys 55 / 81 / 84 (drive the drone repitch past the guard) at
    /// 44.1 / 48 / 96 kHz — every render must be finite and non-silent, never a
    /// panic, NaN, silence, or wild pitch.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn bagpipe_sampled_coverage_extremes_are_finite() {
        for &sr in &[44100.0f32, 48000.0, 96000.0] {
            for &key in &[55u8, 81, 84] {
                let (out, _) = render(&bagpipe_song(key, 0.6, None), &bp_opts(sr, true));
                assert!(
                    out.iter().all(|x| x.is_finite()),
                    "non-finite sample at key {key}, {sr} Hz"
                );
                assert!(
                    rms(&left(&out)) > 1e-4,
                    "silent render at key {key}, {sr} Hz"
                );
            }
        }
    }

    /// Vibrato depth as max-min of a peak-located (Goertzel) pitch track —
    /// robust on the lead's bright, detuned spectrum where the zero-crossing
    /// `cycle_freq_spread` lies (repo lesson).
    fn pitch_spread(sig: &[f32], sr: f32, f_lo: f32, f_hi: f32) -> f32 {
        let w = (0.08 * sr) as usize;
        let hop = (0.02 * sr) as usize;
        let (mut lo, mut hi) = (f32::MAX, f32::MIN);
        let mut i = 0;
        while i + w <= sig.len() {
            let p = crate::testutil::peak_locate(&sig[i..i + w], sr, f_lo, f_hi);
            lo = lo.min(p);
            hi = hi.max(p);
            i += hop;
        }
        hi - lo
    }

    fn render_sawstack_with_mod(prog: u8, mod_val: Option<u8>) -> Vec<f32> {
        let mut events = vec![
            (0.0, EvKind::Prog { ch: 0, prog }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
        ];
        if let Some(val) = mod_val {
            events.push((0.0, EvKind::Cc { ch: 0, num: 1, val }));
        }
        events.extend([
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (2.4, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        left(&render(&test_song(events, 2.5), &test_opts(44100.0)).0)
    }

    fn render_lead_with_mod(mod_val: u8) -> Vec<f32> {
        let song = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 81 }),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 93,
                        val: 0,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 1,
                        val: mod_val,
                    },
                ),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 69,
                        vel: 100,
                    },
                ),
                (2.4, EvKind::NoteOff { ch: 0, key: 69 }),
            ],
            2.5,
        );
        left(&render(&song, &test_opts(44100.0)).0)
    }

    /// Oracle 5: CC1 gives a synth lead mod-wheel vibrato — the pitch wanders
    /// far more than the (detuned-stack) baseline with the wheel down.
    #[test]
    fn cc1_mod_wheel_adds_vibrato_on_lead() {
        let sr = 44100.0;
        let plain = render_lead_with_mod(0);
        let modded = render_lead_with_mod(127);
        let (a, b) = ((0.6 * sr) as usize, (2.2 * sr) as usize);
        let spread_plain = pitch_spread(&plain[a..b], sr, 400.0, 480.0);
        let spread_mod = pitch_spread(&modded[a..b], sr, 400.0, 480.0);
        assert!(
            spread_mod > 12.0,
            "lead mod vibrato too shallow: {spread_mod} Hz"
        );
        assert!(
            spread_mod > 2.0 * spread_plain,
            "plain {spread_plain} Hz vs mod {spread_mod} Hz"
        );
    }

    fn sawstack_legato_render(prog: u8, cc68: Option<u8>) -> (Vec<f32>, Stats) {
        let mut events = vec![(0.0, EvKind::Prog { ch: 0, prog })];
        if let Some(val) = cc68 {
            events.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 68,
                    val,
                },
            ));
        }
        events.extend([
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ),
            (
                0.30,
                EvKind::NoteOn {
                    ch: 0,
                    key: 64,
                    vel: 100,
                },
            ),
            (1.0, EvKind::NoteOff { ch: 0, key: 64 }),
        ]);
        let (stereo, stats) = render(&test_song(events, 1.2), &test_opts(44100.0));
        (left(&stereo), stats)
    }

    /// Req MM-REQ-KILN-00009: strings and choir opt into CC1 vibrato and CC68
    /// legato; pads stay outside the CC68 slur family.
    #[test]
    fn strings_choir_cc1_vibrato_and_cc68_legato_are_opt_in() {
        let sr = 44100.0;
        for prog in 48..=54 {
            let untouched = render_sawstack_with_mod(prog, None);
            let wheel_zero = render_sawstack_with_mod(prog, Some(0));
            assert!(
                untouched
                    .iter()
                    .zip(&wheel_zero)
                    .all(|(a, b)| a.to_bits() == b.to_bits()),
                "program {prog} CC1=0 should not change an otherwise untouched channel"
            );

            let modded = render_sawstack_with_mod(prog, Some(127));
            let (a, b) = ((0.8 * sr) as usize, (2.2 * sr) as usize);
            let spread_plain = pitch_spread(&wheel_zero[a..b], sr, 360.0, 520.0);
            let spread_mod = pitch_spread(&modded[a..b], sr, 360.0, 520.0);
            assert!(
                spread_mod > 9.0,
                "program {prog} CC1 vibrato too shallow: {spread_mod} Hz"
            );
            assert!(
                spread_mod > 1.5 * spread_plain,
                "program {prog} plain {spread_plain} Hz vs mod {spread_mod} Hz"
            );

            assert_eq!(
                sawstack_legato_render(prog, None).1.voices_spawned,
                2,
                "program {prog} without CC68 must still re-attack"
            );
            let (slurred, stats) = sawstack_legato_render(prog, Some(127));
            assert_eq!(
                stats.voices_spawned, 1,
                "program {prog} with CC68 should slur into one voice"
            );
            let f_after = crate::testutil::peak_locate(
                &slurred[(0.55 * sr) as usize..(0.9 * sr) as usize],
                sr,
                300.0,
                360.0,
            );
            let want = key_freq(64);
            assert!(
                (f_after - want).abs() < 6.0,
                "program {prog} slurred pitch {f_after}, want {want}"
            );
        }

        assert_eq!(
            sawstack_legato_render(89, Some(127)).1.voices_spawned,
            2,
            "pads must stay outside the CC68 slur family"
        );
    }

    /// Round-2 GM019: the DEFAULT bank is the drawbar church organ with the
    /// CC1 Leslie (the voice the audition preferred); the CathedralOrgan
    /// pipe model is retired. A default-bank GM19 with CC1 pinned high must
    /// show the Leslie spin-up — the AM rate climbs from the chorale brake
    /// toward Leslie-fast — not the cathedral's fixed 5.5 Hz tremulant
    /// (whose rate never moved, only its depth).
    #[test]
    fn default_gm19_cc1_ramps_the_leslie() {
        let sr = 44100.0;
        let cc = |num: u8, val: u8| EvKind::Cc { ch: 0, num, val };
        let out = render_cc1_events(vec![
            (0.0, EvKind::Prog { ch: 0, prog: 19 }),
            (0.0, cc(93, 0)),
            (0.0, cc(1, 127)),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ),
        ]);
        let early = am_rate(&out, sr, 0.15, 1.15);
        let late = am_rate(&out, sr, 2.9, 3.9);
        assert!(
            late > early + 2.5 && late >= 5.5,
            "default GM19 CC1 must Leslie-ramp: early {early:.2} Hz late {late:.2} Hz"
        );
    }

    #[test]
    fn gm22_cc1_is_harmonica_vibrato_not_leslie() {
        let sr = 44100.0;

        let gm19 = render_cc1_program(19, Some(127), true);
        let gm19_early = am_rate(&gm19, sr, 0.15, 1.15);
        let gm19_late = am_rate(&gm19, sr, 2.9, 3.9);
        assert!(
            gm19_late > gm19_early + 2.5 && gm19_late >= 5.5,
            "GM19 Leslie ramp regressed: early {gm19_early:.2} Hz late {gm19_late:.2} Hz"
        );

        let gm22_plain = render_cc1_program(22, None, true);
        let gm22_mod = render_cc1_program(22, Some(127), true);
        let (a, b) = ((0.8 * sr) as usize, (2.2 * sr) as usize);
        let plain_spread = cycle_freq_spread(&gm22_plain[a..b], sr);
        let mod_spread = cycle_freq_spread(&gm22_mod[a..b], sr);
        assert!(
            mod_spread > 8.0 && mod_spread >= 2.0 * plain_spread.max(1.0),
            "GM22 CC1 should be pitch vibrato, not inert: plain {plain_spread:.2} Hz mod {mod_spread:.2} Hz"
        );
        assert!(
            !organ_leslie_family(22, 0),
            "GM22 must stay out of the Leslie controller branch"
        );

        for program in [20u8, 21, 23] {
            assert!(
                !organ_leslie_family(program, 0),
                "GM{program} must stay out of the Leslie controller branch"
            );
            let plain = render_cc1_program(program, None, true);
            let modded = render_cc1_program(program, Some(127), true);
            assert_eq!(modded, plain, "GM{program} CC1 must be inert");
        }

        let gm19_then_22 = render_cc1_events(vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 19 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 127,
                },
            ),
            (
                0.019,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 0,
                },
            ),
            (0.02, EvKind::Prog { ch: 0, prog: 22 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        let changed_spread = cycle_freq_spread(&gm19_then_22[a..b], sr);
        assert!(
            changed_spread > 8.0,
            "program change 19->22 lost GM22 CC1 vibrato: {changed_spread:.2} Hz"
        );

        let gm22_then_19 = render_cc1_events(vec![
            (0.0, EvKind::Prog { ch: 0, prog: 22 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 127,
                },
            ),
            (
                0.019,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.02, EvKind::Prog { ch: 0, prog: 19 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        let back_early = am_rate(&gm22_then_19, sr, 0.15, 1.15);
        let back_late = am_rate(&gm22_then_19, sr, 2.9, 3.9);
        assert!(
            back_late > back_early + 2.5 && back_late >= 5.5,
            "program change 22->19 lost Leslie ramp: early {back_early:.2} late {back_late:.2}"
        );

        let held_gm19_after_prog22 = render_cc1_events(vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 19 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 127,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (
                0.59,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 0,
                },
            ),
            (0.60, EvKind::Prog { ch: 0, prog: 22 }),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        let held19_early = am_rate(&held_gm19_after_prog22, sr, 0.15, 1.15);
        let held19_late = am_rate(&held_gm19_after_prog22, sr, 2.9, 3.9);
        // GM19's held note is key 69; its 16' foundation adds a partial at
        // key_freq(69)/2 that would leak into a plain zero-crossing spread. The
        // zero-phase f0-band-limited spread rejects that sub-octave (see
        // `cycle_freq_spread_f0`) so this measures the fundamental's pitch
        // wander only — GM19's Leslie is amplitude modulation, not vibrato.
        let held19_pitch_spread =
            cycle_freq_spread_f0(&held_gm19_after_prog22[a..b], sr, key_freq(69));
        println!(
            "gm22_cc1: held19_pitch_spread {held19_pitch_spread:.2} Hz (f0-filtered), GM22 mod_spread {mod_spread:.2} Hz plain_spread {plain_spread:.2} Hz"
        );
        assert!(
            held19_late > held19_early + 2.5 && held19_late >= 5.5,
            "held GM19 lost Leslie after program change to GM22: early {held19_early:.2} late {held19_late:.2}"
        );
        assert!(
            held19_pitch_spread < 4.0,
            "held GM19 picked up GM22 pitch vibrato after program change: {held19_pitch_spread:.2} Hz"
        );

        let held_gm22_after_prog19 = render_cc1_events(vec![
            (0.0, EvKind::Prog { ch: 0, prog: 22 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 127,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (
                0.59,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.60, EvKind::Prog { ch: 0, prog: 19 }),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        let held22_pitch_spread = cycle_freq_spread(&held_gm22_after_prog19[a..b], sr);
        assert!(
            held22_pitch_spread > 8.0,
            "held GM22 lost harmonica vibrato after program change to GM19: {held22_pitch_spread:.2} Hz"
        );

        let held_plain = render_cc1_program(22, None, false);
        let held_mod = render_cc1_program(22, Some(127), false);
        let held_plain_spread = cycle_freq_spread(&held_plain[(1.0 * sr) as usize..b], sr);
        let held_mod_spread = cycle_freq_spread(&held_mod[(1.0 * sr) as usize..b], sr);
        assert!(
            held_mod_spread > held_plain_spread + 6.0,
            "held GM22 note did not pick up CC1 vibrato: plain {held_plain_spread:.2} mod {held_mod_spread:.2}"
        );

        let reset = render_cc1_events(vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 19 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 127,
                },
            ),
            (
                0.02,
                EvKind::Cc {
                    ch: 0,
                    num: 121,
                    val: 0,
                },
            ),
            (
                0.03,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 0,
                },
            ),
            (0.04, EvKind::Prog { ch: 0, prog: 22 }),
            (
                0.06,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        let reset_early = am_rate(&reset, sr, 0.15, 1.15);
        let reset_late = am_rate(&reset, sr, 2.9, 3.9);
        let reset_spread = cycle_freq_spread(&reset[a..b], sr);
        // "CC121 did not leak CC1" means the post-reset channel must behave exactly
        // like a GM22 that never received CC1 — so measure against THAT control
        // rather than an absolute AM bound. GM22 has an intrinsic delayed-onset
        // vibrato whose AM ramps 0 -> ~6 Hz across the note, so an absolute
        // "must not rise" bound scores the harmonica's own voice, not a Leslie
        // leak. It held only because a Program Change used to re-derive chorus 0.20
        // over this setup's authored CC93=0, and that wash suppressed the envelope
        // detector; effect sends now survive a Program Change per RP-015
        // (MM-BUG-KILN-00033), so the control comparison is both correct and
        // stricter — it pins reset to the un-modulated voice instead of to a range.
        let plain_early = am_rate(&gm22_plain, sr, 0.15, 1.15);
        let plain_late = am_rate(&gm22_plain, sr, 2.9, 3.9);
        assert!(
            (reset_early - plain_early).abs() <= 1.0
                && (reset_late - plain_late).abs() <= 1.0
                && (reset_spread - plain_spread).abs() <= 1.0
                && reset_spread < mod_spread * 0.6,
            "GM reset leaked CC1 into GM22: AM {reset_early:.2}->{reset_late:.2} vs \
             never-modulated control {plain_early:.2}->{plain_late:.2}; spread \
             {reset_spread:.2} vs control {plain_spread:.2} / modulated {mod_spread:.2}"
        );

        let alt_plain = render_cc1_events(vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 22 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        let alt_mod = render_cc1_events(vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 22 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 127,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (3.85, EvKind::NoteOff { ch: 0, key: 69 }),
        ]);
        assert_eq!(
            alt_mod, alt_plain,
            "alt-bank GM22 must not take default-bank CC1 vibrato"
        );
    }

    /// CC1 = 127 on the secondary organ spins the tremulant up like a Leslie: the
    /// amplitude-modulation rate must climb over ~2 s, not jump.
    #[test]
    fn cc1_leslie_spins_up_with_inertia() {
        let sr = 44100.0;
        let song = test_song(
            vec![
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: 1,
                    },
                ),
                (0.0, EvKind::Prog { ch: 0, prog: 19 }),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 93,
                        val: 0,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 1,
                        val: 127,
                    },
                ),
                (
                    0.02,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 57,
                        vel: 100,
                    },
                ),
                (3.95, EvKind::NoteOff { ch: 0, key: 57 }),
            ],
            4.0,
        );
        let mono = left(&render(&song, &test_opts(sr)).0);
        // Count tremulant cycles (rising envelope crossings) per window with the
        // shared module `am_rate` follower (4× OnePole @12 Hz, detrended @1.2 Hz).
        // The old local follower here (2× @15 Hz, detrend @1.5 Hz) was under-
        // damped: it let the GM19 16' foundation's sub-octave partial leak into
        // the amplitude envelope and mis-counted the AM rate. The steeper module
        // follower is immune to that sub-octave — the real Leslie tremolo is pure
        // amplitude modulation and is unchanged.
        // CC1 = 127 is authored at t = 0, so the rotor starts at rest
        // (LESLIE_SLOW_HZ ≈ 0.9 Hz) and slews toward 6.8 Hz with a 1.5 s time
        // constant. The windowed AM rate averages ~2 Hz early (rotor still low
        // and climbing) and ~6 Hz late (settled fast). The `late >= 5.5` floor
        // matches every sibling Leslie-ramp assertion under the module `am_rate`
        // follower (`default_gm19_cc1_ramps_the_leslie`, the GM19 clauses of
        // `gm22_cc1_is_harmonica_vibrato_not_leslie`): the steeper 4× follower
        // resolves the settled fast rate as 6 detrended crossings/s, a touch
        // below the old under-damped follower's ~7.
        let early = am_rate(&mono, sr, 0.15, 1.15);
        let late = am_rate(&mono, sr, 2.9, 3.9);
        println!("cc1_leslie_spins_up_with_inertia: early {early:.2} Hz late {late:.2} Hz");
        assert!(
            late > early + 3.0,
            "sweep too narrow: early {early} Hz, late {late} Hz"
        );
        assert!(
            early < 3.5,
            "rotor started too fast (should brake to slow): {early} Hz"
        );
        assert!(late >= 5.5, "rotor never got fast: {late} Hz");
    }

    /// Anti-masking guard for the U7b Leslie/vibrato measurement redesign: the
    /// fixed measurements must still DISCRIMINATE a real defect, not trivially
    /// pass. (a) A STALLED Leslie (GM19, no CC1 authored — the rotor never
    /// ramps) reads a flat, low `am_rate` that must FAIL cc1_leslie's own
    /// discrimination (`late > early + 3.0` ramp AND `late >= 5.5` speed):
    /// measured stalled ≈ early 2 / late 5, active ≈ early 2 / late 6, so the
    /// pair separate. (b) The f0-band-limited cycle spread must still read LARGE
    /// (~20 Hz) for GM22's real pitch vibrato — the band-limit rejects GM19's
    /// 16' sub-octave without nulling a genuine vibrato.
    #[test]
    fn leslie_and_vibrato_measures_still_catch_defects() {
        let sr = 44100.0;
        let stalled = render_cc1_events(vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 19 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.02,
                EvKind::NoteOn {
                    ch: 0,
                    key: 57,
                    vel: 100,
                },
            ),
            (3.95, EvKind::NoteOff { ch: 0, key: 57 }),
        ]);
        let early = am_rate(&stalled, sr, 0.15, 1.15);
        let late = am_rate(&stalled, sr, 2.9, 3.9);
        assert!(
            !(late > early + 3.0 && late >= 5.5),
            "stalled Leslie would falsely pass cc1_leslie — the measurement masks a stuck rotor: early {early:.2} late {late:.2}"
        );

        let (a, b) = ((0.8 * sr) as usize, (2.2 * sr) as usize);
        let gm22_mod = render_cc1_program(22, Some(127), true);
        let gm22_f0 = cycle_freq_spread_f0(&gm22_mod[a..b], sr, key_freq(69));
        assert!(
            gm22_f0 > 8.0,
            "f0-band-limit nulled GM22's real pitch vibrato: {gm22_f0:.2} Hz"
        );
    }

    fn render_pluck_with_cc74(cc74: Option<u8>) -> Vec<f32> {
        let mut events = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 25 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 94,
                    val: 0,
                },
            ),
        ];
        if let Some(val) = cc74 {
            events.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 74,
                    val,
                },
            ));
        }
        events.push((
            0.05,
            EvKind::NoteOn {
                ch: 0,
                key: 64,
                vel: 110,
            },
        ));
        events.push((1.5, EvKind::NoteOff { ch: 0, key: 64 }));
        render(&test_song(events, 1.6), &test_opts(44100.0)).0
    }

    /// CC74 = 20 must strip the top off a bright pluck; CC74 = 127 must be
    /// a true bypass — bit-identical to a render with no filter in the path.
    #[test]
    fn cc74_brightness_filter() {
        let sr = 44100.0;
        let dark = left(&render_pluck_with_cc74(Some(20)));
        let open = render_pluck_with_cc74(Some(127));
        let none = render_pluck_with_cc74(None);
        assert!(open == none, "CC74=127 is not a true bypass");
        // fraction of energy above 3 kHz — collapses with the cutoff ~535 Hz
        let hf_frac = |sig: &[f32]| {
            let mut hp = Biquad::highpass(3000.0, 0.7, sr);
            let (mut hf, mut total) = (0.0f64, 0.0f64);
            for &x in sig {
                let y = hp.process(x);
                hf += (y * y) as f64;
                total += (x * x) as f64;
            }
            hf / total.max(1e-12)
        };
        let f_dark = hf_frac(&dark);
        let f_open = hf_frac(&left(&open));
        assert!(
            f_dark < 0.25 * f_open,
            "no darkening: dark {f_dark} vs open {f_open}"
        );
    }

    /// A NoteOff under the sustain pedal keeps ringing until CC64 lifts,
    /// then releases and dies away.
    #[test]
    fn cc64_sustain_pedal_holds_notes() {
        let sr = 44100.0;
        let events = |pedal: bool| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog: 19 })];
            if pedal {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 64,
                        val: 127,
                    },
                ));
            }
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ));
            ev.push((0.5, EvKind::NoteOff { ch: 0, key: 60 }));
            if pedal {
                ev.push((
                    2.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 64,
                        val: 0,
                    },
                ));
            }
            ev
        };
        let held = left(&render(&test_song(events(true), 3.2), &test_opts(sr)).0);
        let plain = left(&render(&test_song(events(false), 3.2), &test_opts(sr)).0);
        let w = |sig: &[f32], t0: f32, t1: f32| rms(&sig[(t0 * sr) as usize..(t1 * sr) as usize]);
        // a second past the NoteOff the pedalled organ still sounds
        let held_mid = w(&held, 1.4, 1.9);
        let plain_mid = w(&plain, 1.4, 1.9);
        assert!(
            held_mid > 10.0 * plain_mid.max(1e-9),
            "pedal didn't hold: {held_mid} vs {plain_mid}"
        );
        // pedal up at 2.0 s: released, and decayed away a second later
        let after = w(&held, 3.0, 3.4);
        assert!(
            after < 0.05 * held_mid,
            "pedal-up didn't release: {after} vs {held_mid}"
        );
    }

    /// --solo of a channel with no notes renders true silence, even when
    /// other channels are full of notes.
    #[test]
    fn solo_mutes_other_channels() {
        let sr = 44100.0;
        let song = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 25 }),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 60,
                        vel: 100,
                    },
                ),
                (
                    0.06,
                    EvKind::NoteOn {
                        ch: 2,
                        key: 67,
                        vel: 100,
                    },
                ),
                (0.5, EvKind::NoteOff { ch: 0, key: 60 }),
                (0.5, EvKind::NoteOff { ch: 2, key: 67 }),
            ],
            1.0,
        );
        let mut opt = test_opts(sr);
        opt.solo = 1 << 5; // channel 5 never plays a note
        let (out, stats) = render(&song, &opt);
        assert_eq!(stats.voices_spawned, 0);
        assert!(
            out.iter().all(|&x| x == 0.0),
            "solo of an empty channel must be silent"
        );
        // soloing channel 0 keeps exactly its own notes
        opt.solo = 1 << 0;
        let (out2, stats2) = render(&song, &opt);
        assert_eq!(stats2.voices_spawned, 1);
        assert!(out2.iter().any(|&x| x != 0.0));
    }

    // ---- v0.7 authored-controller checks on real rendered audio -----------

    /// Mean fundamental over a segment: lowpass to the fundamental, then
    /// count rising zero-crossings per second.
    fn mean_freq(seg: &[f32], sr: f32) -> f32 {
        let mut lp1 = OnePole::lowpass(700.0, sr);
        let mut lp2 = OnePole::lowpass(700.0, sr);
        let f: Vec<f32> = seg.iter().map(|&x| lp2.process(lp1.process(x))).collect();
        let mut c = 0;
        for w in f.windows(2) {
            if w[0] <= 0.0 && w[1] > 0.0 {
                c += 1;
            }
        }
        c as f32 / (seg.len() as f32 / sr)
    }

    /// Fraction of a signal's energy above `hz`.
    fn energy_above(sig: &[f32], hz: f32, sr: f32) -> f64 {
        let mut hp = Biquad::highpass(hz, 0.7, sr);
        let (mut hi, mut total) = (0.0f64, 0.0f64);
        for &x in sig {
            let y = hp.process(x);
            hi += (y * y) as f64;
            total += (x * x) as f64;
        }
        hi / total.max(1e-12)
    }

    /// Fraction of a signal's energy in a band around `center`.
    fn band_frac(sig: &[f32], center: f32, q: f32, sr: f32) -> f64 {
        let mut bp = Biquad::bandpass(center, q, sr);
        let (mut band, mut total) = (0.0f64, 0.0f64);
        for &x in sig {
            let y = bp.process(x);
            band += (y * y) as f64;
            total += (x * x) as f64;
        }
        band / total.max(1e-12)
    }

    fn render_program_vowel(program: u8, cc70: u8) -> Vec<f32> {
        let song = test_song(
            vec![
                (
                    0.0,
                    EvKind::Prog {
                        ch: 0,
                        prog: program,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 93,
                        val: 0,
                    },
                ), // dry: no chorus bus
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 70,
                        val: cc70,
                    },
                ),
                (
                    0.02,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 48,
                        vel: 90,
                    },
                ),
                (2.4, EvKind::NoteOff { ch: 0, key: 48 }),
            ],
            2.5,
        );
        left(&render(&song, &test_opts(44100.0)).0)
    }

    fn render_program_late_vowel(program: u8, cc70: Option<u8>) -> Vec<f32> {
        let mut events = vec![
            (
                0.0,
                EvKind::Prog {
                    ch: 0,
                    prog: program,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.02,
                EvKind::NoteOn {
                    ch: 0,
                    key: 48,
                    vel: 90,
                },
            ),
        ];
        if let Some(val) = cc70 {
            events.push((
                0.70,
                EvKind::Cc {
                    ch: 0,
                    num: 70,
                    val,
                },
            ));
        }
        events.push((2.4, EvKind::NoteOff { ch: 0, key: 48 }));
        left(&render(&test_song(events, 2.5), &test_opts(44100.0)).0)
    }

    fn render_choir_vowel(cc70: u8) -> Vec<f32> {
        render_program_vowel(52, cc70)
    }

    /// CC70 = 84 ("ah") opens the choir's upper formants (gains 0.60/0.35)
    /// far past CC70 = 0 ("mm", gains 0.30/0.10) — a measurable spectral
    /// shift on the sustained vowel, not just a level change.
    #[test]
    fn cc70_vowel_morph_opens_formants() {
        let sr = 44100.0;
        let mm = render_choir_vowel(0);
        let ah = render_choir_vowel(84);
        // measure well after the onset morph has settled to the CC70 vowel
        let (a, b) = ((1.0 * sr) as usize, (2.0 * sr) as usize);
        let f_mm = energy_above(&mm[a..b], 1500.0, sr);
        let f_ah = energy_above(&ah[a..b], 1500.0, sr);
        assert!(
            f_ah > 1.5 * f_mm,
            "vowel didn't open: mm {f_mm} vs ah {f_ah}"
        );
    }

    /// GM 91 choir-pad is also a formant-capable SawStack once the channel
    /// authors CC70; it must not stay on the plain lowpass pad path.
    #[test]
    fn choir_pad_91_cc70_vowel_morph_opens_formants() {
        let sr = 44100.0;
        let mm = render_program_vowel(91, 0);
        let ah = render_program_vowel(91, 84);
        let (a, b) = ((1.0 * sr) as usize, (2.0 * sr) as usize);
        let f_mm = energy_above(&mm[a..b], 1500.0, sr);
        let f_ah = energy_above(&ah[a..b], 1500.0, sr);
        assert!(
            f_ah > 1.5 * f_mm,
            "choir-pad vowel didn't open: mm {f_mm} vs ah {f_ah}"
        );

        // 91 is now a choir FORMANT by default (an open "aah"), so a late CC70
        // RETARGETS the vowel rather than opening one from a plain lowpass. A
        // contrasting closed "mm" (0) must audibly darken the default open vowel,
        // proving retargeting still works — while staying bit-inert until the
        // controller is actually authored.
        let plain = render_program_late_vowel(91, None);
        let late = render_program_late_vowel(91, Some(0));
        let (pre_a, pre_b) = ((0.2 * sr) as usize, (0.55 * sr) as usize);
        assert!(
            plain[pre_a..pre_b]
                .iter()
                .zip(&late[pre_a..pre_b])
                .all(|(a, b)| a.to_bits() == b.to_bits()),
            "future CC70 changed program 91 before the controller was authored"
        );
        let (a, b) = ((1.4 * sr) as usize, (2.2 * sr) as usize);
        let f_plain = energy_above(&plain[a..b], 1500.0, sr);
        let f_late = energy_above(&late[a..b], 1500.0, sr);
        assert!(
            f_late < 0.8 * f_plain,
            "late-authored closed vowel didn't retarget the default open choir formant: plain {f_plain} vs mm {f_late}"
        );
    }

    /// RPN 0 rescales the pitch-bend range and RPN 1 fine-tune is a constant
    /// pitch multiplier — both read off a plucked A4's rendered pitch.
    #[test]
    fn rpn_bend_range_and_fine_tune() {
        let sr = 44100.0;
        let cc = |num, val| EvKind::Cc { ch: 0, num, val };
        // Read the rendered pitch with a Goertzel peak refined by a parabolic
        // interpolation in log-frequency (the engine already routes precise
        // pitch through peak_locate). mean_freq's zero-crossing count quantizes
        // to ~0.5% over this window AND mis-counts when a bright pluck's 2nd
        // harmonic leaks past its 700 Hz lowpass — too coarse for the fine-tune
        // ratio, and timbre-sensitive (it tips when the steel voice brightens).
        let render_freq = |setup: Vec<(f64, EvKind)>, win: (f32, f32), band: (f32, f32)| -> f32 {
            let mut ev = vec![
                (0.0, EvKind::Prog { ch: 0, prog: 25 }),
                (0.0, cc(93, 0)),
                (0.0, cc(94, 0)),
            ];
            ev.extend(setup);
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 110,
                },
            ));
            ev.push((2.5, EvKind::NoteOff { ch: 0, key: 69 }));
            let mono = left(&render(&test_song(ev, 2.6), &test_opts(sr)).0);
            let seg = &mono[(win.0 * sr) as usize..(win.1 * sr) as usize];
            let c = crate::testutil::peak_locate(seg, sr, band.0, band.1);
            // parabolic vertex over the geometric (×1.005) neighbours of the peak
            let lm = crate::testutil::mag_at(seg, sr, c / 1.005);
            let cm = crate::testutil::mag_at(seg, sr, c);
            let hm = crate::testutil::mag_at(seg, sr, c * 1.005);
            let denom = lm - 2.0 * cm + hm;
            let delta = if denom.abs() > 1e-9 {
                (0.5 * (lm - hm) / denom).clamp(-1.0, 1.0)
            } else {
                0.0
            };
            c * 1.005f32.powf(delta)
        };
        // same half-deflection wheel; GM default range 2 vs RPN-widened 12
        let win = (0.25, 0.7);
        let narrow = render_freq(
            vec![(0.04, EvKind::Bend { ch: 0, semis: 1.0 })],
            win,
            (430.0, 510.0),
        );
        let wide = render_freq(
            vec![
                (0.01, cc(101, 0)),
                (0.01, cc(100, 0)),
                (0.01, cc(6, 12)),
                (0.04, EvKind::Bend { ch: 0, semis: 1.0 }),
            ],
            win,
            (560.0, 690.0),
        );
        // range 2 -> +1 semitone (~466 Hz); range 12 -> +6 semitones (~622 Hz)
        assert!((narrow - 466.2).abs() < 12.0, "narrow bend: {narrow} Hz");
        assert!((wide - 622.3).abs() < 20.0, "wide bend: {wide} Hz");
        // fine tune: RPN 1, +50 cents (MSB 96, LSB 0) with no wheel
        let plain = render_freq(vec![], win, (410.0, 475.0));
        let fine = render_freq(
            vec![(0.01, cc(101, 0)), (0.01, cc(100, 1)), (0.01, cc(6, 96))],
            win,
            (410.0, 475.0),
        );
        let ratio = fine / plain;
        assert!(
            (ratio - 2f32.powf(50.0 / 1200.0)).abs() < 0.008,
            "fine-tune ratio {ratio} (plain {plain} -> fine {fine})"
        );
    }

    /// Req MM-REQ-KILN-00008: Modal and Organ voices must honour the
    /// engine's composed pitch multiplier, not swallow it in the trait default.
    #[test]
    fn modal_organ_pitch_controls_move_sustained_notes() {
        let sr = 44100.0;
        let cc = |num, val| EvKind::Cc { ch: 0, num, val };
        let cases = [(11u8, "modal vibraphone"), (19u8, "organ")];

        let render_case =
            |prog: u8, mut ev: Vec<(f64, EvKind)>, seconds: f64| -> (Vec<f32>, Stats) {
                let mut base = vec![
                    (0.0, EvKind::Prog { ch: 0, prog }),
                    (0.0, cc(91, 0)),
                    (0.0, cc(93, 0)),
                    (0.0, cc(94, 0)),
                ];
                base.append(&mut ev);
                let (stereo, stats) = render(&test_song(base, seconds), &test_opts(sr));
                (left(&stereo), stats)
            };
        let peak = |sig: &[f32], t0: f32, t1: f32, lo: f32, hi: f32| {
            crate::testutil::peak_locate(&sig[(t0 * sr) as usize..(t1 * sr) as usize], sr, lo, hi)
        };

        for (prog, name) in cases {
            let (bent, _) = render_case(
                prog,
                vec![
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 110,
                        },
                    ),
                    (1.0, EvKind::Bend { ch: 0, semis: 1.0 }),
                    (2.45, EvKind::NoteOff { ch: 0, key: 69 }),
                ],
                2.7,
            );
            let pre = peak(&bent, 0.35, 0.80, 420.0, 460.0);
            let post = peak(&bent, 1.45, 2.10, 445.0, 490.0);
            assert!((pre - 440.0).abs() < 8.0, "{name}: pre-bend pitch {pre}");
            assert!(
                (post - 466.2).abs() < 10.0,
                "{name}: pitch bend stayed inert, got {post} Hz"
            );

            let (wide, _) = render_case(
                prog,
                vec![
                    (0.01, cc(101, 0)),
                    (0.01, cc(100, 0)),
                    (0.01, cc(6, 12)),
                    (0.04, EvKind::Bend { ch: 0, semis: 1.0 }),
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 110,
                        },
                    ),
                    (1.2, EvKind::NoteOff { ch: 0, key: 69 }),
                ],
                1.5,
            );
            let wide_pitch = peak(&wide, 0.35, 0.90, 585.0, 660.0);
            assert!(
                (wide_pitch - 622.3).abs() < 18.0,
                "{name}: RPN bend range stayed inert, got {wide_pitch} Hz"
            );

            let (plain, _) = render_case(
                prog,
                vec![
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 110,
                        },
                    ),
                    (1.2, EvKind::NoteOff { ch: 0, key: 69 }),
                ],
                1.5,
            );
            let (fine, _) = render_case(
                prog,
                vec![
                    (0.01, cc(101, 0)),
                    (0.01, cc(100, 1)),
                    (0.01, cc(6, 96)),
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 110,
                        },
                    ),
                    (1.2, EvKind::NoteOff { ch: 0, key: 69 }),
                ],
                1.5,
            );
            let plain_pitch = peak(&plain, 0.35, 0.90, 420.0, 460.0);
            let fine_pitch = peak(&fine, 0.35, 0.90, 440.0, 475.0);
            let want_ratio = 2f32.powf(50.0 / 1200.0);
            let ratio = fine_pitch / plain_pitch;
            assert!(
                (ratio - want_ratio).abs() < 0.012,
                "{name}: RPN fine tune stayed inert, ratio {ratio}"
            );

            let (glide, stats) = render_case(
                prog,
                vec![
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 100,
                        },
                    ),
                    (0.45, EvKind::NoteOff { ch: 0, key: 69 }),
                    (1.0, cc(65, 127)),
                    (1.0, cc(5, 109)),
                    (
                        2.0,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 81,
                            vel: 110,
                        },
                    ),
                    (3.7, EvKind::NoteOff { ch: 0, key: 81 }),
                ],
                4.0,
            );
            assert_eq!(
                stats.voices_spawned, 2,
                "{name}: portamento should spawn a new voice"
            );
            let early = peak(&glide, 2.06, 2.18, 405.0, 485.0);
            let late = peak(&glide, 3.25, 3.60, 820.0, 940.0);
            assert!(
                early < 500.0,
                "{name}: glide did not start near old pitch: {early}"
            );
            assert!(
                (late - 880.0).abs() < 35.0,
                "{name}: glide did not settle to target: {late}"
            );

            let (pressed, _) = render_case(
                prog,
                vec![
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 100,
                        },
                    ),
                    (0.10, EvKind::Aftertouch { ch: 0, val: 127 }),
                    (2.5, EvKind::NoteOff { ch: 0, key: 69 }),
                ],
                2.7,
            );
            let (unpressed, _) = render_case(
                prog,
                vec![
                    (
                        0.05,
                        EvKind::NoteOn {
                            ch: 0,
                            key: 69,
                            vel: 100,
                        },
                    ),
                    (2.5, EvKind::NoteOff { ch: 0, key: 69 }),
                ],
                2.7,
            );
            let a = (1.25 * sr) as usize;
            let b = (2.30 * sr) as usize;
            let plain_spread = pitch_spread(&unpressed[a..b], sr, 405.0, 485.0);
            let pressed_spread = pitch_spread(&pressed[a..b], sr, 405.0, 485.0);
            assert!(
                pressed_spread > 5.0 && pressed_spread > 1.5 * plain_spread,
                "{name}: aftertouch vibrato inert, plain {plain_spread} Hz vs pressed {pressed_spread} Hz"
            );
        }
    }

    /// CC5/CC65 portamento spawns a fresh, normally-attacked voice that
    /// starts at the previous note's pitch and glides to its own target —
    /// distinct from CC68 legato, which retunes the ringing voice in place.
    #[test]
    fn portamento_glides_from_previous_pitch() {
        let sr = 44100.0;
        let cc = |num, val| EvKind::Cc { ch: 0, num, val };
        let song = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 25 }),
                (0.0, cc(93, 0)),
                (0.0, cc(94, 0)),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 69,
                        vel: 100,
                    },
                ), // A4 origin
                (0.5, EvKind::NoteOff { ch: 0, key: 69 }),
                (1.0, cc(65, 127)), // portamento on
                (1.0, cc(5, 109)),  // glide time ~0.3 s
                (
                    2.5,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 57,
                        vel: 110,
                    },
                ), // A3 target
                (4.2, EvKind::NoteOff { ch: 0, key: 57 }),
            ],
            4.5,
        );
        let (stereo, stats) = render(&song, &test_opts(sr));
        // a normal attack, not a legato retune: two distinct voices
        assert_eq!(stats.voices_spawned, 2);
        let mono = left(&stereo);
        let win = |t0: f32, t1: f32| mean_freq(&mono[(t0 * sr) as usize..(t1 * sr) as usize], sr);
        let early = win(2.55, 2.68); // just after onset: still near 440
                                     // settled target read via Goertzel peak — the K1 cubic tap keeps the
                                     // 2nd harmonic ringing, which double-counts zero crossings
        let late = crate::testutil::peak_locate(
            &mono[(3.8 * sr) as usize..(4.1 * sr) as usize],
            sr,
            195.0,
            245.0,
        );
        assert!(early > 320.0, "glide didn't start high: {early} Hz");
        assert!(
            (late - 220.0).abs() < 12.0,
            "glide didn't reach target: {late} Hz"
        );
    }

    fn render_pluck_resonance(cc71: u8) -> Vec<f32> {
        let song = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 25 }),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 93,
                        val: 0,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 94,
                        val: 0,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 74,
                        val: 41,
                    },
                ), // cutoff ~990 Hz
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 71,
                        val: cc71,
                    },
                ),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 64,
                        vel: 110,
                    },
                ), // E4, 3rd ~990
                (1.5, EvKind::NoteOff { ch: 0, key: 64 }),
            ],
            1.6,
        );
        left(&render(&song, &test_opts(44100.0)).0)
    }

    /// CC71 raises the CC74 filter's Q: with the cutoff parked on the note's
    /// 3rd harmonic, high resonance builds a peak there that low resonance
    /// does not.
    #[test]
    fn cc71_resonance_builds_a_peak() {
        let sr = 44100.0;
        let flat = render_pluck_resonance(0); // Q ~0.7
        let peaky = render_pluck_resonance(127); // Q ~8.0
        let (a, b) = ((0.3 * sr) as usize, (1.4 * sr) as usize);
        let e_flat = band_frac(&flat[a..b], 990.0, 4.0, sr);
        let e_peaky = band_frac(&peaky[a..b], 990.0, 4.0, sr);
        assert!(
            e_peaky > 1.5 * e_flat,
            "resonance built no peak: flat {e_flat} vs peaky {e_peaky}"
        );
    }

    fn render_bowed_aftertouch(at: Option<u8>) -> Vec<f32> {
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 40 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 90,
                },
            ),
        ];
        if let Some(v) = at {
            ev.push((0.1, EvKind::Aftertouch { ch: 0, val: v })); // pressure mid-note
        }
        ev.push((2.4, EvKind::NoteOff { ch: 0, key: 69 }));
        left(&render(&test_song(ev, 2.5), &test_opts(44100.0)).0)
    }

    /// Channel aftertouch swells a held bowed note: a gain bloom (~+2.5 dB)
    /// and deeper pitch vibrato than the voice's own.
    #[test]
    fn aftertouch_swells_gain_and_vibrato() {
        let sr = 44100.0;
        let plain = render_bowed_aftertouch(None);
        let pressed = render_bowed_aftertouch(Some(127));
        let (a, b) = ((1.5 * sr) as usize, (2.2 * sr) as usize);
        let ratio = rms(&pressed[a..b]) / rms(&plain[a..b]).max(1e-9);
        assert!(
            (1.15..1.6).contains(&ratio),
            "aftertouch gain bloom off: {ratio}x"
        );
        let sp_plain = cycle_freq_spread(&plain[a..b], sr);
        let sp_press = cycle_freq_spread(&pressed[a..b], sr);
        assert!(
            sp_press > sp_plain + 3.0,
            "no aftertouch vibrato: plain {sp_plain} Hz vs pressed {sp_press} Hz"
        );
    }

    fn render_poly_at_chord(poly: bool) -> Vec<f32> {
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 40 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 90,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 76,
                    vel: 90,
                },
            ),
        ];
        if poly {
            ev.push((
                0.1,
                EvKind::PolyAftertouch {
                    ch: 0,
                    key: 69,
                    val: 127,
                },
            ));
        }
        ev.push((2.4, EvKind::NoteOff { ch: 0, key: 69 }));
        ev.push((2.4, EvKind::NoteOff { ch: 0, key: 76 }));
        left(&render(&test_song(ev, 2.5), &test_opts(44100.0)).0)
    }

    /// Anti-machine-gun, END TO END through the engine (not the voice in isolation):
    /// a fast repeated ride must NOT sound like one sample retriggered. The engine's
    /// per-key round-robin counter cycles the 4 takes, and the note seed drives a per-hit
    /// micro-variation, so even the two hits that land on the SAME round-robin take (hit 0
    /// and hit 4 of a 4-take bank) are meaningfully different.
    ///
    /// The guard: the same-take pair (0, 4) must differ SUBSTANTIALLY. A machine-gun
    /// (fixed take, no micro-variation) renders them bit-identical, so their difference
    /// energy is exactly zero; with the micro-variation's ±40-cent playback-rate spread the
    /// two same-take hits phase-decorrelate, so the normalized difference energy is large.
    /// This is the oracle that fails if the round-robin is seed-modulo (can repeat a take
    /// back-to-back) or if the micro-variation is dropped.
    #[test]
    fn sampled_ride_does_not_machine_gun() {
        let sr = 44100.0;
        let opts = Options {
            samples: true,
            ..test_opts(sr)
        };
        if !crate::embedded_samples_available() {
            return; // the modeled-only build has no sampled cymbals to guard
        }
        // 5 ISOLATED ride hits on ch10, 1.6 s apart — WIDER than the ride's ~1.2 s ring, so
        // no prior hit's tail bleeds into the next attack window. That isolation is
        // load-bearing: at close spacing hit 4's window would contain hits 0-3's overlapping
        // tails and differ from hit 0 for that reason alone, passing the test without ever
        // exercising the micro-variation. With the RIDE bank's 4 round-robins the counter
        // cycles 0,1,2,3,0, so hit 0 and hit 4 both land on take rr0 — a CLEAN same-take pair.
        let gap = 1.6f64;
        let mut ev = Vec::new();
        for i in 0..5u32 {
            let t = 0.05 + gap * i as f64;
            ev.push((
                t,
                EvKind::NoteOn {
                    ch: 9,
                    key: 51,
                    vel: 100,
                },
            ));
            ev.push((t + gap - 0.1, EvKind::NoteOff { ch: 9, key: 51 }));
        }
        let mono = left(&render(&test_song(ev, 0.05 + gap * 5.0), &opts).0);

        let hit = |i: usize| -> &[f32] {
            let a = ((0.05 + gap as f32 * i as f32) * sr) as usize;
            &mono[a..a + (0.06 * sr) as usize]
        };
        let rms = |x: &[f32]| (x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32).sqrt();

        for i in 0..5 {
            assert!(
                rms(hit(i)) > 1e-3,
                "ride hit {i} is silent — sampled cymbal not routed?"
            );
        }
        // The load-bearing check: hits 0 and 4 are the SAME round-robin take, both isolated,
        // yet must differ SUBSTANTIALLY. A machine-gun (fixed take, no micro-variation)
        // renders them bit-identical -> diff/rms == 0; the ±40-cent playback-rate spread
        // phase-decorrelates them -> diff/rms is large. Verified fail-first: with the rate
        // jitter neutralized this drops to ~0.06 (gain jitter only) and the assert fails.
        let h0 = hit(0);
        let h4 = hit(4);
        let diff: Vec<f32> = h0.iter().zip(h4).map(|(a, b)| a - b).collect();
        let ratio = rms(&diff) / rms(h0).max(1e-9);
        assert!(
            ratio > 0.5,
            "same-round-robin ride hits are nearly identical (diff/rms = {ratio:.3}) — \
             MACHINE-GUN: the micro-variation is not decorrelating repeats"
        );
    }

    /// Poly (key) aftertouch is per-note: pressing A4 in an A4+E5 violin
    /// double stop deepens A4's vibrato while the chord-mate E5 stays steady.
    #[test]
    fn poly_aftertouch_targets_only_the_pressed_note() {
        let sr = 44100.0;
        let plain = render_poly_at_chord(false);
        let pressed = render_poly_at_chord(true);
        let (a, b) = ((1.5 * sr) as usize, (2.2 * sr) as usize);
        let sp_a_plain = pitch_spread(&plain[a..b], sr, 405.0, 485.0);
        let sp_a_press = pitch_spread(&pressed[a..b], sr, 405.0, 485.0);
        assert!(
            sp_a_press > 5.0 && sp_a_press > 1.5 * sp_a_plain,
            "poly AT vibrato inert on the pressed note: plain {sp_a_plain} Hz vs pressed {sp_a_press} Hz"
        );
        let sp_e_plain = pitch_spread(&plain[a..b], sr, 610.0, 710.0);
        let sp_e_press = pitch_spread(&pressed[a..b], sr, 610.0, 710.0);
        assert!(
            sp_e_press < 5.0f32.max(1.5 * sp_e_plain),
            "poly AT leaked onto the chord-mate: plain {sp_e_plain} Hz vs pressed {sp_e_press} Hz"
        );
    }

    fn render_flute_breath(cc2: Option<u8>) -> Vec<f32> {
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 73 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
        ];
        if let Some(v) = cc2 {
            ev.push((
                0.5,
                EvKind::Cc {
                    ch: 0,
                    num: 2,
                    val: v,
                },
            )); // breath backs off mid-note
        }
        ev.push((2.4, EvKind::NoteOff { ch: 0, key: 69 }));
        left(&render(&test_song(ev, 2.5), &test_opts(44100.0)).0)
    }

    /// CC2 breath is an expression-like scaler (squared taper): a flute
    /// note whose breath backs off to 40 mid-note sits far below the
    /// untouched render once the smoothing settles.
    #[test]
    fn cc2_breath_scales_wind_level() {
        let sr = 44100.0;
        let plain = render_flute_breath(None);
        let soft = render_flute_breath(Some(40));
        let (a, b) = ((1.5 * sr) as usize, (2.2 * sr) as usize);
        let ratio = rms(&soft[a..b]) / rms(&plain[a..b]).max(1e-9);
        assert!(
            (0.01..0.4).contains(&ratio),
            "CC2 breath backoff inert or overdone: {ratio}x"
        );
    }

    /// The authored-channel invariant for the new lanes: full-scale CC2
    /// (target 1.0, the never-authored default) and a poly aftertouch aimed
    /// at a key with nothing ringing are both bit-exact no-ops.
    #[test]
    fn breath_and_poly_at_neutral_until_authored() {
        let plain = render_flute_breath(None);
        let full = render_flute_breath(Some(127));
        assert_eq!(plain, full, "CC2=127 must be a bit-exact no-op");
        let base = |extra: Option<EvKind>| {
            let mut ev = vec![
                (0.0, EvKind::Prog { ch: 0, prog: 40 }),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 69,
                        vel: 90,
                    },
                ),
            ];
            if let Some(e) = extra {
                ev.push((0.1, e));
            }
            ev.push((2.0, EvKind::NoteOff { ch: 0, key: 69 }));
            left(&render(&test_song(ev, 2.2), &test_opts(44100.0)).0)
        };
        let untouched = base(None);
        let missed = base(Some(EvKind::PolyAftertouch {
            ch: 0,
            key: 60, // nothing ringing on this key
            val: 127,
        }));
        assert_eq!(
            untouched, missed,
            "poly AT on a silent key must be a bit-exact no-op"
        );
    }

    /// CC66 sostenuto holds only the notes ringing when the pedal went down:
    /// a note struck *after* pedal-down is not sustained (unlike CC64), and
    /// the captured note releases when the pedal lifts.
    #[test]
    fn cc66_sostenuto_holds_only_captured_notes() {
        let sr = 44100.0;
        let cc = |num, val| EvKind::Cc { ch: 0, num, val };
        // captured: note rings, THEN the pedal goes down over it
        let captured = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 19 }),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 60,
                        vel: 100,
                    },
                ),
                (0.3, cc(66, 127)), // pedal down captures the ringing note
                (0.5, EvKind::NoteOff { ch: 0, key: 60 }), // deferred by sostenuto
                (2.0, cc(66, 0)),   // pedal up releases it
            ],
            3.5,
        );
        // after: the pedal is already down when the note is struck
        let after = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 19 }),
                (0.05, cc(66, 127)), // pedal down over nothing
                (
                    0.3,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 60,
                        vel: 100,
                    },
                ),
                (0.5, EvKind::NoteOff { ch: 0, key: 60 }), // not captured: dies now
                (2.5, cc(66, 0)),
            ],
            3.5,
        );
        let cap = left(&render(&captured, &test_opts(sr)).0);
        let aft = left(&render(&after, &test_opts(sr)).0);
        let w = |sig: &[f32], t0: f32, t1: f32| rms(&sig[(t0 * sr) as usize..(t1 * sr) as usize]);
        let cap_mid = w(&cap, 1.4, 1.9);
        let aft_mid = w(&aft, 1.4, 1.9);
        assert!(
            cap_mid > 10.0 * aft_mid.max(1e-9),
            "sostenuto didn't select: captured {cap_mid} vs after {aft_mid}"
        );
        // pedal up at 2.5 s: the captured note lets go and decays
        let cap_after = w(&cap, 3.0, 3.4);
        assert!(
            cap_after < 0.05 * cap_mid,
            "pedal-up didn't release: {cap_after} vs {cap_mid}"
        );
    }

    fn dry_core() -> EngineCore {
        EngineCore::new(CoreOptions::from_options(
            &test_opts(44100.0),
            false,
            false,
            false,
        ))
    }

    fn unreleased_driven(core: &EngineCore, ch: u8) -> usize {
        core.active
            .iter()
            .filter(|a| a.ch == ch && needs_drive(a.program) && !a.voice.released())
            .count()
    }

    /// MM-BUG-KILN-00013: the realtime voice cap (`enforce_voice_cap`) must never
    /// touch the offline path — it has no deadline, so it keeps unbounded
    /// polyphony and its goldens stay bit-identical. Spawn far more distinct
    /// voices than `live::LIVE_MAX_VOICES` (128) through the shared event path and
    /// confirm nothing was stolen.
    #[test]
    fn offline_polyphony_is_unbounded() {
        let mut core = dry_core();
        let mut spawned = 0usize;
        'outer: for ch in 0u8..9 {
            for key in 21u8..=108 {
                core.handle_event(EvKind::NoteOn { ch, key, vel: 80 });
                spawned += 1;
                if spawned >= 300 {
                    break 'outer;
                }
            }
        }
        assert_eq!(
            core.active_voice_count(),
            spawned,
            "offline polyphony was capped: {} of {spawned} voices survived",
            core.active_voice_count()
        );
    }

    /// MM-BUG-CRUCIBLE-00026: no argument to a builder can reach the DSP out of
    /// range, so nothing downstream can size a buffer from an impossible value.
    ///
    /// Non-allocating on purpose: it asserts on the accessors, never rendering. The
    /// values that used to abort — `with_echo(100_000.0)` asked `PingPong::new` for
    /// about 64 GiB — are checked here without ever reaching an allocator.
    #[test]
    fn option_builders_clamp_every_knob_into_its_supported_range() {
        let d = Options::default();

        for rate in [0u32, 1, 7_999, u32::MAX, MAX_SAMPLE_RATE + 1] {
            let got = Options::default().with_sample_rate(rate).sample_rate();
            assert!(
                (MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&got),
                "rate {rate} survived as {got}"
            );
        }
        assert_eq!(
            Options::default().with_sample_rate(0).sample_rate(),
            MIN_SAMPLE_RATE
        );
        assert_eq!(
            Options::default().with_sample_rate(u32::MAX).sample_rate(),
            MAX_SAMPLE_RATE
        );

        // Huge finite values clamp to the ceiling; negatives clamp to the floor.
        assert_eq!(Options::default().with_echo(100_000.0).echo(), MAX_ECHO_S);
        assert_eq!(Options::default().with_echo(f32::MAX).echo(), MAX_ECHO_S);
        assert_eq!(Options::default().with_echo(-1.0).echo(), 0.0);
        assert_eq!(Options::default().with_tail(f32::MAX).tail(), MAX_TAIL_S);
        assert_eq!(Options::default().with_tail(-5.0).tail(), 0.0);
        assert_eq!(Options::default().with_reverb(9.0).reverb(), 1.0);
        assert_eq!(Options::default().with_reverb(-9.0).reverb(), 0.0);

        // Non-finite values have no sensible clamp (`f32::clamp` propagates NaN), so
        // each falls back to that knob's default.
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            assert_eq!(Options::default().with_echo(bad).echo(), d.delay_s, "{bad}");
            assert_eq!(Options::default().with_tail(bad).tail(), d.tail, "{bad}");
            assert_eq!(Options::default().with_reverb(bad).reverb(), d.wet, "{bad}");
        }
    }

    /// The clamps must be inert for every value this repo actually renders with —
    /// that is what keeps the catalog bit-identical.
    ///
    /// Checked against values taken from the shipping call sites rather than from the
    /// limits, so it cannot pass by agreeing with the constants it guards: 44.1/48/96
    /// kHz are what the CLI and render-catalog use, and 0.20-0.62 s is the range
    /// `render-catalog`'s own `default_delay_s` already clamps the echo to.
    #[test]
    fn option_builders_leave_shipping_values_untouched() {
        for rate in [44_100u32, 48_000, 88_200, 96_000, 192_000] {
            assert_eq!(
                Options::default().with_sample_rate(rate).sample_rate(),
                rate
            );
        }
        for echo in [0.0f32, 0.20, 0.375, 0.62, 1.0] {
            assert_eq!(Options::default().with_echo(echo).echo(), echo);
        }
        for tail in [0.0f32, 0.1, 0.2, 0.5, 1.0, 6.0, 8.0] {
            assert_eq!(Options::default().with_tail(tail).tail(), tail);
        }
        for wet in [0.0f32, 0.25, 0.32, 1.0] {
            assert_eq!(Options::default().with_reverb(wet).reverb(), wet);
        }
    }

    /// MM-BUG-CRUCIBLE-00025: the single-pass cap must steal exactly what the
    /// quadratic loop it replaces stole.
    ///
    /// Differential against that loop, kept here as a reference over
    /// `(key, released)` pairs, across every combination of population size, cap
    /// and release pattern below — including the boundary
    /// cases (cap 0, cap == len, nothing released, everything released) — 540 in
    /// all. The
    /// linearization is only safe because removing a released voice cannot change
    /// another voice's released state; if that ever stops holding, this fails.
    #[test]
    fn enforce_voice_cap_matches_the_quadratic_reference() {
        fn reference(mut voices: Vec<(u8, bool)>, cap: usize) -> Vec<u8> {
            while voices.len() > cap {
                let victim = voices
                    .iter()
                    .position(|(_, released)| *released)
                    .unwrap_or(0);
                voices.remove(victim);
            }
            voices.into_iter().map(|(key, _)| key).collect()
        }

        let mut checked = 0usize;
        for population in [1usize, 2, 5, 12, 20] {
            // Release patterns as bitmasks over voice index: none, all, every
            // other one from each parity, the first half, the last half, and two
            // irregular ones. Each is a distinct shape for the two-phase choice.
            for pattern in 0u8..12 {
                for cap in 0..=population {
                    let mut core = dry_core();
                    let keys: Vec<u8> = (0..population as u8).map(|i| 60 + i).collect();
                    for &key in &keys {
                        core.handle_event(EvKind::NoteOn {
                            ch: 0,
                            key,
                            vel: 100,
                        });
                    }
                    for (i, &key) in keys.iter().enumerate() {
                        let release = match pattern {
                            0 => false,
                            1 => true,
                            2 => i % 2 == 0,
                            3 => i % 2 == 1,
                            4 => i < population / 2,
                            5 => i >= population / 2,
                            6 => i % 3 == 0,
                            7 => i % 3 == 1,
                            8 => i == 0,
                            9 => i + 1 == population,
                            10 => i > 0 && i + 1 < population,
                            _ => (i * 7 + population) % 5 < 2,
                        };
                        if release {
                            core.handle_event(EvKind::NoteOff { ch: 0, key });
                        }
                    }
                    let before: Vec<(u8, bool)> = core
                        .active
                        .iter()
                        .map(|a| (a.key, a.voice.released()))
                        .collect();
                    assert_eq!(before.len(), population, "note-off removed a voice");
                    let expected = reference(before, cap);

                    core.enforce_voice_cap(cap);

                    let got: Vec<u8> = core.active.iter().map(|a| a.key).collect();
                    assert_eq!(
                        got, expected,
                        "population={population} pattern={pattern} cap={cap}"
                    );
                    checked += 1;
                }
            }
        }
        assert_eq!(checked, 540, "the configuration sweep shrank");
    }

    /// MM-BUG-KILN-00013: the cap steals the RIGHT voices — the oldest first,
    /// and any released (decaying) voice before an older un-released one — not
    /// just the right COUNT.
    #[test]
    fn enforce_voice_cap_steals_oldest_released_first() {
        let mut core = dry_core();
        for key in 60u8..66 {
            core.handle_event(EvKind::NoteOn {
                ch: 0,
                key,
                vel: 100,
            });
        }
        assert_eq!(core.active_voice_count(), 6);
        // No voice is released, so the two OLDEST (keys 60, 61) are stolen.
        core.enforce_voice_cap(4);
        let keys: Vec<u8> = core.active.iter().map(|a| a.key).collect();
        assert_eq!(
            keys,
            vec![62, 63, 64, 65],
            "oldest not stolen first: {keys:?}"
        );
        // Release the NEWEST (65); capping to 3 must steal that released voice
        // before any older un-released one.
        core.handle_event(EvKind::NoteOff { ch: 0, key: 65 });
        core.enforce_voice_cap(3);
        let keys: Vec<u8> = core.active.iter().map(|a| a.key).collect();
        assert_eq!(
            keys,
            vec![62, 63, 64],
            "released voice not stolen first: {keys:?}"
        );
    }

    #[test]
    fn driven_guitar_voice_limit_releases_oldest_across_programs_per_channel() {
        let mut core = dry_core();
        core.handle_event(EvKind::Prog { ch: 0, prog: 29 });
        for key in 40..44 {
            core.handle_event(EvKind::NoteOn {
                ch: 0,
                key,
                vel: 100,
            });
        }
        core.handle_event(EvKind::Prog { ch: 0, prog: 30 });
        for key in 44..48 {
            core.handle_event(EvKind::NoteOn {
                ch: 0,
                key,
                vel: 100,
            });
        }
        core.handle_event(EvKind::Prog { ch: 1, prog: 29 });
        core.handle_event(EvKind::NoteOn {
            ch: 1,
            key: 52,
            vel: 100,
        });
        assert_eq!(unreleased_driven(&core, 0), DRIVEN_GUITAR_VOICE_LIMIT);

        core.handle_event(EvKind::NoteOn {
            ch: 0,
            key: 60,
            vel: 100,
        });
        assert_eq!(unreleased_driven(&core, 0), DRIVEN_GUITAR_VOICE_LIMIT);
        assert_eq!(unreleased_driven(&core, 1), 1, "other channel was stolen");
        let oldest = core
            .active
            .iter()
            .find(|a| a.ch == 0 && a.key == 40)
            .unwrap();
        assert!(
            oldest.voice.released(),
            "oldest driven voice was not stolen"
        );
        let newest = core
            .active
            .iter()
            .find(|a| a.ch == 0 && a.key == 60)
            .unwrap();
        assert!(!newest.voice.released(), "newest driven voice was stolen");
    }

    #[test]
    fn driven_guitar_voice_limit_overrides_sustain_pedal() {
        let mut core = dry_core();
        core.handle_event(EvKind::Prog { ch: 0, prog: 29 });
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 64,
            val: 127,
        });
        for key in 40..48 {
            core.handle_event(EvKind::NoteOn {
                ch: 0,
                key,
                vel: 100,
            });
            core.handle_event(EvKind::NoteOff { ch: 0, key });
        }
        assert!(core.active.iter().filter(|a| a.ch == 0).all(|a| a.held));

        core.handle_event(EvKind::NoteOn {
            ch: 0,
            key: 60,
            vel: 100,
        });
        let oldest = core
            .active
            .iter()
            .find(|a| a.ch == 0 && a.key == 40)
            .unwrap();
        assert!(oldest.voice.released() && !oldest.held);

        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 64,
            val: 0,
        });
        assert_eq!(unreleased_driven(&core, 0), 1);
        assert!(core
            .active
            .iter()
            .find(|a| a.ch == 0 && a.key == 60)
            .is_some_and(|a| !a.voice.released()));
    }

    #[test]
    fn driven_guitar_voice_limit_overrides_sostenuto_capture() {
        let mut core = dry_core();
        core.handle_event(EvKind::Prog { ch: 0, prog: 30 });
        for key in 40..48 {
            core.handle_event(EvKind::NoteOn {
                ch: 0,
                key,
                vel: 100,
            });
        }
        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 66,
            val: 127,
        });
        for key in 40..48 {
            core.handle_event(EvKind::NoteOff { ch: 0, key });
        }
        assert!(core
            .active
            .iter()
            .filter(|a| a.ch == 0)
            .all(|a| a.sost && a.sost_held));

        core.handle_event(EvKind::NoteOn {
            ch: 0,
            key: 60,
            vel: 100,
        });
        let oldest = core
            .active
            .iter()
            .find(|a| a.ch == 0 && a.key == 40)
            .unwrap();
        assert!(oldest.voice.released() && !oldest.sost && !oldest.sost_held);

        core.handle_event(EvKind::Cc {
            ch: 0,
            num: 66,
            val: 0,
        });
        assert_eq!(unreleased_driven(&core, 0), 1);
        assert!(core
            .active
            .iter()
            .find(|a| a.ch == 0 && a.key == 60)
            .is_some_and(|a| !a.voice.released()));
    }

    fn render_piano_una_corda(soft: bool) -> Vec<f32> {
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 0 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
        ];
        if soft {
            ev.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 67,
                    val: 127,
                },
            )); // una corda on
        }
        ev.push((
            0.05,
            EvKind::NoteOn {
                ch: 0,
                key: 60,
                vel: 100,
            },
        ));
        ev.push((3.0, EvKind::NoteOff { ch: 0, key: 60 }));
        left(&render(&test_song(ev, 3.5), &test_opts(44100.0)).0)
    }

    #[cfg(feature = "embedded-samples")]
    fn render_held_gm0(key: u8, vel: u8, samples: bool) -> Vec<f32> {
        let song = test_song(
            vec![
                (0.0, EvKind::Prog { ch: 0, prog: 0 }),
                (0.0, EvKind::NoteOn { ch: 0, key, vel }),
                (0.75, EvKind::NoteOff { ch: 0, key }),
            ],
            0.75,
        );
        let opt = Options {
            samples,
            tail: 0.0,
            ..test_opts(44_100.0)
        };
        left(&render(&song, &opt).0)
    }

    #[cfg(feature = "embedded-samples")]
    fn held_note_rebound_db(signal: &[f32], sr: f32) -> (f32, Vec<f32>) {
        let window = (0.050 * sr) as usize;
        let levels: Vec<f32> = signal
            .chunks_exact(window)
            .map(crate::testutil::rms)
            .collect();
        let rebound_db = (3..9)
            .map(|i| {
                let later = levels[i + 1..14].iter().copied().fold(0.0f32, f32::max);
                20.0 * (later / levels[i].max(1e-12)).log10()
            })
            .fold(f32::NEG_INFINITY, f32::max);
        (rebound_db, levels)
    }

    /// The model remains monotone; the sample-only experiment instead preserves the
    /// recording's natural beating and must keep its body alive through the common
    /// first-second listening window.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn gm0_model_stays_monotone_and_sample_only_body_survives() {
        let sr = 44_100.0;
        for vel in [50u8, 100] {
            for key in 21u8..=108 {
                let model = render_held_gm0(key, vel, false);
                let (rebound_db, levels) = held_note_rebound_db(&model, sr);
                assert!(
                    rebound_db <= 1.5,
                    "GM0 model key {key} vel {vel} rebounds {rebound_db:.2} dB through \
                     the engine after its 150 ms attack budget (50 ms RMS: {levels:?})"
                );

                let sampled = render_held_gm0(key, vel, true);
                assert!(sampled.iter().all(|value| value.is_finite()));
                let late =
                    crate::testutil::rms(&sampled[(0.550 * sr) as usize..(0.700 * sr) as usize]);
                assert!(
                    late > 1e-5,
                    "GM0 sample-only key {key} vel {vel} lost its recorded body before 700 ms"
                );
            }
        }
    }

    /// The sample-only experiment must ignore model seeds. Calibrate that assertion
    /// with the samples-off control so a weak seed pair cannot make both routes look
    /// invariant.
    #[cfg(feature = "embedded-samples")]
    #[test]
    fn sample_only_gm0_is_seed_invariant_while_the_model_control_is_not() {
        let sr = 44_100.0;
        let render = |seed: u32, samples: bool| {
            let mut voice = crate::voices::make(0, 72, 100, sr, seed, samples);
            let mut out = vec![0.0; (0.700 * sr) as usize];
            voice.render(&mut out);
            out
        };
        let seeds = [0x1357_9BDFu32, 0x6A09_E667];
        let a = render(seeds[0], true);
        let a2 = render(seeds[0], true);
        let b = render(seeds[1], true);
        assert!(
            a.iter().zip(&a2).all(|(x, y)| x.to_bits() == y.to_bits()),
            "same engine seed must keep GM0 deterministic"
        );
        assert!(
            a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()),
            "sample-only GM0 still depends on the model seed"
        );

        let model_a = render(seeds[0], false);
        let model_b = render(seeds[1], false);
        let ncc = ncc_max(&model_a, &model_b, 128);
        assert!(
            ncc < 0.99,
            "seed pair does not move the model control (NCC {ncc:.6})"
        );
    }

    fn render_keyboard_una_corda(program: u8, soft: bool) -> Vec<f32> {
        let mut ev = vec![
            (
                0.0,
                EvKind::Prog {
                    ch: 0,
                    prog: program,
                },
            ),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 93,
                    val: 0,
                },
            ),
        ];
        if soft {
            ev.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 67,
                    val: 127,
                },
            ));
        }
        ev.push((
            0.05,
            EvKind::NoteOn {
                ch: 0,
                key: 60,
                vel: 100,
            },
        ));
        ev.push((1.0, EvKind::NoteOff { ch: 0, key: 60 }));
        left(&render(&test_song(ev, 1.4), &test_opts(44100.0)).0)
    }

    /// CC67 una corda softens the piano strike: the scaled velocity makes it
    /// both quieter and duller (velocity drives the model's brightness).
    #[test]
    fn cc67_una_corda_softens_piano() {
        let sr = 44100.0;
        let normal = render_piano_una_corda(false);
        let soft = render_piano_una_corda(true);
        let (a, b) = ((0.06 * sr) as usize, (0.5 * sr) as usize);
        let r_norm = rms(&normal[a..b]);
        let r_soft = rms(&soft[a..b]);
        assert!(
            r_soft < 0.9 * r_norm,
            "una corda not quieter: {r_soft} vs {r_norm}"
        );
        let hf_norm = energy_above(&normal[a..b], 3000.0, sr);
        let hf_soft = energy_above(&soft[a..b], 3000.0, sr);
        assert!(
            hf_soft < 0.85 * hf_norm,
            "una corda not duller: soft {hf_soft} vs normal {hf_norm}"
        );
    }

    #[test]
    fn keyboard_voices_una_corda_is_acoustic_piano_only() {
        let sr = 44100.0;
        let normal = render_keyboard_una_corda(0, false);
        let soft = render_keyboard_una_corda(0, true);
        let (a, b) = ((0.06 * sr) as usize, (0.5 * sr) as usize);
        assert!(
            rms(&soft[a..b]) < 0.9 * rms(&normal[a..b]),
            "GM0 una corda positive control did not soften"
        );

        for program in 4u8..=7 {
            let plain = render_keyboard_una_corda(program, false);
            let soft = render_keyboard_una_corda(program, true);
            assert!(
                plain
                    .iter()
                    .zip(&soft)
                    .all(|(x, y)| x.to_bits() == y.to_bits()),
                "GM{program} was still velocity-scaled by acoustic-piano CC67"
            );
        }
    }

    // -----------------------------------------------------------------------
    // v0.9 engine oracles: programs 55-71 (brass / reeds / orchestra hit)
    // now answer CC1 vibrato, channel aftertouch, CC11 breath, CC68 slur and
    // the section-chorus/echo sends. Every feature oracle here FAILS on
    // v0.8.1 (55-71 rendered as a decaying steel pluck with dead
    // CC1/AT/CC11-timbre and (0,0) sends); the pitch is always argmax of
    // `mag_at` (Goertzel), never zero crossings, per the lessons file.
    // -----------------------------------------------------------------------

    /// Argmax-located fundamental (Hz) spread, in cents, across `n` equal
    /// windows in [t0, t1] of `sig`; each window's pitch is `peak_locate` in
    /// [flo, fhi].
    fn pitch_spread_cents(
        sig: &[f32],
        sr: f32,
        t0: f32,
        t1: f32,
        n: usize,
        flo: f32,
        fhi: f32,
    ) -> f32 {
        let span = (t1 - t0) / n as f32;
        let (mut lo, mut hi) = (f32::MAX, f32::MIN);
        for i in 0..n {
            let a = ((t0 + i as f32 * span) * sr) as usize;
            let b = ((t0 + (i + 1) as f32 * span) * sr) as usize;
            let f = crate::testutil::peak_locate(&sig[a..b], sr, flo, fhi);
            lo = lo.min(f);
            hi = hi.max(f);
        }
        1200.0 * (hi / lo).log2()
    }

    fn render_brass_cc1(cc1: Option<u8>) -> Vec<f32> {
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 56 }),
            (
                0.0,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
        ];
        if let Some(v) = cc1 {
            ev.push((
                0.5,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: v,
                },
            ));
        }
        ev.push((3.0, EvKind::NoteOff { ch: 0, key: 69 }));
        left(&render(&test_song(ev, 3.2), &test_opts(44100.0)).0)
    }

    /// E55-1: CC1 vibrato is live on a dry brass voice (prog 56 Trumpet,
    /// fx_profile (0,0), reverb off) — the pitch wander is unambiguously the
    /// 5.3 Hz engine LFO. Needs the vibrato_family 56..=71 edit (E1).
    #[test]
    fn e55_1_cc1_vibrato_live_on_brass() {
        let sr = 44100.0;
        let plain = render_brass_cc1(None);
        let modded = render_brass_cc1(Some(127));
        let sp_plain = pitch_spread_cents(&plain, sr, 1.2, 1.92, 12, 380.0, 500.0);
        let sp_mod = pitch_spread_cents(&modded, sr, 1.2, 1.92, 12, 380.0, 500.0);
        assert!(
            sp_mod >= 20.0,
            "CC1 brass vibrato too shallow: {sp_mod:.1} cents"
        );
        assert!(
            sp_mod >= 2.0 * sp_plain,
            "CC1 vibrato not 2x the no-CC1 spread: mod {sp_mod:.1} vs plain {sp_plain:.1} cents"
        );
    }

    fn brass_slur_song(cc68: u8) -> (Vec<f32>, Stats) {
        // A4 held through, B4 struck at 0.8 s while A4 still sounds; both off
        // at 2.5 s. CC68=127 makes it one breath (slur), CC68=0 two attacks.
        let ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 57 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 68,
                    val: cc68,
                },
            ),
            (
                0.0,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (
                0.8,
                EvKind::NoteOn {
                    ch: 0,
                    key: 71,
                    vel: 100,
                },
            ),
            (2.5, EvKind::NoteOff { ch: 0, key: 69 }),
            (2.5, EvKind::NoteOff { ch: 0, key: 71 }),
        ];
        let (out, stats) = render(&test_song(ev, 2.7), &test_opts(44100.0));
        (left(&out), stats)
    }

    /// E55-3: a CC68 brass phrase (prog 57 Trombone) slurs A4->B4 as one
    /// breath — exactly ONE sustained voice (no second attack), which reaches
    /// B4 and is still ringing 0.8 s later. The same phrase with CC68=0
    /// spawns two voices: the polyphony collapse IS the "no second attack
    /// transient" proof (a second attack requires a second voice). The
    /// sustained-B4 clause is the brass-voice contract that fails on the
    /// v0.8.1 steel pluck (which has decayed to ~1% by [1.6, 2.0]). The
    /// brass onset is spectrally dark by design (the BR_BLOOM "waa"), so an
    /// HF-chiff comparison is NOT a valid discriminator here — see the report.
    /// Cross-owned with the brass voice's legato_to (already in-tree).
    #[test]
    fn e55_3_cc68_brass_slur_no_second_attack() {
        let sr = 44100.0;
        let (slur, slur_stats) = brass_slur_song(127);
        let (_, tongued_stats) = brass_slur_song(0);
        assert_eq!(
            slur_stats.max_polyphony, 1,
            "brass slur spawned a second voice"
        );
        assert_eq!(
            tongued_stats.max_polyphony, 2,
            "the tongued (CC68=0) phrase should be two voices"
        );
        let f = crate::testutil::peak_locate(
            &slur[(1.6 * sr) as usize..(2.0 * sr) as usize],
            sr,
            400.0,
            560.0,
        );
        let target = 493.883_f32; // key_freq(71) = B4
        assert!(
            (f / target - 1.0).abs() <= 0.005,
            "slur target pitch off: {f:.1} Hz vs {target:.1} Hz"
        );
        // sustained, not a decaying pluck: the slurred voice still rings 0.8 s
        // after the slur (a v0.8.1 STEEL pluck would be ~1% here).
        let sus = rms(&slur[(1.6 * sr) as usize..(2.0 * sr) as usize]);
        let early = rms(&slur[(0.3 * sr) as usize..(0.6 * sr) as usize]);
        assert!(
            sus > 0.5 * early,
            "slurred brass voice decayed like a pluck: sustain ratio {:.3}",
            sus / early
        );
    }

    fn render_chord(prog: u8) -> Vec<f32> {
        let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog })];
        for &k in &[60u8, 64, 67] {
            ev.push((
                0.02,
                EvKind::NoteOn {
                    ch: 0,
                    key: k,
                    vel: 100,
                },
            ));
            ev.push((3.0, EvKind::NoteOff { ch: 0, key: k }));
        }
        ev.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        render(&test_song(ev, 3.2), &test_opts(44100.0)).0
    }

    /// E55-4a: a brass-section chord (prog 61, chorus send 0.25) decorrelates
    /// L/R through the quadrature chorus taps; a dry double-reed chord (prog
    /// 68, sends (0,0)) at centre pan stays ~mono. Needs the fx_profile edit.
    #[test]
    fn e55_4a_section_chorus_decorrelates() {
        let sr = 44100.0;
        let (a, b) = ((0.5 * sr) as usize, (3.0 * sr) as usize);
        let sec = render_chord(61);
        let corr_sec = crate::testutil::inter_corr(&left(&sec)[a..b], &right(&sec)[a..b]);
        let dry = render_chord(68);
        let corr_dry = crate::testutil::inter_corr(&left(&dry)[a..b], &right(&dry)[a..b]);
        assert!(
            corr_sec <= 0.97,
            "section chorus did not decorrelate: corr {corr_sec:.4}"
        );
        assert!(
            corr_dry >= 0.999,
            "dry reed chord not ~mono at centre: corr {corr_dry:.4}"
        );
    }

    fn opts_delay(delay_s: f32) -> Options {
        Options {
            sr: 44100.0,
            wet: 0.0,
            tail: 1.0,
            delay_s,
            samples: false,
            solo: 0xFFFF,
        }
    }

    fn render_sax_echo(delay_s: f32) -> Vec<f32> {
        let ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 65 }),
            (
                0.0,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (0.3, EvKind::NoteOff { ch: 0, key: 69 }),
        ];
        crate::testutil::mono(&render(&test_song(ev, 1.2), &opts_delay(delay_s)).0)
    }

    /// E55-4b: a staccato sax note (prog 65, echo send 0.10) produces a real
    /// ping-pong repeat ~0.25 s later. The delayed-vs-dry difference signal
    /// isolates the echo copy from the dry tail (the corrected oracle form).
    /// Needs the fx_profile edit.
    #[test]
    fn e55_4b_sax_echo_present() {
        let sr = 44100.0;
        let wet = render_sax_echo(0.25);
        let dry = render_sax_echo(0.0);
        let (a, b) = ((0.55 * sr) as usize, (0.65 * sr) as usize);
        let d: Vec<f32> = wet[a..b]
            .iter()
            .zip(&dry[a..b])
            .map(|(x, y)| x - y)
            .collect();
        let e = rms(&d);
        const FLOOR: f32 = 1e-4; // well above render numerical noise
        assert!(
            e >= FLOOR,
            "sax echo missing in the difference window: rms {e:.3e}"
        );
    }

    /// One mallet strike, optionally AUTHORING its own CC94 echo send. Rendered
    /// twice — echo bus on, echo bus off — so the difference is the bus echo and
    /// nothing else (`wet: 0.0`, so no reverb tail contaminates the window).
    fn mallet_echo_rms(prog: u8, authored_del: Option<u8>) -> f32 {
        let sr = 44100.0;
        let render_one = |delay_s: f32| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog })];
            if let Some(val) = authored_del {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 94,
                        val,
                    },
                ));
            }
            ev.push((
                0.0,
                EvKind::NoteOn {
                    ch: 0,
                    key: 76,
                    vel: 64,
                },
            ));
            ev.push((0.1, EvKind::NoteOff { ch: 0, key: 76 }));
            crate::testutil::mono(&render(&test_song(ev, 1.6), &opts_delay(delay_s)).0)
        };
        let wet = render_one(0.30);
        let dry = render_one(0.0);
        // From just before the first repeat (0.30 s) out past the third.
        let (a, b) = ((0.28 * sr) as usize, (1.20 * sr) as usize);
        let d: Vec<f32> = wet[a..b]
            .iter()
            .zip(&dry[a..b])
            .map(|(x, y)| x - y)
            .collect();
        rms(&d)
    }

    /// The mallet bus-echo defaults (2026.07.24). GM 9 glockenspiel takes NO bus
    /// echo at all; GM 8 celesta and GM 10 music box keep a 0.06 trace, down from
    /// the shared 0.15.
    ///
    /// DERIVED, not a constant pin: the send scales a linear (LTI) bus, so the
    /// echo's energy is exactly proportional to it. Each voice is rendered a
    /// second time AUTHORING CC94 = 19 (0.1496 — the retired default), and the
    /// unauthored render is required to sit at 0.06/0.1496 of it. A silent edit
    /// of either number moves the ratio and fails here.
    #[test]
    fn mallet_bus_echo_is_off_for_glockenspiel_and_a_trace_for_its_neighbours() {
        // GM 9 feeds the bus nothing, so the two renders are bit-identical.
        let glock = mallet_echo_rms(9, None);
        assert!(
            glock < 1e-9,
            "GM 9 glockenspiel must take NO bus echo: difference rms {glock:.3e}"
        );

        const OLD_CC94: u8 = 19; // 19/127 = 0.14961 — the retired 8..=10 default
        let expect = 0.06 / (OLD_CC94 as f32 / 127.0);
        for prog in [8u8, 10u8] {
            let got = mallet_echo_rms(prog, None);
            let reference = mallet_echo_rms(prog, Some(OLD_CC94));
            assert!(
                reference > 1e-4,
                "GM {prog} reference echo too quiet to divide by: rms {reference:.3e}"
            );
            let ratio = got / reference;
            assert!(
                (ratio - expect).abs() < 0.02,
                "GM {prog} echo send is not 0.06: measured ratio {ratio:.4} vs the \
                 expected {expect:.4} against an authored CC94={OLD_CC94}"
            );
        }
    }

    fn render_brass_cc11(ramp: bool) -> Vec<f32> {
        // prog 57 Trombone, A2 (key 45) held; CC11 either ramps 30->127 or is
        // pinned at 127.
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 57 }),
            (
                0.0,
                EvKind::NoteOn {
                    ch: 0,
                    key: 45,
                    vel: 100,
                },
            ),
        ];
        if ramp {
            for i in 0..=20u32 {
                let t = 0.1 + i as f64 * 0.09;
                let v = (30 + i * (127 - 30) / 20) as u8;
                ev.push((
                    t,
                    EvKind::Cc {
                        ch: 0,
                        num: 11,
                        val: v,
                    },
                ));
            }
        } else {
            ev.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 11,
                    val: 127,
                },
            ));
        }
        ev.push((2.5, EvKind::NoteOff { ch: 0, key: 45 }));
        ev.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        left(&render(&test_song(ev, 2.7), &test_opts(44100.0)).0)
    }

    /// BR-O4: a CC11 ramp 30->127 opens the brass timbre (centroid rises) AND
    /// raises level, while a pinned CC11=127 stays timbrally flat past the
    /// bloom — the differential isolates the BR9 pressure path from the amp
    /// envelope. Needs the BR9 CC11 writer.
    #[test]
    fn br_o4_cc11_opens_brass_tone() {
        let sr = 44100.0;
        let cf = |sig: &[f32], t0: f32, t1: f32| {
            crate::testutil::centroid(&sig[(t0 * sr) as usize..(t1 * sr) as usize], sr)
        };
        let rw = |sig: &[f32], t0: f32, t1: f32| rms(&sig[(t0 * sr) as usize..(t1 * sr) as usize]);
        let ramp = render_brass_cc11(true);
        let pinned = render_brass_cc11(false);
        let ramp_c = cf(&ramp, 1.8, 2.3) / cf(&ramp, 0.3, 0.8);
        let ramp_r = rw(&ramp, 1.8, 2.3) / rw(&ramp, 0.3, 0.8).max(1e-9);
        let pin_c = cf(&pinned, 1.8, 2.3) / cf(&pinned, 0.3, 0.8);
        assert!(
            ramp_c >= 1.3,
            "CC11 ramp didn't brighten: centroid ratio {ramp_c:.2}"
        );
        assert!(
            ramp_r >= 2.0,
            "CC11 ramp didn't swell: rms ratio {ramp_r:.2}"
        );
        assert!(
            pin_c < 1.1,
            "pinned CC11 shouldn't drift timbre: centroid ratio {pin_c:.2}"
        );
    }

    /// BR-O14: bent + vibratoed brass lands on the right pitch (INT-5). Prog
    /// 56 A4, CC1=90 active, PB +2 semis: the composed bend x vibrato pitch
    /// sits at B4 +/-25 cents; a downward bend spanning NoteOff drags the
    /// release tail >= 80 cents down (set_pitch reaches released voices,
    /// INT-2).
    #[test]
    fn br_o14_bend_and_vibrato_liveness() {
        let sr = 44100.0;
        let mut ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 56 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 90,
                },
            ),
            (
                0.02,
                EvKind::NoteOn {
                    ch: 0,
                    key: 69,
                    vel: 100,
                },
            ),
            (0.5, EvKind::Bend { ch: 0, semis: 2.0 }),
        ];
        // a downward pitch fall spanning the NoteOff at 2.0 s: +2 -> -2 semis
        for i in 0..=10u32 {
            let t = 1.9 + i as f64 * 0.04;
            let semis = 2.0 - i as f32 * 0.4;
            ev.push((t, EvKind::Bend { ch: 0, semis }));
        }
        ev.push((2.0, EvKind::NoteOff { ch: 0, key: 69 }));
        ev.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        let m = left(&render(&test_song(ev, 2.6), &test_opts(sr)).0);
        let target = 493.883_f32; // B4 = A4 + 2 semitones
        let held = crate::testutil::peak_locate(
            &m[(1.0 * sr) as usize..(1.5 * sr) as usize],
            sr,
            440.0,
            540.0,
        );
        let cents = 1200.0 * (held / target).log2();
        assert!(
            cents.abs() <= 25.0,
            "bent+vibratoed brass pitch off: {held:.1} Hz ({cents:.1} cents from B4)"
        );
        let tail = crate::testutil::peak_locate(
            &m[(2.02 * sr) as usize..(2.16 * sr) as usize],
            sr,
            340.0,
            520.0,
        );
        let tail_cents = 1200.0 * (tail / target).log2();
        assert!(
            tail_cents <= -80.0,
            "release tail didn't track the fall: {tail:.1} Hz ({tail_cents:.1} cents from B4)"
        );
    }

    /// RD-O10: reed CC1/CC68 completeness (INT-5/INT-2), engine-level.
    /// (a) A CC68 tenor-sax phrase (prog 66) slurs E4->G4 as ONE voice; the
    /// same phrase with CC68=0 spawns two. (b) A held clarinet (prog 71) with
    /// CC1=96 and PB +2 semis lands within +/-3% of the bent target under the
    /// active modulator. Needs the vibrato_family 64..=71 edit.
    #[test]
    fn rd_o10_reed_slur_and_pitch_liveness() {
        let sr = 44100.0;
        let slur_song = |cc68: u8| {
            let mut ev = vec![
                (0.0, EvKind::Prog { ch: 0, prog: 66 }),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 68,
                        val: cc68,
                    },
                ),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 64,
                        vel: 100,
                    },
                ),
                (
                    0.4,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 67,
                        vel: 100,
                    },
                ),
                (1.5, EvKind::NoteOff { ch: 0, key: 64 }),
                (1.5, EvKind::NoteOff { ch: 0, key: 67 }),
            ];
            ev.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
            render(&test_song(ev, 1.7), &test_opts(sr))
        };
        let (slur_out, slur_stats) = slur_song(127);
        let (_, tongued_stats) = slur_song(0);
        assert_eq!(
            slur_stats.max_polyphony, 1,
            "reed slur spawned a second voice"
        );
        assert_eq!(
            tongued_stats.max_polyphony, 2,
            "tongued reed should be 2 voices"
        );
        let m = left(&slur_out);
        let g4 = 391.995_f32; // key_freq(67)
        let f = crate::testutil::peak_locate(
            &m[(0.8 * sr) as usize..(1.3 * sr) as usize],
            sr,
            320.0,
            460.0,
        );
        // ±1%: G4 sits mid-grid on peak_locate's 0.5% argmax grid (bracketing
        // points 392.61 / 394.57 Hz), so ±0.5% is tighter than the measurement
        // resolution; ±1% still rejects the E4 origin (16% away). See report.
        assert!(
            (f / g4 - 1.0).abs() <= 0.01,
            "reed slur target off: {f:.1} Hz vs {g4:.1} Hz"
        );

        // (b) CC1 + PB liveness on a held clarinet note (key 62 = D4)
        let ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 71 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 96,
                },
            ),
            (
                0.02,
                EvKind::NoteOn {
                    ch: 0,
                    key: 62,
                    vel: 100,
                },
            ),
            (0.5, EvKind::Bend { ch: 0, semis: 2.0 }),
            (2.0, EvKind::NoteOff { ch: 0, key: 62 }),
        ];
        let m2 = left(&render(&test_song(ev, 2.2), &test_opts(sr)).0);
        let target = 329.628_f32; // key_freq(62) * 2^(2/12)
        let f2 = crate::testutil::peak_locate(
            &m2[(1.0 * sr) as usize..(1.5 * sr) as usize],
            sr,
            280.0,
            380.0,
        );
        assert!(
            (f2 / target - 1.0).abs() <= 0.03,
            "clarinet bent+vibrato pitch off: {f2:.1} Hz vs {target:.1} Hz"
        );
    }

    // --- Alt bank (GM Bank-Select alternate orchestral voicings) ---

    fn bank_song(cc0: Option<u8>, prog: u8) -> Vec<(f64, EvKind)> {
        let mut ev = Vec::new();
        if let Some(v) = cc0 {
            ev.push((
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: v,
                },
            ));
        }
        ev.push((0.0, EvKind::Prog { ch: 0, prog }));
        ev.push((
            0.05,
            EvKind::NoteOn {
                ch: 0,
                key: 60,
                vel: 100,
            },
        ));
        ev.push((1.5, EvKind::NoteOff { ch: 0, key: 60 }));
        ev
    }

    /// AC2 + AC4: `CC0 != 0` routes each in-scope program to the alt voicing,
    /// which is a genuinely different render from the default (proving the bank
    /// switch reaches a distinct voice — bowed cello 42, strings 48, choir 52).
    /// Per-voice character is proven by the `altbank` voice oracles; here we
    /// assert the routing produces a real, non-trivial difference. (GM19 left
    /// this list in round 2: both banks are the same drawbar voice now, pinned
    /// bit-identical by default_gm19_is_the_legacy_drawbar_voice.)
    #[test]
    fn alt_bank_selects_distinct_voices() {
        let sr = 44100.0;
        for prog in [42u8, 48, 52] {
            let alt = left(&render(&test_song(bank_song(Some(1), prog), 2.0), &test_opts(sr)).0);
            let def = left(&render(&test_song(bank_song(None, prog), 2.0), &test_opts(sr)).0);
            assert_eq!(alt.len(), def.len());
            // Not byte-identical → the bank routed to a different factory.
            assert_ne!(
                alt, def,
                "prog {prog}: alt bank must produce a distinct render"
            );
            // And a non-trivial magnitude (a real voice swap, not a rounding blip).
            let diff: Vec<f32> = alt.iter().zip(&def).map(|(a, b)| a - b).collect();
            let ratio = rms(&diff) / rms(&def).max(1e-9);
            assert!(
                ratio > 0.01,
                "prog {prog}: alt render too close to default (diff/base = {ratio:.4})"
            );
        }
    }

    /// AC5: the bank latches (CC121 reset-all-controllers does NOT clear it),
    /// `CC0 == 0` returns to the default bank byte-identically, and an alt-bank
    /// channel delegates a non-orchestral program to the default voice.
    #[test]
    fn alt_bank_latch_reset_and_delegation() {
        let sr = 44100.0;
        let def = left(&render(&test_song(bank_song(None, 48), 2.0), &test_opts(sr)).0);
        let alt = left(&render(&test_song(bank_song(Some(1), 48), 2.0), &test_opts(sr)).0);

        // CC0=1 then CC121 → still alt (bank is not a performance controller).
        let rac = vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (0.0, EvKind::Prog { ch: 0, prog: 48 }),
            (
                0.02,
                EvKind::Cc {
                    ch: 0,
                    num: 121,
                    val: 0,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ),
            (1.5, EvKind::NoteOff { ch: 0, key: 60 }),
        ];
        let after_rac = left(&render(&test_song(rac, 2.0), &test_opts(sr)).0);
        assert_eq!(after_rac, alt, "CC121 must not clear the bank");

        // CC0=1 then CC0=0 → back to the default bank.
        let reset = vec![
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 1,
                },
            ),
            (
                0.02,
                EvKind::Cc {
                    ch: 0,
                    num: 0,
                    val: 0,
                },
            ),
            (0.03, EvKind::Prog { ch: 0, prog: 48 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ),
            (1.5, EvKind::NoteOff { ch: 0, key: 60 }),
        ];
        let after_reset = left(&render(&test_song(reset, 2.0), &test_opts(sr)).0);
        assert_eq!(after_reset, def, "CC0=0 must return to the default bank");

        // Alt bank + a program with no alternate definition delegates to default.
        // Piano 0 is no longer such a control: CC0=1 selects its VSCO upright bank
        // (the recording that was GM0's own default until the 2026.07.26 renumber).
        let alt_flute = left(&render(&test_song(bank_song(Some(1), 73), 2.0), &test_opts(sr)).0);
        let def_flute = left(&render(&test_song(bank_song(None, 73), 2.0), &test_opts(sr)).0);
        assert_eq!(
            alt_flute, def_flute,
            "alt bank must delegate non-orchestral programs to the default voice"
        );
    }

    /// Unit 1 (XG CC32 infra): a bank-select LSB naming no *defined* XG
    /// variation falls back to the base GM voice **byte-identically** — the
    /// dispatch reuses the same `seed`, so an undefined `(program, bank_lsb)`
    /// is bit-for-bit the pre-change render. LSB 113 is undefined for every
    /// program (the reference file's 112/113/115/117 all sit past the max
    /// defined XG bank, 101), so this invariant holds even as defined
    /// variations get added in later units.
    #[test]
    fn cc32_undefined_bank_falls_back_byte_identical() {
        let sr = 44100.0;
        let song = |lsb: Option<u8>, prog: u8| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog })];
            if let Some(v) = lsb {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 32,
                        val: v,
                    },
                ));
            }
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ));
            ev.push((1.0, EvKind::NoteOff { ch: 0, key: 60 }));
            ev
        };
        for prog in [24u8, 0, 48, 30] {
            let base = left(&render(&test_song(song(None, prog), 1.5), &test_opts(sr)).0);
            let undef = left(&render(&test_song(song(Some(113), prog), 1.5), &test_opts(sr)).0);
            assert_eq!(
                base, undef,
                "prog {prog}: an undefined CC32 bank must fall back to base GM byte-identically"
            );
        }
    }

    /// Unit 10 (integration): a *defined* CC32 variation routes through the full
    /// engine path — the CC32 handler sets `bank_lsb`, and note-on dispatches
    /// `make_variation` — producing a render that genuinely differs from the
    /// base program. Covers each of the eight defined `(program, LSB)` pairs
    /// end-to-end (the per-voice character is pinned by the voices oracles; here
    /// we prove the wiring reaches a distinct voice, not just the fallback).
    #[test]
    fn cc32_defined_bank_selects_the_variation() {
        let sr = 44100.0;
        // (program, bank LSB, a key in a sensible range for that program)
        let variations: &[(u8, u8, u8)] = &[
            (24, 96, 60),  // Ukulele
            (25, 96, 60),  // Mandolin (owner-recorded LA onset over the double-course model)
            (105, 98, 60), // Oud
            (116, 96, 45), // Gran Cassa
            (48, 3, 60),   // Slow Strings
            (30, 41, 45),  // Feedback Gtr 2
            (99, 19, 60),  // Hollow Release
            (33, 45, 40),  // Fingered Bass 2
            (50, 65, 60),  // Str5
        ];
        let song = |lsb: Option<u8>, prog: u8, key: u8| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 0, prog })];
            if let Some(v) = lsb {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 32,
                        val: v,
                    },
                ));
            }
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key,
                    vel: 100,
                },
            ));
            ev.push((1.6, EvKind::NoteOff { ch: 0, key }));
            ev
        };
        for &(prog, lsb, key) in variations {
            let base = left(&render(&test_song(song(None, prog, key), 2.0), &test_opts(sr)).0);
            let var = left(&render(&test_song(song(Some(lsb), prog, key), 2.0), &test_opts(sr)).0);
            assert_eq!(base.len(), var.len());
            assert_ne!(
                base, var,
                "prog {prog} + CC32={lsb}: the variation must render differently from the base"
            );
            // And a non-trivial magnitude — a real voice swap, not a rounding blip.
            let diff: Vec<f32> = base.iter().zip(&var).map(|(a, b)| a - b).collect();
            let ratio = rms(&diff) / rms(&base).max(1e-9);
            assert!(
                ratio > 0.01,
                "prog {prog} + CC32={lsb}: variation render too close to base (diff/base = {ratio:.4})"
            );
        }
    }

    /// The mandolin's full engine chain — CC32=96 dispatch → `make_variation` →
    /// `mandolin_bank` → repitch → mix — must render an AUDIBLE voice at the
    /// PLAYED pitch, and its MODEL must not be octave-broken. A4 (key 69) is an
    /// in-tune open-string zone, so it plays with essentially no repitch; holds in
    /// `--no-samples` builds too, since the pure `MANDOLIN` model renders the same
    /// fundamental.
    ///
    /// Scope note — this is deliberately NOT the guard for a sample-root octave
    /// error. That failure is owned by `sampler::tests::mandolin_zone_roots_match_
    /// the_fretboard`, which checks the zone-table floats directly. It has to be:
    /// a root stored an octave high drives `LaVoice`'s repitch `step` to ~0.5,
    /// which lands on the edge of the `0.5..=2.05` window and often falls back to
    /// the bare model — and the model plays the correct pitch, masking the error
    /// at the render level (the classic "a fallback hides the thing you measure"
    /// trap). So this test's f0/2 check catches a MODEL octave error (the fallback
    /// is octave-wrong too), not a table one; the table one is caught upstream.
    #[test]
    fn mandolin_variation_renders_at_the_played_pitch() {
        let sr = 44100.0;
        let key = 69u8; // A4 = 440 Hz, an in-tune open-string zone
        let f0 = key_freq(key);
        let ev = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 25 }),
            (
                0.0,
                EvKind::Cc {
                    ch: 0,
                    num: 32,
                    val: 96,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key,
                    vel: 100,
                },
            ),
            (1.6, EvKind::NoteOff { ch: 0, key }),
        ];
        let out = left(&render(&test_song(ev, 2.0), &test_opts(sr)).0);
        // After the onset settles, before the note-off release.
        let seg = &out[(0.15 * sr) as usize..(1.2 * sr) as usize];
        let fund = crate::testutil::mag_at(seg, sr, f0);
        let oct_down = crate::testutil::mag_at(seg, sr, f0 * 0.5);
        assert!(
            fund > 1e-3,
            "mandolin A4 is silent or not at pitch (fundamental {fund:.5})"
        );
        assert!(
            fund > 4.0 * oct_down,
            "mandolin A4 has too much energy an octave down (fund {fund:.5} vs \
             f0/2 {oct_down:.5}) — the MANDOLIN model is octave-broken"
        );
    }

    /// Unit 1 (CC84 portamento control): a `CC84=src` before a NoteOn makes
    /// that note glide up from `key_freq(src)` even with NO CC65 porta-on,
    /// honoring the CC5 glide time — and the pending source is consumed once,
    /// so a following NoteOn with no CC84 starts at its own pitch. Detected by
    /// source-pitch energy (`mag_at`), which is phase-insensitive.
    #[test]
    fn cc84_glides_from_source_without_porta_on_and_is_consumed_once() {
        let sr = 44100.0;
        let src = 48u8; // portamento source key — an octave below the played key
        let key = 60u8;
        let f_src = key_freq(src);
        let events = |cc84: bool| {
            let mut ev = vec![
                // square lead: fast attack, clean fundamental, no sub-octave
                (0.0, EvKind::Prog { ch: 0, prog: 80 }),
                // long glide time so the scoop spans the onset window
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 5,
                        val: 110,
                    },
                ),
            ];
            if cc84 {
                ev.push((
                    0.01,
                    EvKind::Cc {
                        ch: 0,
                        num: 84,
                        val: src,
                    },
                ));
            }
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key,
                    vel: 100,
                },
            ));
            ev.push((0.90, EvKind::NoteOff { ch: 0, key }));
            // A second note with no CC84 must not glide (source already consumed).
            ev.push((
                1.30,
                EvKind::NoteOn {
                    ch: 0,
                    key,
                    vel: 100,
                },
            ));
            ev.push((2.10, EvKind::NoteOff { ch: 0, key }));
            ev
        };
        let render_mono = |cc84: bool| {
            crate::testutil::mono(&render(&test_song(events(cc84), 2.4), &test_opts(sr)).0)
        };
        let with_cc84 = render_mono(true);
        let baseline = render_mono(false);
        let e_src = |buf: &[f32], t0: f32, t1: f32| {
            crate::testutil::mag_at(&buf[(t0 * sr) as usize..(t1 * sr) as usize], sr, f_src)
        };

        // Note 1 onset: the CC84 render scoops up from key 48 → real energy at
        // the source pitch; the no-CC84 baseline sits at key 60 with none.
        let n1_cc84 = e_src(&with_cc84, 0.05, 0.12);
        let n1_base = e_src(&baseline, 0.05, 0.12);
        // Note 2 onset (CC84 render): no CC84 was sent → no source-pitch scoop.
        let n2_cc84 = e_src(&with_cc84, 1.30, 1.37);
        assert!(
            n1_cc84 > 1e-3,
            "note-1 onset should carry real energy: {n1_cc84:.6}"
        );
        assert!(
            n1_cc84 > 5.0 * n1_base,
            "CC84 must glide from key {src}: onset source-pitch energy cc84 {n1_cc84:.5} vs no-CC84 base {n1_base:.5}"
        );
        assert!(
            n1_cc84 > 5.0 * n2_cc84,
            "CC84 must be consumed once: note-1 source-pitch energy {n1_cc84:.5} vs note-2 {n2_cc84:.5}"
        );
    }

    // ---- XG effect SysEx (reverb/chorus type, variation Amp-Sim insertion) ----

    /// Unit 2 (byte-identity spine): the XG effect block is inert until a real
    /// effect is recognized. A song carrying XG System On + a non-Hall reverb
    /// type + a non-Chorus chorus type + an Amp-Sim variation routed to SYSTEM
    /// (never an insert) renders BYTE-IDENTICALLY to the same song with no XG
    /// SysEx — even with the hall bus active (wet > 0). The per-unit face of
    /// the album-wide render-diff = 0 hard gate; stays valid across units 3-5
    /// because none of these words resolve to a recognized effect.
    #[test]
    fn xg_inert_effect_params_are_byte_identical() {
        let sr = 44100.0;
        let opts = Options {
            sr,
            wet: 0.3,
            tail: 0.5,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
        };
        let phrase: Vec<(f64, EvKind)> = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 29 }),
            (0.0, EvKind::Prog { ch: 1, prog: 48 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 45,
                    vel: 100,
                },
            ),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 1,
                    key: 60,
                    vel: 90,
                },
            ),
            (0.9, EvKind::NoteOff { ch: 0, key: 45 }),
            (0.9, EvKind::NoteOff { ch: 1, key: 60 }),
        ];
        let mut with_inert_xg: Vec<(f64, EvKind)> = vec![
            (0.0, EvKind::XgReset),
            // reverb type = a non-Hall1 word -> recognizer no-op
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x00,
                    data: [0x02, 0x00],
                    len: 2,
                },
            ),
            // chorus type = a non-Chorus1 word -> no-op
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x20,
                    data: [0x42, 0x00],
                    len: 2,
                },
            ),
            // Amp-Sim variation type, real Drive/Dry-Wet, but SYSTEM connection
            // and a real part -> resolves to NO insert (system bus is a non-goal).
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x40,
                    data: [0x4B, 0x11],
                    len: 2,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x42,
                    data: [0x00, 0x18],
                    len: 2,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x54,
                    data: [0x00, 0x64],
                    len: 2,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x5A,
                    data: [0x01, 0x00],
                    len: 1,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x5B,
                    data: [0x0E, 0x00],
                    len: 1,
                },
            ),
        ];
        with_inert_xg.extend(phrase.clone());
        let base = render(&test_song(phrase, 1.6), &opts).0;
        let xg = render(&test_song(with_inert_xg, 1.6), &opts).0;
        assert_eq!(
            base, xg,
            "inert XG effect params must not perturb the render (byte-identity spine)"
        );
    }

    /// Unit 2 (state wiring): the reference file's variation block decodes into
    /// the `XgEffects` state exactly — Amp Simulator type, Drive 24, Dry/Wet
    /// 100, INSERTION connection, Part 15 (0-based 14) — and a following XG
    /// System On resets every field to its inert default.
    #[test]
    fn xg_effect_params_update_state() {
        let sr = 44100.0;
        let mut core = EngineCore::new(CoreOptions {
            sr,
            wet: 0.0,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        });
        for kind in [
            EvKind::XgEffectParam {
                addr_lo: 0x40,
                data: [0x4B, 0x11],
                len: 2,
            },
            EvKind::XgEffectParam {
                addr_lo: 0x42,
                data: [0x00, 0x18],
                len: 2,
            },
            EvKind::XgEffectParam {
                addr_lo: 0x54,
                data: [0x00, 0x64],
                len: 2,
            },
            EvKind::XgEffectParam {
                addr_lo: 0x5A,
                data: [0x00, 0x00],
                len: 1,
            },
            EvKind::XgEffectParam {
                addr_lo: 0x5B,
                data: [0x0E, 0x00],
                len: 1,
            },
        ] {
            core.handle_event(kind);
        }
        assert_eq!(core.xg.var_type_msb, 0x4B, "Amp Simulator type MSB");
        assert_eq!(core.xg.var_drive, 24, "Drive 24");
        assert_eq!(core.xg.var_drywet, 100, "Dry/Wet 100");
        assert_eq!(core.xg.var_connection, 0, "INSERTION");
        assert_eq!(core.xg.var_part, 14, "Part 15 = 0-based channel 14");

        core.handle_event(EvKind::XgReset);
        assert_eq!(core.xg.var_part, 127, "System On resets Part to OFF");
        assert_eq!(core.xg.var_drive, 0, "System On resets Drive");
    }

    /// Unit 3 (Hall 1 recognizer targets ONLY the hall): the Hall 1 type word
    /// re-tunes the shared hall's combs to HALL1_ROOM and leaves the drum room
    /// untouched (the cathedral is a different type and has no reconfigure path
    /// at all). A following XG System On restores the hall to its default.
    #[test]
    fn xg_hall1_reconfigures_only_the_hall() {
        let sr = 44100.0;
        let mut core = EngineCore::new(CoreOptions {
            sr,
            wet: 0.3,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
            gtr_symp_on: true,
            drum_room_on: true,
            sitar_symp_on: true,
        });
        let hall_before = core.reverb.debug_comb_feedback();
        let drum_before = core.drum_room.debug_comb_feedback();
        core.handle_event(EvKind::XgEffectParam {
            addr_lo: 0x00,
            data: HALL1_TYPE,
            len: 2,
        });
        assert_eq!(
            core.reverb.debug_comb_feedback(),
            HALL1_ROOM,
            "hall re-tuned to Hall 1"
        );
        assert_ne!(
            core.reverb.debug_comb_feedback(),
            hall_before,
            "hall feedback actually changed"
        );
        assert_eq!(
            core.drum_room.debug_comb_feedback(),
            drum_before,
            "drum room must be untouched"
        );
        core.handle_event(EvKind::XgReset);
        assert_eq!(
            core.reverb.debug_comb_feedback(),
            DEFAULT_HALL_ROOM,
            "System On restores the hall default"
        );
    }

    /// Unit 3 (Hall 1 changes the render; other reverb types are inert): with
    /// the hall bus active, a Hall 1 type event changes the rendered tail vs a
    /// no-XG render, while an unrecognized reverb type leaves it byte-identical.
    #[test]
    fn xg_hall1_changes_render_other_types_inert() {
        let sr = 44100.0;
        let opts = Options {
            sr,
            wet: 0.4,
            tail: 0.8,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
        };
        let song = |reverb_type: Option<[u8; 2]>| {
            let mut ev: Vec<(f64, EvKind)> = Vec::new();
            if let Some(t) = reverb_type {
                ev.push((
                    0.0,
                    EvKind::XgEffectParam {
                        addr_lo: 0x00,
                        data: t,
                        len: 2,
                    },
                ));
            }
            // strings: a sustained tone with a real tail into the hall
            ev.push((0.0, EvKind::Prog { ch: 0, prog: 48 }));
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ));
            ev.push((0.5, EvKind::NoteOff { ch: 0, key: 60 }));
            test_song(ev, 1.2)
        };
        let base = render(&song(None), &opts).0;
        let hall1 = render(&song(Some(HALL1_TYPE)), &opts).0;
        let other = render(&song(Some([0x02, 0x00])), &opts).0;
        assert_ne!(base, hall1, "Hall 1 must change the hall render");
        assert_eq!(base, other, "an unrecognized reverb type must be inert");
    }

    /// Unit 4 (Chorus::reconfigure mechanism): reconfiguring the LFO changes the
    /// processed output; reconfiguring to the engine defaults is an exact no-op
    /// (this also PROVES DEFAULT_CHORUS_* mirror Chorus::new — the byte-identity
    /// spine for System On); and rate alone is wired (Chorus 1 rate over the
    /// default base/depth still changes the output).
    #[test]
    fn chorus_reconfigure_changes_output_and_defaults_are_noop() {
        let sr = 44100.0;
        let n = (0.5 * sr) as usize;
        let send: Vec<f32> = (0..n)
            .map(|i| (TAU * 220.0 * i as f32 / sr).sin())
            .collect();
        let run = |reconfig: Option<(f32, f32, f32)>| {
            let mut c = Chorus::new(sr);
            if let Some((r, b, d)) = reconfig {
                c.reconfigure(r, b, d);
            }
            let mut l = vec![0.0; n];
            let mut r = vec![0.0; n];
            c.process(&send, &mut l, &mut r);
            (l, r)
        };
        let default = run(None);
        let same = run(Some((
            DEFAULT_CHORUS_RATE,
            DEFAULT_CHORUS_BASE_S,
            DEFAULT_CHORUS_DEPTH_S,
        )));
        let chorus1 = run(Some((CHORUS1_RATE, CHORUS1_BASE_S, CHORUS1_DEPTH_S)));
        let rate_only = run(Some((
            CHORUS1_RATE,
            DEFAULT_CHORUS_BASE_S,
            DEFAULT_CHORUS_DEPTH_S,
        )));
        assert_eq!(default, same, "reconfigure to the defaults must be a no-op");
        assert_ne!(default, chorus1, "Chorus 1 params must change the output");
        assert_ne!(default, rate_only, "the LFO rate must be wired");
    }

    /// Unit 4 (Chorus 1 recognizer): with a pad on the chorus bus, a Chorus 1
    /// type event changes the render vs no-XG; an unrecognized chorus type is
    /// inert.
    #[test]
    fn xg_chorus1_changes_render_other_types_inert() {
        let sr = 44100.0;
        let opts = Options {
            sr,
            wet: 0.0,
            tail: 0.5,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
        };
        let song = |chorus_type: Option<[u8; 2]>| {
            let mut ev: Vec<(f64, EvKind)> = Vec::new();
            if let Some(t) = chorus_type {
                ev.push((
                    0.0,
                    EvKind::XgEffectParam {
                        addr_lo: 0x20,
                        data: t,
                        len: 2,
                    },
                ));
            }
            // pad (fx_profile 88..=95 -> chorus_send 0.45)
            ev.push((0.0, EvKind::Prog { ch: 0, prog: 90 }));
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ));
            ev.push((0.6, EvKind::NoteOff { ch: 0, key: 60 }));
            test_song(ev, 1.2)
        };
        let base = render(&song(None), &opts).0;
        let chorus1 = render(&song(Some(CHORUS1_TYPE)), &opts).0;
        let other = render(&song(Some([0x00, 0x00])), &opts).0;
        assert_ne!(base, chorus1, "Chorus 1 must change the chorus render");
        assert_eq!(base, other, "an unrecognized chorus type must be inert");
    }

    /// The XG Effect1 messages that install an Amp-Simulator variation on
    /// `part`, with the given Drive / Dry-Wet / connection.
    fn xg_amp_sim_block(part: u8, drive: u8, drywet: u8, connection: u8) -> Vec<(f64, EvKind)> {
        vec![
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x40,
                    data: [AMP_SIM_TYPE_MSB, 0x00],
                    len: 2,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x42,
                    data: [0x00, drive],
                    len: 2,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x54,
                    data: [0x00, drywet],
                    len: 2,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x5A,
                    data: [connection, 0x00],
                    len: 1,
                },
            ),
            (
                0.0,
                EvKind::XgEffectParam {
                    addr_lo: 0x5B,
                    data: [part, 0x00],
                    len: 1,
                },
            ),
        ]
    }

    /// Unit 5 (routing): an Amp-Sim INSERTION on part 14 changes that channel's
    /// render, leaves a non-target channel byte-identical, and installs nothing
    /// when connection == SYSTEM or the part is OFF (127).
    #[test]
    fn xg_variation_routes_to_the_target_channel_only() {
        let sr = 44100.0;
        let opts = |solo: u16| Options {
            sr,
            wet: 0.0,
            tail: 0.5,
            delay_s: 0.0,
            samples: false,
            solo,
        };
        let song = |xg: Vec<(f64, EvKind)>| {
            let mut ev = vec![
                (0.0, EvKind::Prog { ch: 14, prog: 29 }),
                (0.0, EvKind::Prog { ch: 0, prog: 29 }),
            ];
            ev.extend(xg);
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 14,
                    key: 45,
                    vel: 100,
                },
            ));
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 52,
                    vel: 100,
                },
            ));
            ev.push((0.9, EvKind::NoteOff { ch: 14, key: 45 }));
            ev.push((0.9, EvKind::NoteOff { ch: 0, key: 52 }));
            test_song(ev, 1.4)
        };
        let insert = xg_amp_sim_block(14, 24, 100, XG_VAR_INSERTION);
        let all = 0xFFFF;
        let ch0_only = 1u16 << 0;

        let base = render(&song(vec![]), &opts(all)).0;
        let with_var = render(&song(insert.clone()), &opts(all)).0;
        assert_ne!(
            base, with_var,
            "the Amp-Sim insert must change the target render"
        );

        let ch0_base = render(&song(vec![]), &opts(ch0_only)).0;
        let ch0_var = render(&song(insert.clone()), &opts(ch0_only)).0;
        assert_eq!(
            ch0_base, ch0_var,
            "a non-target channel must be byte-identical"
        );

        let system = render(&song(xg_amp_sim_block(14, 24, 100, 0x01)), &opts(all)).0;
        assert_eq!(system, base, "SYSTEM connection must install no insert");
        let off = render(
            &song(xg_amp_sim_block(127, 24, 100, XG_VAR_INSERTION)),
            &opts(all),
        )
        .0;
        assert_eq!(off, base, "part OFF (127) must install no insert");
    }

    /// Unit 5 (REPLACE, not stack — white-box): with the Amp-Sim insert on a
    /// program-29 channel, the presence or absence of the program `drive` makes
    /// no difference — the insert takes precedence and the program drive never
    /// runs. Under a (wrong) STACK the two would differ.
    #[test]
    fn xg_variation_replaces_not_stacks_the_program_drive() {
        let build = |clear_drive: bool| {
            let mut core = EngineCore::new(CoreOptions {
                sr: 44100.0,
                wet: 0.0,
                delay_s: 0.0,
                samples: false,
                solo: 0xFFFF,
                gtr_symp_on: true,
                drum_room_on: true,
                sitar_symp_on: true,
            });
            core.handle_event(EvKind::Prog { ch: 14, prog: 29 });
            assert!(
                core.strips[14].drive.is_some(),
                "program 29 builds a program drive"
            );
            for (_, kind) in xg_amp_sim_block(14, 24, 100, XG_VAR_INSERTION) {
                core.handle_event(kind);
            }
            assert!(
                core.strips[14].xg_insert.is_some(),
                "Amp-Sim insert must be installed"
            );
            if clear_drive {
                core.strips[14].drive = None;
            }
            core.handle_event(EvKind::NoteOn {
                ch: 14,
                key: 45,
                vel: 100,
            });
            let mut out = Vec::new();
            let mut sink = vec![0f32; BLOCK * 2];
            for _ in 0..30 {
                sink.iter_mut().for_each(|x| *x = 0.0);
                core.render_block_add(BLOCK, &mut sink);
                out.extend_from_slice(&sink);
            }
            out
        };
        assert_eq!(
            build(false),
            build(true),
            "the insert must REPLACE the program drive (it never runs when an insert is present)"
        );
    }

    /// Unit 5 (Dry/Wet blend): lower Dry/Wet moves the render monotonically away
    /// from full-wet toward the dry (un-amped) signal — the base-rate apply-site
    /// blend interpolates linearly.
    #[test]
    fn xg_variation_drywet_blends_toward_full_wet() {
        let sr = 44100.0;
        let opts = Options {
            sr,
            wet: 0.0,
            tail: 0.5,
            delay_s: 0.0,
            samples: false,
            solo: 0xFFFF,
        };
        let render_dw = |drywet: u8| {
            let mut ev = vec![(0.0, EvKind::Prog { ch: 14, prog: 29 })];
            ev.extend(xg_amp_sim_block(14, 90, drywet, XG_VAR_INSERTION));
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 14,
                    key: 45,
                    vel: 100,
                },
            ));
            ev.push((0.9, EvKind::NoteOff { ch: 14, key: 45 }));
            left(&render(&test_song(ev, 1.4), &opts).0)
        };
        let full = render_dw(127);
        let mid = render_dw(64);
        let dry = render_dw(1);
        let dist =
            |a: &[f32], b: &[f32]| rms(&a.iter().zip(b).map(|(x, y)| x - y).collect::<Vec<_>>());
        let d_dry = dist(&dry, &full);
        let d_mid = dist(&mid, &full);
        assert!(d_mid > 1e-6, "Dry/Wet 64 must differ from full wet");
        assert!(
            d_dry > d_mid * 1.3,
            "lower Dry/Wet must move monotonically away from full wet: dry {d_dry:.6} mid {d_mid:.6}"
        );
    }

    /// Unit 5 (Drive parameter): more XG Drive drives the amp-sim harder — a pure
    /// sine picks up more 2nd/3rd-harmonic energy relative to its fundamental.
    #[test]
    fn amp_sim_higher_drive_adds_harmonics() {
        let sr = 44100.0;
        let f0 = 200.0;
        let n = 8192;
        let thd = |drive: u8| {
            let mut buf: Vec<f32> = (0..n)
                .map(|i| 0.3 * (TAU * f0 * i as f32 / sr).sin())
                .collect();
            Drive::amp_sim(sr, drive).process(&mut buf);
            let fund = crate::testutil::mag_at(&buf, sr, f0).max(1e-9);
            let h2 = crate::testutil::mag_at(&buf, sr, 2.0 * f0);
            let h3 = crate::testutil::mag_at(&buf, sr, 3.0 * f0);
            (h2 + h3) / fund
        };
        let mild = thd(20);
        let hot = thd(110);
        assert!(
            hot > mild * 1.5,
            "more XG Drive must add harmonics: mild {mild:.4} hot {hot:.4}"
        );
    }

    /// KP-O3 (v0.12 brush kit selection seam, re-anchored on trunk's V3
    /// default): a ch-10 Program Change of EXACTLY 40 selects the brush kit;
    /// any other program keeps selecting V3 (the showcase demo's prog 8 must
    /// not change meaning), and a later non-40 program hands the channel back
    /// to V3 for subsequently spawned hits.
    #[test]
    fn ch10_program_40_selects_brush() {
        let sr = 44100.0;
        let song = |progs: &[(f64, u8)]| {
            let mut ev: Vec<(f64, EvKind)> = progs
                .iter()
                .map(|&(t, p)| (t, EvKind::Prog { ch: 9, prog: p }))
                .collect();
            ev.push((
                0.3,
                EvKind::NoteOn {
                    ch: 9,
                    key: 38,
                    vel: 100,
                },
            ));
            ev.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
            test_song(ev, 1.0)
        };
        let r = |progs: &[(f64, u8)]| render(&song(progs), &test_opts(sr)).0;
        let v3 = r(&[]);
        let prog8 = r(&[(0.0, 8)]);
        let brush = r(&[(0.0, 40)]);
        let back = r(&[(0.0, 40), (0.1, 8)]);
        assert_eq!(prog8, v3, "non-40 programs must keep the V3 kit");
        assert_ne!(brush, v3, "prog 40 must select Brush, not V3");
        assert_eq!(back, v3, "a later non-40 program must hand back to V3");
    }

    /// G5 (v0.12 tam-tam, authored-only): a GM 14 channel that never authors
    /// CC0 renders byte-identically with and without an explicit CC0=0
    /// (tubular bells, the default bank), and only a non-zero CC0 swaps in
    /// the alt-bank tam-tam — whose ~98 Hz gong fundamental confirms the
    /// routing.
    #[test]
    fn alt_bank_gm14_tamtam_authored_only() {
        let sr = 44100.0;
        let base = vec![
            (0.0, EvKind::Prog { ch: 0, prog: 14 }),
            (
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 43,
                    vel: 100,
                },
            ),
        ];
        let with_cc0 = |val: u8| {
            let mut ev = vec![(0.0, EvKind::Cc { ch: 0, num: 0, val })];
            ev.extend(base.iter().cloned());
            ev
        };
        let no_cc = render(&test_song(base.clone(), 2.0), &test_opts(sr)).0;
        let cc0_zero = render(&test_song(with_cc0(0), 2.0), &test_opts(sr)).0;
        let cc0_alt = render(&test_song(with_cc0(8), 2.0), &test_opts(sr)).0;
        assert_eq!(cc0_zero, no_cc, "CC0=0 must be a no-op (default bank)");
        assert_ne!(cc0_alt, no_cc, "CC0!=0 on GM 14 must swap in the tam-tam");
        let l = left(&cc0_alt);
        let f = crate::testutil::peak_locate(
            &l[(0.5 * sr) as usize..(1.8 * sr) as usize],
            sr,
            55.0,
            140.0,
        );
        assert!(
            (f - 98.0).abs() <= 3.0,
            "alt GM 14 fundamental {f:.1} Hz is not the key-43 gong"
        );
    }

    /// Cathedral GM19 and the legacy CC0=1 GM19 can overlap on one channel
    /// without sharing their spawn-time tremulant/Leslie, chorus-default, or
    /// room routes. The oracle compares that overlap with the same two voices
    /// on separate, identically controlled channels: global linear buses and
    /// the final glue must see the same signal either way.
    #[test]
    fn gm19_bank_overlap_matches_split_channels() {
        let sr = 44100.0;
        let overlap_events = |split: bool, first_alt: bool| {
            let first_ch = 0;
            let second_ch = u8::from(split);
            let mut events = vec![];
            for (ch, alt) in [(first_ch, first_alt), (second_ch, !first_alt)] {
                events.push((
                    0.0,
                    EvKind::Cc {
                        ch,
                        num: 0,
                        val: u8::from(alt),
                    },
                ));
                events.push((0.0, EvKind::Prog { ch, prog: 19 }));
                if !split {
                    break;
                }
            }
            events.push((
                0.05,
                EvKind::NoteOn {
                    ch: first_ch,
                    key: 48,
                    vel: 100,
                },
            ));
            if !split {
                events.push((
                    0.30,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: u8::from(!first_alt),
                    },
                ));
            }
            events.push((
                0.35,
                EvKind::NoteOn {
                    ch: second_ch,
                    key: 60,
                    vel: 100,
                },
            ));
            for (time, num, val) in [
                (0.45, 91, 100),
                (0.50, 1, 90),
                (0.65, 93, 64),
                (0.75, 94, 72),
            ] {
                events.push((time, EvKind::Cc { ch: 0, num, val }));
                if split {
                    events.push((time, EvKind::Cc { ch: 1, num, val }));
                }
            }
            events.push((
                1.00,
                EvKind::Cc {
                    ch: 0,
                    num: 121,
                    val: 0,
                },
            ));
            if split {
                events.push((
                    1.00,
                    EvKind::Cc {
                        ch: 1,
                        num: 121,
                        val: 0,
                    },
                ));
            }
            events.push((
                1.50,
                EvKind::NoteOff {
                    ch: first_ch,
                    key: 48,
                },
            ));
            events.push((
                1.70,
                EvKind::NoteOff {
                    ch: second_ch,
                    key: 60,
                },
            ));
            events
        };

        let mut opts = test_opts(sr);
        opts.wet = 0.32;
        opts.delay_s = 0.12;
        opts.tail = 1.0;
        for first_alt in [false, true] {
            let overlap = render(&test_song(overlap_events(false, first_alt), 2.0), &opts).0;
            let split = render(&test_song(overlap_events(true, first_alt), 2.0), &opts).0;
            assert_eq!(overlap.len(), split.len());
            let diff: Vec<f32> = overlap.iter().zip(&split).map(|(x, y)| x - y).collect();
            let ratio = rms(&diff) / rms(&split).max(1e-9);
            assert!(
                ratio < 2e-4,
                "held GM19 routes leaked with first_alt={first_alt}: diff/base {ratio:.6}"
            );
        }
    }

    /// Round-2 GM019 differential pin: with the CathedralOrgan retired, the
    /// default bank IS the legacy drawbar voice — a default-bank GM19 render
    /// must be bit-identical to the CC0=1 render under identical controls
    /// (this is what let the audition drop its GM19 A/B slot). Any drift
    /// here means the banks' routing or spawn paths diverged again.
    #[test]
    fn default_gm19_is_the_legacy_drawbar_voice() {
        let events = |alt: bool| {
            let mut ev = Vec::new();
            if alt {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: 1,
                    },
                ));
            }
            ev.push((0.0, EvKind::Prog { ch: 0, prog: 19 }));
            ev.push((
                0.2,
                EvKind::Cc {
                    ch: 0,
                    num: 1,
                    val: 96,
                },
            ));
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 60,
                    vel: 100,
                },
            ));
            ev.push((1.6, EvKind::NoteOff { ch: 0, key: 60 }));
            ev
        };
        let mut opts = test_opts(44100.0);
        opts.wet = 0.32;
        opts.delay_s = 0.12;
        opts.tail = 0.5;
        let default_bank = render(&test_song(events(false), 2.0), &opts).0;
        let legacy = render(&test_song(events(true), 2.0), &opts).0;
        assert!(
            default_bank
                .iter()
                .zip(&legacy)
                .all(|(a, b)| a.to_bits() == b.to_bits()),
            "default GM19 and CC0 legacy GM19 renders diverged"
        );
    }

    /// GM19 CC0=2 selects the restored CathedralOrgan pipe model — a distinct
    /// church-organ colour from the default/CC0=1 Leslie drawbar, carrying its
    /// own long stone-room FDN reverb tail. Default and CC0=1 stay the Leslie
    /// (bit-identical). Regression-first: before the restore CC0=2 fell through
    /// to legacy_church_organ, so all three banks rendered identically and both
    /// asserts below (distinct + wet tail) would fail.
    #[test]
    fn gm19_cc0_2_is_the_cathedral_organ() {
        let events = |bank: u8| {
            let mut ev = Vec::new();
            if bank > 0 {
                ev.push((
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: bank,
                    },
                ));
            }
            ev.push((0.0, EvKind::Prog { ch: 0, prog: 19 }));
            ev.push((
                0.05,
                EvKind::NoteOn {
                    ch: 0,
                    key: 48,
                    vel: 100,
                },
            ));
            ev.push((1.2, EvKind::NoteOff { ch: 0, key: 48 }));
            ev
        };
        let mut opts = test_opts(44100.0);
        opts.wet = 0.32;
        opts.tail = 1.0;
        let default_bank = render(&test_song(events(0), 2.5), &opts).0;
        let legacy = render(&test_song(events(1), 2.5), &opts).0;
        let cathedral = render(&test_song(events(2), 2.5), &opts).0;
        // Default and CC0=1 are the identical Leslie drawbar (Ninth Bell safety).
        assert!(
            default_bank
                .iter()
                .zip(&legacy)
                .all(|(a, b)| a.to_bits() == b.to_bits()),
            "default and CC0=1 GM19 must stay the identical Leslie drawbar"
        );
        // CC0=2 is a genuinely different render: the cathedral pipe voice.
        assert!(
            cathedral
                .iter()
                .zip(&legacy)
                .any(|(a, b)| a.to_bits() != b.to_bits()),
            "CC0=2 GM19 did not differ from the Leslie — cathedral voice not routed"
        );
        // The cathedral rings on its dedicated stone-room FDN well past the
        // note-off; measure RMS in the final 0.3 s vs the Leslie's shared-hall
        // decay.
        let sr = 44100usize;
        let tail = |v: &[f32]| {
            let seg = &v[v.len().saturating_sub((0.3 * sr as f32) as usize)..];
            (seg.iter().map(|x| x * x).sum::<f32>() / seg.len().max(1) as f32).sqrt()
        };
        let (cat_tail, leg_tail) = (tail(&cathedral), tail(&legacy));
        assert!(
            cat_tail > leg_tail * 2.0 && cat_tail > 1e-4,
            "cathedral reverb tail ({cat_tail:.2e}) should ring well past the Leslie's ({leg_tail:.2e})"
        );
    }

    /// Human-decision artifact for the parked cathedral-send question. The
    /// shipped path intentionally leaves the cathedral send full-band; this
    /// ignored test compares it with the ordinary hall's 150 Hz high-pass using
    /// the same GM19/CC0=2 phrase and the real engine routing.
    ///
    /// Subtracting an otherwise identical wet=0 render isolates each wet return.
    /// The high-passed return is then gain-matched to the current return by
    /// BS.1770 integrated loudness. A common final gain preserves that match.
    #[test]
    #[ignore = "writes matched cathedral-send A/B WAVs to the OS temp directory"]
    fn write_cathedral_send_hpf_matched_ab() {
        fn render_variant(song: &Song, opt: &Options, highpass: bool) -> Vec<f32> {
            let total = render_sample_count(song, opt);
            let mut out = vec![0.0f32; total * 2];
            drive_render(
                song,
                opt,
                true,
                true,
                true,
                &mut |_| {},
                |core, block_start, n| {
                    core.cathedral_send_hpf_on = highpass;
                    core.render_block_add(n, &mut out[block_start * 2..(block_start + n) * 2]);
                    Ok::<(), std::convert::Infallible>(())
                },
            )
            .expect("an infallible render sink cannot fail");
            out
        }

        let song = test_song(
            vec![
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 0,
                        val: 2,
                    },
                ),
                (0.0, EvKind::Prog { ch: 0, prog: 19 }),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 7,
                        val: 70,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 11,
                        val: 100,
                    },
                ),
                (
                    0.0,
                    EvKind::Cc {
                        ch: 0,
                        num: 91,
                        val: 90,
                    },
                ),
                (
                    0.05,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 36,
                        vel: 84,
                    },
                ),
                (
                    0.35,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 43,
                        vel: 80,
                    },
                ),
                (
                    0.65,
                    EvKind::NoteOn {
                        ch: 0,
                        key: 48,
                        vel: 76,
                    },
                ),
                (3.35, EvKind::NoteOff { ch: 0, key: 48 }),
                (3.50, EvKind::NoteOff { ch: 0, key: 43 }),
                (3.65, EvKind::NoteOff { ch: 0, key: 36 }),
            ],
            4.0,
        );
        let mut wet_options = test_opts(44_100.0);
        wet_options.wet = 0.32;
        wet_options.tail = 8.0;
        let mut dry_options = wet_options.clone();
        dry_options.wet = 0.0;

        let dry = render_variant(&song, &dry_options, false);
        let full_band_mix = render_variant(&song, &wet_options, false);
        let highpass_mix = render_variant(&song, &wet_options, true);
        let full_band_return: Vec<f32> = full_band_mix
            .iter()
            .zip(&dry)
            .map(|(wet, dry)| wet - dry)
            .collect();
        let mut highpass_return: Vec<f32> = highpass_mix
            .iter()
            .zip(&dry)
            .map(|(wet, dry)| wet - dry)
            .collect();

        let sr = wet_options.sr as u32;
        let full_band_lufs = crate::loudness::integrated_lufs(&full_band_return, sr);
        let highpass_lufs = crate::loudness::integrated_lufs(&highpass_return, sr);
        assert!(
            full_band_lufs.is_finite() && highpass_lufs.is_finite(),
            "both isolated cathedral returns must have measurable loudness"
        );
        let match_gain_db = full_band_lufs - highpass_lufs;
        let match_gain = 10f32.powf(match_gain_db / 20.0);
        for sample in &mut highpass_return {
            *sample *= match_gain;
        }
        let matched_lufs = crate::loudness::integrated_lufs(&highpass_return, sr);
        assert!(
            (full_band_lufs - matched_lufs).abs() < 0.05,
            "matched return differs by {:.3} LU",
            full_band_lufs - matched_lufs
        );

        let common_peak = full_band_return
            .iter()
            .chain(&highpass_return)
            .copied()
            .map(f32::abs)
            .fold(0.0f32, f32::max);
        assert!(common_peak > 1e-6, "cathedral returns are silent");
        let common_gain = 0.80 / common_peak;
        let output_dir = std::env::temp_dir().join("ferrosintesis-cathedral-send-hpf");
        std::fs::create_dir_all(&output_dir).expect("create cathedral A/B directory");
        for (name, samples) in [
            ("current-full-band-return.wav", &full_band_return),
            ("candidate-150hz-hpf-return.wav", &highpass_return),
        ] {
            let pcm = dither_quantize(samples, common_gain);
            let path = output_dir.join(name);
            crate::wav::write_wav(&path, sr, &pcm)
                .unwrap_or_else(|error| panic!("write {}: {error}", path.display()));
            println!("{}", path.display());
        }
        println!(
            "current {full_band_lufs:.3} LUFS; HPF {highpass_lufs:.3} LUFS raw, \
             {matched_lufs:.3} LUFS matched; HPF match gain {match_gain_db:+.3} dB; \
             common output gain {:+.3} dB",
            20.0 * common_gain.log10()
        );
    }
}