rumpl 0.3.0

Sample-free General MIDI player and 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
use crate::synth::env::EnvSpec;
use crate::synth::filter::FilterMode;
use crate::synth::osc::Wave;

pub use crate::synth::choir::ChoirSpec;
use crate::synth::choir::{Vowel, vf};
pub use crate::synth::fx::FxKind;
pub use crate::synth::leslie::LeslieSpec;
pub use crate::synth::reed::FreeReedSpec;

#[derive(Clone, Copy, Debug)]
pub struct OscSpec {
  pub wave: Wave,
  pub detune_cents: f32,
  pub mix: f32,
  pub octave: i32,
  /// T60 in seconds of this oscillator's own decay on top of the patch
  /// envelope (organ percussion, key click, chiff); 0 = sustained.
  pub decay: f32,
}

impl OscSpec {
  pub const fn new(wave: Wave, detune_cents: f32, mix: f32) -> Self {
    Self {
      wave,
      detune_cents,
      mix,
      octave: 0,
      decay: 0.0,
    }
  }

  pub const fn at(
    wave: Wave,
    detune_cents: f32,
    mix: f32,
    octave: i32,
  ) -> Self {
    Self {
      wave,
      detune_cents,
      mix,
      octave,
      decay: 0.0,
    }
  }

  /// A percussive partial: like `at`, but dying away with T60 `decay` s.
  pub const fn perc(
    wave: Wave,
    detune_cents: f32,
    mix: f32,
    octave: i32,
    decay: f32,
  ) -> Self {
    Self {
      wave,
      detune_cents,
      mix,
      octave,
      decay,
    }
  }
}

#[derive(Clone, Copy, Debug)]
pub struct FilterSpec {
  pub mode: FilterMode,
  pub cutoff: f32,
  pub res: f32,
  pub key_track: f32,  // 0..1
  pub env_amount: f32, // semitones-equivalent multiplier (0..1)
  /// Velocity tracking: octaves the cutoff rises from a mezzo-forte note
  /// to a fortissimo one (and falls towards pianissimo). Tonal voices only.
  pub vel_track: f32,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LfoTarget {
  Pitch,
  Filter,
  Amp,
}

#[derive(Clone, Copy, Debug)]
pub struct LfoSpec {
  pub rate: f32, // Hz
  pub depth: f32,
  pub target: LfoTarget,
  pub delay: f32, // seconds before LFO ramps in
}

/// One string rank of a plucked-string (Karplus-Strong) voice. A harpsichord
/// stop is several of these — e.g. an 8' rank plus a 4' rank an octave up.
#[derive(Clone, Copy, Debug)]
pub struct StringSpec {
  pub detune_cents: f32,
  pub octave: i32,
  pub mix: f32,
}

/// Parameters for a plucked-string voice synthesised with an extended
/// Karplus-Strong loop (delay line + damping loop filter + noise excitation).
/// When a `Patch` carries one of these the synth builds a `VoiceKind::Plucked`
/// instead of the oscillator-based `VoiceKind::Tonal`.
#[derive(Clone, Copy, Debug)]
pub struct PluckSpec {
  pub strings: &'static [StringSpec],
  pub decay: f32, // ring time in seconds at middle C (scaled shorter for higher notes)
  pub damp: f32, // loop low-pass amount 0..0.5 — higher damps the highs faster (darker)
  /// T60 in seconds of a 1 kHz partial, the same for every note (one-pole
  /// loop filter; overrides `damp`). 0 = use the two-tap `damp` filter, whose
  /// high-frequency loss per second shrinks with pitch — too little for bass.
  pub hf_decay: f32,
  pub pluck_pos: f32, // 0..0.5 plucking point; shapes the comb colouration of the attack
  pub damper: f32,    // note-off damping time in seconds
  pub noise: f32,     // pluck noise mixed into the initial string shape (chiff)
  /// Magnetic pickup: output the string's velocity rather than its
  /// displacement, so harmonics fall as 1/n instead of 1/n².
  pub magnetic: bool,
  /// Buzzing bridge (sitar jawari, shamisen sawari): how much the string's
  /// speaking length shortens as it wraps onto the curved bridge, as a
  /// fraction of its length at full (unit) displacement. Keeps the upper
  /// partials alive while the note is loud. 0 = off.
  pub buzz: f32,
}

/// Parameters for a modal piano voice (see `synth::piano`). When a `Patch`
/// carries one of these the synth builds a `VoiceKind::Piano`.
#[derive(Clone, Copy, Debug)]
pub struct PianoSpec {
  pub decay: f32, // prompt-sound T60 at middle C, seconds (halves per 2 octaves up)
  pub brightness: f32, // hammer hardness: shortens contact, raises brilliance
  pub unison_cents: f32, // detune spread between the 2–3 strings of a key
  pub strike_pos: f32, // hammer position as a fraction of string length
  pub hammer: f32, // level of the hammer/action knock
  pub damper: f32, // damper T60 at middle C, seconds
  pub body: f32,  // level of the soundboard/frame knock at the attack
}

/// One vibration mode of a struck bar/tube/tine (see `synth::modal`).
#[derive(Clone, Copy, Debug)]
pub struct Mode {
  pub ratio: f32, // frequency relative to the note's pitch
  pub level: f32, // amplitude before the mallet low-pass
  pub decay: f32, // T60 relative to `ModalSpec::decay`
}

const fn mode(ratio: f32, level: f32, decay: f32) -> Mode {
  Mode {
    ratio,
    level,
    decay,
  }
}

/// Parameters for a modal (struck bar / tube / tine) voice. When a `Patch`
/// carries one of these the synth builds a `VoiceKind::Modal`.
#[derive(Clone, Copy, Debug)]
pub struct ModalSpec {
  pub modes: &'static [Mode],
  pub decay: f32, // T60 of a `decay: 1.0` mode at middle C, seconds
  pub key_decay: f32, // T60 scales by 2^(-key_decay) per octave up
  pub corner: f32, // mallet low-pass corner at mf, Hz
  pub hardness: f32, // how strongly the corner follows velocity
  pub click: f32, // mallet contact noise level
  pub onset: f32, // attack ramp time constant, seconds
  pub spread_cents: f32, // split each mode into a beating doublet (0 = off)
  pub pickup: f32, // magnetic-pickup nonlinearity (Rhodes bark), 0 = off
  pub damper: f32, // T60 after note-off, seconds; 0 = undamped
  pub tremolo_hz: f32,
  pub tremolo_depth: f32, // 0..1 amplitude dip
}

/// Parameters for a bowed-string waveguide voice (see `synth::bowed`). When a
/// `Patch` carries one of these the synth builds a `VoiceKind::Bowed`.
#[derive(Clone, Copy, Debug)]
pub struct BowSpec {
  /// One entry per player (a section is several detuned strings).
  pub players: &'static [StringSpec],
  pub bow_pos: f32, // bow–bridge distance as a fraction of the string (β)
  pub pressure: f32, // bow force 0..1: more grip, a grittier, brighter tone
  pub brightness: f32, // string loop low-pass corner, multiples of f0
  pub ring: f32,    // free-string T60 at middle C once the bow lifts, s
  pub body: f32,    // body size: resonance frequencies × this (violin = 1)
  /// Sections: pick the body by the note, from double bass up to violin,
  /// as an orchestra hands low notes to the larger instruments.
  pub body_follows_key: bool,
  pub bow_noise: f32, // rosin roughness on the bow speed
  pub attack: f32,    // bow speed ramp-in, s
  pub release: f32,   // bow lift time, s
  pub vibrato_hz: f32,
  pub vibrato_cents: f32,
  pub vibrato_delay: f32,
  pub tremolo_hz: f32, // bow-stroke reversals per second / 2; 0 = one stroke
}

/// How a wind instrument's bore is excited (see `synth::wind`).
#[derive(Clone, Copy, Debug)]
pub enum Exciter {
  /// Single reed on a cylinder (clarinet). `slope`: reed stiffness.
  Reed { slope: f32 },
  /// Reed on a conical bore, as a cylinder split at `pos` (sax, double
  /// reeds).
  Cone { slope: f32, pos: f32 },
  /// Lip valve (brass).
  Lips,
  /// Air jet across an edge (flutes). `stopped`: closed far end, so mostly
  /// odd harmonics (pan pipes, vessel flutes).
  Jet { stopped: bool },
}

/// Parameters for a wind waveguide voice. When a `Patch` carries one of
/// these the synth builds a `VoiceKind::Wind`.
#[derive(Clone, Copy, Debug)]
pub struct WindSpec {
  pub exciter: Exciter,
  /// One entry per player (a section is several detuned instruments).
  pub players: &'static [StringSpec],
  pub breath: f32,   // mouth pressure at mf
  pub dynamics: f32, // how much velocity changes the pressure
  pub cutoff: f32,   // bell / open-end reflection low-pass corner, Hz
  pub loss: f32,     // reflection gain at the fundamental
  pub noise: f32,    // breath turbulence
  pub attack: f32,   // breath onset, s
  pub release: f32,  // breath stop, s
  pub vibrato_hz: f32,
  pub vibrato_cents: f32,
  pub vibrato_delay: f32,
  pub level: f32, // output normalisation
  /// Brass: nonlinear steepening along the bore (samples of shift at full
  /// breath) — the "brassy" brightening of loud notes. 0 for other winds.
  pub brassy: f32,
  /// Fixed resonances of the instrument body (mouthpiece, tone-hole
  /// lattice, bell), applied to the radiated sound. They stay put in Hz
  /// while the note moves, which is much of what tells instruments of one
  /// family apart.
  pub formants: &'static [Formant],
  /// Radiation high-pass corner, Hz (0 = none): a narrow bore and small
  /// tone holes radiate the low harmonics poorly (oboe, English horn).
  pub radiation: f32,
}

/// A peaking-EQ resonance: centre `hz`, quality `q`, `db` of boost.
#[derive(Clone, Copy, Debug)]
pub struct Formant {
  pub hz: f32,
  pub q: f32,
  pub db: f32,
}

/// Two-operator FM: modulator/carrier ratio and modulation index in radians,
/// both encoded as fixed-point ×10 to keep `const` evaluation simple.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FmSpec {
  pub ratio_x10: u32,
  pub index_x10: u32,
}

impl FmSpec {
  pub const fn new(ratio_x10: u32, index_x10: u32) -> Self {
    Self {
      ratio_x10,
      index_x10,
    }
  }

  pub fn parts(self) -> (f32, f32) {
    (self.ratio_x10 as f32 / 10.0, self.index_x10 as f32 / 10.0)
  }
}

#[derive(Clone, Copy, Debug)]
pub struct Patch {
  pub oscs: &'static [OscSpec],
  pub env: EnvSpec,
  pub filter: Option<FilterSpec>,
  pub lfo: Option<LfoSpec>,
  pub fm: Option<FmSpec>,
  pub gain: f32,
  pub pluck: Option<PluckSpec>,
  pub piano: Option<PianoSpec>,
  pub modal: Option<ModalSpec>,
  pub bowed: Option<BowSpec>,
  pub wind: Option<WindSpec>,
  pub choir: Option<ChoirSpec>,
  pub reed: Option<FreeReedSpec>,
  pub fx: Option<FxKind>,
  /// Rotating-speaker cabinet on the channel (organs).
  pub leslie: Option<LeslieSpec>,
  /// Soft-clipping drive (tanh) before the filter, for tonal and plucked
  /// voices; 0 = clean.
  pub drive: f32,
}

impl Patch {
  /// Same patch with a filter (for plucked voices: a static pickup/cabinet
  /// tone filter after the string).
  const fn with_filter(self, filter: Option<FilterSpec>) -> Self {
    Self { filter, ..self }
  }

  const fn with_drive(self, drive: f32) -> Self {
    Self { drive, ..self }
  }

  const fn with_leslie(self, leslie: LeslieSpec) -> Self {
    Self {
      leslie: Some(leslie),
      ..self
    }
  }
}

/// Field defaults shared by every constructor below.
const BASE: Patch = Patch {
  oscs: SINE,
  env: EnvSpec::adsr(0.001, 1.0, 0.0, 0.2),
  filter: None,
  lfo: None,
  fm: None,
  gain: 1.0,
  pluck: None,
  piano: None,
  modal: None,
  bowed: None,
  wind: None,
  choir: None,
  reed: None,
  fx: None,
  leslie: None,
  drive: 0.0,
};

const fn p(
  oscs: &'static [OscSpec],
  env: EnvSpec,
  filter: Option<FilterSpec>,
  lfo: Option<LfoSpec>,
  fm: Option<FmSpec>,
  gain: f32,
) -> Patch {
  Patch {
    oscs,
    env,
    filter,
    lfo,
    fm,
    gain,
    ..BASE
  }
}

/// Build a plucked-string patch. `oscs`/`env` are kept only as an inert
/// fallback (and to satisfy the patch-table invariants); the actual voice is
/// driven entirely by the Karplus-Strong `PluckSpec`.
const fn plucked(
  oscs: &'static [OscSpec],
  gain: f32,
  pluck: PluckSpec,
) -> Patch {
  Patch {
    oscs,
    env: EnvSpec::adsr(0.001, 0.5, 0.0, 0.1),
    gain,
    pluck: Some(pluck),
    ..BASE
  }
}

/// Build a modal piano patch. As with `plucked`, `oscs`/`env` are an inert
/// fallback; the voice is driven entirely by the `PianoSpec`.
const fn piano(gain: f32, spec: PianoSpec) -> Patch {
  Patch {
    oscs: PIANO_OSC,
    env: EnvSpec::adsr(0.001, 1.0, 0.0, 0.2),
    gain,
    piano: Some(spec),
    ..BASE
  }
}

/// Build a modal (struck bar / tube / tine) patch. As with `piano`,
/// `oscs`/`env` are an inert fallback.
const fn modal(gain: f32, spec: ModalSpec) -> Patch {
  Patch {
    gain,
    modal: Some(spec),
    ..BASE
  }
}

/// Build a bowed-string patch (`oscs`/`env` are an inert fallback).
const fn bowed(gain: f32, spec: BowSpec) -> Patch {
  Patch {
    oscs: SAW,
    env: EnvSpec::adsr(0.05, 0.1, 1.0, 0.2),
    gain,
    bowed: Some(spec),
    ..BASE
  }
}

/// Build a wind patch (`oscs`/`env` are an inert fallback).
const fn wind(gain: f32, spec: WindSpec) -> Patch {
  Patch {
    oscs: SAW,
    env: EnvSpec::adsr(0.05, 0.1, 1.0, 0.2),
    gain,
    wind: Some(spec),
    ..BASE
  }
}

/// Build a choir / vocal patch (`oscs`/`env` are an inert fallback).
const fn choir(gain: f32, spec: ChoirSpec) -> Patch {
  Patch {
    oscs: SAW,
    env: EnvSpec::adsr(0.1, 0.1, 1.0, 0.3),
    gain,
    choir: Some(spec),
    ..BASE
  }
}

/// Build a free-reed patch (`oscs`/`env` are an inert fallback).
const fn reed(gain: f32, spec: FreeReedSpec) -> Patch {
  Patch {
    oscs: SAW,
    env: EnvSpec::adsr(0.03, 0.1, 1.0, 0.1),
    gain,
    reed: Some(spec),
    ..BASE
  }
}

/// Build a sound-effect patch (`oscs`/`env` are an inert fallback).
const fn fx(gain: f32, kind: FxKind) -> Patch {
  Patch {
    oscs: NOISE_OSC,
    env: EnvSpec::adsr(0.001, 0.5, 0.0, 0.1),
    gain,
    fx: Some(kind),
    ..BASE
  }
}

const fn lp(
  cutoff: f32,
  res: f32,
  key_track: f32,
  env_amount: f32,
) -> Option<FilterSpec> {
  Some(FilterSpec {
    mode: FilterMode::Low,
    cutoff,
    res,
    key_track,
    env_amount,
    vel_track: 0.0,
  })
}

/// Velocity-sensitive low-pass: like `lp`, with the cutoff moving
/// `vel_track` octaves between mf and ff.
const fn lpv(
  cutoff: f32,
  res: f32,
  key_track: f32,
  env_amount: f32,
  vel_track: f32,
) -> Option<FilterSpec> {
  Some(FilterSpec {
    mode: FilterMode::Low,
    cutoff,
    res,
    key_track,
    env_amount,
    vel_track,
  })
}

const fn vibrato(rate: f32, depth: f32, delay: f32) -> Option<LfoSpec> {
  Some(LfoSpec {
    rate,
    depth,
    target: LfoTarget::Pitch,
    delay,
  })
}

// ---- oscillator stacks ---------------------------------------------------

const SINE: &[OscSpec] = &[OscSpec::new(Wave::Sine, 0.0, 1.0)];
const TRI: &[OscSpec] = &[OscSpec::new(Wave::Triangle, 0.0, 1.0)];
const SAW: &[OscSpec] = &[OscSpec::new(Wave::Saw, 0.0, 1.0)];
const SQR: &[OscSpec] = &[OscSpec::new(Wave::Square, 0.0, 1.0)];

// Inert oscillator fallback for the modal pianos.
const PIANO_OSC: &[OscSpec] = &[OscSpec::new(Wave::Sine, 0.0, 1.0)];

const PIANO_GRAND: PianoSpec = PianoSpec {
  decay: 2.6,
  brightness: 1.0,
  unison_cents: 0.7,
  strike_pos: 0.119,
  hammer: 1.0,
  damper: 0.36,
  body: 0.7,
};

// Same instrument, harder (voiced-up) hammers.
const PIANO_BRIGHT: PianoSpec = PianoSpec {
  brightness: 1.5,
  hammer: 1.2,
  ..PIANO_GRAND
};

// Electric grand (CP-70 style): short strings read by pickups, so no
// soundboard bloom — shorter sustain, brighter, more chorus between strings.
const PIANO_ELECTRIC_GRAND: PianoSpec = PianoSpec {
  decay: 1.6,
  brightness: 1.3,
  unison_cents: 2.5,
  strike_pos: 0.1,
  hammer: 0.5,
  damper: 0.3,
  body: 0.2, // pickups, no soundboard
};

// Honky-tonk: an upright whose unisons have drifted well apart.
const PIANO_HONKY_TONK: PianoSpec = PianoSpec {
  decay: 2.0,
  brightness: 1.1,
  unison_cents: 14.0,
  strike_pos: 0.125,
  hammer: 1.3,
  damper: 0.4,
  body: 1.3, // upright: boxy, knocky
};

const ENS_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -10.0, 0.5),
  OscSpec::new(Wave::Saw, 0.0, 0.5),
  OscSpec::new(Wave::Saw, 10.0, 0.5),
];

const PAD_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -12.0, 0.45),
  OscSpec::new(Wave::Saw, 12.0, 0.45),
  OscSpec::at(Wave::Sine, 0.0, 0.3, 1),
];

const NOISE_OSC: &[OscSpec] = &[OscSpec::new(Wave::Noise, 0.0, 1.0)];

// Inert oscillator fallback for the harpsichord; the real voice is the
// Karplus-Strong pluck below.
const HARPSI_OSC: &[OscSpec] = &[OscSpec::new(Wave::Saw, 0.0, 1.0)];

// Harpsichord: an 8' rank plus the octave-up 4' rank. The 4' is mixed lower and
// detuned a few cents sharp so the two strings beat against each other.
const HARPSI_STRINGS: &[StringSpec] = &[
  StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  }, // 8'
  StringSpec {
    detune_cents: 4.0,
    octave: 1,
    mix: 0.5,
  }, // 4'
];

const PLUCK_HARPSI: PluckSpec = PluckSpec {
  strings: HARPSI_STRINGS,
  decay: 1.6,
  damp: 0.03,
  pluck_pos: 0.15,
  hf_decay: 0.0,
  damper: 0.08,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

const FIFTHS_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, 0.0, 0.6),
  OscSpec::at(Wave::Saw, 700.0, 0.5, 0),
];

const CRYSTAL_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Sine, 0.0, 0.6),
  OscSpec::at(Wave::Sine, 700.0, 0.4, 0),
];

// ---- electric pianos -----------------------------------------------------

// Rhodes: a tine + tone bar read by a magnetic pickup. The tine itself is
// almost a pure tone; a short inharmonic ping marks the strike and the
// pickup's asymmetric nonlinearity adds the even-harmonic "bark" that grows
// with velocity and fades with the note.
const EP_RHODES: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.0, 0.06, 0.5),  // tone bar
    mode(7.2, 0.10, 0.04), // tine ping
  ],
  decay: 5.0,
  key_decay: 0.5,
  corner: 3_000.0,
  hardness: 0.6,
  click: 0.02,
  onset: 0.0015,
  spread_cents: 0.0,
  pickup: 1.2,
  damper: 0.15,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// DX-style FM electric piano: glassier, harmonic overtones that decay into a
// sine, a bright "tine" transient high up, and a chorus between two detuned
// copies of every partial. No pickup bark.
const EP_FM: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.0, 0.45, 0.5),
    mode(3.0, 0.2, 0.3),
    mode(4.0, 0.1, 0.2),
    mode(5.0, 0.05, 0.12),
    mode(14.0, 0.25, 0.03),
  ],
  decay: 4.0,
  key_decay: 0.5,
  corner: 5_000.0,
  hardness: 0.8,
  click: 0.0,
  onset: 0.001,
  spread_cents: 7.0,
  pickup: 0.0,
  damper: 0.2,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// ---- chromatic percussion ------------------------------------------------

// Celesta: felt hammers on steel plates over wooden resonators — nearly a
// pure tone with a faint metallic shimmer; keyboard dampers.
const CELESTA: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.76, 0.07, 0.3),
    mode(5.40, 0.02, 0.12),
  ],
  decay: 2.0,
  key_decay: 0.5,
  corner: 2_500.0,
  hardness: 0.5,
  click: 0.03,
  onset: 0.002,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.25,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Glockenspiel: hard mallets on untuned steel bars (free-free beam ratios).
// Undamped; upper modes rolled off so the top octave doesn't sting.
const GLOCKENSPIEL: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.76, 0.35, 0.4),
    mode(5.40, 0.12, 0.18),
    mode(8.93, 0.04, 0.08),
  ],
  decay: 4.0,
  key_decay: 0.4,
  corner: 5_000.0,
  hardness: 0.6,
  click: 0.05,
  onset: 0.0008,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Vibraphone: aluminium bars tuned 1:4:10, soft yarn mallets, long sustain,
// damper bar, and the motor-driven resonator discs' tremolo.
const VIBRAPHONE: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(4.0, 0.10, 0.2),
    mode(10.0, 0.02, 0.06),
  ],
  decay: 5.0,
  key_decay: 0.5,
  corner: 2_000.0,
  hardness: 0.6,
  click: 0.03,
  onset: 0.003,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.5,
  tremolo_hz: 5.5,
  tremolo_depth: 0.3,
};

// Marimba: rosewood bars tuned 1:4:10 (in practice ~1:3.9:9.2) over tube
// resonators. Rubber/yarn mallets; the resonator-supported fundamental rings,
// the overtones die almost at once. Undamped.
const MARIMBA: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(3.93, 0.30, 0.18),
    mode(9.2, 0.08, 0.07),
  ],
  decay: 1.4,
  key_decay: 0.8,
  corner: 1_800.0,
  hardness: 0.8,
  click: 0.1,
  onset: 0.0015,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Xylophone: hard mallets on rosewood bars tuned 1:3 (a twelfth), short ring.
const XYLOPHONE: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(3.0, 0.40, 0.4),
    mode(6.1, 0.12, 0.2),
    mode(10.4, 0.04, 0.1),
  ],
  decay: 0.8,
  key_decay: 0.6,
  corner: 4_000.0,
  hardness: 1.0,
  click: 0.25,
  onset: 0.0005,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Tubular bells: a free-free tube's modes go as (2n+1)², and the pitch you
// hear (the strike tone) is an octave below the 4th mode, implied by modes
// 4–6 standing near 2:3:4. So the modes sit at (2n+1)²/81·2 × the note:
// 0.62, 1.21, 2, 2.99, 4.17, 5.56, 7.14. Long ring, slowly beating
// doublets (the tube is never perfectly round), a hard-mallet clang.
const TUBULAR_BELLS: ModalSpec = ModalSpec {
  modes: &[
    mode(0.617, 0.20, 1.3),
    mode(1.210, 0.45, 1.15),
    mode(2.000, 1.00, 1.0),
    mode(2.988, 0.80, 0.8),
    mode(4.173, 0.55, 0.6),
    mode(5.556, 0.30, 0.45),
    mode(7.136, 0.15, 0.3),
  ],
  decay: 7.0,
  key_decay: 0.4,
  corner: 5_000.0,
  hardness: 0.6,
  click: 0.12,
  onset: 0.0008,
  spread_cents: 0.5,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// ---- struck and plucked strings ------------------------------------------

const ONE_STRING: &[StringSpec] = &[StringSpec {
  detune_cents: 0.0,
  octave: 0,
  mix: 1.0,
}];

// Clavinet: a hammer tip strikes the string right next to its end, so the
// spectrum is bright and nasal; a yarn damper silences it the moment the key
// rises. Two pickups under the strings give the band-passed "quack".
const PLUCK_CLAV: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 1.4,
  damp: 0.02,
  pluck_pos: 0.06,
  hf_decay: 0.0,
  damper: 0.02,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

// Hammered dulcimer: courses of three unison strings hit with light wooden
// hammers, slightly out of tune with each other, and no dampers.
const DULCIMER_STRINGS: &[StringSpec] = &[
  StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  },
  StringSpec {
    detune_cents: 3.0,
    octave: 0,
    mix: 0.9,
  },
  StringSpec {
    detune_cents: -2.5,
    octave: 0,
    mix: 0.8,
  },
];

const PLUCK_DULCIMER: PluckSpec = PluckSpec {
  strings: DULCIMER_STRINGS,
  decay: 4.0,
  damp: 0.1,
  pluck_pos: 0.1,
  hf_decay: 0.0,
  damper: 1.5,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

const PLUCK_NYLON: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 2.5,
  damp: 0.3,
  pluck_pos: 0.18,
  hf_decay: 0.0,
  damper: 0.12,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

const PLUCK_STEEL: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 3.5,
  damp: 0.15,
  pluck_pos: 0.13,
  hf_decay: 0.0,
  damper: 0.12,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

// Electric guitars: solid body, so the string rings long and its tone is
// set by the pickup (a resonant low-pass from the coil's inductance) and,
// for the driven sounds, the amp's clipping and the speaker cabinet.
const PLUCK_JAZZ: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 3.0,
  damp: 0.15,
  pluck_pos: 0.25, // neck pickup region, thumb/pick near the neck
  hf_decay: 0.0,
  damper: 0.1,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

// Clean (chorused): a second, slightly detuned copy of the string stands in
// for the chorus pedal.
const CLEAN_STRINGS: &[StringSpec] = &[
  StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  },
  StringSpec {
    detune_cents: 6.0,
    octave: 0,
    mix: 0.35,
  },
];

const PLUCK_CLEAN: PluckSpec = PluckSpec {
  strings: CLEAN_STRINGS,
  decay: 3.5,
  damp: 0.04,
  pluck_pos: 0.12,
  hf_decay: 0.0,
  damper: 0.1,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

// Palm-muted: the hand on the bridge kills the highs and the ring.
const PLUCK_MUTED: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 0.3,
  damp: 0.3,
  pluck_pos: 0.15,
  hf_decay: 0.0,
  damper: 0.05,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

const PLUCK_DRIVEN: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 6.0,
  damp: 0.05,
  pluck_pos: 0.14,
  hf_decay: 0.0,
  damper: 0.08,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

// Natural harmonic at the 12th fret: the string sounds an octave up with
// only its even partials, chime-like and soft-edged.
const HARMONIC_STRINGS: &[StringSpec] = &[StringSpec {
  detune_cents: 0.0,
  octave: 1,
  mix: 1.0,
}];

const PLUCK_HARMONICS: PluckSpec = PluckSpec {
  strings: HARMONIC_STRINGS,
  decay: 3.0,
  damp: 0.12,
  pluck_pos: 0.25,
  hf_decay: 0.0,
  damper: 0.15,
  noise: 0.85,
  magnetic: false,
  buzz: 0.0,
};

// Basses: long, heavy strings. The fundamental sustains for seconds while
// the upper partials die within a fraction of one (`hf_decay`), so the note
// opens with a bright attack and settles into a round, dark tone. The tone
// stage after the string stands in for the pickup and amp (or, for the
// upright, the body).

// Upright (pizzicato jazz bass): plucked with the side of the finger well up
// the string — a soft, round attack (little chiff) and a dark tone that
// blooms and sustains rather than thumping and dying away.
const PLUCK_UPRIGHT: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 3.0,
  damp: 0.0,
  hf_decay: 0.25,
  pluck_pos: 0.3,
  damper: 0.12,
  noise: 0.1,
  magnetic: false,
  buzz: 0.0,
};

// Fingered electric: roundwound steel plucked by fingertips between the
// pickups — warm, long sustain, and the upper partials ring on for a while
// rather than dying straight away.
const PLUCK_FINGER: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 3.0,
  damp: 0.0,
  hf_decay: 0.8,
  pluck_pos: 0.2,
  damper: 0.1,
  noise: 0.2,
  magnetic: true,
  buzz: 0.0,
};

// Picked electric: a plectrum near the bridge — brighter, with a click.
const PLUCK_PICK: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 2.4,
  damp: 0.0,
  hf_decay: 0.7,
  pluck_pos: 0.09,
  damper: 0.06,
  noise: 0.85,
  magnetic: true,
  buzz: 0.0,
};

// Fretless: the string stops on the fingertip instead of a fret, so the upper
// mids hang on and sing ("mwah") — even longer `hf_decay`, plucked near the
// bridge for a nasal tone, a resonant tone stage, and a faint second string a
// few cents sharp for the slightly loose intonation of a fretless.
const FRETLESS_STRINGS: &[StringSpec] = &[
  StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  },
  StringSpec {
    detune_cents: 4.0,
    octave: 0,
    mix: 0.25,
  },
];

const PLUCK_FRETLESS: PluckSpec = PluckSpec {
  strings: FRETLESS_STRINGS,
  decay: 3.5,
  damp: 0.0,
  hf_decay: 1.5,
  pluck_pos: 0.12,
  damper: 0.1,
  noise: 0.1,
  magnetic: true,
  buzz: 0.0,
};

// Slap (thumb): the string is struck right at the end of the neck and
// smacks the frets — bright, percussive, sharp click.
const PLUCK_SLAP: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 1.8,
  damp: 0.0,
  hf_decay: 0.5,
  pluck_pos: 0.05,
  damper: 0.05,
  noise: 1.0,
  magnetic: true,
  buzz: 0.0,
};

// Pop: the string is pulled away and snapped back onto the frets — even
// brighter and more metallic than the thumb.
const PLUCK_POP: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 1.8,
  damp: 0.0,
  hf_decay: 0.8,
  pluck_pos: 0.035,
  damper: 0.05,
  noise: 1.0,
  magnetic: true,
  buzz: 0.0,
};

// ---- bowed strings --------------------------------------------------------

// Solo strings: bowed a little nearer the bridge than the fingerboard, with
// a singing vibrato that comes in after the note has spoken. The body sets
// the instrument: a violin's air and wood resonances sit around 275–560 Hz,
// a cello's about an octave lower, a double bass's lower still.
const VIOLIN: BowSpec = BowSpec {
  players: ONE_STRING,
  bow_pos: 0.12,
  pressure: 0.75,
  brightness: 12.0,
  ring: 1.0,
  body: 1.0,
  body_follows_key: false,
  bow_noise: 0.04,
  attack: 0.08,
  release: 0.12,
  vibrato_hz: 5.6,
  vibrato_cents: 14.0,
  vibrato_delay: 0.3,
  tremolo_hz: 0.0,
};

const VIOLA: BowSpec = BowSpec {
  bow_pos: 0.13,
  body: 0.78,
  vibrato_hz: 5.4,
  ..VIOLIN
};

const CELLO: BowSpec = BowSpec {
  bow_pos: 0.13,
  body: 0.45,
  ring: 1.5,
  attack: 0.1,
  vibrato_hz: 5.2,
  vibrato_cents: 12.0,
  ..VIOLIN
};

const CONTRABASS: BowSpec = BowSpec {
  bow_pos: 0.14,
  body: 0.3,
  ring: 2.0,
  attack: 0.12,
  release: 0.15,
  vibrato_hz: 4.8,
  vibrato_cents: 10.0,
  ..VIOLIN
};

// A section: several players, each a few cents off and with their own
// vibrato, so the sum shimmers rather than beating like a chorus effect.
const SECTION: &[StringSpec] = &[
  StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  },
  StringSpec {
    detune_cents: 6.0,
    octave: 0,
    mix: 0.9,
  },
  StringSpec {
    detune_cents: -5.0,
    octave: 0,
    mix: 0.9,
  },
];

// Tremolo: the section saws rapidly up and down at the tip of the bow.
const TREMOLO_STRINGS: BowSpec = BowSpec {
  players: SECTION,
  body_follows_key: true,
  attack: 0.03,
  vibrato_cents: 6.0,
  tremolo_hz: 6.5,
  ..VIOLIN
};

// String ensembles: a section of three on each note, played on the
// instrument whose body suits the note. "Slow strings" swell in with long bows.
const STRING_ENSEMBLE: BowSpec = BowSpec {
  players: SECTION,
  body_follows_key: true,
  attack: 0.15,
  release: 0.3,
  vibrato_cents: 10.0,
  vibrato_delay: 0.2,
  ..VIOLIN
};

const SLOW_STRINGS: BowSpec = BowSpec {
  attack: 0.45,
  release: 0.5,
  pressure: 0.65,
  ..STRING_ENSEMBLE
};

// Fiddle: a violin played folk-style — more bow pressure nearer the bridge
// (brighter, grittier), quicker attacks and only a little vibrato.
const FIDDLE: BowSpec = BowSpec {
  bow_pos: 0.09,
  pressure: 0.9,
  bow_noise: 0.07,
  attack: 0.04,
  vibrato_cents: 7.0,
  vibrato_delay: 0.25,
  ..VIOLIN
};

// ---- winds ---------------------------------------------------------------
//
// `breath` is quoted for mf; `cutoff` is where the bell starts letting the
// harmonics out instead of reflecting them (lower = darker, and the brass
// get brighter with `dynamics` as the breath rises).

const ONE_PLAYER: &[StringSpec] = ONE_STRING;

// Three players, a few cents apart, for the brass section.
const BRASS_PLAYERS: &[StringSpec] = &[
  StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  },
  StringSpec {
    detune_cents: 5.0,
    octave: 0,
    mix: 0.85,
  },
  StringSpec {
    detune_cents: -4.0,
    octave: 0,
    mix: 0.85,
  },
];

const TRUMPET: WindSpec = WindSpec {
  exciter: Exciter::Lips,
  players: ONE_PLAYER,
  breath: 0.8,
  dynamics: 0.5,
  cutoff: 5_000.0,
  loss: 0.95,
  noise: 0.03,
  attack: 0.03,
  release: 0.05,
  vibrato_hz: 5.0,
  vibrato_cents: 8.0,
  vibrato_delay: 0.35,
  level: 1.0,
  brassy: 2.5,
  formants: &[],
  radiation: 0.0,
};

const TROMBONE: WindSpec = WindSpec {
  cutoff: 3_000.0,
  brassy: 3.0,
  attack: 0.04,
  vibrato_cents: 6.0,
  ..TRUMPET
};

const TUBA: WindSpec = WindSpec {
  cutoff: 1_500.0,
  attack: 0.05,
  vibrato_cents: 4.0,
  ..TRUMPET
};

// French horn: the hand in the bell and the backward-facing bell darken
// and soften it.
const FRENCH_HORN: WindSpec = WindSpec {
  cutoff: 1_200.0,
  brassy: 1.0,
  attack: 0.06,
  release: 0.08,
  vibrato_cents: 3.0,
  ..TRUMPET
};

const BRASS_SECTION: WindSpec = WindSpec {
  players: BRASS_PLAYERS,
  cutoff: 3_500.0,
  attack: 0.04,
  vibrato_cents: 6.0,
  ..TRUMPET
};

const CLARINET: WindSpec = WindSpec {
  exciter: Exciter::Reed { slope: 0.3 },
  players: ONE_PLAYER,
  breath: 0.7,
  dynamics: 0.4,
  cutoff: 3_000.0,
  loss: 0.95,
  noise: 0.1,
  attack: 0.025,
  release: 0.05,
  vibrato_hz: 5.0,
  vibrato_cents: 3.0,
  vibrato_delay: 0.4,
  level: 1.0,
  brassy: 0.0,
  formants: &[],
  radiation: 0.0,
};

// Saxophones: a soft single reed on a wide cone — every harmonic, bright,
// with a jazz vibrato. Smaller horns are brighter.
const ALTO_SAX: WindSpec = WindSpec {
  // A slope of 0.25 overblows the top notes an octave when played softly.
  exciter: Exciter::Cone {
    slope: 0.3,
    pos: 0.4,
  },
  players: ONE_PLAYER,
  breath: 0.9,
  dynamics: 0.3,
  cutoff: 4_500.0,
  loss: 0.95,
  noise: 0.05,
  attack: 0.015, // tongued: the reed speaks at once
  release: 0.05,
  vibrato_hz: 5.0,
  vibrato_cents: 15.0,
  vibrato_delay: 0.3,
  level: 1.0,
  brassy: 0.0,
  formants: ALTO_FORMANTS,
  radiation: 0.0,
};

// The four saxophones share a reed and a bore shape; what sets them apart
// is size. Each step down the family (soprano → alto → tenor → baritone) is
// about a fourth or fifth longer, and the body resonances move down with
// it: a low "throat" formant where the tone-hole lattice still reflects
// strongly, and the mouthpiece/reed resonance that gives the edge. Soprano:
// bright and nasal, quick narrow vibrato. Tenor: warmer and breathier, wider
// slower vibrato. Baritone: dark with a honk in the low mids.
const ALTO_FORMANTS: &[Formant] = &[
  Formant {
    hz: 800.0,
    q: 1.2,
    db: 7.0,
  },
  Formant {
    hz: 2_400.0,
    q: 2.0,
    db: 7.0,
  },
];

const SOPRANO_SAX: WindSpec = WindSpec {
  cutoff: 6_000.0,
  noise: 0.04,
  vibrato_hz: 5.6,
  vibrato_cents: 12.0,
  formants: &[
    Formant {
      hz: 1_200.0,
      q: 1.5,
      db: 8.0,
    },
    Formant {
      hz: 3_600.0,
      q: 2.0,
      db: 8.0,
    },
  ],
  ..ALTO_SAX
};

const TENOR_SAX: WindSpec = WindSpec {
  cutoff: 3_500.0,
  noise: 0.07,
  vibrato_hz: 4.8,
  vibrato_cents: 18.0,
  formants: &[
    Formant {
      hz: 600.0,
      q: 1.2,
      db: 7.0,
    },
    Formant {
      hz: 1_800.0,
      q: 1.8,
      db: 8.0,
    },
  ],
  ..ALTO_SAX
};

const BARITONE_SAX: WindSpec = WindSpec {
  cutoff: 3_000.0,
  noise: 0.06,
  vibrato_hz: 4.5,
  vibrato_cents: 10.0,
  formants: &[
    Formant {
      hz: 400.0,
      q: 1.0,
      db: 8.0,
    },
    Formant {
      hz: 1_200.0,
      q: 1.6,
      db: 9.0,
    },
  ],
  ..ALTO_SAX
};

// Double reeds: a stiffer, narrower reed on a narrow cone. The narrow bore
// and small tone holes radiate the low harmonics poorly, so the fundamental
// is weaker than the 2nd–4th harmonics, and strong fixed formants (oboe
// ≈1.2 and ≈2.9 kHz) give the nasal, reedy colour.
const OBOE: WindSpec = WindSpec {
  exciter: Exciter::Cone {
    slope: 0.3,
    pos: 0.38,
  },
  cutoff: 6_000.0,
  // A high-resistance double reed: hardly any breath noise.
  noise: 0.02,
  vibrato_hz: 5.5,
  vibrato_cents: 10.0,
  formants: &[
    Formant {
      hz: 1_200.0,
      q: 1.5,
      db: 9.0,
    },
    Formant {
      hz: 2_900.0,
      q: 2.0,
      db: 6.0,
    },
  ],
  radiation: 800.0,
  ..ALTO_SAX
};

// A fifth lower, and the bulb bell (Liebesfuß) covers the tone: formants
// further down, a darker top.
const ENGLISH_HORN: WindSpec = WindSpec {
  cutoff: 3_500.0,
  formants: &[
    Formant {
      hz: 900.0,
      q: 1.4,
      db: 9.0,
    },
    Formant {
      hz: 2_300.0,
      q: 2.0,
      db: 4.0,
    },
  ],
  radiation: 550.0,
  ..OBOE
};

const BASSOON: WindSpec = WindSpec {
  exciter: Exciter::Cone {
    slope: 0.35,
    pos: 0.4,
  },
  cutoff: 1_500.0,
  // Its stiffer reed beats shut at the saxophones' pressure.
  breath: 0.8,
  vibrato_cents: 8.0,
  formants: &[],
  radiation: 0.0,
  ..OBOE
};

// Shehnai: a shawm — a wide double reed, loud, very bright and nasal, with
// a wide, fast ornamental vibrato.
const SHANAI: WindSpec = WindSpec {
  exciter: Exciter::Cone {
    slope: 0.3,
    pos: 0.4,
  },
  cutoff: 8_000.0,
  vibrato_hz: 6.0,
  vibrato_cents: 20.0,
  formants: &[],
  ..ALTO_SAX
};

// Bagpipe chanter: a double reed fed from the bag, so the pressure is
// constant — no dynamics, no vibrato, and the notes stop dead.
const BAGPIPE: WindSpec = WindSpec {
  exciter: Exciter::Cone {
    slope: 0.25,
    pos: 0.42,
  },
  cutoff: 7_000.0,
  dynamics: 0.0,
  attack: 0.015,
  release: 0.02,
  vibrato_cents: 0.0,
  formants: &[],
  ..ALTO_SAX
};

const FLUTE: WindSpec = WindSpec {
  exciter: Exciter::Jet { stopped: false },
  players: ONE_PLAYER,
  breath: 1.0,
  dynamics: 0.4,
  cutoff: 4_000.0,
  loss: 0.98,
  noise: 0.1,
  attack: 0.05,
  release: 0.06,
  vibrato_hz: 5.5,
  vibrato_cents: 12.0,
  vibrato_delay: 0.3,
  level: 1.0,
  brassy: 0.0,
  formants: &[],
  radiation: 0.0,
};

const PICCOLO: WindSpec = WindSpec {
  cutoff: 6_000.0,
  noise: 0.08,
  ..FLUTE
};

// Recorder: a fixed windway, so a steadier, purer tone and little vibrato.
const RECORDER: WindSpec = WindSpec {
  cutoff: 3_000.0,
  noise: 0.04,
  attack: 0.03,
  vibrato_cents: 3.0,
  ..FLUTE
};

const PAN_FLUTE: WindSpec = WindSpec {
  exciter: Exciter::Jet { stopped: true },
  cutoff: 2_500.0,
  noise: 0.25,
  vibrato_cents: 8.0,
  ..FLUTE
};

// Blowing across a bottle: a Helmholtz resonator — almost a pure tone in a
// lot of breath.
const BLOWN_BOTTLE: WindSpec = WindSpec {
  exciter: Exciter::Jet { stopped: true },
  cutoff: 800.0,
  noise: 0.35,
  attack: 0.08,
  vibrato_cents: 0.0,
  ..FLUTE
};

// Shakuhachi: an end-blown bamboo flute with a sharp edge — very breathy,
// with a slow, deep vibrato made by shaking the head.
const SHAKUHACHI: WindSpec = WindSpec {
  cutoff: 2_500.0,
  noise: 0.35,
  attack: 0.08,
  vibrato_hz: 4.5,
  vibrato_cents: 20.0,
  vibrato_delay: 0.45,
  ..FLUTE
};

const WHISTLE: WindSpec = WindSpec {
  cutoff: 6_000.0,
  noise: 0.05,
  attack: 0.02,
  vibrato_cents: 10.0,
  ..FLUTE
};

// Ocarina: a vessel flute, another Helmholtz resonator — round and pure.
const OCARINA: WindSpec = WindSpec {
  exciter: Exciter::Jet { stopped: true },
  cutoff: 1_000.0,
  noise: 0.06,
  vibrato_cents: 6.0,
  ..FLUTE
};

// ---- plucked and struck orchestral and ethnic instruments ----------------

// Pizzicato: gut strings plucked with the fingertip over the fingerboard — a
// dark, soft "plunk" whose highs vanish at once, ringing only briefly
// through the body. A section of three.
const PLUCK_PIZZICATO: PluckSpec = PluckSpec {
  strings: SECTION,
  decay: 0.7,
  damp: 0.0,
  hf_decay: 0.12,
  pluck_pos: 0.3,
  damper: 0.25,
  noise: 0.15,
  magnetic: false,
  buzz: 0.0,
};

// Concert harp: gut and wire strings plucked mid-length by the fingertips
// (round tone, weak even harmonics), long ring, no dampers.
const PLUCK_HARP: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 4.0,
  damp: 0.0,
  hf_decay: 0.6,
  pluck_pos: 0.42,
  damper: 2.5,
  noise: 0.1,
  magnetic: false,
  buzz: 0.0,
};

// Sitar: steel strings over the wide, curved jawari bridge, which they keep
// touching and buzzing against — the bright, sustained "zing". A struck
// plectrum (mizrab).
const PLUCK_SITAR: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 3.5,
  damp: 0.0,
  hf_decay: 1.2,
  pluck_pos: 0.1,
  damper: 0.6,
  noise: 0.5,
  magnetic: false,
  buzz: 0.03,
};

// Banjo: steel strings on a bridge standing on a drum head — bright, twangy,
// and quick to die as the membrane soaks up the energy.
const PLUCK_BANJO: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 1.1,
  damp: 0.04,
  hf_decay: 0.0,
  pluck_pos: 0.08,
  damper: 0.15,
  noise: 0.9,
  magnetic: false,
  buzz: 0.0,
};

// Shamisen: silk strings struck with a big plectrum (bachi) that also slaps
// the skin; the lowest string buzzes against the neck (sawari).
const PLUCK_SHAMISEN: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 1.2,
  damp: 0.0,
  hf_decay: 0.5,
  pluck_pos: 0.07,
  damper: 0.2,
  noise: 1.0,
  magnetic: false,
  buzz: 0.02,
};

// Koto: long silk/nylon strings on movable bridges over a paulownia body,
// plucked near the end with ivory picks.
const PLUCK_KOTO: PluckSpec = PluckSpec {
  strings: ONE_STRING,
  decay: 2.8,
  damp: 0.0,
  hf_decay: 0.45,
  pluck_pos: 0.11,
  damper: 0.6,
  noise: 0.6,
  magnetic: false,
  buzz: 0.0,
};

// Timpani: a membrane over a kettle. The enclosed air pulls the drumhead's
// modes into a near-harmonic series (Rossing: 1 : 1.5 : 1.98 : 2.44 : 2.94,
// with the (1,1) mode as the pitch); the inharmonic (0,1) "thump" below it
// radiates strongly but dies at once. Felt mallets.
const TIMPANI: ModalSpec = ModalSpec {
  modes: &[
    mode(0.86, 0.5, 0.08),  // (0,1) — thump
    mode(1.0, 1.0, 1.0),    // (1,1) — principal
    mode(1.50, 0.55, 0.8),  // (2,1)
    mode(1.98, 0.35, 0.65), // (3,1)
    mode(2.44, 0.20, 0.5),  // (4,1)
    mode(2.94, 0.10, 0.4),  // (5,1)
    mode(3.42, 0.05, 0.3),
  ],
  decay: 3.5,
  key_decay: 0.6,
  corner: 900.0,
  hardness: 1.0,
  click: 0.15,
  onset: 0.002,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Music box: a steel comb whose teeth are clamped–free bars (modes at
// 1 : 6.27 : 17.55), plucked by pins and ringing on undamped over the box.
const MUSIC_BOX: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(6.27, 0.25, 0.3),
    mode(17.55, 0.06, 0.1),
  ],
  decay: 3.5,
  key_decay: 0.5,
  corner: 6_000.0,
  hardness: 0.4,
  click: 0.06,
  onset: 0.0005,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Kalimba: steel tines on a hollow box, pressed down and released by the
// thumb. The tine's first overtone sits far up (~6×) and dies fast; the box
// adds a short woody knock.
const KALIMBA: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(5.9, 0.18, 0.12),
    mode(15.6, 0.04, 0.05),
  ],
  decay: 1.6,
  key_decay: 0.5,
  corner: 2_500.0,
  hardness: 0.5,
  click: 0.12,
  onset: 0.001,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Tinkle bell: a small cast bell. Inharmonic partials, each split into a
// slowly beating doublet (no bell is perfectly round); long ring.
const TINKLE_BELL: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.32, 0.7, 0.7),
    mode(4.25, 0.45, 0.45),
    mode(6.63, 0.25, 0.3),
    mode(9.38, 0.12, 0.2),
  ],
  decay: 3.0,
  key_decay: 0.4,
  corner: 6_000.0,
  hardness: 0.5,
  click: 0.08,
  onset: 0.0005,
  spread_cents: 3.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Agogô: a thin iron cone struck with a stick — a clanking, inharmonic,
// short ring.
const AGOGO: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.57, 0.6, 0.6),
    mode(4.09, 0.35, 0.4),
    mode(5.95, 0.2, 0.3),
  ],
  decay: 0.9,
  key_decay: 0.3,
  corner: 5_000.0,
  hardness: 0.6,
  click: 0.2,
  onset: 0.0004,
  spread_cents: 4.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Steel drum: each note is a hammered dome on the pan, tuned so its first
// modes fall on the fundamental, octave and twelfth; rubber-tipped sticks.
// The tuned modes beat slightly against their neighbours.
const STEEL_DRUM: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.0, 0.65, 0.8),
    mode(3.0, 0.3, 0.6),
    mode(4.02, 0.12, 0.4),
    mode(5.1, 0.05, 0.3),
  ],
  decay: 1.4,
  key_decay: 0.4,
  corner: 2_800.0,
  hardness: 0.7,
  click: 0.1,
  onset: 0.001,
  spread_cents: 2.5,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Woodblock: a slotted hardwood block — a hollow knock with a couple of
// inharmonic body modes, gone in a tenth of a second.
const WOODBLOCK: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(2.43, 0.4, 0.6),
    mode(3.87, 0.15, 0.4),
  ],
  decay: 0.22,
  key_decay: 0.3,
  corner: 4_000.0,
  hardness: 0.5,
  click: 0.35,
  onset: 0.0003,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Taiko: a huge, thick cowhide membrane. Ideal circular-membrane modes
// (Bessel zeros 1 : 1.59 : 2.14 : 2.30 : 2.65 : 2.92) an octave below the
// played note, struck with heavy sticks.
const TAIKO: ModalSpec = ModalSpec {
  modes: &[
    mode(0.5, 1.0, 1.0),
    mode(0.797, 0.6, 0.6),
    mode(1.068, 0.4, 0.45),
    mode(1.150, 0.3, 0.4),
    mode(1.327, 0.2, 0.3),
    mode(1.459, 0.12, 0.25),
  ],
  decay: 1.0,
  key_decay: 0.3,
  corner: 900.0,
  hardness: 0.8,
  click: 0.3,
  onset: 0.001,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// Melodic tom: a tunable single-headed tom — membrane modes on the note,
// sticks, a short ring.
const MELODIC_TOM: ModalSpec = ModalSpec {
  modes: &[
    mode(1.0, 1.0, 1.0),
    mode(1.59, 0.55, 0.6),
    mode(2.14, 0.35, 0.45),
    mode(2.30, 0.25, 0.4),
    mode(2.65, 0.15, 0.3),
  ],
  decay: 0.6,
  key_decay: 0.3,
  corner: 1_800.0,
  hardness: 0.8,
  click: 0.25,
  onset: 0.0008,
  spread_cents: 0.0,
  pickup: 0.0,
  damper: 0.0,
  tremolo_hz: 0.0,
  tremolo_depth: 0.0,
};

// ---- organs --------------------------------------------------------------
//
// Hammond drawbars as (octave, cents) above the 8' fundamental:
// 16' (-1), 5⅓' (0, +702), 8' (0), 4' (1), 2⅔' (1, +702), 2' (2),
// 1⅗' (2, +386), 1⅓' (2, +702), 1' (3). Each drawbar step is ~3 dB.

// Key click: the contacts closing on nine busbars at once.
const fn click(mix: f32) -> OscSpec {
  OscSpec::perc(Wave::Noise, 0.0, mix, 0, 0.012)
}

// "88 8000 000" — the full, round jazz/gospel registration.
const DRAWBAR_OSC: &[OscSpec] = &[
  OscSpec::at(Wave::Sine, 0.0, 1.0, -1),
  OscSpec::at(Wave::Sine, 702.0, 1.0, 0),
  OscSpec::at(Wave::Sine, 0.0, 1.0, 0),
  OscSpec::at(Wave::Sine, 0.0, 0.25, 1),
  click(0.08),
];

// "00 8000 000" + third-harmonic percussion (fast decay): the bright,
// plucky attack of the classic percussive organ.
const PERC_ORGAN_OSC: &[OscSpec] = &[
  OscSpec::at(Wave::Sine, 0.0, 0.35, -1),
  OscSpec::at(Wave::Sine, 0.0, 1.0, 0),
  OscSpec::at(Wave::Sine, 0.0, 0.5, 1),
  OscSpec::perc(Wave::Sine, 702.0, 1.6, 1, 0.45),
  click(0.12),
];

// "88 8888 888" — every drawbar out, for an overdriven Leslie'd rock organ.
const ROCK_ORGAN_OSC: &[OscSpec] = &[
  OscSpec::at(Wave::Sine, 0.0, 1.0, -1),
  OscSpec::at(Wave::Sine, 702.0, 1.0, 0),
  OscSpec::at(Wave::Sine, 0.0, 1.0, 0),
  OscSpec::at(Wave::Sine, 0.0, 0.8, 1),
  OscSpec::at(Wave::Sine, 702.0, 0.6, 1),
  OscSpec::at(Wave::Sine, 0.0, 0.6, 2),
  OscSpec::at(Wave::Sine, 386.0, 0.35, 2),
  OscSpec::at(Wave::Sine, 702.0, 0.35, 2),
  OscSpec::at(Wave::Sine, 0.0, 0.35, 3),
  click(0.1),
];

// Pipe organ principal chorus: 16' bourdon, 8' principal, 4' octave,
// 2⅔' twelfth, 2' fifteenth and a mixture rank. Independent pipes are never
// exactly in tune, hence the small detunes; flue pipes "chiff" as they speak.
const CHURCH_ORGAN_OSC: &[OscSpec] = &[
  OscSpec::at(Wave::Sine, 0.0, 0.45, -1),
  OscSpec::at(Wave::Saw, 0.0, 0.7, 0),
  OscSpec::at(Wave::Triangle, 1.5, 0.6, 0),
  OscSpec::at(Wave::Triangle, -1.2, 0.5, 1),
  OscSpec::at(Wave::Triangle, 703.0, 0.3, 1),
  OscSpec::at(Wave::Triangle, 0.8, 0.3, 2),
  OscSpec::at(Wave::Sine, 701.0, 0.15, 2),
  OscSpec::perc(Wave::Noise, 0.0, 0.08, 0, 0.06),
];

// ---- voices (see `synth::choir`) ----------------------------------------

const fn rank(detune_cents: f32, octave: i32, mix: f32) -> StringSpec {
  StringSpec {
    detune_cents,
    octave,
    mix,
  }
}

// Formants (Hz, bandwidth Hz, dB) of the classic voice-type tables, averaged
// into a low (bass + tenor) and a high (alto + soprano) set per vowel.
const AH_LOW: Vowel = [
  vf(625.0, 70.0, 0.0),
  vf(1060.0, 80.0, -6.5),
  vf(2450.0, 115.0, -8.0),
  vf(2675.0, 125.0, -8.5),
  vf(3000.0, 135.0, -21.0),
];
const AH_HIGH: Vowel = [
  vf(800.0, 80.0, 0.0),
  vf(1150.0, 90.0, -5.0),
  vf(2850.0, 120.0, -26.0),
  vf(3700.0, 130.0, -28.0),
  vf(4950.0, 140.0, -55.0),
];
const OO_LOW: Vowel = [
  vf(350.0, 40.0, 0.0),
  vf(600.0, 70.0, -20.0),
  vf(2550.0, 100.0, -24.0),
  vf(2790.0, 120.0, -21.0),
  vf(3125.0, 120.0, -31.0),
];
const OO_HIGH: Vowel = [
  vf(340.0, 50.0, 0.0),
  vf(650.0, 60.0, -16.0),
  vf(2600.0, 170.0, -24.0),
  vf(3200.0, 180.0, -27.0),
  vf(4100.0, 200.0, -45.0),
];
const OH_LOW: Vowel = [
  vf(400.0, 40.0, 0.0),
  vf(775.0, 80.0, -10.5),
  vf(2500.0, 100.0, -16.5),
  vf(2700.0, 120.0, -16.0),
  vf(2950.0, 120.0, -33.0),
];
const OH_HIGH: Vowel = [
  vf(450.0, 70.0, 0.0),
  vf(800.0, 80.0, -10.0),
  vf(2830.0, 100.0, -19.0),
  vf(3650.0, 130.0, -25.0),
  vf(4950.0, 135.0, -52.0),
];

// Six singers per note: enough incoherent voices to read as a section.
const CHOIR_SECTION: &[StringSpec] = &[
  rank(0.0, 0, 1.0),
  rank(9.0, 0, 0.9),
  rank(-8.0, 0, 0.9),
  rank(4.0, 0, 0.8),
  rank(-13.0, 0, 0.8),
  rank(15.0, 0, 0.7),
];

const SMALL_SECTION: &[StringSpec] = &[
  rank(0.0, 0, 1.0),
  rank(7.0, 0, 0.9),
  rank(-6.0, 0, 0.9),
  rank(12.0, 0, 0.7),
];

const CHOIR_AAHS: ChoirSpec = ChoirSpec {
  singers: CHOIR_SECTION,
  low: AH_LOW,
  high: AH_HIGH,
  split: 60.0,
  brightness: 2_500.0,
  breath: 0.15,
  drift_cents: 6.0,
  stagger: 0.06,
  attack: 0.18,
  release: 0.4,
  vibrato_hz: 5.2,
  vibrato_cents: 18.0,
  vibrato_delay: 0.25,
};

// "Ooh": rounder, softer, less vibrato.
const VOICE_OOHS: ChoirSpec = ChoirSpec {
  singers: SMALL_SECTION,
  low: OO_LOW,
  high: OO_HIGH,
  brightness: 1_500.0,
  breath: 0.2,
  drift_cents: 5.0,
  stagger: 0.04,
  attack: 0.12,
  release: 0.35,
  vibrato_hz: 5.0,
  vibrato_cents: 10.0,
  vibrato_delay: 0.3,
  ..CHOIR_AAHS
};

// Synth voice: an "oh" from two perfectly steady voices — the formants of a
// singer without a singer's wander.
const SYNTH_VOICE: ChoirSpec = ChoirSpec {
  singers: &[rank(-7.0, 0, 1.0), rank(7.0, 0, 1.0)],
  low: OH_LOW,
  high: OH_HIGH,
  brightness: 4_000.0,
  breath: 0.0,
  drift_cents: 0.0,
  stagger: 0.0,
  attack: 0.08,
  release: 0.3,
  vibrato_hz: 5.5,
  vibrato_cents: 8.0,
  vibrato_delay: 0.4,
  ..CHOIR_AAHS
};

// Lead 6 (voice): one bright, forward "ah".
const VOICE_LEAD: ChoirSpec = ChoirSpec {
  singers: &[rank(0.0, 0, 1.0)],
  brightness: 5_000.0,
  breath: 0.05,
  drift_cents: 0.0,
  stagger: 0.0,
  attack: 0.02,
  release: 0.15,
  vibrato_hz: 5.5,
  vibrato_cents: 12.0,
  vibrato_delay: 0.2,
  ..CHOIR_AAHS
};

// Pad 4 (choir): a section on "oh", swelling slowly.
const CHOIR_PAD: ChoirSpec = ChoirSpec {
  low: OH_LOW,
  high: OH_HIGH,
  brightness: 1_800.0,
  breath: 0.1,
  stagger: 0.2,
  attack: 0.8,
  release: 1.2,
  vibrato_cents: 6.0,
  vibrato_delay: 0.5,
  ..CHOIR_AAHS
};

// Pad 7 (halo): "oo" voices with an octave above, bright and airy.
const HALO_PAD: ChoirSpec = ChoirSpec {
  singers: &[
    rank(0.0, 0, 1.0),
    rank(8.0, 0, 0.8),
    rank(-6.0, 1, 0.5),
    rank(5.0, 1, 0.4),
  ],
  low: OO_LOW,
  high: OO_HIGH,
  brightness: 3_500.0,
  breath: 0.25,
  stagger: 0.15,
  attack: 0.6,
  release: 1.5,
  vibrato_cents: 4.0,
  vibrato_delay: 0.6,
  ..CHOIR_AAHS
};

// ---- free reeds (see `synth::reed`) --------------------------------------

// Musette accordion: three 8' reeds, one in tune and two a little flat and
// sharp, beating against each other — the "wet" French tuning.
const ACCORDION: FreeReedSpec = FreeReedSpec {
  reeds: &[rank(-14.0, 0, 0.8), rank(0.0, 0, 1.0), rank(13.0, 0, 0.8)],
  slot: 0.45,
  asym: 0.5,
  dynamics: 0.6,
  attack: 0.04,
  release: 0.06,
  noise: 0.02,
  tone: 5_500.0,
  formants: &[
    Formant {
      hz: 1_200.0,
      q: 1.0,
      db: 4.0,
    },
    Formant {
      hz: 3_000.0,
      q: 2.0,
      db: 3.0,
    },
  ],
  vibrato_hz: 0.0,
  vibrato_cents: 0.0,
  tremolo: 0.0,
  level: 1.0,
};

// Harmonica: one reed per hole, played into the player's mouth, whose
// cavity is a strong resonance; breathy, with a little hand tremolo.
const HARMONICA: FreeReedSpec = FreeReedSpec {
  reeds: &[rank(0.0, 0, 1.0)],
  slot: 0.55,
  asym: 0.25,
  dynamics: 0.8,
  attack: 0.03,
  release: 0.05,
  noise: 0.06,
  tone: 4_500.0,
  formants: &[
    Formant {
      hz: 900.0,
      q: 1.5,
      db: 6.0,
    },
    Formant {
      hz: 2_200.0,
      q: 2.0,
      db: 4.0,
    },
  ],
  vibrato_hz: 5.0,
  vibrato_cents: 6.0,
  tremolo: 0.15,
  level: 1.0,
};

// Tango accordion (bandoneon): dry octave-paired reeds, darker and breathier.
const BANDONEON: FreeReedSpec = FreeReedSpec {
  reeds: &[rank(0.0, 0, 1.0), rank(3.0, 1, 0.55)],
  slot: 0.35,
  asym: 0.6,
  dynamics: 0.7,
  attack: 0.06,
  release: 0.08,
  noise: 0.03,
  tone: 3_500.0,
  formants: &[Formant {
    hz: 700.0,
    q: 1.0,
    db: 4.0,
  }],
  ..ACCORDION
};

// Reed organ (harmonium): large reed cells, foot-pumped — mellow, steady,
// with a céleste rank tuned a few cents sharp.
const REED_ORGAN: FreeReedSpec = FreeReedSpec {
  reeds: &[rank(0.0, 0, 1.0), rank(4.0, 0, 0.6)],
  slot: 0.3,
  asym: 0.7,
  dynamics: 0.3,
  attack: 0.08,
  release: 0.12,
  noise: 0.015,
  tone: 2_500.0,
  formants: &[Formant {
    hz: 500.0,
    q: 0.8,
    db: 3.0,
  }],
  ..ACCORDION
};

// ---- synth stacks ---------------------------------------------------------

const SYNTH_BASS2_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Square, 0.0, 0.6),
  OscSpec::at(Wave::Sine, 0.0, 0.7, -1),
];

const SYNTH_STRINGS2_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Square, -14.0, 0.5),
  OscSpec::new(Wave::Square, 14.0, 0.5),
  OscSpec::at(Wave::Saw, 0.0, 0.3, -1),
];

// Orchestra hit: strings and brass stacked over three octaves with an open
// fifth, a drum thump and a burst of noise — the sampled tutti chord. The
// bright upper octave dies faster than the body, as the sample's does.
const ORCH_HIT_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -8.0, 0.6),
  OscSpec::new(Wave::Saw, 8.0, 0.6),
  OscSpec::at(Wave::Saw, 0.0, 0.5, -1),
  OscSpec::at(Wave::Saw, 702.0, 0.35, 0),
  OscSpec::perc(Wave::Square, 3.0, 0.4, 1, 0.6),
  OscSpec::perc(Wave::Sine, 0.0, 0.8, -2, 0.3),
  OscSpec::perc(Wave::Noise, 0.0, 0.5, 0, 0.1),
];

const SYNTH_BRASS_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -6.0, 0.5),
  OscSpec::new(Wave::Saw, 6.0, 0.5),
];

const SYNTH_BRASS2_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Square, -4.0, 0.5),
  OscSpec::new(Wave::Saw, 4.0, 0.5),
];

// Calliope: steam whistles — round, breathy, with a quick vibrato.
const CALLIOPE_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Triangle, 0.0, 1.0),
  OscSpec::at(Wave::Sine, 0.0, 0.3, 1),
  OscSpec::new(Wave::Noise, 0.0, 0.12),
];

// Chiff lead: a hollow square with a burst of air as each note speaks.
const CHIFF_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Square, 0.0, 0.7),
  OscSpec::at(Wave::Triangle, 0.0, 0.3, 1),
  OscSpec::perc(Wave::Noise, 0.0, 0.6, 0, 0.05),
];

const CHARANG_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, 0.0, 1.0),
  OscSpec::at(Wave::Saw, 5.0, 0.3, 1),
];

const BASS_LEAD_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, 0.0, 1.0),
  OscSpec::at(Wave::Square, 0.0, 0.8, -1),
];

const WARM_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -7.0, 0.5),
  OscSpec::new(Wave::Saw, 7.0, 0.5),
  OscSpec::at(Wave::Triangle, 0.0, 0.4, -1),
];

const POLY_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -5.0, 0.5),
  OscSpec::new(Wave::Square, 5.0, 0.5),
];

const BRIGHT_OSC: &[OscSpec] = &[
  OscSpec::new(Wave::Saw, -6.0, 0.5),
  OscSpec::new(Wave::Saw, 6.0, 0.5),
  OscSpec::at(Wave::Saw, 0.0, 0.4, 1),
];

// Pad 5 (bowed): the string section with long, light, sul tasto bows.
const BOWED_PAD: BowSpec = BowSpec {
  attack: 0.7,
  release: 1.0,
  pressure: 0.65,
  brightness: 8.0,
  vibrato_cents: 5.0,
  vibrato_delay: 0.6,
  ..STRING_ENSEMBLE
};

const fn filter_lfo(rate: f32, depth: f32) -> Option<LfoSpec> {
  Some(LfoSpec {
    rate,
    depth,
    target: LfoTarget::Filter,
    delay: 0.0,
  })
}

const fn amp_lfo(rate: f32, depth: f32) -> Option<LfoSpec> {
  Some(LfoSpec {
    rate,
    depth,
    target: LfoTarget::Amp,
    delay: 0.0,
  })
}

const LESLIE_SLOW: LeslieSpec = LeslieSpec { fast: false };
const LESLIE_FAST: LeslieSpec = LeslieSpec { fast: true };

// ---- patch table ---------------------------------------------------------

pub fn gm_patch(program: u8) -> Patch {
  let prog = program.min(127);
  PATCHES[prog as usize]
}

/// General MIDI program name for a 0-based program number (clamped to 0..=127).
pub fn gm_program_name(program: u8) -> &'static str {
  GM_NAMES[program.min(127) as usize]
}

#[rustfmt::skip]
static GM_NAMES: [&str; 128] = [
  // 0-7 Piano
  "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano",
  "Honky-tonk Piano", "Electric Piano 1", "Electric Piano 2", "Harpsichord",
  "Clavinet",
  // 8-15 Chromatic Percussion
  "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone",
  "Tubular Bells", "Dulcimer",
  // 16-23 Organ
  "Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ",
  "Reed Organ", "Accordion", "Harmonica", "Tango Accordion",
  // 24-31 Guitar
  "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  "Electric Guitar (clean)", "Electric Guitar (muted)", "Overdriven Guitar",
  "Distortion Guitar", "Guitar Harmonics",
  // 32-39 Bass
  "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2",
  // 40-47 Strings
  "Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings",
  "Pizzicato Strings", "Orchestral Harp", "Timpani",
  // 48-55 Ensemble
  "String Ensemble 1", "String Ensemble 2", "Synth Strings 1",
  "Synth Strings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit",
  // 56-63 Brass
  "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section",
  "Synth Brass 1", "Synth Brass 2",
  // 64-71 Reed
  "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn",
  "Bassoon", "Clarinet",
  // 72-79 Pipe
  "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi",
  "Whistle", "Ocarina",
  // 80-87 Synth Lead
  "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass + lead)",
  // 88-95 Synth Pad
  "Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)",
  "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)",
  // 96-103 Synth Effects
  "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)",
  "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  // 104-111 Ethnic
  "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle",
  "Shanai",
  // 112-119 Percussive
  "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum",
  "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  // 120-127 Sound Effects
  "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet",
  "Telephone Ring", "Helicopter", "Applause", "Gunshot",
];

static PATCHES: [Patch; 128] = build_patches();

const fn build_patches() -> [Patch; 128] {
  let mut out = [DEFAULT_PATCH; 128];
  let mut i = 0;
  while i < 128 {
    out[i] = patch_for(i as u8);
    i += 1;
  }
  out
}

const DEFAULT_PATCH: Patch = p(
  TRI,
  EnvSpec::adsr(0.005, 0.4, 0.3, 0.3),
  lp(4_000.0, 0.7, 0.5, 0.0),
  None,
  None,
  0.7,
);

const fn patch_for(prog: u8) -> Patch {
  match prog {
    // 0..7 — Pianos
    0 => piano(0.29, PIANO_GRAND),
    1 => piano(0.29, PIANO_BRIGHT),
    2 => piano(0.40, PIANO_ELECTRIC_GRAND),
    3 => piano(0.46, PIANO_HONKY_TONK),
    4 => modal(0.45, EP_RHODES),
    5 => modal(0.75, EP_FM),
    6 => plucked(
      // harpsichord: physically modelled plucked string (Karplus-Strong)
      HARPSI_OSC,
      0.9,
      PLUCK_HARPSI,
    ),
    7 => plucked(SAW, 2.0, PLUCK_CLAV)
      .with_filter(Some(FilterSpec {
        mode: FilterMode::Band,
        cutoff: 1_100.0,
        res: 0.6,
        key_track: 0.5,
        env_amount: 0.0,
        vel_track: 0.0,
      }))
      .with_drive(1.5),

    // 8..15 — Chromatic percussion
    8 => modal(0.7, CELESTA),
    9 => modal(0.6, GLOCKENSPIEL),
    10 => modal(0.78, MUSIC_BOX),
    11 => modal(0.7, VIBRAPHONE),
    12 => modal(1.2, MARIMBA),
    13 => modal(1.2, XYLOPHONE),
    14 => modal(0.75, TUBULAR_BELLS),
    15 => plucked(TRI, 1.3, PLUCK_DULCIMER),

    // 16..23 — Organs. The tonewheel organs play through a Leslie cabinet
    // (chorale for 16/17, tremolo for 18; the mod wheel switches to fast).
    16 => p(
      DRAWBAR_OSC,
      EnvSpec::adsr(0.005, 0.05, 1.0, 0.03),
      None,
      None,
      None,
      0.48,
    )
    .with_leslie(LESLIE_SLOW),
    17 => p(
      PERC_ORGAN_OSC,
      EnvSpec::adsr(0.003, 0.05, 1.0, 0.02),
      None,
      None,
      None,
      0.6,
    )
    .with_leslie(LESLIE_SLOW),
    18 => p(
      ROCK_ORGAN_OSC,
      EnvSpec::adsr(0.005, 0.05, 1.0, 0.03),
      lp(5_000.0, 0.7, 0.0, 0.0), // speaker roll-off
      None,
      None,
      0.33,
    )
    .with_drive(3.0)
    .with_leslie(LESLIE_FAST),
    19 => p(
      CHURCH_ORGAN_OSC,
      EnvSpec::adsr(0.06, 0.1, 1.0, 0.25),
      lp(4_500.0, 0.7, 0.3, 0.0),
      None,
      None,
      0.8,
    ),
    20 => reed(0.45, REED_ORGAN),
    21 => reed(0.4, ACCORDION),
    22 => reed(0.45, HARMONICA),
    23 => reed(0.45, BANDONEON),

    // 24..31 — Guitars (Karplus-Strong strings)
    24 => {
      plucked(TRI, 1.0, PLUCK_NYLON).with_filter(lp(3_500.0, 0.7, 0.5, 0.0))
    }
    25 => {
      plucked(TRI, 0.9, PLUCK_STEEL).with_filter(lp(6_000.0, 0.7, 0.5, 0.0))
    }
    26 => plucked(SAW, 0.8, PLUCK_JAZZ)
      .with_filter(lp(2_200.0, 0.9, 0.0, 0.0))
      .with_drive(1.2),
    27 => {
      plucked(SAW, 0.9, PLUCK_CLEAN).with_filter(lp(4_500.0, 1.4, 0.0, 0.0))
    }
    28 => plucked(SAW, 1.4, PLUCK_MUTED)
      .with_filter(lp(2_500.0, 0.9, 0.0, 0.0))
      .with_drive(1.5),
    29 => plucked(SAW, 0.45, PLUCK_DRIVEN)
      .with_filter(lp(4_000.0, 1.0, 0.0, 0.0))
      .with_drive(6.0),
    30 => plucked(SAW, 0.35, PLUCK_DRIVEN)
      .with_filter(lp(3_500.0, 1.2, 0.0, 0.0))
      .with_drive(18.0),
    31 => {
      plucked(SAW, 0.9, PLUCK_HARMONICS).with_filter(lp(5_000.0, 0.8, 0.0, 0.0))
    }

    // 32..39 — Bass (32–37 Karplus-Strong strings)
    32 => {
      plucked(TRI, 0.85, PLUCK_UPRIGHT).with_filter(lp(1_100.0, 0.9, 0.0, 0.0))
    }
    33 => {
      plucked(TRI, 0.9, PLUCK_FINGER).with_filter(lp(1_400.0, 1.6, 0.0, 0.0))
    }
    34 => plucked(SAW, 1.8, PLUCK_PICK)
      .with_filter(lp(3_500.0, 1.0, 0.0, 0.0))
      .with_drive(1.2),
    35 => {
      plucked(TRI, 1.0, PLUCK_FRETLESS).with_filter(lp(1_000.0, 2.4, 0.0, 0.0))
    }
    36 => plucked(SAW, 2.0, PLUCK_SLAP)
      .with_filter(lp(5_000.0, 0.8, 0.0, 0.0))
      .with_drive(1.5),
    37 => plucked(SAW, 1.6, PLUCK_POP)
      .with_filter(lp(6_000.0, 1.2, 0.0, 0.0))
      .with_drive(2.0),
    // Synth bass 1: a resonant saw whose filter snaps open on each note.
    38 => p(
      SAW,
      EnvSpec::adsr(0.003, 0.3, 0.5, 0.08),
      lpv(300.0, 3.0, 0.3, 0.9, 1.0),
      None,
      None,
      0.7,
    ),
    // Synth bass 2: square over a sub-octave sine, round and heavy.
    39 => p(
      SYNTH_BASS2_OSC,
      EnvSpec::adsr(0.005, 0.5, 0.6, 0.1),
      lpv(900.0, 1.0, 0.3, 0.3, 0.8),
      None,
      None,
      0.75,
    ),

    // 40..47 — Solo strings
    40 => bowed(0.74, VIOLIN),
    41 => bowed(1.27, VIOLA),
    42 => bowed(1.35, CELLO),
    43 => bowed(1.35, CONTRABASS),
    44 => bowed(1.4, TREMOLO_STRINGS),
    45 => plucked(TRI, 0.77, PLUCK_PIZZICATO)
      .with_filter(lp(2_500.0, 0.8, 0.5, 0.0)),
    46 => plucked(TRI, 0.67, PLUCK_HARP),
    47 => modal(1.06, TIMPANI),

    // 48..55 — Ensemble
    48 => bowed(0.63, STRING_ENSEMBLE),
    49 => bowed(0.82, SLOW_STRINGS),
    50 => p(
      // synth strings 1: bright detuned saws
      ENS_OSC,
      EnvSpec::adsr(0.08, 0.5, 0.85, 0.4),
      lpv(4_000.0, 0.8, 0.5, 0.0, 0.6),
      vibrato(5.5, 0.01, 0.3),
      None,
      0.55,
    ),
    51 => p(
      // synth strings 2: slow, dark, wide pulse ensemble
      SYNTH_STRINGS2_OSC,
      EnvSpec::adsr(0.35, 0.8, 0.8, 0.8),
      lpv(2_000.0, 0.9, 0.5, 0.2, 0.5),
      vibrato(4.5, 0.008, 0.5),
      None,
      0.55,
    ),
    52 => choir(0.7, CHOIR_AAHS),
    53 => choir(0.7, VOICE_OOHS),
    54 => choir(0.7, SYNTH_VOICE),
    55 => p(
      // Rings out for about a second whatever the note length (a hit is a
      // one-shot sample); the filter starts wide open and closes with it.
      ORCH_HIT_OSC,
      EnvSpec::adsr(0.002, 1.6, 0.0, 1.2),
      lpv(3_000.0, 0.8, 0.3, 1.0, 0.6),
      None,
      None,
      0.8,
    ),

    // 56..63 — Brass
    56 => wind(1.02, TRUMPET),
    57 => wind(1.06, TROMBONE),
    58 => wind(1.06, TUBA),
    // Harmon mute: the bell is plugged, leaving a thin, nasal buzz.
    59 => wind(1.36, TRUMPET).with_filter(Some(FilterSpec {
      mode: FilterMode::Band,
      cutoff: 1_800.0,
      res: 1.5,
      key_track: 0.3,
      env_amount: 0.0,
      vel_track: 0.0,
    })),
    60 => wind(0.46, FRENCH_HORN),
    61 => wind(1.07, BRASS_SECTION),
    62 => p(
      // synth brass 1: the filter swells open and settles
      SYNTH_BRASS_OSC,
      EnvSpec::adsr(0.03, 0.3, 0.75, 0.15),
      lpv(900.0, 1.3, 0.5, 0.8, 1.0),
      None,
      None,
      0.6,
    ),
    63 => p(
      // synth brass 2: softer and slower
      SYNTH_BRASS2_OSC,
      EnvSpec::adsr(0.08, 0.4, 0.8, 0.25),
      lpv(1_400.0, 0.9, 0.5, 0.4, 0.7),
      None,
      None,
      0.55,
    ),

    // 64..71 — Reed
    64 => wind(0.63, SOPRANO_SAX),
    65 => wind(0.65, ALTO_SAX),
    66 => wind(0.73, TENOR_SAX),
    67 => wind(0.83, BARITONE_SAX),
    68 => wind(0.99, OBOE),
    69 => wind(0.77, ENGLISH_HORN),
    70 => wind(1.43, BASSOON),
    71 => wind(1.02, CLARINET),

    // 72..79 — Pipe
    72 => wind(0.98, PICCOLO),
    73 => wind(0.98, FLUTE),
    74 => wind(0.98, RECORDER),
    75 => wind(0.99, PAN_FLUTE),
    76 => wind(1.23, BLOWN_BOTTLE),
    77 => wind(1.17, SHAKUHACHI),
    78 => wind(1.11, WHISTLE),
    79 => wind(1.2, OCARINA),

    // 80..87 — Synth lead
    80 => p(
      // square lead
      SQR,
      EnvSpec::adsr(0.005, 0.1, 0.9, 0.1),
      lpv(3_000.0, 0.9, 0.5, 0.0, 0.8),
      None,
      None,
      0.6,
    ),
    81 => p(
      // saw lead
      SAW,
      EnvSpec::adsr(0.005, 0.1, 0.9, 0.1),
      lpv(3_500.0, 0.9, 0.5, 0.0, 0.8),
      None,
      None,
      0.6,
    ),
    82 => p(
      CALLIOPE_OSC,
      EnvSpec::adsr(0.02, 0.1, 0.9, 0.15),
      lp(3_500.0, 0.7, 0.5, 0.0),
      vibrato(6.0, 0.012, 0.1),
      None,
      0.55,
    ),
    83 => p(
      CHIFF_OSC,
      EnvSpec::adsr(0.005, 0.2, 0.8, 0.15),
      lpv(2_500.0, 1.0, 0.5, 0.3, 0.8),
      vibrato(5.5, 0.01, 0.4),
      None,
      0.55,
    ),
    84 => p(
      // charang: an overdriven, guitar-like saw
      CHARANG_OSC,
      EnvSpec::adsr(0.003, 0.3, 0.8, 0.2),
      lpv(3_000.0, 1.2, 0.3, 0.3, 0.8),
      None,
      None,
      0.45,
    )
    .with_drive(4.0),
    85 => choir(0.75, VOICE_LEAD),
    86 => p(
      // fifths
      FIFTHS_OSC,
      EnvSpec::adsr(0.01, 0.2, 0.85, 0.15),
      lpv(2_500.0, 1.0, 0.5, 0.0, 0.8),
      None,
      None,
      0.55,
    ),
    87 => p(
      // bass + lead: saw over a square an octave down, resonant
      BASS_LEAD_OSC,
      EnvSpec::adsr(0.005, 0.3, 0.7, 0.15),
      lpv(1_500.0, 2.0, 0.4, 0.6, 1.0),
      None,
      None,
      0.55,
    ),

    // 88..95 — Synth pad
    88 => p(
      // new age: a glassy FM bell inside a soft pad
      SINE,
      EnvSpec::adsr(0.05, 2.0, 0.6, 1.5),
      lp(5_000.0, 0.7, 0.3, 0.0),
      vibrato(4.0, 0.003, 0.5),
      Some(FmSpec::new(35, 20)),
      0.5,
    ),
    89 => p(
      // warm
      WARM_OSC,
      EnvSpec::adsr(0.5, 1.0, 0.85, 1.2),
      lpv(1_100.0, 0.8, 0.4, 0.2, 0.5),
      vibrato(4.0, 0.004, 0.5),
      None,
      0.55,
    ),
    90 => p(
      // polysynth: brassy, with a decaying filter sweep
      POLY_OSC,
      EnvSpec::adsr(0.01, 0.6, 0.6, 0.4),
      lpv(1_200.0, 1.5, 0.4, 0.7, 1.0),
      None,
      None,
      0.5,
    ),
    91 => choir(0.7, CHOIR_PAD),
    92 => bowed(0.75, BOWED_PAD),
    93 => p(
      // metallic: inharmonic FM
      SINE,
      EnvSpec::adsr(0.3, 1.5, 0.7, 1.5),
      lp(4_000.0, 0.8, 0.3, 0.0),
      None,
      Some(FmSpec::new(14, 30)),
      0.5,
    ),
    94 => choir(0.7, HALO_PAD),
    95 => p(
      // sweep: a resonant filter slowly opening and closing
      PAD_OSC,
      EnvSpec::adsr(0.6, 1.0, 0.8, 1.0),
      lpv(1_200.0, 2.5, 0.3, 0.0, 0.3),
      filter_lfo(0.15, 1_500.0),
      None,
      0.5,
    ),

    // 96..103 — Synth FX
    96 => p(
      // rain: glassy FM droplets shimmering
      SINE,
      EnvSpec::adsr(0.005, 0.8, 0.3, 1.0),
      lpv(6_000.0, 0.8, 0.3, 0.0, 0.5),
      amp_lfo(7.0, 0.3),
      Some(FmSpec::new(70, 15)),
      0.5,
    ),
    97 => p(
      // soundtrack: dark, slow pad
      PAD_OSC,
      EnvSpec::adsr(1.2, 2.0, 0.75, 2.0),
      lp(1_400.0, 1.0, 0.4, 0.3),
      filter_lfo(0.2, 250.0),
      None,
      0.5,
    ),
    98 => p(
      // crystal
      CRYSTAL_OSC,
      EnvSpec::adsr(0.005, 1.5, 0.4, 1.0),
      lp(3_000.0, 1.0, 0.5, 0.0),
      None,
      Some(FmSpec::new(30, 30)),
      0.55,
    ),
    99 => p(
      // atmosphere: a plucked FM tone that blooms into a pad
      SINE,
      EnvSpec::adsr(0.01, 2.5, 0.5, 1.5),
      lp(3_000.0, 0.8, 0.4, 0.3),
      vibrato(4.5, 0.003, 0.4),
      Some(FmSpec::new(20, 15)),
      0.55,
    ),
    100 => p(
      // brightness
      BRIGHT_OSC,
      EnvSpec::adsr(0.3, 1.0, 0.8, 1.0),
      lpv(6_000.0, 1.0, 0.5, 0.0, 0.5),
      vibrato(5.0, 0.003, 0.3),
      None,
      0.45,
    ),
    101 => p(
      // goblins: a slow, wobbling resonance
      PAD_OSC,
      EnvSpec::adsr(1.5, 1.0, 0.8, 1.5),
      lp(900.0, 4.0, 0.0, 0.0),
      filter_lfo(0.4, 600.0),
      None,
      0.5,
    ),
    102 => p(
      // echoes: pulsing repeats
      PAD_OSC,
      EnvSpec::adsr(0.01, 1.5, 0.5, 2.0),
      lp(2_500.0, 1.0, 0.5, 0.3),
      amp_lfo(2.5, 0.7),
      None,
      0.5,
    ),
    103 => p(
      // sci-fi: FM with a slow pitch wobble
      SINE,
      EnvSpec::adsr(0.3, 1.0, 0.7, 1.5),
      lp(3_500.0, 1.0, 0.3, 0.0),
      Some(LfoSpec {
        rate: 0.5,
        depth: 0.1,
        target: LfoTarget::Pitch,
        delay: 0.0,
      }),
      Some(FmSpec::new(15, 40)),
      0.45,
    ),

    // 104..111 — Ethnic
    104 => {
      plucked(SAW, 0.89, PLUCK_SITAR).with_filter(lp(5_000.0, 0.8, 0.0, 0.0))
    }
    105 => {
      plucked(SAW, 0.89, PLUCK_BANJO).with_filter(lp(4_500.0, 1.8, 0.0, 0.0))
    }
    106 => {
      plucked(SAW, 1.38, PLUCK_SHAMISEN).with_filter(lp(4_000.0, 1.2, 0.0, 0.0))
    }
    107 => {
      plucked(TRI, 0.93, PLUCK_KOTO).with_filter(lp(4_000.0, 0.9, 0.0, 0.0))
    }
    108 => modal(0.75, KALIMBA),
    109 => wind(0.34, BAGPIPE),
    110 => bowed(1.5, FIDDLE),
    111 => wind(1.05, SHANAI),

    // 112..119 — Percussive
    112 => modal(1.5, TINKLE_BELL),
    113 => modal(1.29, AGOGO),
    114 => modal(1.18, STEEL_DRUM),
    115 => modal(1.08, WOODBLOCK),
    116 => modal(0.88, TAIKO),
    117 => modal(1.17, MELODIC_TOM),
    118 => fx(1.0, FxKind::SynthDrum),
    119 => fx(0.6, FxKind::ReverseCymbal),

    // 120..127 — Sound FX
    120 => fx(0.9, FxKind::FretNoise),
    121 => fx(0.5, FxKind::BreathNoise),
    122 => fx(1.8, FxKind::Seashore),
    123 => fx(0.8, FxKind::BirdTweet),
    124 => fx(1.0, FxKind::Telephone),
    125 => fx(0.8, FxKind::Helicopter),
    126 => fx(0.8, FxKind::Applause),
    _ => fx(1.0, FxKind::Gunshot),
  }
}

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

  #[test]
  fn every_program_has_a_patch() {
    for prog in 0u8..128 {
      let pa = gm_patch(prog);
      assert!(!pa.oscs.is_empty(), "program {prog} has no oscillators");
      assert!(pa.gain > 0.0, "program {prog} has zero gain");
    }
  }
}

#[cfg(test)]
mod sound_tests {
  use crate::synth::Synth;

  const SR: f32 = 44_100.0;

  /// Render one note of `program` (held for `hold` s) and return the mono mix.
  fn render(
    program: u8,
    note: u8,
    velocity: u8,
    hold: f32,
    len: f32,
  ) -> Vec<f32> {
    let mut s = Synth::new(SR);
    s.channels[0].reverb = 0.0;
    s.program_change(0, program);
    s.note_on(0, note, velocity);
    let mut out = Vec::new();
    let block = 512;
    let mut buf = vec![0.0f32; block * 2];
    let total = (len * SR) as usize;
    let off = (hold * SR) as usize;
    let mut n = 0;
    while n < total {
      if n <= off && off < n + block {
        s.note_off(0, note);
      }
      s.render(&mut buf);
      out.extend(buf.chunks(2).map(|f| 0.5 * (f[0] + f[1])));
      n += block;
    }
    out
  }

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

  /// Power-weighted mean frequency, from the first difference: a sine at f
  /// has rms(diff)/rms(x) = 2·sin(π·f/sr).
  fn mean_freq(x: &[f32]) -> f32 {
    let d: Vec<f32> = x.windows(2).map(|w| w[1] - w[0]).collect();
    let r = (rms(&d) / rms(x).max(1e-9) / 2.0).min(1.0);
    r.asin() * SR / std::f32::consts::PI
  }

  /// Level (dB re the strongest) of the half-harmonics k·f/2, k = 1..=16, of
  /// a held note — catches sub-octave (16') ranks as well as overtones.
  fn harmonic_profile(program: u8, note: u8) -> Vec<f32> {
    let x = render(program, note, 100, 1.0, 0.6);
    let seg = &x[(0.1 * SR) as usize..(0.5 * SR) as usize];
    let f0 = 440.0 * 2f32.powf((note as f32 - 69.0) / 12.0);
    let mags: Vec<f32> = (1..=16)
      .map(|k| {
        let w = std::f32::consts::TAU * f0 * k as f32 / 2.0 / SR;
        let (mut re, mut im) = (0.0f32, 0.0f32);
        for (i, v) in seg.iter().enumerate() {
          let ph = w * i as f32;
          re += v * ph.cos();
          im += v * ph.sin();
        }
        (re * re + im * im).sqrt()
      })
      .collect();
    let max = mags.iter().cloned().fold(1e-12, f32::max);
    mags
      .iter()
      .map(|m| (20.0 * (m / max).log10()).max(-60.0))
      .collect()
  }

  fn profile_distance(a: u8, b: u8) -> f32 {
    let (pa, pb) = (harmonic_profile(a, 60), harmonic_profile(b, 60));
    pa.iter().zip(&pb).map(|(x, y)| (x - y).abs()).sum::<f32>()
      / pa.len() as f32
  }

  #[test]
  fn mallets_are_not_shrill() {
    // Celesta, glockenspiel, vibraphone, marimba, xylophone at C6, ff: the
    // sound's power-weighted mean frequency stays near the fundamental
    // (1047 Hz) rather than up in the ear's most sensitive 2–5 kHz band.
    for prog in [8u8, 9, 11, 12, 13] {
      let x = render(prog, 84, 127, 0.5, 0.5);
      let f = mean_freq(&x);
      assert!(f < 1_500.0, "program {prog}: mean frequency {f:.0} Hz");
    }
  }

  #[test]
  fn electric_pianos_differ() {
    let d = profile_distance(4, 5);
    assert!(
      d > 4.0,
      "EP1 and EP2 harmonic profiles differ by only {d:.1} dB"
    );
  }

  #[test]
  fn organs_differ() {
    for a in 16u8..=20 {
      for b in a + 1..=20 {
        let d = profile_distance(a, b);
        assert!(d > 4.0, "organs {a} and {b} differ by only {d:.1} dB");
      }
    }
  }

  #[test]
  fn saxophones_differ() {
    // Same reed and bore model; the body resonances must set them apart.
    for a in 64u8..=67 {
      for b in a + 1..=67 {
        let d = profile_distance(a, b);
        assert!(d > 3.0, "saxophones {a} and {b} differ by only {d:.1} dB");
      }
    }
  }

  #[test]
  fn oboe_is_reedy_and_english_horn_darker() {
    // A narrow double-reed bore radiates its fundamental poorly: in the low
    // register the 2nd–4th harmonics carry the tone.
    let x = render(68, 62, 90, 1.0, 1.0);
    let seg = &x[(0.35 * SR) as usize..(0.95 * SR) as usize];
    let f = 440.0 * 2f32.powf((62.0 - 69.0) / 12.0);
    let h = harmonics_db(seg, f, 4);
    assert!(
      h[0] < h[1].max(h[2]).max(h[3]) - 3.0,
      "oboe D4 fundamental dominates: {h:?}"
    );
    let bright = |prog| {
      let x = render(prog, 64, 90, 1.0, 1.0);
      mean_freq(&x[(0.35 * SR) as usize..(0.95 * SR) as usize])
    };
    let (oboe, horn) = (bright(68), bright(69));
    assert!(
      horn < 0.85 * oboe,
      "English horn {horn:.0} Hz vs oboe {oboe:.0} Hz"
    );
  }

  #[test]
  fn tubular_bell_strike_tone_partials() {
    // The note's pitch is the strike tone, implied by modes near 2, 3 and 4
    // times it — those must dominate the actual fundamental.
    let p = harmonic_profile(14, 72);
    let (h2, h4, h6, h8) = (p[1], p[3], p[5], p[7]);
    assert!(h4 > h2 + 6.0, "2·f0 {h4:.1} dB vs f0 {h2:.1} dB");
    assert!(h6 > h2, "≈3·f0 {h6:.1} dB vs f0 {h2:.1} dB");
    assert!(
      h8 < h4,
      "4·f0 sits at 4.17×, not on the harmonic: {h8:.1} dB"
    );
  }

  #[test]
  fn guitars_ring_and_stay_bright() {
    // Acoustic and clean electric guitars: a string, not a filtered synth
    // tone — still ringing after a second and with real upper partials.
    for prog in [24u8, 25, 27] {
      let x = render(prog, 52, 100, 2.0, 1.5);
      let early = rms(&x[..(0.2 * SR) as usize]);
      let late = rms(&x[(1.0 * SR) as usize..(1.2 * SR) as usize]);
      assert!(late > early * 0.05, "program {prog} died: {early} → {late}");
      let f = mean_freq(&x[..(0.3 * SR) as usize]);
      assert!(f > 500.0, "program {prog} is muffled: {f:.0} Hz");
    }
  }

  /// Fundamental by autocorrelation near `f` (parabolic peak refinement).
  fn pitch_near(x: &[f32], f: f32) -> f32 {
    let p = SR / f;
    let (lo, hi) = ((p * 0.8) as usize, (p * 1.25) as usize + 2);
    let n = x.len() - hi;
    let ac: Vec<f32> = (lo..=hi)
      .map(|lag| (0..n).map(|i| x[i] * x[i + lag]).sum())
      .collect();
    let mut b = 1;
    for i in 1..ac.len() - 1 {
      if ac[i] > ac[b] {
        b = i;
      }
    }
    let (y0, y1, y2) = (ac[b - 1], ac[b], ac[b + 1]);
    let off = 0.5 * (y0 - y2) / (y0 - 2.0 * y1 + y2);
    SR / ((lo + b) as f32 + off)
  }

  /// Level (dB re the strongest) of harmonics 1..=k of `f` in `x`.
  fn harmonics_db(x: &[f32], f: f32, k: usize) -> Vec<f32> {
    let mags: Vec<f32> = (1..=k)
      .map(|h| {
        let w = std::f32::consts::TAU * f * h as f32 / SR;
        let (mut re, mut im) = (0.0f32, 0.0f32);
        for (i, v) in x.iter().enumerate() {
          let win = 0.5
            - 0.5 * (std::f32::consts::TAU * i as f32 / x.len() as f32).cos();
          re += v * win * (w * i as f32).cos();
          im += v * win * (w * i as f32).sin();
        }
        (re * re + im * im).sqrt()
      })
      .collect();
    let max = mags.iter().cloned().fold(1e-12, f32::max);
    mags.iter().map(|m| 20.0 * (m / max).log10()).collect()
  }

  /// Bowed strings and winds oscillate by themselves, so they can fail to
  /// start, lock onto an upper mode or drift off pitch. Across each
  /// instrument's range, soft and loud: they must speak, on the fundamental,
  /// in tune (vibrato averages out over the window).
  #[test]
  fn self_oscillating_instruments_speak_in_tune() {
    let ranges: &[(u8, &[u8])] = &[
      (40, &[55, 74, 93]), // violin
      (41, &[48, 66, 84]), // viola
      (42, &[36, 55, 76]), // cello
      (43, &[28, 43, 60]), // contrabass
      (48, &[36, 62, 91]), // string ensemble
      (92, &[48, 72]),     // bowed pad
      (110, &[55, 91]),    // fiddle
      (56, &[55, 82]),     // trumpet
      (57, &[40, 72]),     // trombone
      (58, &[29, 58]),     // tuba
      (60, &[36, 77]),     // horn
      (61, &[45, 79]),     // brass section
      (64, &[57, 87]),     // soprano sax
      (65, &[49, 81]),     // alto sax
      (66, &[44, 76]),     // tenor sax
      (67, &[36, 69]),     // baritone sax
      (68, &[58, 91]),     // oboe
      (69, &[52, 81]),     // English horn
      (70, &[34, 75]),     // bassoon
      (71, &[50, 91]),     // clarinet
      (109, &[55, 74]),    // bagpipe
      (111, &[60, 84]),    // shanai
      (72, &[74, 100]),    // piccolo
      (73, &[60, 96]),     // flute
      (74, &[65, 98]),     // recorder
      (75, &[60, 96]),     // pan flute
      (76, &[60, 84]),     // blown bottle
      (77, &[55, 88]),     // shakuhachi
      (78, &[74, 100]),    // whistle
      (79, &[60, 89]),     // ocarina
    ];
    for &(prog, notes) in ranges {
      for &note in notes {
        for vel in [35u8, 120] {
          let x = render(prog, note, vel, 1.0, 1.0);
          let seg = &x[(0.35 * SR) as usize..(0.95 * SR) as usize];
          let f = 440.0 * 2f32.powf((note as f32 - 69.0) / 12.0);
          let tag = format!("program {prog} note {note} vel {vel}");
          assert!(rms(seg) > 1e-4, "{tag}: silent ({})", rms(seg));
          let cents = 1200.0 * (pitch_near(seg, f) / f).log2();
          assert!(cents.abs() < 12.0, "{tag}: {cents:+.1} cents");
          // On its fundamental. The fundamental itself may be weak (a low
          // oboe radiates it poorly), so look at what an upper register
          // removes: an octave up leaves no odd harmonics, a twelfth up
          // none of the first two.
          let h = harmonics_db(seg, f, 6);
          let odd = h[0].max(h[2]).max(h[4]);
          assert!(odd > -15.0, "{tag}: octave up ({h:?})");
          assert!(h[0].max(h[1]) > -15.0, "{tag}: twelfth up ({h:?})");
        }
      }
    }
  }

  /// Programs that used to share one patch must now sound different.
  #[test]
  fn former_duplicates_differ() {
    let mut pairs = vec![
      (21u8, 22u8),
      (21, 23),
      (20, 21),
      (38, 39),
      (50, 51),
      (52, 53),
      (52, 54),
      (82, 83),
      (84, 85),
      (86, 87),
      (96, 97),
      (98, 99),
      (100, 101),
      (102, 103),
    ];
    for a in 88u8..=95 {
      for b in a + 1..=95 {
        pairs.push((a, b));
      }
    }
    for (a, b) in pairs {
      let d = profile_distance(a, b);
      assert!(d > 3.0, "programs {a} and {b} differ by only {d:.1} dB");
    }
  }

  /// Choirs and free reeds speak on their note.
  #[test]
  fn choirs_and_free_reeds_are_in_tune() {
    for prog in [20u8, 21, 22, 23, 52, 53, 54, 85] {
      for note in [48u8, 69] {
        let x = render(prog, note, 90, 1.0, 1.0);
        let seg = &x[(0.4 * SR) as usize..(0.95 * SR) as usize];
        let f = 440.0 * 2f32.powf((note as f32 - 69.0) / 12.0);
        let cents = 1200.0 * (pitch_near(seg, f) / f).log2();
        assert!(rms(seg) > 1e-3, "program {prog} note {note}: silent");
        assert!(
          cents.abs() < 15.0,
          "program {prog} note {note}: {cents:+.1} cents"
        );
      }
    }
  }

  /// "Ah" carries more energy around 1 kHz than "ooh".
  #[test]
  fn aahs_are_brighter_than_oohs() {
    let ah = render(52, 57, 90, 1.0, 1.0);
    let oo = render(53, 57, 90, 1.0, 1.0);
    let w = |x: &[f32]| mean_freq(&x[(0.4 * SR) as usize..]);
    assert!(
      w(&ah) > 1.3 * w(&oo),
      "ah {} Hz vs oo {} Hz",
      w(&ah),
      w(&oo)
    );
  }

  /// Synth patches with velocity tracking get brighter when played harder.
  #[test]
  fn synth_filters_follow_velocity() {
    for prog in [38u8, 62, 81, 90] {
      let soft = render(prog, 48, 40, 0.6, 0.5);
      let hard = render(prog, 48, 120, 0.6, 0.5);
      let (fs, fh) = (mean_freq(&soft[2_000..]), mean_freq(&hard[2_000..]));
      assert!(
        fh > 1.3 * fs,
        "program {prog}: soft {fs:.0} Hz, hard {fh:.0} Hz"
      );
    }
  }

  /// Free reeds are brighter when played louder (the bellows pressure
  /// widens the reed's swing past the slot).
  #[test]
  fn accordion_brightens_with_pressure() {
    let soft = render(21, 57, 35, 1.0, 1.0);
    let hard = render(21, 57, 120, 1.0, 1.0);
    let (fs, fh) = (
      mean_freq(&soft[(0.3 * SR) as usize..]),
      mean_freq(&hard[(0.3 * SR) as usize..]),
    );
    assert!(fh > 1.1 * fs, "soft {fs:.0} Hz, hard {fh:.0} Hz");
  }

  #[test]
  fn saxophones_speak_promptly() {
    // Until the reed oscillation builds up, all that sounds is breath noise;
    // a slow build-up is heard as a hiss before every note.
    // Near the bottom and the middle of each saxophone's range.
    for (prog, notes) in [
      (64u8, [57u8, 72]),
      (65, [50, 65]),
      (66, [45, 60]),
      (67, [38, 53]),
    ] {
      for note in notes {
        for vel in [35u8, 100] {
          let x = render(prog, note, vel, 1.0, 1.0);
          let steady = rms(&x[(0.5 * SR) as usize..(0.9 * SR) as usize]);
          let early = rms(&x[(0.06 * SR) as usize..(0.08 * SR) as usize]);
          let db = 20.0 * (early / steady).log10();
          assert!(
            db > -20.0,
            "program {prog} note {note} vel {vel}: {db:.1} dB at 60–80 ms"
          );
        }
      }
    }
  }

  #[test]
  fn self_oscillating_instruments_stop() {
    // After note-off the bow lifts / the breath stops and the instrument
    // rings down to silence; nothing keeps itself going.
    for prog in [40u8, 43, 48, 56, 58, 61, 65, 68, 71, 73, 75, 109] {
      let x = render(prog, 52, 100, 0.5, 4.0);
      let held = rms(&x[(0.3 * SR) as usize..(0.5 * SR) as usize]);
      let tail = rms(&x[(3.5 * SR) as usize..]);
      assert!(tail < held * 1e-3, "program {prog}: {held} → {tail}");
    }
  }

  #[test]
  fn bowed_strings_make_helmholtz_motion() {
    // Stick–slip at the right bow force gives a sawtooth-like string
    // velocity: the fundamental leads and the harmonics fall off gently —
    // not a sine, and not the whistly multiple-slip octave.
    for prog in [40u8, 42, 110] {
      for note in [62u8, 74] {
        let x = render(prog, note, 90, 1.0, 1.0);
        let f = 440.0 * 2f32.powf((note as f32 - 69.0) / 12.0);
        let h =
          harmonics_db(&x[(0.4 * SR) as usize..(0.9 * SR) as usize], f, 4);
        assert!(h[0] > -1.0, "program {prog} note {note}: {h:?}");
        let upper = h[1].max(h[2]).max(h[3]);
        assert!(upper > -20.0, "program {prog} note {note}: {h:?}");
      }
    }
  }

  #[test]
  fn brass_brightens_with_dynamics() {
    for prog in [56u8, 57, 60] {
      let soft =
        mean_freq(&render(prog, 60, 35, 1.0, 0.8)[(0.3 * SR) as usize..]);
      let loud =
        mean_freq(&render(prog, 60, 127, 1.0, 0.8)[(0.3 * SR) as usize..]);
      assert!(
        loud > 1.8 * soft,
        "program {prog}: pp {soft:.0} Hz, ff {loud:.0} Hz"
      );
    }
  }

  #[test]
  fn clarinet_is_odd_and_saxophone_is_not() {
    let f = 440.0 * 2f32.powf((60.0 - 69.0) / 12.0);
    let seg = |p| render(p, 60, 100, 1.0, 1.0)[(0.4 * SR) as usize..].to_vec();
    let cl = harmonics_db(&seg(71), f, 4);
    let sx = harmonics_db(&seg(65), f, 4);
    assert!(
      cl[1] < cl[2] - 15.0,
      "clarinet h2 {:.1} vs h3 {:.1}",
      cl[1],
      cl[2]
    );
    assert!(sx[1] > -15.0, "saxophone h2 {:.1}", sx[1]);
  }

  #[test]
  fn basses_are_plucked_strings() {
    // Acoustic, finger, pick, fretless, slap, pop at E1 and E2: a string, not
    // a held synth tone — a bright attack that darkens, and a decaying level.
    for prog in 32u8..=37 {
      for note in [28u8, 40] {
        let x = render(prog, note, 100, 2.0, 1.5);
        let seg = |a: f32, b: f32| &x[(a * SR) as usize..(b * SR) as usize];
        let (attack, body) =
          (mean_freq(seg(0.0, 0.05)), mean_freq(seg(0.3, 0.5)));
        // The upright's finger pluck is soft: it darkens, but gently.
        let contrast = if prog == 32 { 1.2 } else { 1.5 };
        assert!(
          attack > contrast * body,
          "program {prog} note {note}: attack {attack:.0} Hz vs body {body:.0} Hz"
        );
        let (early, late) = (rms(seg(0.0, 0.3)), rms(seg(1.0, 1.3)));
        assert!(
          late < early * 0.5,
          "program {prog} note {note} does not decay: {early} → {late}"
        );
      }
    }
    // Electric basses (magnetic pickups) keep strong low harmonics; a lone
    // fundamental is the filtered-synth sound this replaces.
    for prog in 33u8..=37 {
      let p = harmonic_profile(prog, 40);
      let (h2, h3) = (p[3], p[5]); // 2·f0, 3·f0 (half-harmonic bins)
      assert!(
        h2 > -12.0 && h3 > -20.0,
        "program {prog}: h2 {h2:.1}, h3 {h3:.1} dB"
      );
    }
  }
}