phosphor-core 0.3.32

Audio engine, mixer, and transport for the Phosphor DAW
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
//! Per-track audio mixer with MIDI recording and clip playback.
//!
//! The mixer owns all audio tracks and processes the track graph:
//! routing MIDI to the active track, recording armed tracks,
//! playing back clips, applying mute/solo/volume, and mixing to master.

use std::sync::Arc;

use crossbeam_channel::{Receiver, Sender};
use phosphor_midi::message::MidiMessage;
use phosphor_plugin::{MidiEvent, Plugin};

use crate::clip::{ClipEvent, ClipSnapshot, MidiClip, RecordBuffer};
use crate::engine::VuLevels;
use crate::metronome::Metronome;
use crate::pattern::{EventSink, PatternBlock, PatternEvent, PatternPlayer, PlaybackWindow};
use crate::project::{TrackHandle, TrackKind};
use crate::transport::Transport;

// ── Commands ──

// Clippy would have `SetPattern` box its block, and boxing it is exactly the
// thing this design exists to avoid: a `Box` arriving on the audio thread is a
// `free` on the audio thread when the command is dropped. The command queue is
// short and the memory is nothing; the deadline is not.
#[allow(clippy::large_enum_variant)]
pub enum MixerCommand {
    AddTrack {
        kind: TrackKind,
        handle: Arc<TrackHandle>,
    },
    SetInstrument {
        track_id: usize,
        instrument: Box<dyn Plugin + Send>,
    },
    RemoveTrack {
        track_id: usize,
    },
    SetParameter {
        track_id: usize,
        param_index: usize,
        value: f32,
    },
    /// Create a new empty clip on a track.
    CreateClip {
        track_id: usize,
        start_tick: i64,
        length_ticks: i64,
    },
    /// Replace a clip's events with edited data from the UI.
    UpdateClip {
        track_id: usize,
        clip_index: usize,
        events: Vec<ClipEvent>,
    },
    /// Update a clip's timeline position and length on the audio thread.
    UpdateClipPosition {
        track_id: usize,
        clip_index: usize,
        start_tick: i64,
        length_ticks: i64,
    },
    /// Remove a clip from a track on the audio thread.
    RemoveClip {
        track_id: usize,
        clip_index: usize,
    },
    /// Give one of a sequencer track's eight pattern slots new contents, and
    /// with it the UI's current word on the track-level settings that ride on
    /// a block — see [`PatternBlock`].
    ///
    /// The block travels by value. It is [`Copy`] and about two and a half
    /// kilobytes, so receiving one is a memcpy into memory that already
    /// exists: no `Vec` to free, no `Box` to drop, nothing for the audio
    /// thread to hand back to the allocator. The first pattern a track is
    /// given allocates its player, exactly as `SetInstrument` allocates a
    /// voice array; every one after it does not.
    SetPattern {
        track_id: usize,
        slot: u8,
        block: PatternBlock,
    },
}

// ── Command budget ──
//
// The audio callback has a hard deadline — 1.45 ms at the default 64 frames,
// 0.73 ms if the device asks for 32 — and applying commands is the one thing
// in it whose size the audio thread does not control. Loading a preset queues
// one command per control, 59 of them on the Odyssey; opening a session
// queues an AddTrack, a SetInstrument and a full parameter block per track,
// plus two commands per clip. Draining all of that in one callback is an
// unbounded amount of work behind a fixed deadline, which is a dropout.
//
// So each callback spends a fixed budget and stops. Nothing is dropped and
// nothing is reordered: what is left stays queued, in order, and the next
// callback continues from there. A burst that does not fit is spread over
// consecutive callbacks — for a session load that is a few milliseconds with
// the transport stopped, and for a preset it is at worst one buffer rendered
// with part of the old panel, which is 1.45 ms.

/// The cost of a command that goes to the allocator. See [`command_cost`].
const HEAVY_COMMAND: u32 = 16;

/// What one command costs, in the units [`COMMAND_BUDGET`] is denominated in.
///
/// Two tiers, and the line between them is the allocator:
///
/// * **1** — writes into memory that already exists. Setting a parameter is a
///   clamp and a store; moving a clip writes two integers.
/// * **[`HEAVY_COMMAND`]** — allocates, frees, or both. `SetInstrument` calls
///   `Plugin::init`, which builds a voice array and, on the Juno, a chorus
///   delay line; `AddTrack` allocates two audio buffers; `RemoveTrack` and
///   `UpdateClip` free what they replace.
///
/// Measured in release on a 64-frame callback: four instrument loads take
/// 30 µs against 1.4 µs for four `AddTrack` and 6.8 µs for sixty-four
/// parameter changes, and the callback's own rendering with one instrument on
/// it is 15 µs. So a flat count would be wrong in both directions: sixty-four
/// parameter changes belong in one callback, and sixty-four instrument loads
/// would be half a millisecond of it.
fn command_cost(cmd: &MixerCommand) -> u32 {
    match cmd {
        MixerCommand::SetParameter { .. } | MixerCommand::UpdateClipPosition { .. } => 1,
        MixerCommand::AddTrack { .. }
        | MixerCommand::SetInstrument { .. }
        | MixerCommand::RemoveTrack { .. }
        | MixerCommand::CreateClip { .. }
        | MixerCommand::UpdateClip { .. }
        | MixerCommand::RemoveClip { .. }
        // Only the first pattern a track receives allocates — it builds the
        // player — and the cost is charged before the command is opened, so
        // it cannot be told apart from the ones that only copy. Charging all
        // of them the allocating rate makes the bound hold for the one that
        // does; the copy itself is 2.4 kB, which is nothing next to a
        // `Plugin::init`.
        | MixerCommand::SetPattern { .. } => HEAVY_COMMAND,
    }
}

/// How much command work one callback will do.
///
/// 64 units: a whole parameter block in one callback — the widest panel in the
/// project is the Odyssey's 59 controls — or four allocating commands.
///
/// A panel wider than this is not a fault, only a preset load spread over two
/// callbacks, which shows up as one buffer rendered with part of the old panel
/// and is 1.45 ms long.
///
/// Sized against the shortest callback the application can be given, 32 frames
/// at 44.1 kHz, which is 726 µs: a full budget of the expensive kind measures
/// 30 µs, or four percent of that deadline, and the cheap kind 7 µs.
///
/// The bound this buys is `COMMAND_BUDGET - 1 + HEAVY_COMMAND` units of work
/// per callback, not `COMMAND_BUDGET`: the budget is checked before a command
/// is taken and its cost is known only after. Tightening that would need a
/// `peek` the channel does not offer, and the overshoot is one command.
const COMMAND_BUDGET: u32 = 64;

/// How many tracks a mixer has room for before its track list has to grow.
///
/// Growing it is a reallocation on the audio thread, so the list is built with
/// room for more tracks than a session is going to hold. It is not a limit:
/// `AddTrack` past this still works, at the cost of one reallocation, and the
/// next 64 are free again. 64 `AudioTrack` headers are a few kilobytes, which
/// is nothing next to the two audio buffers each one already owns.
const TRACK_CAPACITY: usize = 64;

// ── Master limiter ──

/// Peak ceiling the limiter holds the master bus to, −1 dBFS.
///
/// Not 1.0: the samples we write are points on a waveform the converter
/// reconstructs between, and that reconstruction can overshoot the samples
/// themselves. A dB of margin is the usual allowance for it.
const LIMITER_CEILING: f32 = 0.891;

/// Release time constant, 50 ms.
///
/// Long enough not to modulate the waveform of a low note — a 40 Hz cycle is
/// 25 ms, and a release near that period distorts the fundamental instead of
/// riding it. Short enough that a single loud transient does not duck the
/// following bar. Attack is not a time constant at all: see [`MasterLimiter`].
const LIMITER_RELEASE_SECONDS: f32 = 0.050;

/// Stereo-linked peak limiter on the master bus.
///
/// The last stage before the audio device, and the only hard guarantee that
/// nothing leaves at more than full scale. Gain staging in the instruments
/// and the soft saturator on their outputs are what keep this idle; this is
/// what catches everything they cannot — many loud tracks at once, a plugin
/// with no output bound, a NaN out of a diverging filter.
///
/// Design notes:
///
/// * **Stereo-linked.** One gain, computed from `max(|L|, |R|)` and applied
///   to both channels, so a peak in one channel does not pull the image
///   across to the other.
/// * **Instant attack.** The gain that a sample needs is applied to that
///   same sample, not `n` samples later, so there is no overshoot to clean
///   up afterwards and no lookahead buffer to pay for. The alternative — a
///   millisecond attack — would let a millisecond of overshoot through, and
///   the only thing left to catch it would be a hard clip.
/// * **Smooth release.** One-pole, so the gain walks back to unity rather
///   than stepping.
///
/// Real-time safe: three floats of state, no allocation, no locks, no
/// branches that can panic.
struct MasterLimiter {
    /// Current gain, 0..=1. Never above unity: this only ever attenuates.
    gain: f32,
    /// One-pole coefficient for the release ramp.
    release_coeff: f32,
}

impl MasterLimiter {
    fn new(sample_rate: u32) -> Self {
        let sr = (sample_rate as f32).max(1.0);
        Self {
            gain: 1.0,
            release_coeff: 1.0 - (-1.0 / (LIMITER_RELEASE_SECONDS * sr)).exp(),
        }
    }

    fn reset(&mut self) {
        self.gain = 1.0;
    }

    /// Limit an interleaved stereo buffer in place.
    ///
    /// On return every sample is finite and within ±1.0. Any frame that was
    /// not finite on the way in leaves as silence.
    fn process(&mut self, output: &mut [f32]) {
        let mut frames = output.chunks_exact_mut(2);
        for frame in frames.by_ref() {
            // A NaN or infinity reaching the device is a full-scale noise
            // burst, so it is turned into silence here — and, just as
            // important, before it can be fed into the detector below, where
            // it would poison the gain state for every sample after it.
            let l = if frame[0].is_finite() { frame[0] } else { 0.0 };
            let r = if frame[1].is_finite() { frame[1] } else { 0.0 };

            let peak = l.abs().max(r.abs());
            // The backoff is not a fudge factor. `CEILING / peak` rounds to
            // nearest, and so does the multiply that applies it, so the
            // product can land up to three rounding steps above the ceiling.
            // Two epsilons of headroom covers that with margin and makes "at
            // or below the ceiling" exact rather than approximate.
            let target = if peak > LIMITER_CEILING {
                (LIMITER_CEILING / peak) * (1.0 - 2.0 * f32::EPSILON)
            } else {
                1.0
            };

            if target < self.gain {
                self.gain = target;
            } else {
                self.gain += (target - self.gain) * self.release_coeff;
            }

            // Belt and braces. `gain <= CEILING / peak` holds by
            // construction, so the product cannot exceed the ceiling and this
            // clamp cannot fire — it is here because it is the last line
            // before the audio device and the cost of being wrong is a
            // speaker.
            frame[0] = (l * self.gain).clamp(-1.0, 1.0);
            frame[1] = (r * self.gain).clamp(-1.0, 1.0);
        }

        // An interleaved stereo buffer with an odd sample count is malformed
        // and no device produces one, but the guarantee is unconditional: a
        // trailing sample gets the same treatment rather than going out
        // unchecked.
        for tail in frames.into_remainder() {
            let s = if tail.is_finite() { *tail } else { 0.0 };
            *tail = (s * self.gain).clamp(-LIMITER_CEILING, LIMITER_CEILING);
        }
    }
}

// ── AudioTrack ──

/// How many events one track's plugin queue holds before it would have to
/// grow.
///
/// It never grows: the pattern player is handed the queue's remaining room as
/// its budget and stops when it runs out, and clip playback has always fitted
/// inside it. Sized for the densest thing the sequencer can ask for — eight
/// lanes of five-note chords, each with the note-off of whatever it replaced,
/// across the two or three steps a callback can span — plus room for live
/// MIDI on top.
const PLUGIN_EVENT_CAPACITY: usize = 512;

pub struct AudioTrack {
    pub id: usize,
    pub kind: TrackKind,
    pub handle: Arc<TrackHandle>,
    pub instrument: Option<Box<dyn Plugin>>,
    /// Recorded clips on this track's timeline.
    pub clips: Vec<MidiClip>,
    /// The step sequencer on this track, when it has one.
    ///
    /// Boxed because it carries all eight pattern slots — around 19 kB — and
    /// a track without a sequencer should not pay for them, least of all
    /// inside the `Vec<AudioTrack>` that is memcpy'd when a track is added.
    pattern: Option<Box<PatternPlayer>>,
    /// Active recording buffer (when armed + transport recording).
    record_buf: RecordBuffer,
    /// Whether we were recording last buffer (to detect stop).
    was_recording: bool,
    /// Last tick position seen during recording (to detect loop wraps).
    last_record_tick: i64,
    buf_l: Vec<f32>,
    buf_r: Vec<f32>,
    plugin_events: Vec<MidiEvent>,
}

impl AudioTrack {
    pub fn new(handle: Arc<TrackHandle>, max_buffer_size: usize) -> Self {
        Self {
            id: handle.id,
            kind: handle.kind,
            handle,
            instrument: None,
            clips: Vec::new(),
            pattern: None,
            record_buf: RecordBuffer::new(),
            was_recording: false,
            last_record_tick: -1,
            buf_l: vec![0.0; max_buffer_size],
            buf_r: vec![0.0; max_buffer_size],
            plugin_events: Vec::with_capacity(PLUGIN_EVENT_CAPACITY),
        }
    }
}

/// Writes pattern events straight into a track's plugin queue.
///
/// The conversion from song time to buffer position happens here, through
/// [`PlaybackWindow::sample_offset`] — the same call clip playback makes a few
/// lines further down, which is what "a pattern step and a clip note on the
/// same beat land on the same sample" rests on.
///
/// The queue is never grown. When it is full the sink refuses, and the
/// generator stops rather than dropping events out of the middle of a step.
struct TrackEventSink<'a> {
    events: &'a mut Vec<MidiEvent>,
    window: &'a PlaybackWindow,
}

impl EventSink for TrackEventSink<'_> {
    fn accept(&mut self, event: PatternEvent) -> bool {
        if self.events.len() >= self.events.capacity() {
            return false;
        }
        self.events.push(MidiEvent {
            sample_offset: self.window.sample_offset(event.tick),
            status: event.status,
            data1: event.data1,
            data2: event.data2,
        });
        true
    }
}

/// Put a track's events in the order the instrument will read them.
///
/// A hand-written insertion sort, and not for speed: `slice::sort_by_key` is
/// a merge sort that allocates a scratch buffer past twenty elements, which
/// on the audio thread is exactly the thing this whole crate is arranged to
/// avoid. These lists are short and arrive nearly sorted — clips are stored
/// in tick order and a pattern generates step by step — so the insertion sort
/// is linear in practice as well as allocation-free.
///
/// Stable, which is load-bearing: a note-off written before a note-on at the
/// same offset has to stay before it, or a pattern switch kills the voice it
/// just started.
fn sort_events_by_offset(events: &mut [MidiEvent]) {
    for i in 1..events.len() {
        let mut j = i;
        while j > 0 && events[j - 1].sample_offset > events[j].sample_offset {
            events.swap(j - 1, j);
            j -= 1;
        }
    }
}

// ── Mixer ──

pub struct Mixer {
    tracks: Vec<AudioTrack>,
    master_vu: Arc<VuLevels>,
    command_rx: Receiver<MixerCommand>,
    clip_tx: Sender<ClipSnapshot>,
    metronome: Metronome,
    sample_rate: u32,
    max_buffer_size: usize,
    /// Pre-allocated scratch buffers for mix — avoids allocation in process().
    scratch_l: Vec<f32>,
    scratch_r: Vec<f32>,
    /// Pre-allocated buffer for live MIDI conversion.
    live_events: Vec<MidiEvent>,
    /// The window the previous callback rendered, when playback was running.
    ///
    /// One per mixer rather than one per track: the window is a fact about
    /// the transport and the block, so every track's is the same window, and
    /// two tracks that computed it separately could disagree. `None` whenever
    /// the transport is not rolling, which is what makes the first block
    /// after a start discontinuous — see [`PlaybackWindow::is_continuous`].
    last_window: Option<PlaybackWindow>,
    /// Final stage before the audio device — see [`MasterLimiter`].
    limiter: MasterLimiter,
}

impl Mixer {
    pub fn new(
        command_rx: Receiver<MixerCommand>,
        master_vu: Arc<VuLevels>,
        clip_tx: Sender<ClipSnapshot>,
        sample_rate: u32,
        max_buffer_size: usize,
    ) -> Self {
        Self {
            tracks: Vec::with_capacity(TRACK_CAPACITY),
            master_vu,
            command_rx,
            clip_tx,
            metronome: Metronome::new(sample_rate as f64),
            sample_rate,
            max_buffer_size,
            scratch_l: vec![0.0; max_buffer_size],
            scratch_r: vec![0.0; max_buffer_size],
            live_events: Vec::with_capacity(256),
            last_window: None,
            limiter: MasterLimiter::new(sample_rate),
        }
    }

    /// Process one buffer cycle.
    pub fn process(&mut self, output: &mut [f32], midi_messages: &[MidiMessage], transport: &Transport) {
        // Bounded: whatever does not fit in this callback's budget is applied
        // by the next one, in order. See `drain_commands`.
        let _ = self.drain_commands();

        let num_frames = output.len() / 2;
        let playing = transport.is_playing();
        let recording = transport.is_recording();
        let looping = transport.is_looping();
        let current_tick = transport.position_ticks();
        let bpm = transport.tempo_bpm();
        let ticks_per_sample = (bpm * Transport::PPQ as f64) / (60.0 * self.sample_rate as f64);
        let loop_end = transport.loop_end();

        // ── The window ──
        //
        // The span of song time this callback renders, computed once and read
        // by everything that turns song time into notes. Clip playback and
        // pattern playback both take their events from this one value, which
        // is what makes them sample-identical on the same beat rather than
        // two implementations that have to be kept in agreement.
        let window = PlaybackWindow::for_block(
            current_tick,
            num_frames as u32,
            ticks_per_sample,
            looping.then(|| (transport.loop_start(), loop_end)),
            self.last_window,
        );
        self.last_window = playing.then_some(window);

        // Convert live MIDI to plugin events (reuse pre-allocated buffer)
        self.live_events.clear();
        for msg in midi_messages {
            if let Some(ev) = midi_to_plugin_event(msg) {
                self.live_events.push(ev);
            }
        }

        let any_solo = self.tracks.iter().any(|t| t.handle.config.is_soloed());

        // Reuse pre-allocated scratch buffers for master mix.
        // Swap out of self to avoid borrow conflicts in the track loop.
        let mut master_l = std::mem::take(&mut self.scratch_l);
        let mut master_r = std::mem::take(&mut self.scratch_r);
        let live_events = std::mem::take(&mut self.live_events);
        // Dead code in practice, and deliberately kept. `max_buffer_size` is
        // the largest block the device said it could deliver, so a block that
        // does not fit means a driver exceeded its own stated maximum. One
        // allocation is a glitch; the alternative here is wrong output or a
        // panic on the audio thread.
        if master_l.len() < num_frames {
            master_l.resize(num_frames, 0.0);
            master_r.resize(num_frames, 0.0);
        }
        master_l[..num_frames].fill(0.0);
        master_r[..num_frames].fill(0.0);

        let clip_tx = &self.clip_tx;

        for track in &mut self.tracks {
            if track.buf_l.len() < num_frames {
                track.buf_l.resize(num_frames, 0.0);
                track.buf_r.resize(num_frames, 0.0);
            }
            track.buf_l[..num_frames].fill(0.0);
            track.buf_r[..num_frames].fill(0.0);
            track.plugin_events.clear();

            let is_midi_active = track.kind == TrackKind::Instrument
                && track.handle.config.is_midi_active();
            let is_armed = track.handle.config.is_armed();
            let should_record = playing && recording && is_armed && is_midi_active;

            // ── Recording ──
            if should_record && !track.was_recording {
                // Start recording at the loop start, not the current position,
                // so the clip spans the full loop region
                let rec_start = if looping { transport.loop_start() } else { current_tick };
                track.record_buf.start(rec_start);
                tracing::debug!("rec start track={} tick={}", track.id, current_tick);
            }

            // Detect loop wrap: current tick jumped backward means transport looped.
            if should_record && track.was_recording && looping
                && track.record_buf.is_active() && track.last_record_tick >= 0
                && current_tick < track.last_record_tick
            {
                commit_recording(track, loop_end, clip_tx);
                // Start new recording at loop start, not current_tick
                // (current_tick may be a few ticks past 0 due to buffer boundaries)
                track.record_buf.start(transport.loop_start());
            }
            if should_record {
                track.last_record_tick = current_tick;
            }

            // Commit when recording stops (user pressed stop)
            if !should_record && track.was_recording {
                commit_recording(track, current_tick, clip_tx);
            }
            track.was_recording = should_record;

            // Record live MIDI events (and pass through for monitoring)
            if is_midi_active {
                for ev in &live_events {
                    track.plugin_events.push(*ev);
                    if should_record {
                        let event_tick = current_tick
                            + (ev.sample_offset as f64 * ticks_per_sample) as i64;
                        track.record_buf.record(event_tick, ev.status, ev.data1, ev.data2);
                    }
                }
            }

            // ── Pattern playback ──
            //
            // Before the clips, and unconditionally: a player that has just
            // been stopped still has note-offs to write, and the transport
            // being stopped is exactly when it has to write them.
            if let Some(ref mut player) = track.pattern {
                let mut sink = TrackEventSink { events: &mut track.plugin_events, window: &window };
                player.render(&window, playing, &mut sink);
                track.handle.pattern.publish(
                    player.live_slot(),
                    player.queued_slot(),
                    player.current_step(),
                    playing && player.is_playing(),
                );
            }

            // ── Clip playback ──
            //
            // Same window, same `sample_offset`. The loop wrap needs no
            // branch of its own any more: the window already starts at the
            // loop point when the transport has just gone round.
            if playing && !track.clips.is_empty() {
                for clip in &track.clips {
                    for (tick, event) in clip.events_between(window.from(), window.to()) {
                        if track.plugin_events.len() >= track.plugin_events.capacity() {
                            break;
                        }
                        track.plugin_events.push(MidiEvent {
                            sample_offset: window.sample_offset(tick),
                            status: event.status,
                            data1: event.data1,
                            data2: event.data2,
                        });
                    }
                }
            }

            if !track.plugin_events.is_empty() {
                sort_events_by_offset(&mut track.plugin_events);
            }

            // Track position for wrap detection (used by both recording and playback)
            if playing {
                track.last_record_tick = current_tick;
            }

            // ── Process instrument (allocation-free) ──
            if let Some(ref mut instrument) = track.instrument {
                let out_l = &mut track.buf_l[..num_frames];
                let out_r = &mut track.buf_r[..num_frames];
                let mut out_slices: [&mut [f32]; 2] = [out_l, out_r];
                instrument.process(&[], &mut out_slices, &track.plugin_events);
            }

            // ── VU + Mix ──
            let muted = track.handle.config.is_muted();
            let soloed = track.handle.config.is_soloed();
            let audible = !muted && (!any_solo || soloed);
            let volume = track.handle.config.get_volume();

            let mut peak_l = 0.0f32;
            let mut peak_r = 0.0f32;
            for i in 0..num_frames {
                peak_l = peak_l.max(track.buf_l[i].abs());
                peak_r = peak_r.max(track.buf_r[i].abs());
            }

            let (old_l, old_r) = track.handle.vu.get();
            let decay = 0.85f32;
            track.handle.vu.set(
                if peak_l > old_l { peak_l } else { old_l * decay },
                if peak_r > old_r { peak_r } else { old_r * decay },
            );

            if audible {
                for i in 0..num_frames {
                    master_l[i] += track.buf_l[i] * volume;
                    master_r[i] += track.buf_r[i] * volume;
                }
            }
        }

        // Write tracks to interleaved output
        for i in 0..num_frames {
            output[i * 2] = master_l[i];
            output[i * 2 + 1] = master_r[i];
        }

        // Return scratch buffers to self (no allocation, just moves)
        self.scratch_l = master_l;
        self.scratch_r = master_r;
        self.live_events = live_events;

        // Mix metronome click into output (after tracks, so it's always audible)
        self.metronome.process(output, transport);

        // ── Master limiter ──
        // Everything that reaches the device passes through here, the
        // metronome included: it is summed on top of the track mix, so
        // limiting before it would leave a gap in the guarantee.
        self.limiter.process(output);

        // Master VU (includes metronome), read after limiting so the meter
        // shows what actually left rather than what would have.
        let mut mp_l = 0.0f32;
        let mut mp_r = 0.0f32;
        for i in 0..num_frames {
            mp_l = mp_l.max(output[i * 2].abs());
            mp_r = mp_r.max(output[i * 2 + 1].abs());
        }

        let (old_l, old_r) = self.master_vu.get();
        let decay = 0.85f32;
        self.master_vu.set(
            if mp_l > old_l { mp_l } else { old_l * decay },
            if mp_r > old_r { mp_r } else { old_r * decay },
        );
    }

    pub fn reset_all(&mut self) {
        let clip_tx = &self.clip_tx;
        for track in &mut self.tracks {
            if let Some(ref mut inst) = track.instrument {
                inst.reset();
            }
            track.handle.vu.set(0.0, 0.0);
            // Commit any active recording before resetting (don't lose overdubs)
            if track.record_buf.is_active() && track.was_recording {
                let end_tick = track.last_record_tick.max(0);
                commit_recording(track, end_tick, clip_tx);
            } else if track.record_buf.is_active() {
                track.record_buf.discard();
            }
            track.was_recording = false;
            // A panic resets the instruments underneath the sequencer, so the
            // notes it is holding are already gone: the table is dropped
            // rather than sounded, which would only send offs to voices that
            // no longer exist.
            if let Some(ref mut player) = track.pattern {
                player.silence();
            }
        }
        self.last_window = None;
        self.metronome.reset();
        self.limiter.reset();
    }

    /// Apply queued commands until the callback's budget is spent.
    ///
    /// Returns the units spent, which is what the tests assert the bound on.
    ///
    /// Anything left in the channel stays there, in the order it was sent, and
    /// the next callback continues from it. That is the whole of the ordering
    /// guarantee: commands are taken one at a time from a FIFO and applied
    /// immediately, so `AddTrack` before `SetInstrument` for the same track
    /// cannot be seen the other way round even when the two land in different
    /// callbacks.
    fn drain_commands(&mut self) -> u32 {
        let mut spent = 0;
        while spent < COMMAND_BUDGET {
            let Ok(cmd) = self.command_rx.try_recv() else { break };
            spent += command_cost(&cmd);
            self.apply_command(cmd);
        }
        spent
    }

    fn apply_command(&mut self, cmd: MixerCommand) {
        match cmd {
            MixerCommand::AddTrack { kind: _, handle } => {
                let track = AudioTrack::new(handle, self.max_buffer_size);
                self.tracks.push(track);
            }
            MixerCommand::SetInstrument { track_id, mut instrument } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    instrument.init(self.sample_rate as f64, self.max_buffer_size);
                    track.instrument = Some(instrument);
                }
            }
            MixerCommand::RemoveTrack { track_id } => {
                self.tracks.retain(|t| t.id != track_id);
            }
            MixerCommand::SetParameter { track_id, param_index, value } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    if let Some(ref mut inst) = track.instrument {
                        inst.set_parameter(param_index, value);
                    }
                }
            }
            MixerCommand::CreateClip { track_id, start_tick, length_ticks } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    track.clips.push(MidiClip::new(start_tick, length_ticks, Vec::new()));
                }
            }
            MixerCommand::UpdateClip { track_id, clip_index, events } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    if let Some(clip) = track.clips.get_mut(clip_index) {
                        clip.events = events;
                        clip.events.sort_by_key(|e| e.tick);
                    }
                }
            }
            MixerCommand::UpdateClipPosition { track_id, clip_index, start_tick, length_ticks } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    if let Some(clip) = track.clips.get_mut(clip_index) {
                        clip.start_tick = start_tick;
                        clip.length_ticks = length_ticks;
                    }
                }
            }
            MixerCommand::RemoveClip { track_id, clip_index } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    if clip_index < track.clips.len() {
                        track.clips.remove(clip_index);
                    }
                }
            }
            MixerCommand::SetPattern { track_id, slot, block } => {
                if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
                    let player = track.pattern.get_or_insert_with(|| Box::new(PatternPlayer::new()));
                    player.apply(slot, block);
                }
            }
        }
    }
}

/// Commit a recording buffer into a clip and send snapshot to UI.
fn commit_recording(track: &mut AudioTrack, end_tick: i64, clip_tx: &Sender<ClipSnapshot>) {
    if let Some(clip) = track.record_buf.commit(end_tick) {
        let idx = track.clips.len();
        tracing::debug!(
            "rec commit track={}: {} events, ticks {}..{}",
            track.id, clip.events.len(), clip.start_tick, clip.end_tick()
        );
        let snapshot = ClipSnapshot::from_clip(track.id, idx, &clip);
        track.clips.push(clip);
        let _ = clip_tx.send(snapshot);
    }
}

/// Which live MIDI messages reach a plugin.
///
/// Channel pressure is here because instruments route it: the Prophet-6 has
/// an aftertouch section with six destinations and an amount that reads as
/// bipolar, and every one of its 500 factory programs stores a setting for
/// it. It is a two-byte message, so `raw[2]` is whatever the parser left
/// there and a plugin reads the pressure from `data1`, as the MIDI
/// specification puts it.
///
/// Polyphonic key pressure is *not* here, and that is the instruments rather
/// than an oversight — the Prophet-6 provides "monophonic (or 'channel')
/// aftertouch" and nothing in the rack has a per-key pressure destination.
/// `phosphor-midi` does not parse it into a variant of its own either.
pub fn midi_to_plugin_event(msg: &MidiMessage) -> Option<MidiEvent> {
    use phosphor_midi::message::MidiMessageType;
    match msg.message_type {
        MidiMessageType::NoteOn { .. }
        | MidiMessageType::NoteOff { .. }
        | MidiMessageType::ControlChange { .. }
        | MidiMessageType::PitchBend { .. }
        | MidiMessageType::ChannelPressure { .. } => Some(MidiEvent {
            sample_offset: 0,
            status: msg.raw[0],
            data1: msg.raw[1],
            data2: msg.raw[2],
        }),
        _ => None,
    }
}

pub fn mixer_command_channel() -> (Sender<MixerCommand>, Receiver<MixerCommand>) {
    crossbeam_channel::unbounded()
}

/// Create a channel for clip snapshots (audio → UI).
pub fn clip_snapshot_channel() -> (Sender<ClipSnapshot>, Receiver<ClipSnapshot>) {
    crossbeam_channel::unbounded()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cpal_backend::{Requested, StreamFormat};
    use crate::project::TrackConfig;
    use phosphor_dsp::synth::PhosphorSynth;
    use phosphor_midi::message::{MidiMessage, MidiMessageType};

    fn make_note_on(note: u8, vel: u8) -> MidiMessage {
        MidiMessage {
            timestamp: Some(0),
            message_type: MidiMessageType::NoteOn { channel: 0, note, velocity: vel },
            raw: [0x90, note, vel],
            len: 3,
        }
    }

    /// Aftertouch has to reach a plugin, or an instrument with an aftertouch
    /// section has one that never does anything.
    #[test]
    fn channel_pressure_reaches_the_plugin_and_key_pressure_does_not() {
        let pressure = MidiMessage {
            timestamp: Some(0),
            message_type: MidiMessageType::ChannelPressure { channel: 0, pressure: 96 },
            raw: [0xD0, 96, 0],
            len: 2,
        };
        let event = midi_to_plugin_event(&pressure).expect("channel pressure is dropped");
        assert_eq!(event.status, 0xD0);
        assert_eq!(event.data1, 96);

        // Polyphonic key pressure parses as `Other` and stays there: nothing
        // in the rack has a per-key pressure destination.
        let key = MidiMessage::from_bytes(&[0xA0, 60, 96], 0).expect("parsed");
        assert!(
            midi_to_plugin_event(&key).is_none(),
            "polyphonic key pressure has no destination in the rack"
        );
    }

    fn make_note_off(note: u8) -> MidiMessage {
        MidiMessage {
            timestamp: Some(0),
            message_type: MidiMessageType::NoteOff { channel: 0, note, velocity: 0 },
            raw: [0x80, note, 0],
            len: 3,
        }
    }

    fn setup_mixer() -> (Mixer, Sender<MixerCommand>, Receiver<ClipSnapshot>, Arc<Transport>) {
        let (tx, rx) = mixer_command_channel();
        let (clip_tx, clip_rx) = clip_snapshot_channel();
        let master_vu = Arc::new(VuLevels::new());
        let transport = Arc::new(Transport::new(120.0));
        let mixer = Mixer::new(rx, master_vu, clip_tx, 44100, 256);
        (mixer, tx, clip_rx, transport)
    }

    fn add_armed_synth(tx: &Sender<MixerCommand>, id: usize) -> Arc<TrackHandle> {
        let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
        handle.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
        handle.config.armed.store(true, std::sync::atomic::Ordering::Relaxed);
        tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle: handle.clone() }).unwrap();
        tx.send(MixerCommand::SetInstrument { track_id: id, instrument: Box::new(PhosphorSynth::new()) }).unwrap();
        handle
    }

    #[test]
    fn mixer_empty_output() {
        let (mut mixer, _tx, _clip_rx, transport) = setup_mixer();
        let mut output = vec![0.0f32; 128];
        mixer.process(&mut output, &[], &transport);
        assert!(output.iter().all(|&s| s == 0.0));
    }

    #[test]
    fn mixer_live_midi_produces_sound() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        transport.play();

        let midi = vec![make_note_on(60, 100)];
        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &midi, &transport);

        let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        // Threshold is "not silence", not a level check — the instruments
        // carry a deep headroom trim on their output.
        assert!(peak > 0.001, "Should produce sound, peak={peak}");
    }

    #[test]
    fn mixer_records_midi_clip() {
        let (mut mixer, tx, clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        transport.play();
        transport.toggle_record();

        // Play a note while recording
        let midi = vec![make_note_on(60, 100)];
        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &midi, &transport);

        // Note off
        let midi = vec![make_note_off(60)];
        mixer.process(&mut output, &midi, &transport);

        // Stop recording
        transport.toggle_record();
        mixer.process(&mut output, &[], &transport);

        // Should have received a clip snapshot
        let snap = clip_rx.try_recv().expect("Should receive clip snapshot");
        assert_eq!(snap.track_id, 0);
        assert!(snap.event_count >= 2, "Should have note on + off, got {}", snap.event_count);
        assert!(!snap.notes.is_empty(), "Should have parsed notes");
    }

    #[test]
    fn mixer_plays_back_recorded_clip() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        transport.play();
        transport.toggle_record();

        // Record a note
        let midi = vec![make_note_on(60, 100)];
        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &midi, &transport);

        let midi = vec![make_note_off(60)];
        mixer.process(&mut output, &midi, &transport);

        // Stop recording
        transport.toggle_record();
        mixer.process(&mut output, &[], &transport);

        // Stop and rewind
        transport.stop();

        // Play back — should hear the recorded clip
        transport.play();
        output.fill(0.0);
        mixer.process(&mut output, &[], &transport);

        let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak > 0.001, "Playback should produce sound, peak={peak}");
    }

    #[test]
    fn mixer_mute_silences() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let handle = add_armed_synth(&tx, 0);
        handle.config.muted.store(true, std::sync::atomic::Ordering::Relaxed);
        transport.play();

        let midi = vec![make_note_on(60, 100)];
        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &midi, &transport);

        let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak == 0.0, "Muted track should be silent, peak={peak}");
    }

    #[test]
    fn mixer_no_record_when_not_armed() {
        let (mut mixer, tx, clip_rx, transport) = setup_mixer();
        let handle = add_armed_synth(&tx, 0);
        handle.config.armed.store(false, std::sync::atomic::Ordering::Relaxed);
        transport.play();
        transport.toggle_record();

        let midi = vec![make_note_on(60, 100)];
        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &midi, &transport);

        transport.toggle_record();
        mixer.process(&mut output, &[], &transport);

        assert!(clip_rx.try_recv().is_err(), "Should not record when not armed");
    }

    #[test]
    fn mixer_reset_commits_recording() {
        let (mut mixer, tx, clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        transport.play();
        transport.toggle_record();

        let midi = vec![make_note_on(60, 100)];
        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &midi, &transport);

        mixer.reset_all();

        // Reset should commit the active recording, not discard it
        assert!(clip_rx.try_recv().is_ok(), "Reset should commit active recording");
    }

    #[test]
    fn end_to_end_record_and_playback() {
        // Simulates exact app flow: add track, arm, record, play notes,
        // stop, rewind, play back — with transport.advance() each buffer.
        let (mut mixer, tx, clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        let sr = 44100u32;
        let buf_frames = 256;
        let buf_samples = buf_frames * 2; // stereo

        // 1. Enable recording, then play
        transport.toggle_record();
        transport.play();

        // 2. Process a few empty buffers (advance transport)
        let mut output = vec![0.0f32; buf_samples];
        for _ in 0..4 {
            mixer.process(&mut output, &[], &transport);
            transport.advance(buf_frames as u32, sr);
        }

        // 3. Play a note (should be recorded)
        let midi = vec![make_note_on(60, 100)];
        mixer.process(&mut output, &midi, &transport);
        let peak_during = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak_during > 0.001, "Should hear note during recording (monitoring)");
        transport.advance(buf_frames as u32, sr);

        // 4. A few more buffers of sustain
        for _ in 0..8 {
            output.fill(0.0);
            mixer.process(&mut output, &[], &transport);
            transport.advance(buf_frames as u32, sr);
        }

        // 5. Note off
        let midi = vec![make_note_off(60)];
        mixer.process(&mut output, &midi, &transport);
        transport.advance(buf_frames as u32, sr);

        // 6. A few more buffers
        for _ in 0..4 {
            output.fill(0.0);
            mixer.process(&mut output, &[], &transport);
            transport.advance(buf_frames as u32, sr);
        }

        // 7. Stop recording (commit clip)
        transport.toggle_record();
        mixer.process(&mut output, &[], &transport);
        transport.advance(buf_frames as u32, sr);

        // 8. Check we got a clip snapshot
        let snap = clip_rx.try_recv().expect("Should receive clip snapshot after stopping record");
        assert!(snap.event_count >= 2, "Clip should have note on + off");
        assert!(!snap.notes.is_empty(), "Clip should have parsed notes");

        // 9. Stop transport and rewind to 0
        transport.stop();

        // 10. Play back — the synth should be reset (no stuck notes from recording)
        transport.play();

        // 11. Process enough buffers to reach the recorded note position
        // The note was recorded after 4 initial buffers, so roughly at that tick position
        for _ in 0..4 {
            output.fill(0.0);
            mixer.process(&mut output, &[], &transport);
            transport.advance(buf_frames as u32, sr);
        }

        // 12. The next buffer should contain the played-back note
        output.fill(0.0);
        mixer.process(&mut output, &[], &transport);
        let peak_playback = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak_playback > 0.001, "Playback should produce sound at the recorded position, peak={peak_playback}");
    }

    #[test]
    fn loop_record_commits_on_wrap() {
        let (mut mixer, tx, clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        let sr = 44100u32;
        let buf_frames = 256u32;

        // Set loop to 1 bar (3840 ticks at 120bpm ≈ 346 buffers of 256 samples)
        transport.set_loop_bars(1, 1);
        transport.start_loop_record();

        let mut output = vec![0.0f32; buf_frames as usize * 2];

        // Play a note early in the loop
        let midi = vec![make_note_on(60, 100)];
        mixer.process(&mut output, &midi, &transport);
        transport.advance(buf_frames, sr);

        // Note off a few buffers later
        for _ in 0..5 {
            mixer.process(&mut output, &[], &transport);
            transport.advance(buf_frames, sr);
        }
        let midi = vec![make_note_off(60)];
        mixer.process(&mut output, &midi, &transport);
        transport.advance(buf_frames, sr);

        // Continue until we cross the loop boundary
        // 1 bar at 120bpm, 256 frames, 44100Hz ≈ 346 buffers
        for _ in 0..400 {
            mixer.process(&mut output, &[], &transport);
            transport.advance(buf_frames, sr);

            if let Ok(snap) = clip_rx.try_recv() {
                assert!(snap.event_count >= 2, "Clip should have events, got {}", snap.event_count);
                assert!(!snap.notes.is_empty(), "Clip should have notes");
                // Recording committed on loop wrap — success
                transport.stop_loop_record();
                return;
            }
        }

        panic!("Recording should have committed when the loop wrapped");
    }

    #[test]
    fn loop_playback_after_record() {
        let (mut mixer, tx, clip_rx, transport) = setup_mixer();
        let _handle = add_armed_synth(&tx, 0);
        let sr = 44100u32;
        let bf = 256u32;

        // Set loop to 1 bar, start recording
        transport.set_loop_bars(1, 1);
        transport.start_loop_record();

        let mut output = vec![0.0f32; bf as usize * 2];

        // Record a note
        mixer.process(&mut output, &[make_note_on(60, 100)], &transport);
        transport.advance(bf, sr);
        for _ in 0..3 {
            mixer.process(&mut output, &[], &transport);
            transport.advance(bf, sr);
        }
        mixer.process(&mut output, &[make_note_off(60)], &transport);
        transport.advance(bf, sr);

        // Run until loop wraps and clip commits
        for _ in 0..200 {
            mixer.process(&mut output, &[], &transport);
            transport.advance(bf, sr);
            if clip_rx.try_recv().is_ok() { break; }
        }

        // Stop recording, rewind
        transport.stop_loop_record();
        transport.set_position(0);

        // Play back with looping on
        transport.toggle_loop(); // enable looping
        transport.play();

        output.fill(0.0);
        mixer.process(&mut output, &[], &transport);
        let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak > 0.001, "Should hear playback, peak={peak}");
    }

    // ── Command budget ──

    /// The most work one callback can do, in the units [`command_cost`]
    /// returns: the budget is tested before a command is taken and charged
    /// after, so the last one can overshoot by its own cost.
    const WORST_CALLBACK: u32 = COMMAND_BUDGET - 1 + HEAVY_COMMAND;

    /// A plugin that remembers every parameter it was given, in order, so a
    /// test can see exactly what reached the audio thread and when.
    ///
    /// The lock is not something an instrument would do — nothing may block in
    /// `process` — but `set_parameter` is called from the command drain and
    /// this one never renders.
    #[derive(Clone)]
    struct ParamLog(Arc<std::sync::Mutex<Vec<(usize, f32)>>>);

    impl ParamLog {
        fn new() -> Self {
            Self(Arc::new(std::sync::Mutex::new(Vec::new())))
        }
        fn seen(&self) -> Vec<(usize, f32)> {
            self.0.lock().unwrap().clone()
        }
    }

    impl Plugin for ParamLog {
        fn info(&self) -> phosphor_plugin::PluginInfo {
            phosphor_plugin::PluginInfo {
                name: "ParamLog".into(),
                version: "0".into(),
                author: "test".into(),
                category: phosphor_plugin::PluginCategory::Instrument,
            }
        }
        fn init(&mut self, _sample_rate: f64, _max_buffer_size: usize) {}
        fn process(&mut self, _inputs: &[&[f32]], _outputs: &mut [&mut [f32]], _midi: &[MidiEvent]) {}
        fn parameter_count(&self) -> usize { 8 }
        fn parameter_info(&self, _index: usize) -> Option<phosphor_plugin::ParameterInfo> { None }
        fn get_parameter(&self, _index: usize) -> f32 { 0.0 }
        fn set_parameter(&mut self, index: usize, value: f32) {
            self.0.lock().unwrap().push((index, value));
        }
        fn reset(&mut self) {}
    }

    /// Add a track carrying a [`ParamLog`], applying the commands immediately.
    fn add_logging_track(mixer: &mut Mixer, tx: &Sender<MixerCommand>, id: usize) -> ParamLog {
        let log = ParamLog::new();
        let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
        tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
        tx.send(MixerCommand::SetInstrument {
            track_id: id,
            instrument: Box::new(log.clone()),
        }).unwrap();
        mixer.drain_commands();
        log
    }

    /// The defect: the drain used to be `while let Ok(cmd) = try_recv()`, so
    /// the callback did as much work as the UI had queued. Opening a session
    /// queues hundreds of commands and the callback has a hard deadline.
    #[test]
    fn one_callback_applies_a_bounded_amount_of_work() {
        let (mut mixer, tx, _clip_rx, _transport) = setup_mixer();
        let log = add_logging_track(&mut mixer, &tx, 0);

        for i in 0..500 {
            tx.send(MixerCommand::SetParameter {
                track_id: 0,
                param_index: i % 8,
                value: i as f32,
            }).unwrap();
        }

        let spent = mixer.drain_commands();
        assert!(
            spent <= WORST_CALLBACK,
            "one callback spent {spent} units, over the {WORST_CALLBACK} bound"
        );
        assert_eq!(
            log.seen().len(),
            COMMAND_BUDGET as usize,
            "a parameter costs one unit, so a full budget is exactly that many"
        );
        assert!(!mixer.command_rx.is_empty(), "the rest has to still be queued");
    }

    /// Bounded is only half of it: everything queued still has to arrive, once
    /// each, in the order it was sent.
    #[test]
    fn nothing_is_lost_or_reordered_across_callbacks() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let log = add_logging_track(&mut mixer, &tx, 0);

        let sent: Vec<(usize, f32)> = (0..500).map(|i| (i % 8, i as f32)).collect();
        for &(param_index, value) in &sent {
            tx.send(MixerCommand::SetParameter { track_id: 0, param_index, value }).unwrap();
        }

        // Run callbacks until the queue is empty, counting them: 500 commands
        // at one unit each cannot fit in fewer than eight budgets, which is
        // what makes this a test of the bound and not just of the FIFO.
        let mut output = vec![0.0f32; 128];
        let mut callbacks = 0;
        while !mixer.command_rx.is_empty() {
            mixer.process(&mut output, &[], &transport);
            callbacks += 1;
            assert!(callbacks < 100, "the drain is not making progress");
        }
        assert!(
            callbacks >= 500 / COMMAND_BUDGET as usize,
            "500 commands went through in {callbacks} callbacks, so the budget did not hold"
        );
        assert_eq!(log.seen(), sent, "the audio thread saw a different sequence");
    }

    /// The ordering guarantee, at the one place it matters: a track has to
    /// exist before its instrument is attached. Splitting the queue between
    /// the two would drop the instrument on the floor — `SetInstrument` for a
    /// track that is not there yet is silently discarded — and the track would
    /// play nothing for the rest of the session.
    #[test]
    fn a_track_and_its_instrument_survive_a_budget_boundary() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let log = ParamLog::new();

        // Fill this callback's budget with cheap commands first, so that the
        // pair below is guaranteed to land in a later one.
        for _ in 0..COMMAND_BUDGET {
            tx.send(MixerCommand::SetParameter { track_id: 99, param_index: 0, value: 0.0 })
                .unwrap();
        }
        let handle = Arc::new(TrackHandle::new(7, TrackKind::Instrument));
        tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
        tx.send(MixerCommand::SetInstrument {
            track_id: 7,
            instrument: Box::new(log.clone()),
        }).unwrap();
        tx.send(MixerCommand::SetParameter { track_id: 7, param_index: 3, value: 0.5 }).unwrap();

        let mut output = vec![0.0f32; 128];
        mixer.process(&mut output, &[], &transport);
        assert!(mixer.tracks.is_empty(), "the budget did not stop at the parameters");

        while !mixer.command_rx.is_empty() {
            mixer.process(&mut output, &[], &transport);
        }
        assert_eq!(mixer.tracks.len(), 1);
        assert!(mixer.tracks[0].instrument.is_some(), "the instrument never arrived");
        assert_eq!(
            log.seen(),
            vec![(3, 0.5)],
            "the parameter that follows the instrument did not reach it"
        );
    }

    /// An instrument load is not a parameter change: it calls `Plugin::init`,
    /// which allocates a voice array and, on some instruments, a delay line.
    /// A flat count of commands per callback would let sixteen of those
    /// through where it lets sixteen stores through.
    #[test]
    fn an_instrument_load_costs_more_than_a_parameter() {
        let param = MixerCommand::SetParameter { track_id: 0, param_index: 0, value: 0.0 };
        let load = MixerCommand::SetInstrument {
            track_id: 0,
            instrument: Box::new(FixedOutput(0.0)),
        };
        assert!(command_cost(&load) > command_cost(&param));

        // Four loads per callback, not sixty-four.
        let (mut mixer, tx, _clip_rx, _transport) = setup_mixer();
        for id in 0..8 {
            let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
            tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
        }
        while !mixer.command_rx.is_empty() {
            mixer.drain_commands();
        }
        for id in 0..8 {
            tx.send(MixerCommand::SetInstrument {
                track_id: id,
                instrument: Box::new(FixedOutput(0.25)),
            }).unwrap();
        }
        mixer.drain_commands();
        let loaded = mixer.tracks.iter().filter(|t| t.instrument.is_some()).count();
        assert_eq!(loaded, (COMMAND_BUDGET / HEAVY_COMMAND) as usize);
    }

    /// `AddTrack` pushes onto the track list, and a push that grows the list
    /// reallocates — on the audio thread. The list is built with room for more
    /// tracks than a session will hold so that it does not.
    #[test]
    fn adding_tracks_does_not_grow_the_track_list() {
        let (mut mixer, tx, _clip_rx, _transport) = setup_mixer();
        let capacity = mixer.tracks.capacity();
        assert!(capacity >= TRACK_CAPACITY);

        for id in 0..TRACK_CAPACITY {
            let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
            tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
        }
        while !mixer.command_rx.is_empty() {
            mixer.drain_commands();
        }
        assert_eq!(mixer.tracks.len(), TRACK_CAPACITY);
        assert_eq!(
            mixer.tracks.capacity(), capacity,
            "the track list reallocated on the audio thread"
        );
    }

    // ── Master limiter ──

    /// A plugin that writes whatever it is told to, so the limiter can be
    /// driven with signals no real instrument would produce.
    struct FixedOutput(f32);

    impl Plugin for FixedOutput {
        fn info(&self) -> phosphor_plugin::PluginInfo {
            phosphor_plugin::PluginInfo {
                name: "Fixed".into(),
                version: "0".into(),
                author: "test".into(),
                category: phosphor_plugin::PluginCategory::Instrument,
            }
        }
        fn init(&mut self, _sample_rate: f64, _max_buffer_size: usize) {}
        fn process(&mut self, _inputs: &[&[f32]], outputs: &mut [&mut [f32]], _midi: &[MidiEvent]) {
            for ch in outputs.iter_mut() {
                ch.fill(self.0);
            }
        }
        fn parameter_count(&self) -> usize { 0 }
        fn parameter_info(&self, _index: usize) -> Option<phosphor_plugin::ParameterInfo> { None }
        fn get_parameter(&self, _index: usize) -> f32 { 0.0 }
        fn set_parameter(&mut self, _index: usize, _value: f32) {}
        fn reset(&mut self) {}
    }

    fn add_fixed_track(tx: &Sender<MixerCommand>, id: usize, value: f32) -> Arc<TrackHandle> {
        let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
        handle.config.set_volume(1.0);
        tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle: handle.clone() }).unwrap();
        tx.send(MixerCommand::SetInstrument {
            track_id: id,
            instrument: Box::new(FixedOutput(value)),
        }).unwrap();
        handle
    }

    /// The guarantee. Six tracks each running at three quarters of full scale
    /// sum to 4.5x — without the limiter that is what would reach the device.
    #[test]
    fn master_limiter_bounds_many_loud_tracks() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        for id in 0..6 {
            add_fixed_track(&tx, id, 0.75);
        }
        transport.play();

        let mut output = vec![0.0f32; 512];
        for _ in 0..8 {
            mixer.process(&mut output, &[], &transport);
            for (i, &s) in output.iter().enumerate() {
                assert!(s.is_finite(), "non-finite sample at {i}");
                assert!(s.abs() <= 1.0, "sample {i} left the mixer at {s}");
            }
        }

        // And it is actually holding the ceiling, not silencing the mix.
        let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak > 0.8, "limiter over-attenuated, peak={peak}");
    }

    /// A NaN out of a diverging filter must not reach the device: at full
    /// scale it is a noise burst, and it also poisons every sample after it
    /// if it is allowed into the limiter's gain state.
    #[test]
    fn non_finite_track_output_becomes_silence() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        add_fixed_track(&tx, 0, f32::NAN);
        transport.play();

        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &[], &transport);
        assert!(output.iter().all(|s| *s == 0.0), "NaN track should render as silence");

        // ...and the mixer still works afterwards: the gain state was not
        // left as NaN by the sample that was thrown away.
        tx.send(MixerCommand::RemoveTrack { track_id: 0 }).unwrap();
        add_fixed_track(&tx, 1, 0.5);
        mixer.process(&mut output, &[], &transport);
        let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!((peak - 0.5).abs() < 1.0e-6, "mixer did not recover, peak={peak}");
    }

    #[test]
    fn infinite_track_output_becomes_silence() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        add_fixed_track(&tx, 0, f32::INFINITY);
        transport.play();

        let mut output = vec![0.0f32; 512];
        mixer.process(&mut output, &[], &transport);
        assert!(output.iter().all(|s| *s == 0.0), "infinite track should render as silence");
    }

    /// Below the ceiling the limiter is not a processor, it is a wire. Any
    /// deviation here would be gain riding on material that never asked for
    /// it — which is exactly what makes a limiter audible.
    #[test]
    fn limiter_is_bit_identical_below_the_ceiling() {
        let mut limiter = MasterLimiter::new(44_100);

        // A sweep of levels up to the ceiling, plus signs and denormals.
        let mut input: Vec<f32> = Vec::new();
        for i in 0..20_000u32 {
            let phase = i as f32 * 0.01;
            let amp = LIMITER_CEILING * (i as f32 / 20_000.0);
            input.push(phase.sin() * amp);
            input.push(phase.cos() * amp);
        }
        input.push(LIMITER_CEILING);
        input.push(-LIMITER_CEILING);
        input.push(0.0);
        input.push(-0.0);
        input.push(f32::MIN_POSITIVE);
        input.push(-f32::MIN_POSITIVE);

        let mut output = input.clone();
        limiter.process(&mut output);

        for (i, (a, b)) in input.iter().zip(output.iter()).enumerate() {
            assert_eq!(a.to_bits(), b.to_bits(), "limiter altered sample {i}: {a} -> {b}");
        }
    }

    /// The ceiling holds for anything, including levels no instrument in the
    /// project can produce.
    #[test]
    fn limiter_holds_the_ceiling_under_abuse() {
        let mut limiter = MasterLimiter::new(44_100);
        for amplitude in [1.0f32, 2.0, 10.0, 1.0e3, 1.0e6, 1.0e30] {
            let mut buf: Vec<f32> = (0..4_096)
                .map(|i| (i as f32 * 0.05).sin() * amplitude)
                .collect();
            limiter.process(&mut buf);
            for (i, &s) in buf.iter().enumerate() {
                assert!(s.is_finite(), "amplitude {amplitude}: sample {i} is {s}");
                assert!(
                    s.abs() <= LIMITER_CEILING,
                    "amplitude {amplitude}: sample {i} reached {s}, above the ceiling"
                );
            }
        }
    }

    /// A step from silence to well over the ceiling: the very first sample of
    /// the step must already be limited. Anything else means overshoot, and
    /// the only thing left to catch overshoot is a hard clip.
    #[test]
    fn limiter_attack_has_no_overshoot() {
        let mut limiter = MasterLimiter::new(44_100);
        let mut buf = vec![0.0f32; 64];
        limiter.process(&mut buf);
        let mut step = vec![4.0f32; 64];
        limiter.process(&mut step);
        assert!(
            step[0].abs() <= LIMITER_CEILING,
            "first sample of the step overshot to {}",
            step[0]
        );
    }

    /// Gain reduction must come back smoothly, not step. A step would be a
    /// click; a release faster than a low note's period would distort it.
    #[test]
    fn limiter_release_is_gradual() {
        let mut limiter = MasterLimiter::new(44_100);
        let mut loud = vec![4.0f32; 64];
        limiter.process(&mut loud);
        let reduced = limiter.gain;
        assert!(reduced < 0.5, "limiter did not engage, gain={reduced}");

        // 10 ms of quiet material (441 stereo frames): partly recovered, not
        // all the way.
        let mut quiet = vec![0.1f32; 441 * 2];
        limiter.process(&mut quiet);
        assert!(limiter.gain > reduced, "gain did not recover at all");
        assert!(
            limiter.gain < 1.0,
            "gain snapped back to unity within 10 ms, which is a click"
        );

        // 500 ms is ten time constants: fully recovered.
        let mut long = vec![0.1f32; 22_050 * 2];
        limiter.process(&mut long);
        assert!(
            (limiter.gain - 1.0).abs() < 1.0e-4,
            "gain never returned to unity: {}",
            limiter.gain
        );
    }

    /// Stereo-linked: one gain from `max(|L|, |R|)`, so a peak on one side
    /// does not pull the image across to the other.
    #[test]
    fn limiter_does_not_shift_the_stereo_image() {
        let mut limiter = MasterLimiter::new(44_100);
        // Left twice the level of right, both well over the ceiling.
        let mut buf: Vec<f32> = Vec::new();
        for i in 0..1_024 {
            let phase = i as f32 * 0.05;
            buf.push(phase.sin() * 3.0);
            buf.push(phase.sin() * 1.5);
        }
        limiter.process(&mut buf);
        for frame in buf.chunks_exact(2) {
            if frame[1].abs() > 1.0e-4 {
                let ratio = frame[0] / frame[1];
                assert!(
                    (ratio - 2.0).abs() < 1.0e-3,
                    "channel balance moved: L/R = {ratio}"
                );
            }
        }
    }

    /// The loudest single voice in the project: ROM3A's TIMPANI, voice 147 of
    /// the DX7's 256 factory voices, which is what `phosphor-dsp`'s headroom
    /// sweep measures as the hottest thing any instrument here can produce.
    ///
    /// The DX7 has two selectors — a cartridge and a voice — so picking one by
    /// number goes through `voice_knobs`.
    fn loudest_dx7_voice() -> phosphor_dsp::dx7::Dx7Synth {
        use phosphor_dsp::dx7;
        let mut synth = dx7::Dx7Synth::new();
        let (bank, patch) = dx7::voice_knobs(147);
        synth.set_parameter(dx7::P_BANK, bank);
        synth.set_parameter(dx7::P_PATCH, patch);
        debug_assert_eq!(dx7::voice_name(147), "TIMPANI");
        synth
    }

    /// Four tracks of the loudest DX7 voice, each playing a two-handed
    /// eight-note chord at full velocity with the fader open — a heavier mix
    /// than anything the application can produce by accident.
    #[test]
    fn master_limiter_bounds_four_loud_instrument_tracks() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        for id in 0..4 {
            let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
            handle.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
            handle.config.set_volume(1.0);
            let synth = loudest_dx7_voice();
            tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
            tx.send(MixerCommand::SetInstrument {
                track_id: id,
                instrument: Box::new(synth),
            }).unwrap();
        }
        transport.play();

        let chord: Vec<MidiMessage> = [36u8, 43, 48, 55, 60, 64, 67, 72]
            .iter()
            .map(|&note| make_note_on(note, 127))
            .collect();

        let mut output = vec![0.0f32; 512];
        let mut peak = 0.0f32;
        for block in 0..200 {
            output.fill(0.0);
            if block == 0 {
                mixer.process(&mut output, &chord, &transport);
            } else {
                mixer.process(&mut output, &[], &transport);
            }
            for (i, &s) in output.iter().enumerate() {
                assert!(s.is_finite(), "block {block} sample {i} is {s}");
                assert!(s.abs() <= 1.0, "block {block} sample {i} left the mixer at {s}");
                peak = peak.max(s.abs());
            }
        }
        assert!(peak > 0.5, "four loud tracks should be loud, peak={peak}");
    }

    /// The limiter must be inaudible in ordinary playing, which means it must
    /// not engage at all. The worst single track the application can produce
    /// is the loudest preset in the bank, an eight-note chord at velocity 127,
    /// with the fader all the way open — and that still has to leave the gain
    /// at exactly unity, so the mix is the track sum sample for sample.
    #[test]
    fn limiter_idle_for_the_worst_single_track() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let handle = Arc::new(TrackHandle::new(0, TrackKind::Instrument));
        handle.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
        handle.config.set_volume(1.0);
        let synth = loudest_dx7_voice();
        tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
        tx.send(MixerCommand::SetInstrument { track_id: 0, instrument: Box::new(synth) }).unwrap();
        transport.play();

        let chord: Vec<MidiMessage> = [36u8, 43, 48, 55, 60, 64, 67, 72]
            .iter()
            .map(|&note| make_note_on(note, 127))
            .collect();

        let mut output = vec![0.0f32; 512];
        let mut peak = 0.0f32;
        for block in 0..200 {
            output.fill(0.0);
            if block == 0 {
                mixer.process(&mut output, &chord, &transport);
            } else {
                mixer.process(&mut output, &[], &transport);
            }
            peak = peak.max(output.iter().map(|s| s.abs()).fold(0.0f32, f32::max));
            assert_eq!(
                mixer.limiter.gain, 1.0,
                "limiter engaged at block {block}, peak {peak}"
            );
        }
        assert!(peak > 0.3, "expected a loud chord, peak={peak}");
    }

    // ── Fader ──

    /// Render the loudest thing one track in this project can produce, with
    /// the fader at `volume`. Returns the output peak and the lowest gain the
    /// limiter reached.
    fn worst_track_through_the_mixer(volume: f32) -> (f32, f32) {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let handle = Arc::new(TrackHandle::new(0, TrackKind::Instrument));
        handle.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
        handle.config.set_volume(volume);
        let synth = loudest_dx7_voice();
        tx.send(MixerCommand::AddTrack { kind: TrackKind::Instrument, handle }).unwrap();
        tx.send(MixerCommand::SetInstrument { track_id: 0, instrument: Box::new(synth) }).unwrap();
        transport.play();

        let chord: Vec<MidiMessage> = [36u8, 43, 48, 55, 60, 64, 67, 72]
            .iter()
            .map(|&note| make_note_on(note, 127))
            .collect();

        let mut output = vec![0.0f32; 512];
        let mut peak = 0.0f32;
        let mut min_gain = 1.0f32;
        for block in 0..200 {
            output.fill(0.0);
            if block == 0 {
                mixer.process(&mut output, &chord, &transport);
            } else {
                mixer.process(&mut output, &[], &transport);
            }
            for &s in output.iter() {
                assert!(s.is_finite(), "block {block}: non-finite sample");
                assert!(s.abs() <= 1.0, "block {block}: sample left the mixer at {s}");
                peak = peak.max(s.abs());
            }
            min_gain = min_gain.min(mixer.limiter.gain);
        }
        (peak, min_gain)
    }

    /// Anywhere from the bottom of the fader up to unity, the limiter is not
    /// in the signal path at all — not "barely", not at all — even for the
    /// loudest patch in the project played as hard as the format allows.
    ///
    /// This is what the instrument trims buy. Gain reduction on the master
    /// bus is then always a mix decision (several loud tracks at once) rather
    /// than something one instrument can cause on its own.
    #[test]
    fn fader_below_unity_never_engages_the_limiter() {
        for volume in [
            0.25,
            TrackConfig::DEFAULT_VOLUME,
            TrackConfig::UNITY_VOLUME,
        ] {
            let (peak, min_gain) = worst_track_through_the_mixer(volume);
            assert_eq!(
                min_gain, 1.0,
                "limiter reduced by {:.2} dB at fader {volume} (peak {peak:.4})",
                20.0 * min_gain.log10()
            );
        }
    }

    /// Above unity the fader is makeup gain the user asked for, and the
    /// limiter is what makes asking for it safe. Two things have to hold:
    /// the output stays bounded, and turning the fader up never makes the
    /// track quieter than leaving it at unity — a limiter that over-ducks
    /// would turn the top of the fader into a trap.
    #[test]
    fn fader_makeup_gain_is_bounded_not_wasted() {
        let (unity_peak, _) = worst_track_through_the_mixer(TrackConfig::UNITY_VOLUME);
        let (max_peak, min_gain) = worst_track_through_the_mixer(TrackConfig::MAX_VOLUME);

        assert!(
            max_peak <= LIMITER_CEILING,
            "fader at maximum let {max_peak:.4} through, above the ceiling"
        );
        assert!(
            max_peak >= unity_peak,
            "turning the fader up made the track quieter: {unity_peak:.4} -> {max_peak:.4}"
        );
        // The limiter took back some of the boost, but not more than the
        // fader added — otherwise it is attenuating, not limiting.
        let reduction_db = -20.0 * min_gain.log10();
        let boost_db = 20.0 * (TrackConfig::MAX_VOLUME / TrackConfig::UNITY_VOLUME).log10();
        assert!(
            reduction_db <= boost_db,
            "limiter took {reduction_db:.2} dB off a {boost_db:.2} dB boost"
        );
    }

    // ── Metronome balance ──

    /// The click has no fader and is not mixed through a track, so nothing
    /// downstream can compensate for it being wrong: it only sits right
    /// relative to the music if `CLICK_VOLUME` tracks the instruments'
    /// headroom trims. That coupling is invisible from either file and has
    /// already drifted once, when the trims moved and the click did not.
    ///
    /// So: a click against the level a user hears while playing — the default
    /// preset, a triad at velocity 100, fader at its default. Loud enough to
    /// play to, not so loud it is the loudest thing in the mix.
    #[test]
    fn metronome_click_sits_with_the_music() {
        use phosphor_dsp::dx7;

        fn render(with_track: bool, metronome: bool) -> f32 {
            let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
            let chord: Vec<MidiMessage> = if with_track {
                let handle = Arc::new(TrackHandle::new(0, TrackKind::Instrument));
                handle.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
                tx.send(MixerCommand::AddTrack {
                    kind: TrackKind::Instrument,
                    handle,
                })
                .unwrap();
                tx.send(MixerCommand::SetInstrument {
                    track_id: 0,
                    instrument: Box::new(dx7::Dx7Synth::new()),
                })
                .unwrap();
                [60u8, 64, 67].iter().map(|&n| make_note_on(n, 100)).collect()
            } else {
                Vec::new()
            };
            if metronome {
                transport.toggle_metronome();
            }
            transport.play();

            let mut output = vec![0.0f32; 512];
            let mut peak = 0.0f32;
            for block in 0..200 {
                output.fill(0.0);
                if block == 0 {
                    mixer.process(&mut output, &chord, &transport);
                } else {
                    mixer.process(&mut output, &[], &transport);
                }
                peak = peak.max(output.iter().map(|s| s.abs()).fold(0.0f32, f32::max));
                transport.advance(256, 44_100);
            }
            peak
        }

        let music = render(true, false);
        let click = render(false, true);
        assert!(music > 0.0 && click > 0.0, "music {music}, click {click}");

        let relative_db = 20.0 * (click / music).log10();
        assert!(
            (-12.0..=0.0).contains(&relative_db),
            "the click is {relative_db:.1} dB against a triad (click {click:.4}, \
             music {music:.4}); it has to be audible over the music without \
             being the loudest thing in the mix"
        );
    }

    /// The fader reaches the audio thread. Not a tautology: `volume` is read
    /// per buffer through the atomic, so this catches a mix path that caches
    /// it or ignores it.
    #[test]
    fn fader_scales_the_track() {
        let (mut mixer, tx, _clip_rx, transport) = setup_mixer();
        let handle = add_fixed_track(&tx, 0, 0.25);
        transport.play();

        let mut output = vec![0.0f32; 512];
        for (volume, expected) in [(0.0f32, 0.0f32), (0.5, 0.125), (1.0, 0.25), (2.0, 0.5)] {
            handle.config.set_volume(volume);
            output.fill(0.0);
            mixer.process(&mut output, &[], &transport);
            let peak = output.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
            assert!(
                (peak - expected).abs() < 1.0e-6,
                "fader at {volume} gave {peak}, expected {expected}"
            );
        }
    }

    // ── The device decides the rate ──

    /// A device that would not give us the rate we asked for.
    fn refused(asked: u32, sample_rate: u32, max_buffer_frames: u32) -> StreamFormat {
        StreamFormat {
            sample_rate,
            buffer_size: Some(64),
            max_buffer_frames,
            channels: 2,
            sample_rate_request: Requested::Refused(asked),
            buffer_size_request: Requested::Granted,
        }
    }

    /// The defect: the mixer was built from the command-line sample rate while
    /// the stream ran at the device's. Everything the mixer derives from the
    /// rate — oscillator increments, envelope times, the tick advance — was
    /// then wrong by the ratio between the two.
    #[test]
    fn the_mixer_runs_at_the_rate_the_device_granted() {
        let requested = crate::EngineConfig { buffer_size: 64, sample_rate: 44100 };
        let format = refused(44100, 48000, 4096);
        let effective = crate::EngineConfig::from(format);

        let (_tx, rx) = mixer_command_channel();
        let (clip_tx, _clip_rx) = clip_snapshot_channel();
        let mixer = Mixer::new(
            rx,
            Arc::new(VuLevels::new()),
            clip_tx,
            effective.sample_rate,
            format.max_buffer_frames as usize,
        );

        assert_eq!(mixer.sample_rate, 48000, "mixer must adopt the device's rate");
        assert_ne!(
            mixer.sample_rate, requested.sample_rate,
            "the request was 44100 and the device said 48000; taking the \
             request here is the 8.84%-sharp bug"
        );
        assert_eq!(mixer.max_buffer_size, 4096);
    }

    /// A device that offers exactly what was asked for changes nothing.
    #[test]
    fn a_device_that_agrees_leaves_the_request_alone() {
        let requested = crate::EngineConfig { buffer_size: 64, sample_rate: 44100 };
        let format = StreamFormat {
            sample_rate: 44100,
            buffer_size: Some(64),
            max_buffer_frames: 4096,
            channels: 2,
            sample_rate_request: Requested::Granted,
            buffer_size_request: Requested::Granted,
        };
        assert_eq!(crate::EngineConfig::from(format), requested);
    }

    /// The default path, and the one that has to be right for the most
    /// people: nothing asked for, so the mixer is built at whatever the
    /// device was already set to.
    #[test]
    fn asking_for_nothing_builds_the_mixer_at_the_devices_rate() {
        let format = StreamFormat {
            sample_rate: 48000,
            buffer_size: None,
            max_buffer_frames: 4096,
            channels: 2,
            sample_rate_request: Requested::Unasked,
            buffer_size_request: Requested::Unasked,
        };
        let effective = crate::EngineConfig::from(format);

        let (_tx, rx) = mixer_command_channel();
        let (clip_tx, _clip_rx) = clip_snapshot_channel();
        let mixer = Mixer::new(
            rx,
            Arc::new(VuLevels::new()),
            clip_tx,
            effective.sample_rate,
            format.max_buffer_frames as usize,
        );
        assert_eq!(mixer.sample_rate, 48000);
        assert_eq!(mixer.max_buffer_size, 4096);
        assert!(format.divergence_notice().is_none(), "following the device is not news");
    }

    /// The defect: buffers were sized from the requested block, the device
    /// handed the callback a larger one, and `process` grew them — a heap
    /// allocation on the audio thread, on the very first callback.
    #[test]
    fn the_largest_block_the_device_promised_never_grows_a_buffer() {
        let max_frames = 512usize;
        let (tx, rx) = mixer_command_channel();
        let (clip_tx, _clip_rx) = clip_snapshot_channel();
        let mut mixer = Mixer::new(
            rx,
            Arc::new(VuLevels::new()),
            clip_tx,
            48000,
            max_frames,
        );
        let transport = Arc::new(Transport::new(120.0));
        let _handle = add_armed_synth(&tx, 0);
        mixer.drain_commands();

        // Snapshot after the track exists: adding one is a UI-driven
        // allocation, not a per-callback one.
        let before = (
            mixer.scratch_l.capacity(),
            mixer.scratch_r.capacity(),
            mixer.tracks[0].buf_l.capacity(),
            mixer.tracks[0].buf_r.capacity(),
        );

        transport.play();
        let mut output = vec![0.0f32; max_frames * 2];
        mixer.process(&mut output, &[make_note_on(60, 100)], &transport);

        let after = (
            mixer.scratch_l.capacity(),
            mixer.scratch_r.capacity(),
            mixer.tracks[0].buf_l.capacity(),
            mixer.tracks[0].buf_r.capacity(),
        );
        assert_eq!(
            before, after,
            "a block the size the device promised must fit the buffers as \
             allocated; growing one means the audio thread called the allocator"
        );
    }

    /// The invariant stated everywhere in this crate, held to by the
    /// allocator rather than by reading the code: a steady-state callback
    /// touches no heap.
    #[test]
    fn a_steady_state_callback_does_not_allocate() {
        let max_frames = 512usize;
        let (tx, rx) = mixer_command_channel();
        let (clip_tx, _clip_rx) = clip_snapshot_channel();
        let mut mixer = Mixer::new(rx, Arc::new(VuLevels::new()), clip_tx, 48000, max_frames);
        let transport = Arc::new(Transport::new(120.0));
        let _handle = add_armed_synth(&tx, 0);
        mixer.drain_commands();
        transport.play();

        let mut output = vec![0.0f32; max_frames * 2];
        // One warm-up block: anything lazily built on first use — the
        // wavetable bank behind its `OnceLock`, for one — is built here,
        // outside the region under test.
        mixer.process(&mut output, &[make_note_on(60, 100)], &transport);

        let allocations = crate::alloc_count::allocations_during(|| {
            for _ in 0..8 {
                mixer.process(&mut output, &[], &transport);
            }
        });
        assert_eq!(allocations, 0, "Mixer::process reached the allocator");
    }

    // ── The step sequencer ──

    use crate::pattern::{ChainEntry, Lane, PatternEvent, Rate, Step};

    /// A mixer at a given rate, with nothing on it.
    fn bare_mixer(
        sample_rate: u32,
        max_frames: usize,
    ) -> (Mixer, Sender<MixerCommand>, Arc<Transport>) {
        let (tx, rx) = mixer_command_channel();
        let (clip_tx, _clip_rx) = clip_snapshot_channel();
        let mixer = Mixer::new(rx, Arc::new(VuLevels::new()), clip_tx, sample_rate, max_frames);
        (mixer, tx, Arc::new(Transport::new(120.0)))
    }

    /// A pattern with one drum lane on the steps named.
    fn kick_pattern(on: &[usize]) -> PatternBlock {
        let mut block = PatternBlock::empty();
        block.playing = true;
        block.lanes[0] = Lane::drum(36);
        for &index in on {
            block.lanes[0].steps[index].on = true;
        }
        block
    }

    fn add_track(tx: &Sender<MixerCommand>, id: usize) -> Arc<TrackHandle> {
        let handle = Arc::new(TrackHandle::new(id, TrackKind::Instrument));
        tx.send(MixerCommand::AddTrack {
            kind: TrackKind::Instrument,
            handle: handle.clone(),
        })
        .unwrap();
        handle
    }

    fn apply_all(mixer: &mut Mixer) {
        while !mixer.command_rx.is_empty() {
            mixer.drain_commands();
        }
    }

    fn note_ons(track: &AudioTrack) -> impl Iterator<Item = &MidiEvent> {
        track.plugin_events.iter().filter(|e| e.status == 0x90 && e.data2 > 0)
    }

    /// **The sync guarantee.** A pattern step and a clip note on the same
    /// beat have to reach the instrument at the same sample, in the same
    /// callback — at every block size and every sample rate, because those
    /// are what a wrong answer would be a function of.
    ///
    /// It holds by construction rather than by agreement: both go through
    /// one `PlaybackWindow`. This is the test that would catch that ceasing
    /// to be true.
    #[test]
    fn a_pattern_step_and_a_clip_note_land_on_the_same_sample() {
        for sample_rate in [44_100u32, 48_000, 96_000] {
            for frames in [64usize, 256, 470] {
                let (mut mixer, tx, transport) = bare_mixer(sample_rate, 512);

                // Track 0: a clip with one note on beat two.
                let _clip_track = add_track(&tx, 0);
                tx.send(MixerCommand::CreateClip {
                    track_id: 0,
                    start_tick: 0,
                    length_ticks: 3840,
                })
                .unwrap();
                tx.send(MixerCommand::UpdateClip {
                    track_id: 0,
                    clip_index: 0,
                    events: vec![ClipEvent { tick: 960, status: 0x90, data1: 60, data2: 100 }],
                })
                .unwrap();

                // Track 1: a pattern whose fourth sixteenth is beat two.
                let _seq_track = add_track(&tx, 1);
                tx.send(MixerCommand::SetPattern {
                    track_id: 1,
                    slot: 0,
                    block: kick_pattern(&[4]),
                })
                .unwrap();
                apply_all(&mut mixer);

                transport.play();
                let mut output = vec![0.0f32; frames * 2];
                let mut landed = None;
                while transport.position_ticks() < 1_200 {
                    mixer.process(&mut output, &[], &transport);
                    let clip_note = note_ons(&mixer.tracks[0]).find(|e| e.data1 == 60);
                    let step_note = note_ons(&mixer.tracks[1]).find(|e| e.data1 == 36);
                    match (clip_note, step_note) {
                        (Some(c), Some(s)) => {
                            landed = Some((c.sample_offset, s.sample_offset));
                            break;
                        }
                        (None, None) => {}
                        (clip, step) => panic!(
                            "at {sample_rate} Hz / {frames} frames only one of them fired: \
                             clip={clip:?} step={step:?}"
                        ),
                    }
                    transport.advance(frames as u32, sample_rate);
                }
                let (clip_at, step_at) =
                    landed.unwrap_or_else(|| panic!("nothing fired at {sample_rate}/{frames}"));
                assert_eq!(
                    clip_at, step_at,
                    "at {sample_rate} Hz / {frames} frames the clip note landed on sample \
                     {clip_at} and the step on {step_at}"
                );
            }
        }
    }

    /// A pattern is timed in ticks, so the same pattern has to occupy the
    /// same wall-clock time at every sample rate the application supports.
    #[test]
    fn step_timing_is_the_same_at_every_sample_rate() {
        let frames = 256usize;
        for sample_rate in [44_100u32, 48_000, 96_000] {
            let (mut mixer, tx, transport) = bare_mixer(sample_rate, 512);
            let _track = add_track(&tx, 0);
            tx.send(MixerCommand::SetPattern {
                track_id: 0,
                slot: 0,
                block: kick_pattern(&[0, 4, 8, 12]),
            })
            .unwrap();
            apply_all(&mut mixer);

            transport.play();
            let mut output = vec![0.0f32; frames * 2];
            let mut seconds = Vec::new();
            let mut block = 0usize;
            while seconds.len() < 4 && transport.position_ticks() < 3_600 {
                mixer.process(&mut output, &[], &transport);
                for event in note_ons(&mixer.tracks[0]) {
                    let sample = block * frames + event.sample_offset as usize;
                    seconds.push(sample as f64 / f64::from(sample_rate));
                }
                transport.advance(frames as u32, sample_rate);
                block += 1;
            }

            // Four steps a beat apart at 120 BPM: half a second each.
            assert_eq!(seconds.len(), 4, "at {sample_rate} Hz");
            for (index, at) in seconds.iter().enumerate() {
                let expected = index as f64 * 0.5;
                assert!(
                    (at - expected).abs() < 0.002,
                    "at {sample_rate} Hz step {index} landed at {at:.4}s, expected {expected:.4}s"
                );
            }
        }
    }

    /// The wrap, which is where a sequencer written around a free-running
    /// cursor loses or repeats a step. Sixteen onsets per time round, every
    /// time round: the window stops at the loop point so nothing on the far
    /// side of it plays early, and the step is derived from the position so
    /// nothing is skipped when it comes back.
    #[test]
    fn a_loop_wrap_neither_drops_nor_doubles_the_first_step() {
        let frames = 256usize;
        let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
        let _track = add_track(&tx, 0);
        let all_sixteen: Vec<usize> = (0..16).collect();
        tx.send(MixerCommand::SetPattern {
            track_id: 0,
            slot: 0,
            block: kick_pattern(&all_sixteen),
        })
        .unwrap();
        apply_all(&mut mixer);

        transport.set_loop_bars(1, 1);
        transport.toggle_loop();
        transport.play();

        let mut output = vec![0.0f32; frames * 2];
        let mut fired = 0usize;
        let mut wraps = 0usize;
        let mut last = transport.position_ticks();
        for _ in 0..4_000 {
            mixer.process(&mut output, &[], &transport);
            fired += note_ons(&mixer.tracks[0]).count();
            transport.advance(frames as u32, 44_100);
            let now = transport.position_ticks();
            if now < last {
                wraps += 1;
                if wraps == 4 {
                    break;
                }
            }
            last = now;
        }
        assert_eq!(wraps, 4, "the transport did not loop");
        assert_eq!(fired, 64, "four times round a 16-step pattern is 64 onsets");
    }

    /// A sequencer track makes no sound of its own: it drives the instrument
    /// in the track's plugin slot, which is an ordinary instrument in an
    /// ordinary slot. Nothing in the audio path knows a sequencer exists.
    #[test]
    fn a_sequencer_track_plays_its_child_instrument() {
        let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
        let handle = add_track(&tx, 0);
        handle.config.set_volume(1.0);
        tx.send(MixerCommand::SetInstrument {
            track_id: 0,
            instrument: Box::new(PhosphorSynth::new()),
        })
        .unwrap();
        let mut block = PatternBlock::empty();
        block.playing = true;
        block.lanes[0].steps[0].on = true;
        block.lanes[0].steps[0].gate = 200;
        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block }).unwrap();
        apply_all(&mut mixer);

        transport.play();
        let mut output = vec![0.0f32; 512 * 2];
        let mut peak = 0.0f32;
        for _ in 0..8 {
            mixer.process(&mut output, &[], &transport);
            peak = peak.max(output.iter().map(|s| s.abs()).fold(0.0, f32::max));
            transport.advance(512, 44_100);
        }
        assert!(peak > 0.001, "the child instrument never sounded, peak={peak}");
    }

    /// Stopping the transport ends every note the sequencer is holding. A
    /// tied step has no note-off of its own, so without this it is a voice
    /// that sounds until the next panic.
    #[test]
    fn stopping_the_transport_ends_every_pattern_note() {
        let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
        let _track = add_track(&tx, 0);
        let mut block = kick_pattern(&[0]);
        block.lanes[0].steps[0].gate = Step::TIE;
        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block }).unwrap();
        apply_all(&mut mixer);

        transport.play();
        let mut output = vec![0.0f32; 256 * 2];
        mixer.process(&mut output, &[], &transport);
        assert_eq!(note_ons(&mixer.tracks[0]).count(), 1);
        transport.advance(256, 44_100);

        transport.pause();
        mixer.process(&mut output, &[], &transport);
        let offs: Vec<u8> = mixer.tracks[0]
            .plugin_events
            .iter()
            .filter(|e| e.status == 0x80)
            .map(|e| e.data1)
            .collect();
        assert_eq!(offs, vec![36], "the tied note was left sounding");

        // ...and only once.
        mixer.process(&mut output, &[], &transport);
        assert!(mixer.tracks[0].plugin_events.is_empty());
    }

    /// A panic drops the table rather than sounding it: the instruments are
    /// being reset underneath, so the offs would be addressed to voices that
    /// no longer exist.
    #[test]
    fn a_panic_leaves_the_sequencer_holding_nothing() {
        let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
        let _track = add_track(&tx, 0);
        let mut block = kick_pattern(&[0]);
        block.lanes[0].steps[0].gate = Step::TIE;
        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block }).unwrap();
        apply_all(&mut mixer);

        transport.play();
        let mut output = vec![0.0f32; 256 * 2];
        mixer.process(&mut output, &[], &transport);
        assert!(mixer.tracks[0].pattern.as_ref().unwrap().held_notes() > 0);

        mixer.reset_all();
        assert_eq!(mixer.tracks[0].pattern.as_ref().unwrap().held_notes(), 0);
    }

    /// The bounce, end to end and through a real instrument: one cycle of a
    /// swung pattern compiled to a clip, played back as a clip, has to be the
    /// same audio the sequencer produced live. Sample for sample — the two
    /// paths share a generator, so anything less is a defect rather than a
    /// tolerance.
    ///
    /// Every gate closes inside the cycle. A bounce is one time through, so a
    /// note that outlives the cycle has nowhere to go and the two renders
    /// would legitimately differ at the tail.
    #[test]
    fn a_bounced_pattern_renders_identically_to_the_live_one() {
        const SWING: u8 = 62;
        let mut block = PatternBlock::empty();
        block.playing = true;
        block.swing = SWING;
        block.rate = Rate::Sixteenth;
        for (index, (key, chord, gate)) in [
            (0usize, 0u8, 5u8, 50u8),
            (3, 3, 6, 90),
            (5, 7, 1, 25),
            (9, 5, 14, 75),
            (11, 10, 12, 40),
            (14, 0, 15, 60),
        ]
        .iter()
        .map(|(i, k, c, g)| (*i, (*k, *c, *g)))
        {
            let step = &mut block.lanes[0].steps[index];
            step.on = true;
            step.key = key;
            step.chord = chord;
            step.gate = gate;
            step.accent = index % 2 == 1;
        }

        let cycle = block.length_ticks();
        let blocks = 24; // 24 x 512 frames at 44.1 kHz covers a bar and a bit

        // Live: the sequencer driving the synth.
        let live = {
            let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
            let handle = add_track(&tx, 0);
            handle.config.set_volume(1.0);
            tx.send(MixerCommand::SetInstrument {
                track_id: 0,
                instrument: Box::new(PhosphorSynth::new()),
            })
            .unwrap();
            tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block }).unwrap();
            apply_all(&mut mixer);
            transport.play();

            let mut rendered = Vec::new();
            let mut output = vec![0.0f32; 512 * 2];
            for _ in 0..blocks {
                mixer.process(&mut output, &[], &transport);
                rendered.extend_from_slice(&output);
                transport.advance(512, 44_100);
            }
            rendered
        };

        // Bounced: the same cycle compiled to a clip, played as a clip.
        let bounced = {
            let mut events = Vec::new();
            crate::pattern::compile_cycle(&block, 0, &mut events);
            assert!(!events.is_empty());
            let clip_events: Vec<ClipEvent> = events
                .iter()
                .map(|e: &PatternEvent| ClipEvent {
                    tick: e.tick,
                    status: e.status,
                    data1: e.data1,
                    data2: e.data2,
                })
                .collect();

            let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
            let handle = add_track(&tx, 0);
            handle.config.set_volume(1.0);
            tx.send(MixerCommand::SetInstrument {
                track_id: 0,
                instrument: Box::new(PhosphorSynth::new()),
            })
            .unwrap();
            tx.send(MixerCommand::CreateClip {
                track_id: 0,
                start_tick: 0,
                length_ticks: cycle,
            })
            .unwrap();
            tx.send(MixerCommand::UpdateClip {
                track_id: 0,
                clip_index: 0,
                events: clip_events,
            })
            .unwrap();
            apply_all(&mut mixer);
            transport.play();

            let mut rendered = Vec::new();
            let mut output = vec![0.0f32; 512 * 2];
            for _ in 0..blocks {
                mixer.process(&mut output, &[], &transport);
                rendered.extend_from_slice(&output);
                transport.advance(512, 44_100);
            }
            rendered
        };

        assert_eq!(live.len(), bounced.len());
        let peak = live.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
        assert!(peak > 0.001, "the live render was silent, so this proves nothing");
        for (i, (a, b)) in live.iter().zip(&bounced).enumerate() {
            assert_eq!(
                a.to_bits(),
                b.to_bits(),
                "sample {i} differs: live {a} bounced {b} at {SWING}% swing"
            );
        }
    }

    /// The rule the audio thread lives by, with a sequencer on it: taking a
    /// new pattern while notes are sounding, switching patterns, advancing a
    /// chain, playing chords and turning everything off are all writes into
    /// memory that already exists.
    #[test]
    fn pattern_playback_does_not_allocate() {
        let (mut mixer, tx, transport) = bare_mixer(48_000, 512);
        let _track = add_track(&tx, 0);
        tx.send(MixerCommand::SetInstrument {
            track_id: 0,
            instrument: Box::new(PhosphorSynth::new()),
        })
        .unwrap();

        // Slot 0: chords on a melodic lane. Slot 1: a drum lane.
        let mut chords = PatternBlock::empty();
        chords.playing = true;
        chords.mode = crate::pattern::Mode::Aeolian;
        for index in 0..16 {
            let step = &mut chords.lanes[0].steps[index];
            step.on = true;
            step.chord = 4; // diatonic seventh
            step.voicing = 1 | Step::ROOT_BELOW;
            step.key = (index as u8 * 2) % 12;
        }
        let drums = kick_pattern(&[0, 4, 8, 12]);

        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 1, block: drums }).unwrap();
        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block: chords }).unwrap();
        // A clip on the same track, so the shared window is exercised from
        // both sides while the measurement is running.
        tx.send(MixerCommand::CreateClip { track_id: 0, start_tick: 0, length_ticks: 3840 })
            .unwrap();
        tx.send(MixerCommand::UpdateClip {
            track_id: 0,
            clip_index: 0,
            events: (0..16)
                .flat_map(|i| {
                    [
                        ClipEvent { tick: i * 240, status: 0x90, data1: 40, data2: 90 },
                        ClipEvent { tick: i * 240 + 120, status: 0x80, data1: 40, data2: 0 },
                    ]
                })
                .collect(),
        })
        .unwrap();
        apply_all(&mut mixer);
        transport.play();

        let mut output = vec![0.0f32; 512 * 2];
        // Warm-up: anything built lazily on first use is built here.
        for _ in 0..2 {
            mixer.process(&mut output, &[], &transport);
            transport.advance(512, 48_000);
        }

        let mut queued = chords;
        queued.pending_slot = Some(1);
        let mut chained = chords;
        chained.chain[0] = ChainEntry { slot: 0, repeats: 1 };
        chained.chain[1] = ChainEntry { slot: 1, repeats: 1 };
        chained.chain_len = 2;

        let allocations = crate::alloc_count::allocations_during(|| {
            for block in 0..400 {
                if block == 20 {
                    tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block: queued })
                        .unwrap();
                }
                if block == 120 {
                    tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block: chained })
                        .unwrap();
                }
                mixer.process(&mut output, &[], &transport);
                transport.advance(512, 48_000);
            }
            transport.pause();
            mixer.process(&mut output, &[], &transport);
        });
        assert_eq!(allocations, 0, "the sequencer reached the allocator");
    }

    /// What a queued command costs to sit in the channel. The block travels
    /// by value so that receiving one cannot reach the allocator, and this is
    /// the price of that: every `MixerCommand`, whichever variant, is now as
    /// wide as the widest one.
    ///
    /// Worth stating out loud rather than discovering later. A full command
    /// budget in flight is 150 kB of queue, which is nothing on the heap and
    /// everything on the audio thread's deadline, and that is the trade.
    #[test]
    fn a_command_is_as_wide_as_a_pattern() {
        assert_eq!(
            std::mem::size_of::<MixerCommand>(),
            crate::pattern::PatternBlock::SIZE + 11
        );
    }

    /// What the UI reads to draw the playhead and the queued-slot countdown.
    /// Atomics on the track handle, the same shape as the VU meters.
    #[test]
    fn the_track_handle_reports_where_the_pattern_is() {
        let (mut mixer, tx, transport) = bare_mixer(44_100, 512);
        let handle = add_track(&tx, 0);
        let all_sixteen: Vec<usize> = (0..16).collect();
        let block = kick_pattern(&all_sixteen);
        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 1, block }).unwrap();
        let mut queued = block;
        queued.pending_slot = Some(1);
        tx.send(MixerCommand::SetPattern { track_id: 0, slot: 0, block: queued }).unwrap();
        apply_all(&mut mixer);

        // One step in, rather than on the downbeat: tick zero is itself a
        // pattern boundary, so a switch queued there is due immediately.
        transport.set_position(240);
        transport.play();
        let mut output = vec![0.0f32; 256 * 2];
        mixer.process(&mut output, &[], &transport);
        assert_eq!(handle.pattern.live_slot(), 0);
        assert_eq!(handle.pattern.queued_slot(), Some(1));
        assert_eq!(handle.pattern.step(), 1);
        assert!(handle.pattern.is_running());

        // Half a bar in: step 8, and the switch has not happened yet.
        transport.set_position(1920);
        mixer.process(&mut output, &[], &transport);
        assert_eq!(handle.pattern.step(), 8);
        assert_eq!(handle.pattern.live_slot(), 0);

        // Past the pattern end: the queued slot took over.
        transport.set_position(3840);
        mixer.process(&mut output, &[], &transport);
        assert_eq!(handle.pattern.live_slot(), 1);
        assert_eq!(handle.pattern.queued_slot(), None);
    }

    /// The same, for the shorter blocks the device may hand us when the
    /// buffers were sized for its maximum.
    #[test]
    fn a_short_callback_does_not_allocate_either() {
        let max_frames = 512usize;
        let (tx, rx) = mixer_command_channel();
        let (clip_tx, _clip_rx) = clip_snapshot_channel();
        let mut mixer = Mixer::new(rx, Arc::new(VuLevels::new()), clip_tx, 48000, max_frames);
        let transport = Arc::new(Transport::new(120.0));
        let _handle = add_armed_synth(&tx, 0);
        mixer.drain_commands();
        transport.play();

        let mut output = vec![0.0f32; 64 * 2];
        mixer.process(&mut output, &[make_note_on(60, 100)], &transport);

        let allocations = crate::alloc_count::allocations_during(|| {
            for _ in 0..8 {
                mixer.process(&mut output, &[], &transport);
            }
        });
        assert_eq!(allocations, 0, "Mixer::process reached the allocator");
    }
}