tunes 1.1.0

A music composition, synthesis, and audio generation library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
//! Mixer implementation
//!
//! The mixer combines multiple buses together and handles the core audio rendering.
//! Each bus contains tracks, and buses are mixed through the master chain.

use super::bus::{Bus, BusBuilder};
use super::events::*;
use super::track::Track;
use crate::cache::{CacheKey, CachedSample, SampleCache};
use crate::composition::timing::Tempo;
#[cfg(feature = "gpu")]
use crate::gpu::GpuSynthesizer;
use crate::synthesis::effects::{EffectChain, ResolvedSidechainSource};
use crate::track::ids::{BusId, TrackId};
use std::collections::HashMap;

// Use rayon for parallel processing on native platforms
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
use std::sync::Arc;

/// Envelope cache for sidechaining (OPTIMIZED: Vec-based for O(1) access)
///
/// Stores RMS envelope values for tracks and buses during a single sample_at() call.
/// This allows sidechained effects to access the envelope of their source signal.
///
/// **Performance:** Uses Vec indexed by ID instead of HashMap with String keys.
/// This eliminates string hashing and allocation, providing O(1) direct access.
///
/// **Lazy clearing:** Uses generation counters for O(1) clear instead of O(n) fill.
/// Each slot tracks when it was last written; stale slots return 0.0.
#[derive(Debug, Clone)]
struct EnvelopeCache {
    tracks: Vec<f32>,         // Track ID -> RMS envelope (direct index)
    buses: Vec<f32>,          // Bus ID -> RMS envelope (direct index)
    track_gens: Vec<u64>,     // Track ID -> generation when last written
    bus_gens: Vec<u64>,       // Bus ID -> generation when last written
    generation: u64,          // Current generation (incremented on clear)
}

impl EnvelopeCache {
    /// Create a new envelope cache with pre-allocated capacity
    ///
    /// # Arguments
    /// * `max_tracks` - Maximum number of tracks to support
    /// * `max_buses` - Maximum number of buses to support
    fn new(max_tracks: usize, max_buses: usize) -> Self {
        Self {
            tracks: vec![0.0; max_tracks],
            buses: vec![0.0; max_buses],
            track_gens: vec![0; max_tracks],
            bus_gens: vec![0; max_buses],
            generation: 1, // Start at 1 so generation 0 means "never written"
        }
    }

    /// Clear all cached envelope values (O(1) lazy invalidation)
    ///
    /// Called at the start of each sample_at() to reset state.
    /// Instead of zeroing all values, just increment generation counter.
    /// Stale values (wrong generation) return 0.0 on read.
    #[inline(always)]
    fn clear(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        // Skip generation 0 (reserved for "never written")
        if self.generation == 0 {
            self.generation = 1;
        }
    }

    /// Store a track's envelope by ID
    ///
    /// # Arguments
    /// * `track_id` - Unique track identifier
    /// * `envelope` - RMS envelope value
    #[inline(always)]
    fn cache_track(&mut self, track_id: TrackId, envelope: f32) {
        let idx = track_id as usize;
        if idx < self.tracks.len() {
            self.tracks[idx] = envelope;
            self.track_gens[idx] = self.generation;
        }
    }

    /// Store a bus's envelope by ID
    ///
    /// # Arguments
    /// * `bus_id` - Unique bus identifier
    /// * `envelope` - RMS envelope value
    #[inline(always)]
    fn cache_bus(&mut self, bus_id: BusId, envelope: f32) {
        let idx = bus_id as usize;
        if idx < self.buses.len() {
            self.buses[idx] = envelope;
            self.bus_gens[idx] = self.generation;
        }
    }

    /// Get a track's envelope by ID (returns 0.0 if not found or stale)
    #[inline(always)]
    fn get_track(&self, track_id: TrackId) -> f32 {
        let idx = track_id as usize;
        if idx < self.tracks.len() && self.track_gens[idx] == self.generation {
            self.tracks[idx]
        } else {
            0.0
        }
    }

    /// Get a bus's envelope by ID (returns 0.0 if not found or stale)
    #[inline(always)]
    fn get_bus(&self, bus_id: BusId) -> f32 {
        let idx = bus_id as usize;
        if idx < self.buses.len() && self.bus_gens[idx] == self.generation {
            self.buses[idx]
        } else {
            0.0
        }
    }
}

/// Pre-allocated track output (avoids allocation in hot path)
///
/// Stores the output of a single track for later bus mixing.
/// Uses integer bus_id instead of string bus_name for O(1) comparison.
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
struct TrackOutput {
    bus_id: BusId, // Which bus this track belongs to (INTEGER!)
    left: f32,     // Left channel output
    right: f32,    // Right channel output
    envelope: f32, // RMS envelope for sidechaining
}

/// Pre-allocated bus output (avoids allocation in hot path)
///
/// Stores the output of a single bus for later master mixing.
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
struct BusOutput {
    bus_id: BusId, // Bus identifier (unused, kept for potential future use)
    left: f32,     // Left channel output
    right: f32,    // Right channel output
}

/// Mix multiple buses together (OPTIMIZED: Vec-based with pre-allocated buffers)
///
/// The Mixer organizes audio into buses, where each bus contains one or more tracks.
/// Signal flow: Tracks → Buses → Master → Output
///
/// **Performance optimizations:**
/// - Buses stored in Vec<Bus> indexed by BusId (not HashMap<String, Bus>)
/// - Pre-allocated buffers for track_outputs_by_bus, bus_outputs, envelope_cache
/// - Integer IDs instead of string comparisons in hot path
#[derive(Debug, Clone)]
pub struct Mixer {
    // Hot path: Integer-indexed buses for fast iteration
    pub(super) buses: Vec<Option<Bus>>, // Sparse Vec: Some(bus) at bus.id index, None otherwise
    bus_order: Vec<BusId>,              // Order in which to process buses

    // Cold path: String lookup for user-facing API
    bus_name_to_id: HashMap<String, BusId>,

    // Pre-allocated buffers (reused every sample_at() call)
    // OPTIMIZED: track_outputs indexed by bus_id for O(1) lookup instead of O(n) linear search
    track_outputs_by_bus: Vec<Vec<TrackOutput>>,
    bus_outputs: Vec<BusOutput>,
    envelope_cache: EnvelopeCache,

    // Sample cache for pre-rendered synthesis (lock-free with DashMap)
    cache: Option<Arc<SampleCache>>,

    // GPU synthesizer for experimental acceleration (optional, falls back to CPU)
    #[cfg(feature = "gpu")]
    gpu_synthesizer: Option<Arc<GpuSynthesizer>>,

    // Track if we've pre-rendered notes (skip cache checks during streaming)
    prerendered: bool,

    pub tempo: Tempo,
    pub(super) sample_count: u64, // For quantized automation lookups
    pub master: EffectChain,      // Master effects chain (stereo processing)
}

impl Mixer {
    /// Create a new mixer with the specified tempo
    ///
    /// # Arguments
    /// * `tempo` - Tempo for the composition (used for MIDI export)
    pub fn new(tempo: Tempo) -> Self {
        // Pre-allocate reasonable capacities to avoid allocations during audio rendering
        const INITIAL_BUS_CAPACITY: usize = 16;
        const INITIAL_TRACK_CAPACITY: usize = 128;

        Self {
            buses: Vec::with_capacity(INITIAL_BUS_CAPACITY),
            bus_order: Vec::with_capacity(INITIAL_BUS_CAPACITY),
            bus_name_to_id: HashMap::new(),
            track_outputs_by_bus: (0..INITIAL_BUS_CAPACITY)
                .map(|_| Vec::with_capacity(INITIAL_TRACK_CAPACITY / INITIAL_BUS_CAPACITY))
                .collect(),
            bus_outputs: Vec::with_capacity(INITIAL_BUS_CAPACITY),
            envelope_cache: EnvelopeCache::new(INITIAL_TRACK_CAPACITY, INITIAL_BUS_CAPACITY),
            cache: None, // Cache disabled by default
            #[cfg(feature = "gpu")]
            gpu_synthesizer: None, // GPU disabled by default (requires explicit enable_gpu call)
            prerendered: false,
            tempo,
            sample_count: 0,
            master: EffectChain::new(),
        }
    }

    /// Add a bus to the mixer
    ///
    /// # Arguments
    /// * `bus` - The bus to add
    pub fn add_bus(&mut self, bus: Bus) {
        let bus_id = bus.id;
        let bus_name = bus.name.clone();

        // Ensure buses Vec is large enough to hold this bus ID
        if bus_id as usize >= self.buses.len() {
            self.buses.resize(bus_id as usize + 1, None);
        }

        // Store the bus at its ID index
        self.buses[bus_id as usize] = Some(bus);

        // Add to processing order
        self.bus_order.push(bus_id);

        // Map name to ID for user-facing API
        self.bus_name_to_id.insert(bus_name, bus_id);

        // Expand envelope cache if needed
        if bus_id as usize >= self.envelope_cache.buses.len() {
            self.envelope_cache.buses.resize(bus_id as usize + 1, 0.0);
            self.envelope_cache.bus_gens.resize(bus_id as usize + 1, 0);
        }

        // Expand track_outputs_by_bus if needed
        while self.track_outputs_by_bus.len() <= bus_id as usize {
            self.track_outputs_by_bus.push(Vec::with_capacity(8));
        }
    }

    /// Add a track to the default bus for backward compatibility
    ///
    /// This maintains compatibility with existing code that adds tracks directly.
    /// Tracks are added to a bus named "default".
    ///
    /// # Arguments
    /// * `track` - The track to add
    pub fn add_track(&mut self, track: Track) {
        self.get_or_create_bus("default").add_track(track);
    }

    /// Get or create a bus by name
    ///
    /// # Arguments
    /// * `name` - Name of the bus
    pub fn get_or_create_bus(&mut self, name: &str) -> &mut Bus {
        // Check if bus already exists
        if let Some(&bus_id) = self.bus_name_to_id.get(name) {
            // Bus exists, return mutable reference
            return self.buses[bus_id as usize]
                .as_mut()
                .expect("Internal error: bus_name_to_id points to empty bus slot");
        }

        // Bus doesn't exist, create it
        let new_bus_id = self.buses.len() as BusId; // Use current length as new ID
        let new_bus = Bus::new(new_bus_id, name.to_string());

        self.add_bus(new_bus);

        // Return reference to the newly added bus
        self.buses[new_bus_id as usize]
            .as_mut()
            .expect("Internal error: bus not found immediately after adding")
    }

    /// Get a bus by name
    ///
    /// # Arguments
    /// * `name` - Name of the bus
    pub fn get_bus(&self, name: &str) -> Option<&Bus> {
        self.bus_name_to_id
            .get(name)
            .and_then(|&id| self.buses.get(id as usize).and_then(|opt| opt.as_ref()))
    }

    /// Get a mutable bus by name
    ///
    /// # Arguments
    /// * `name` - Name of the bus
    pub fn get_bus_mut(&mut self, name: &str) -> Option<&mut Bus> {
        self.bus_name_to_id
            .get(name)
            .copied()
            .and_then(move |id| self.buses.get_mut(id as usize).and_then(|opt| opt.as_mut()))
    }

    /// Get the BusId for a bus by name
    ///
    /// Used internally for resolving sidechain sources.
    ///
    /// # Arguments
    /// * `name` - Name of the bus
    #[allow(dead_code)]
    pub(crate) fn get_bus_id(&self, name: &str) -> Option<BusId> {
        self.bus_name_to_id.get(name).copied()
    }

    /// Resolve all sidechain sources from string names to integer IDs
    ///
    /// This is called during Composition::into_mixer() to optimize the hot path
    /// by converting user-facing string-based sidechain references to efficient
    /// integer ID lookups.
    pub(crate) fn resolve_sidechains(&mut self) {
        // Clone name mappings to avoid borrowing issues
        let bus_name_to_id = self.bus_name_to_id.clone();

        // First pass: collect all track names and IDs for resolution
        let mut track_name_to_id: HashMap<String, TrackId> = HashMap::new();
        for bus in self.buses.iter().flatten() {
            for track in &bus.tracks {
                if let Some(ref track_name) = track.name {
                    track_name_to_id.insert(track_name.clone(), track.id);
                }
            }
        }

        // Second pass: resolve sidechains with mutable access
        for bus_opt in self.buses.iter_mut() {
            let bus = match bus_opt {
                Some(b) => b,
                None => continue,
            };

            // Resolve bus-level compressor sidechain
            if let Some(ref mut compressor) = bus.effects.compressor {
                if let Some(ref source) = compressor.sidechain_source {
                    compressor.resolved_sidechain_source =
                        Self::resolve_sidechain_source(source, &track_name_to_id, &bus_name_to_id);
                }
            }

            // Resolve track-level compressor sidechains
            for track in &mut bus.tracks {
                if let Some(ref mut compressor) = track.effects.compressor {
                    if let Some(ref source) = compressor.sidechain_source {
                        compressor.resolved_sidechain_source = Self::resolve_sidechain_source(
                            source,
                            &track_name_to_id,
                            &bus_name_to_id,
                        );
                    }
                }
            }
        }
    }

    /// Resolve a single sidechain source to an integer ID
    fn resolve_sidechain_source(
        source: &crate::synthesis::effects::SidechainSource,
        track_name_to_id: &HashMap<String, TrackId>,
        bus_name_to_id: &HashMap<String, BusId>,
    ) -> Option<ResolvedSidechainSource> {
        use crate::synthesis::effects::{ResolvedSidechainSource, SidechainSource};

        match source {
            SidechainSource::Track(name) => {
                // Look up track by name
                track_name_to_id
                    .get(name)
                    .copied()
                    .map(ResolvedSidechainSource::Track)
                    .or_else(|| {
                        eprintln!("Warning: Sidechain track '{}' not found", name);
                        None
                    })
            }
            SidechainSource::Bus(name) => {
                // Look up bus by name
                bus_name_to_id
                    .get(name)
                    .copied()
                    .map(ResolvedSidechainSource::Bus)
                    .or_else(|| {
                        eprintln!("Warning: Sidechain bus '{}' not found", name);
                        None
                    })
            }
        }
    }

    /// Get a builder for applying effects to a bus
    ///
    /// Creates or gets an existing bus and returns a builder for applying effects,
    /// volume, and pan settings in a fluent API.
    ///
    /// # Arguments
    /// * `name` - Name of the bus
    ///
    /// # Example
    /// ```
    /// # use tunes::prelude::*;
    /// # use tunes::synthesis::effects::{Reverb, Compressor};
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.track("kick")
    ///     .bus("drums")
    ///     .drum(DrumType::Kick, 0.0);
    ///
    /// let mut mixer = comp.into_mixer();
    ///
    /// // Apply effects to the drums bus
    /// mixer.bus("drums")
    ///     .reverb(Reverb::new(0.3, 0.4, 0.3))
    ///     .compressor(Compressor::new(0.65, 4.0, 0.01, 0.08, 1.0))
    ///     .volume(0.9);
    /// ```
    pub fn bus(&mut self, name: &str) -> BusBuilder<'_> {
        let bus = self.get_or_create_bus(name);
        BusBuilder::new(bus)
    }

    /// Enable sample caching with default settings
    ///
    /// This enables automatic caching of synthesized notes, dramatically improving
    /// performance when the same synthesis parameters are used multiple times.
    ///
    /// Default cache settings:
    /// - 500 MB memory limit
    /// - Only cache sounds > 100ms duration
    /// - LRU eviction when full
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// let mut mixer = Composition::new(Tempo::new(120.0)).into_mixer();
    /// mixer.enable_cache();
    /// ```
    pub fn enable_cache(&mut self) -> &mut Self {
        self.cache = Some(Arc::new(SampleCache::new()));
        self
    }

    /// Enable sample caching with custom settings
    ///
    /// # Arguments
    /// * `cache` - Pre-configured SampleCache
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// # use tunes::cache::SampleCache;
    /// let cache = SampleCache::new()
    ///     .with_max_size_mb(1000)
    ///     .with_min_duration_ms(50.0);
    ///
    /// let mut mixer = Composition::new(Tempo::new(120.0)).into_mixer();
    /// mixer.enable_cache_with(cache);
    /// ```
    pub fn enable_cache_with(&mut self, cache: SampleCache) -> &mut Self {
        self.cache = Some(Arc::new(cache));
        self
    }

    /// Disable sample caching
    pub fn disable_cache(&mut self) -> &mut Self {
        self.cache = None;
        self
    }

    /// Get cache statistics (if caching is enabled)
    ///
    /// Returns `None` if caching is disabled.
    pub fn cache_stats(&self) -> Option<crate::cache::CacheStatsSnapshot> {
        self.cache
            .as_ref()
            .map(|c| c.stats().snapshot())
    }

    /// Print cache statistics (if caching is enabled)
    pub fn print_cache_stats(&self) {
        if let Some(cache) = &self.cache {
            cache.print_stats();
        } else {
            println!("Sample caching is disabled");
        }
    }

    /// Clear the sample cache (if caching is enabled)
    pub fn clear_cache(&self) {
        if let Some(cache) = &self.cache {
            cache.clear();
        }
    }

    /// Enable GPU-accelerated synthesis
    ///
    /// This enables GPU compute shaders for potentially 500-1000x faster synthesis
    /// **on discrete GPUs**. Performance depends heavily on GPU hardware:
    ///
    /// - **Discrete GPUs** (RTX 3060+, RX 6000+): 50-500x faster than CPU
    /// - **Integrated GPUs** (Intel HD/UHD): May be slower than CPU
    /// - **No GPU**: Automatic fallback to fast CPU synthesis
    ///
    /// **Note**: GPU acceleration works best with:
    /// - Large workloads (100+ unique sounds)
    /// - Complex synthesis (multi-oscillator FM, filters)
    /// - Discrete graphics cards
    ///
    /// **Important**: GPU synthesis requires caching to be enabled.
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// let mut mixer = Composition::new(Tempo::new(120.0)).into_mixer();
    /// mixer.enable_cache();  // Required!
    /// mixer.enable_gpu();    // Try GPU acceleration
    /// ```
    #[cfg(feature = "gpu")]
    pub fn enable_gpu(&mut self) -> &mut Self {
        self.enable_gpu_with_output(true)
    }

    /// Enable GPU with optional console output
    #[cfg(feature = "gpu")]
    pub fn enable_gpu_with_output(&mut self, print_info: bool) -> &mut Self {
        use crate::gpu::{GpuDevice, GpuSynthesizer};

        // Try to initialize GPU
        match GpuDevice::new() {
            Ok(device) => match GpuSynthesizer::new(device) {
                Ok(synthesizer) => {
                    self.gpu_synthesizer = Some(Arc::new(synthesizer));
                    if print_info {
                        println!("✅ GPU synthesis enabled");
                    }
                }
                Err(e) => {
                    if print_info {
                        eprintln!("⚠️  Failed to create GPU synthesizer: {}", e);
                        eprintln!("   Falling back to CPU synthesis");
                    }
                }
            },
            Err(e) => {
                if print_info {
                    eprintln!("⚠️  GPU not available: {}", e);
                    eprintln!("   Using CPU synthesis");
                }
            }
        }

        self
    }

    /// Disable GPU synthesis (fall back to CPU)
    #[cfg(feature = "gpu")]
    pub fn disable_gpu(&mut self) -> &mut Self {
        self.gpu_synthesizer = None;
        self
    }

    /// Check if GPU synthesis is enabled
    #[cfg(feature = "gpu")]
    pub fn gpu_enabled(&self) -> bool {
        self.gpu_synthesizer.is_some()
    }

    /// Enable both cache and GPU acceleration in one call
    ///
    /// This is a convenience wrapper that enables both the sample cache and GPU
    /// compute shaders. Since GPU acceleration requires caching to be effective,
    /// this is the recommended way to enable maximum performance.
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.track("drums").note(&[C4], 0.5);
    ///
    /// let mut mixer = comp.into_mixer();
    /// mixer.enable_cache_and_gpu();  // Experimental GPU acceleration
    ///
    /// // Now export or play with GPU acceleration
    /// # let engine = AudioEngine::new()?;
    /// engine.export_wav(&mut mixer, "output.wav")?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    #[cfg(feature = "gpu")]
    pub fn enable_cache_and_gpu(&mut self) -> &mut Self {
        self.enable_cache();
        self.enable_gpu();
        self
    }

    /// Pre-render all unique notes in the composition
    ///
    /// This scans all tracks, finds unique notes, and batch renders them on GPU
    /// (or CPU fallback). This is called automatically before streaming if GPU or
    /// cache is enabled, eliminating per-block cache lookups.
    ///
    /// **This is the key to GPU performance!** Instead of checking cache during
    /// streaming (causing overhead), we render everything upfront and stream
    /// from a fully-populated cache.
    pub fn prerender_notes(&mut self, sample_rate: f32) {
        // Only prerender if cache is enabled
        let cache = match &self.cache {
            Some(c) => c,
            None => return,
        };

        println!("🔄 Pre-rendering unique notes...");

        // Collect all unique notes from all tracks
        let mut unique_notes: HashMap<CacheKey, NoteEvent> = HashMap::new();

        for bus in self.buses.iter().flatten() {
            for track in &bus.tracks {
                    for event in &track.events {
                        if let AudioEvent::Note(note_event) = event {
                            let cache_key = CacheKey::from_note_event(note_event, sample_rate);

                            // Only add if not already seen
                            unique_notes
                                .entry(cache_key)
                                .or_insert_with(|| note_event.clone());
                        }
                    }
                }
        }

        let total_notes = unique_notes.len();
        println!("   Found {} unique notes to render", total_notes);

        // Batch render all unique notes
        let start = std::time::Instant::now();
        let mut rendered_count = 0;

        for (cache_key, note_event) in unique_notes {
            // Check if already cached
            if cache.get(&cache_key).is_some() {
                continue; // Already in cache
            }

            // Render the note (GPU if available, CPU fallback)
            let total_duration = note_event.envelope.total_duration(note_event.duration);

            if total_duration > 0.0 && total_duration < 10.0 {
                let rendered_samples = Self::render_note_to_buffer(
                    &note_event,
                    sample_rate,
                    #[cfg(feature = "gpu")]
                    self.gpu_synthesizer.as_ref(),
                );

                let cached_sample = CachedSample::new(
                    rendered_samples,
                    sample_rate,
                    total_duration,
                    note_event.frequencies[0],
                );

                cache.insert(cache_key, cached_sample);
                rendered_count += 1;
            }
        }

        let elapsed = start.elapsed();

        #[cfg(feature = "gpu")]
        {
            if self.gpu_enabled() {
                let notes_per_second = rendered_count as f32 / elapsed.as_secs_f32();
                println!(
                    "   ✅ Pre-rendered {} notes in {:.3}s ({:.0} notes/sec)",
                    rendered_count,
                    elapsed.as_secs_f32(),
                    notes_per_second
                );
            } else {
                println!(
                    "   ✅ Pre-rendered {} notes in {:.3}s",
                    rendered_count,
                    elapsed.as_secs_f32()
                );
            }
        }
        #[cfg(not(feature = "gpu"))]
        {
            println!(
                "   ✅ Pre-rendered {} notes in {:.3}s",
                rendered_count,
                elapsed.as_secs_f32()
            );
        }

        // Mark as pre-rendered so streaming skips cache lookups
        self.prerendered = true;
    }

    /// Get the total duration across all buses in seconds
    ///
    /// Returns the end time of the longest bus.
    /// Returns 0.0 if the mixer has no buses.
    pub fn total_duration(&self) -> f32 {
        self.buses
            .iter()
            .filter_map(|opt| opt.as_ref())
            .map(|b| b.total_duration())
            .fold(0.0, f32::max)
    }

    /// Check if the mixer has any audio events
    ///
    /// Returns `true` if all buses/tracks are empty (no notes, drums, or samples).
    /// Useful for detecting empty compositions before playback.
    ///
    /// # Example
    /// ```
    /// # use tunes::prelude::*;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mixer = comp.into_mixer();
    /// assert!(mixer.is_empty());
    ///
    /// let mut comp2 = Composition::new(Tempo::new(120.0));
    /// comp2.instrument("piano", &Instrument::electric_piano())
    ///     .note(&[440.0], 1.0);
    /// let mixer2 = comp2.into_mixer();
    /// assert!(!mixer2.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.buses
            .iter()
            .filter_map(|opt| opt.as_ref())
            .all(|b| b.tracks.iter().all(|t| t.events.is_empty()))
    }

    /// Get all tracks across all buses as a flat vector
    ///
    /// This is useful for export functions that need to iterate over all tracks.
    /// Note: This creates a new vector, so use sparingly.
    pub fn all_tracks(&self) -> Vec<&Track> {
        self.buses
            .iter()
            .filter_map(|opt| opt.as_ref())
            .flat_map(|bus| bus.tracks.iter())
            .collect()
    }

    /// Get all tracks across all buses as a mutable flat vector
    ///
    /// This is useful for export functions that need to iterate over all tracks.
    /// Note: This creates a new vector, so use sparingly.
    pub fn all_tracks_mut(&mut self) -> Vec<&mut Track> {
        self.buses
            .iter_mut()
            .filter_map(|opt| opt.as_mut())
            .flat_map(|bus| bus.tracks.iter_mut())
            .collect()
    }

    /// Get the tracks field for backward compatibility with tests
    ///
    /// Returns a cloned Vec of tracks from the default bus.
    /// This works around lifetime issues in tests where `comp.into_mixer().tracks()`
    /// would create a temporary.
    #[cfg(test)]
    pub fn tracks(&self) -> Vec<Track> {
        self.get_bus("default")
            .map(|b| b.tracks.clone())
            .unwrap_or_default()
    }

    /// Get mutable access to the tracks field for backward compatibility with tests
    #[cfg(test)]
    pub fn tracks_mut(&mut self) -> &mut Vec<Track> {
        &mut self.get_or_create_bus("default").tracks
    }

    /// Repeat all tracks in the mixer N times
    ///
    /// This duplicates all events in all tracks, placing copies sequentially.
    /// Useful for looping an entire composition.
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::engine::AudioEngine;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut comp = Composition::new(Tempo::new(120.0));
    /// # let engine = AudioEngine::new()?;
    /// let mixer = comp.into_mixer().repeat(3); // Play composition 4 times total
    /// engine.play_mixer(&mixer)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn repeat(mut self, times: usize) -> Self {
        if times == 0 {
            return self;
        }

        let total_duration = self.total_duration();

        // For each bus, repeat all its track events
        for bus_opt in self.buses.iter_mut() {
            let bus = match bus_opt {
                Some(b) => b,
                None => continue,
            };

            for track in &mut bus.tracks {
                let original_events: Vec<_> = track.events.clone();
                // Pre-allocate space for all repetitions to avoid reallocations
                track.events.reserve(original_events.len() * times);

                for i in 0..times {
                    let offset = total_duration * (i + 1) as f32;

                    for event in &original_events {
                        match event {
                            AudioEvent::Note(note) => {
                                track.add_note_with_waveform_envelope_and_bend(
                                    &note.frequencies[..note.num_freqs],
                                    note.start_time + offset,
                                    note.duration,
                                    note.waveform,
                                    note.envelope,
                                    note.pitch_bend_semitones,
                                );
                            }
                            AudioEvent::Drum(drum) => {
                                track.add_drum(
                                    drum.drum_type,
                                    drum.start_time + offset,
                                    drum.spatial_position,
                                );
                            }
                            AudioEvent::Sample(sample) => {
                                track
                                    .events
                                    .push(AudioEvent::Sample(crate::track::SampleEvent {
                                        sample: sample.sample.clone(),
                                        start_time: sample.start_time + offset,
                                        playback_rate: sample.playback_rate,
                                        volume: sample.volume,
                                        spatial_position: sample.spatial_position,
                                    }));
                                track.invalidate_time_cache();
                            }
                            AudioEvent::TempoChange(tempo) => {
                                track.events.push(AudioEvent::TempoChange(
                                    crate::track::TempoChangeEvent {
                                        start_time: tempo.start_time + offset,
                                        bpm: tempo.bpm,
                                    },
                                ));
                                track.invalidate_time_cache();
                            }
                            AudioEvent::TimeSignature(time_sig) => {
                                track.events.push(AudioEvent::TimeSignature(
                                    crate::track::TimeSignatureEvent {
                                        start_time: time_sig.start_time + offset,
                                        numerator: time_sig.numerator,
                                        denominator: time_sig.denominator,
                                    },
                                ));
                                track.invalidate_time_cache();
                            }
                            AudioEvent::KeySignature(key_sig) => {
                                track
                                    .events
                                    .push(AudioEvent::KeySignature(KeySignatureEvent {
                                        start_time: key_sig.start_time + offset,
                                        key_signature: key_sig.key_signature,
                                    }));
                                track.invalidate_time_cache();
                            }
                        }
                    }
                }
            }
        }

        self
    }

    /// Generate a stereo sample at a given time by mixing all buses
    ///
    /// This is the core rendering method that generates audio samples by:
    /// 1. Processing each bus (which mixes its tracks and applies bus effects)
    /// 2. Summing all bus outputs
    /// 3. Applying master effects to the final mix
    ///
    /// # Arguments
    /// * `time` - The time position in seconds
    /// * `sample_rate` - Sample rate in Hz (e.g., 44100)
    /// * `_sample_clock` - Reserved for future use
    /// * `_listener` - Reserved for spatial audio (handled at track level)
    /// * `_spatial_params` - Reserved for spatial audio (handled at track level)
    ///
    /// # Returns
    /// A tuple of (left_channel, right_channel) audio samples in range -1.0 to 1.0
    #[inline(always)]
    pub fn sample_at(
        &mut self,
        time: f32,
        sample_rate: f32,
        _sample_clock: f32,
        _listener: Option<&crate::synthesis::spatial::ListenerConfig>,
        _spatial_params: Option<&crate::synthesis::spatial::SpatialParams>,
    ) -> (f32, f32) {
        // Increment sample count for quantized automation lookups
        self.sample_count = self.sample_count.wrapping_add(1);

        // Clear pre-allocated buffers (NO ALLOCATION!)
        for bus_outputs in &mut self.track_outputs_by_bus {
            bus_outputs.clear();
        }
        self.bus_outputs.clear();
        self.envelope_cache.clear();

        let mut mixed_left = 0.0;
        let mut mixed_right = 0.0;

        // PASS 1: Process tracks and cache their envelopes
        // We need to process all tracks first to build the envelope cache
        // before applying bus effects (which may use sidechaining)

        // Iterate over buses using Vec<Option<Bus>>
        for bus_opt in self.buses.iter_mut() {
            let bus = match bus_opt {
                Some(b) => b,
                None => continue,
            };

            if bus.muted {
                continue;
            }

            let sample_count = self.sample_count;
            let bus_id = bus.id;

            for track in &mut bus.tracks {
                let (track_left, track_right) =
                    Self::process_track_static(track, time, sample_rate, sample_count);

                // Calculate RMS envelope for this track
                let envelope = ((track_left * track_left + track_right * track_right) / 2.0).sqrt();

                // Cache track envelope using integer ID
                self.envelope_cache.cache_track(track.id, envelope);

                // Store output indexed by bus ID (O(1) lookup in Pass 2!)
                self.track_outputs_by_bus[bus_id as usize].push(TrackOutput {
                    bus_id,
                    left: track_left,
                    right: track_right,
                    envelope,
                });
            }
        }

        // PASS 2: Mix tracks into buses and apply bus effects with sidechain support

        // Iterate over buses for processing
        for bus_opt in self.buses.iter_mut() {
            let bus = match bus_opt {
                Some(b) => b,
                None => continue,
            };

            if bus.muted {
                continue;
            }

            let bus_id = bus.id;

            // Sum tracks belonging to this bus (O(1) lookup via indexed Vec!)
            let mut bus_left = 0.0;
            let mut bus_right = 0.0;
            for track_output in &self.track_outputs_by_bus[bus_id as usize] {
                bus_left += track_output.left;
                bus_right += track_output.right;
            }

            // Calculate bus envelope BEFORE effects
            let bus_envelope = ((bus_left * bus_left + bus_right * bus_right) / 2.0).sqrt();
            self.envelope_cache.cache_bus(bus_id, bus_envelope);

            // Look up sidechain envelope using resolved IDs (OPTIMIZED: Integer lookup!)
            let sidechain_env = if let Some(ref compressor) = bus.effects.compressor {
                if let Some(ref resolved_source) = compressor.resolved_sidechain_source {
                    match resolved_source {
                        ResolvedSidechainSource::Track(track_id) => {
                            Some(self.envelope_cache.get_track(*track_id))
                        }
                        ResolvedSidechainSource::Bus(sidechain_bus_id) => {
                            Some(self.envelope_cache.get_bus(*sidechain_bus_id))
                        }
                    }
                } else {
                    None
                }
            } else {
                None
            };

            // Apply bus effects (stereo processing) with sidechain support
            let (effected_left, effected_right) = bus.effects.process_stereo(
                bus_left,
                bus_right,
                sample_rate,
                time,
                self.sample_count,
                sidechain_env,
            );

            // Apply bus volume and pan
            let pan_left = if bus.pan <= 0.0 { 1.0 } else { 1.0 - bus.pan };
            let pan_right = if bus.pan >= 0.0 { 1.0 } else { 1.0 + bus.pan };

            let final_bus_left = effected_left * bus.volume * pan_left;
            let final_bus_right = effected_right * bus.volume * pan_right;

            // Store output using integer bus ID (NO STRING CLONE!)
            self.bus_outputs.push(BusOutput {
                bus_id,
                left: final_bus_left,
                right: final_bus_right,
            });
        }

        // Sum all bus outputs
        for bus_output in &self.bus_outputs {
            mixed_left += bus_output.left;
            mixed_right += bus_output.right;
        }

        // Apply master effects (stereo processing) - no sidechaining on master
        let (master_left, master_right) = self.master.process_stereo(
            mixed_left,
            mixed_right,
            sample_rate,
            time,
            self.sample_count,
            None,
        );

        // Apply soft clipping to prevent harsh distortion
        // tanh provides smooth saturation - maintains dynamics while preventing clipping
        (master_left.tanh(), master_right.tanh())
    }

    /// Process a block of samples
    ///
    /// This is the new block-based processing API that processes multiple samples at once,
    /// significantly reducing function call overhead and enabling future optimizations.
    ///
    /// # Arguments
    /// * `buffer` - Interleaved stereo buffer [L0, R0, L1, R1, ...] to fill
    /// * `sample_rate` - Sample rate in Hz
    /// * `start_time` - Starting time in seconds
    /// * `listener` - Optional spatial audio listener configuration
    /// * `spatial_params` - Optional spatial audio parameters
    #[allow(unused_variables)]
    pub fn process_block(
        &mut self,
        buffer: &mut [f32],
        sample_rate: f32,
        start_time: f32,
        listener: Option<&crate::synthesis::spatial::ListenerConfig>,
        spatial_params: Option<&crate::synthesis::spatial::SpatialParams>,
    ) {
        // Clear output buffer
        buffer.fill(0.0);

        let num_frames = buffer.len() / 2;
        let start_sample_count = self.sample_count;
        self.sample_count = self.sample_count.wrapping_add(num_frames as u64);

        // Clear envelope cache for this block
        self.envelope_cache.clear();

        // TWO-PASS BUS PROCESSING for parallelization with sidechain support:
        // Pass 1: Render all bus audio + calculate envelopes (can be parallel)
        // Pass 2: Apply effects + mix to output (can be parallel, envelopes now available)

        // PASS 1: Render bus audio and calculate envelopes in PARALLEL
        struct BusRenderResult {
            bus_id: BusId,
            bus_buffer: Vec<f32>,
            bus_envelope: f32,
            track_envelopes: Vec<(TrackId, f32)>,
        }

        // Parallel bus processing on native, sequential on web
        #[cfg(not(target_arch = "wasm32"))]
        let bus_results: Vec<BusRenderResult> = self
            .buses
            .par_iter_mut()
            .filter_map(|bus_opt| {
                let bus = bus_opt.as_mut()?;
                if bus.muted {
                    return None;
                }

                let bus_id = bus.id;
                let mut bus_buffer = vec![0.0f32; buffer.len()];

                // Clone the Arc to share the cache across threads (cheap - just incrementing ref count)
                let cache_clone = self.cache.clone();
                #[cfg(feature = "gpu")]
                let gpu_clone = self.gpu_synthesizer.clone();
                let prerendered = self.prerendered;

                // Process each track in this bus IN PARALLEL using Rayon
                let track_results: Vec<_> = bus
                    .tracks
                    .par_iter_mut()
                    .map(|track| {
                        let track_id = track.id;
                        let mut track_buffer = vec![0.0f32; num_frames];

                        // Generate mono track audio using block processing
                        // Cache is thread-safe via Arc<Mutex>, GPU synthesizer via Arc
                        Self::process_track_block(
                            track,
                            &mut track_buffer,
                            sample_rate,
                            start_time,
                            start_sample_count,
                            cache_clone.as_ref(),
                            #[cfg(feature = "gpu")]
                            gpu_clone.as_ref(),
                            prerendered,
                        );

                        // Calculate RMS envelope for this track (SIMD-optimized)
                        use crate::synthesis::simd::SIMD;
                        let sum_squares = SIMD.sum_of_squares(&track_buffer);
                        let track_envelope = (sum_squares / num_frames as f32).sqrt();

                        (track_id, track_buffer, track_envelope, track.pan)
                    })
                    .collect();

                // Mix track results into bus buffer
                let mut track_envelopes = Vec::with_capacity(track_results.len());
                for (track_id, track_buffer, track_envelope, pan) in track_results {
                    track_envelopes.push((track_id, track_envelope));

                    // Apply stereo panning and mix (SIMD-optimized)
                    // Use fast trig for pan calculations (no stdlib call overhead)
                    use crate::synthesis::simd::SimdLanes;
                    let pan_angle = (pan + 1.0) * 0.25 * std::f32::consts::PI;
                    let left_gain = pan_angle.fast_cos();
                    let right_gain = pan_angle.fast_sin();

                    use crate::synthesis::simd::SIMD;
                    SIMD.mix_mono_to_stereo(&mut bus_buffer, &track_buffer, left_gain, right_gain);
                }

                // Calculate bus envelope (before effects) - SIMD-optimized
                // For stereo, RMS = sqrt((sum(L²) + sum(R²)) / (2 * num_frames))
                use crate::synthesis::simd::SIMD;
                let total_sum_squares = SIMD.sum_of_squares(&bus_buffer);
                let bus_envelope = (total_sum_squares / (2.0 * num_frames as f32)).sqrt();

                Some(BusRenderResult {
                    bus_id,
                    bus_buffer,
                    bus_envelope,
                    track_envelopes,
                })
            })
            .collect();

        #[cfg(target_arch = "wasm32")]
        let bus_results: Vec<BusRenderResult> = self
            .buses
            .iter_mut()
            .filter_map(|bus_opt| {
                let bus = bus_opt.as_mut()?;
                if bus.muted {
                    return None;
                }

                let bus_id = bus.id;
                let mut bus_buffer = vec![0.0f32; buffer.len()];

                // Clone the Arc to share the cache (not actually across threads on web)
                let cache_clone = self.cache.clone();
                #[cfg(feature = "gpu")]
                let gpu_clone = self.gpu_synthesizer.clone();
                let prerendered = self.prerendered;

                // Process each track in this bus SEQUENTIALLY on web
                let track_results: Vec<_> = bus
                    .tracks
                    .iter_mut()
                    .map(|track| {
                        let track_id = track.id;
                        let mut track_buffer = vec![0.0f32; num_frames];

                        // Generate mono track audio using block processing
                        Self::process_track_block(
                            track,
                            &mut track_buffer,
                            sample_rate,
                            start_time,
                            start_sample_count,
                            cache_clone.as_ref(),
                            #[cfg(feature = "gpu")]
                            gpu_clone.as_ref(),
                            prerendered,
                        );

                        // Calculate RMS envelope for this track (SIMD-optimized)
                        use crate::synthesis::simd::SIMD;
                        let sum_squares = SIMD.sum_of_squares(&track_buffer);
                        let track_envelope = (sum_squares / num_frames as f32).sqrt();

                        (track_id, track_buffer, track_envelope, track.pan)
                    })
                    .collect();

                // Mix track results into bus buffer
                let mut track_envelopes = Vec::with_capacity(track_results.len());
                for (track_id, track_buffer, track_envelope, pan) in track_results {
                    track_envelopes.push((track_id, track_envelope));

                    // Apply stereo panning and mix (SIMD-optimized)
                    // Use fast trig for pan calculations (no stdlib call overhead)
                    use crate::synthesis::simd::SimdLanes;
                    let pan_angle = (pan + 1.0) * 0.25 * std::f32::consts::PI;
                    let left_gain = pan_angle.fast_cos();
                    let right_gain = pan_angle.fast_sin();

                    use crate::synthesis::simd::SIMD;
                    SIMD.mix_mono_to_stereo(&mut bus_buffer, &track_buffer, left_gain, right_gain);
                }

                // Calculate bus envelope (before effects) - SIMD-optimized
                // For stereo, RMS = sqrt((sum(L²) + sum(R²)) / (2 * num_frames))
                use crate::synthesis::simd::SIMD;
                let total_sum_squares = SIMD.sum_of_squares(&bus_buffer);
                let bus_envelope = (total_sum_squares / (2.0 * num_frames as f32)).sqrt();

                Some(BusRenderResult {
                    bus_id,
                    bus_buffer,
                    bus_envelope,
                    track_envelopes,
                })
            })
            .collect();

        // Cache all track and bus envelopes (now safe since all are computed)
        for result in &bus_results {
            for (track_id, envelope) in &result.track_envelopes {
                self.envelope_cache.cache_track(*track_id, *envelope);
            }
            self.envelope_cache
                .cache_bus(result.bus_id, result.bus_envelope);
        }

        // PASS 2: Apply effects and mix to output (can still check for parallelization)
        // Note: We keep this sequential for now since effects have state, but envelopes are cached
        for result in bus_results {
            let mut bus_buffer = result.bus_buffer;

            // Find the original bus to apply effects
            let bus = self
                .buses
                .iter_mut()
                .find_map(|b| b.as_mut().filter(|bus| bus.id == result.bus_id))
                .expect("Bus should exist");

            // Look up sidechain envelope (now safe - all envelopes cached in pass 1)
            let sidechain_env = if let Some(ref compressor) = bus.effects.compressor {
                if let Some(ref resolved_source) = compressor.resolved_sidechain_source {
                    match resolved_source {
                        ResolvedSidechainSource::Track(track_id) => {
                            Some(self.envelope_cache.get_track(*track_id))
                        }
                        ResolvedSidechainSource::Bus(sidechain_bus_id) => {
                            Some(self.envelope_cache.get_bus(*sidechain_bus_id))
                        }
                    }
                } else {
                    None
                }
            } else {
                None
            };

            // Apply bus effects
            bus.effects.process_stereo_block(
                &mut bus_buffer,
                sample_rate,
                start_time,
                start_sample_count,
                sidechain_env,
            );

            // Mix into output buffer with SIMD optimization (automatic fallback)
            // Use fast trig for pan calculations
            use crate::synthesis::simd::SimdLanes;
            let bus_pan_angle = (bus.pan + 1.0) * 0.25 * std::f32::consts::PI;
            let bus_left_gain = bus_pan_angle.fast_cos() * bus.volume;
            let bus_right_gain = bus_pan_angle.fast_sin() * bus.volume;

            // Use the SIMD abstraction for clean, portable stereo mixing
            use crate::synthesis::simd::SIMD;
            SIMD.mix_stereo_interleaved(buffer, &bus_buffer, bus_left_gain, bus_right_gain);
        }

        // Look up master sidechain envelope if configured
        let master_sidechain_env = if let Some(ref compressor) = self.master.compressor {
            if let Some(ref resolved_source) = compressor.resolved_sidechain_source {
                match resolved_source {
                    ResolvedSidechainSource::Track(track_id) => {
                        Some(self.envelope_cache.get_track(*track_id))
                    }
                    ResolvedSidechainSource::Bus(bus_id) => {
                        Some(self.envelope_cache.get_bus(*bus_id))
                    }
                }
            } else {
                None
            }
        } else {
            None
        };

        // Apply master effects (block processing) with sidechain support
        self.master.process_stereo_block(
            buffer,
            sample_rate,
            start_time,
            start_sample_count,
            master_sidechain_env,
        );
    }

    /// Render a complete note into a buffer
    ///
    /// This synthesizes an entire note from start to finish, used for caching.
    /// If GPU synthesizer is provided, uses GPU, otherwise falls back to CPU.
    fn render_note_to_buffer(
        note: &NoteEvent,
        sample_rate: f32,
        #[cfg(feature = "gpu")] gpu_synthesizer: Option<&Arc<GpuSynthesizer>>,
    ) -> Vec<f32> {
        // Try GPU first if available
        #[cfg(feature = "gpu")]
        if let Some(gpu) = gpu_synthesizer {
            if let Ok(samples) = gpu.synthesize_note(note, sample_rate) {
                return samples;
            }
            // GPU failed, fall through to CPU
        }

        // CPU synthesis fallback
        let total_duration = note.envelope.total_duration(note.duration);
        let num_samples = (total_duration * sample_rate) as usize;
        let mut buffer = vec![0.0f32; num_samples];

        let time_delta = 1.0 / sample_rate;

        for (i, sample_out) in buffer.iter_mut().enumerate() {
            let time_in_note = i as f32 * time_delta;
            let envelope_amp = note.envelope.amplitude_at(time_in_note, note.duration);

            let mut note_value = 0.0;

            // Synthesize for the first frequency only (monophonic cache)
            // Polyphonic notes will be handled separately
            if note.num_freqs > 0 {
                let base_freq = note.frequencies[0];

                let freq = if note.pitch_bend_semitones != 0.0 {
                    let bend_progress = (time_in_note / note.duration).min(1.0);
                    let bend_multiplier =
                        2.0f32.powf((note.pitch_bend_semitones * bend_progress) / 12.0);
                    base_freq * bend_multiplier
                } else {
                    base_freq
                };

                let sample = if note.fm_params.mod_index > 0.0 {
                    note.fm_params.sample(freq, time_in_note, note.duration)
                } else if let Some(ref wavetable) = note.custom_wavetable {
                    let phase = (time_in_note * freq) % 1.0;
                    wavetable.sample(phase)
                } else {
                    let phase = (time_in_note * freq) % 1.0;
                    note.waveform.sample(phase)
                };

                note_value += sample * envelope_amp;
            }

            *sample_out = note_value;
        }

        buffer
    }

    /// Process a single track into a mono buffer (block-processing version)
    ///
    /// This is the high-performance version that generates multiple samples at once,
    /// reducing function call overhead and enabling better cache locality.
    ///
    /// # Arguments
    /// * `track` - The track to process
    /// * `buffer` - Output mono buffer to fill
    /// * `sample_rate` - Sample rate in Hz
    /// * `start_time` - Starting time for the block
    /// * `start_sample_count` - Starting sample counter
    /// * `cache` - Optional sample cache for pre-rendered synthesis
    /// * `gpu_synthesizer` - Optional GPU synthesizer for 500-1000x faster rendering
    /// * `prerendered` - If true, skip cache-miss detection (already pre-rendered)
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn process_track_block(
        track: &mut Track,
        buffer: &mut [f32],
        sample_rate: f32,
        start_time: f32,
        start_sample_count: u64,
        cache: Option<&Arc<SampleCache>>,
        #[cfg(feature = "gpu")] gpu_synthesizer: Option<&Arc<GpuSynthesizer>>,
        prerendered: bool,
    ) {
        // Clear output buffer
        buffer.fill(0.0);

        // Ensure events are sorted by start_time for binary search
        track.ensure_sorted();

        let track_start = track.start_time();
        let track_end = track.end_time();
        let time_delta = 1.0 / sample_rate;
        let block_duration = buffer.len() as f32 * time_delta;
        let block_end_time = start_time + block_duration;

        // Skip track entirely if we're completely outside its active range
        if (block_end_time < track_start || start_time > track_end)
            && track.effects.delay.is_none()
            && track.effects.reverb.is_none()
        {
            return;
        }

        // Binary search ONCE to find events that might be active during this block
        // We need to search at the start of the block
        let (start_idx, end_idx) = track.find_active_range(start_time);

        // OPTIMIZED: Lock-free cache operations with DashMap
        // No mutex overhead - concurrent cache access from Rayon threads!
        let mut cached_note_indices = std::collections::HashSet::new();

        if let Some(cache_ref) = cache {
            // Special case: if pre-rendered, all notes are cached
            if prerendered {
                for (idx, event) in track.events[start_idx..end_idx].iter().enumerate() {
                    if let AudioEvent::Note(_) = event {
                        cached_note_indices.insert(start_idx + idx);
                    }
                }
            }

            // Single pass through events: check misses, build indices, copy samples
            for (idx, event) in track.events[start_idx..end_idx].iter().enumerate() {
                if let AudioEvent::Note(note_event) = event {
                    let cache_key = CacheKey::from_note_event(note_event, sample_rate);

                    // Step 1: Handle cache miss (render if needed)
                    if !prerendered && cache_ref.get(&cache_key).is_none() {
                        let total_duration =
                            note_event.envelope.total_duration(note_event.duration);

                        // Only cache notes with reasonable duration
                        if total_duration > 0.0 && total_duration < 10.0 {
                            let rendered_samples = Self::render_note_to_buffer(
                                note_event,
                                sample_rate,
                                #[cfg(feature = "gpu")]
                                gpu_synthesizer,
                            );

                            let cached_sample = CachedSample::new(
                                rendered_samples,
                                sample_rate,
                                total_duration,
                                note_event.frequencies[0],
                            );
                            cache_ref.insert(cache_key, cached_sample);
                        }
                    }

                    // Step 2 & 3: If cached, build index AND copy to buffer
                    if let Some(cached_sample) = cache_ref.get(&cache_key) {
                        // Add to cached indices (for synthesis loop to skip)
                        if !prerendered {
                            cached_note_indices.insert(start_idx + idx);
                        }

                        // Copy cached sample DIRECTLY to output buffer (SIMD-optimized)
                        let note_start = note_event.start_time;
                        let note_end = note_start + cached_sample.duration;

                        // Skip if note doesn't overlap with current block
                        if note_end >= start_time
                            && note_start < start_time + (buffer.len() as f32 / sample_rate)
                        {
                            // Compute sample ranges
                            let time_offset_in_note = (start_time - note_start).max(0.0);
                            let cache_start_sample = (time_offset_in_note * sample_rate) as usize;

                            let buffer_start_sample = if note_start > start_time {
                                ((note_start - start_time) * sample_rate) as usize
                            } else {
                                0
                            };

                            // Calculate how many samples to copy
                            let samples_remaining_in_cache = cached_sample
                                .samples
                                .len()
                                .saturating_sub(cache_start_sample);
                            let samples_remaining_in_buffer =
                                buffer.len().saturating_sub(buffer_start_sample);
                            let num_samples_to_copy =
                                samples_remaining_in_cache.min(samples_remaining_in_buffer);

                            // SIMD-optimized bulk copy
                            if num_samples_to_copy > 0
                                && cache_start_sample < cached_sample.samples.len()
                            {
                                use wide::f32x8;

                                let src = &cached_sample.samples[cache_start_sample..];
                                let dst = &mut buffer[buffer_start_sample..];

                                // SIMD-optimized bulk copy
                                let simd_chunks = num_samples_to_copy / 8;
                                let remainder = num_samples_to_copy % 8;

                                for chunk_idx in 0..simd_chunks {
                                    let i = chunk_idx * 8;
                                    let src_simd = f32x8::new(src[i..i + 8].try_into().unwrap());
                                    let dst_simd = f32x8::new(dst[i..i + 8].try_into().unwrap());
                                    let result = dst_simd + src_simd;
                                    dst[i..i + 8].copy_from_slice(&result.to_array());
                                }

                                // Handle remaining samples
                                let simd_end = simd_chunks * 8;
                                for i in simd_end..simd_end + remainder {
                                    dst[i] += src[i];
                                }
                            }
                        }
                    }
                }
            }
        }

        // Pre-render sample events with SIMD for better performance
        // This processes whole blocks instead of per-sample, enabling vectorization
        let mut sample_buffer = vec![0.0f32; buffer.len()];
        for event in &track.events[start_idx..end_idx] {
            if let AudioEvent::Sample(sample_event) = event {
                sample_event.sample.fill_buffer_simd_mono(
                    &mut sample_buffer,
                    sample_event.start_time,
                    start_time,
                    time_delta,
                    sample_event.playback_rate,
                    sample_event.volume,
                );
            }
        }

        // For each sample in the block
        for (i, sample_out) in buffer.iter_mut().enumerate() {
            let time = start_time + (i as f32 * time_delta);
            // Start with current buffer value (which may contain cached samples written above)
            let mut track_value = *sample_out;

            // Process events (reuse binary search result for entire block)
            for (relative_idx, event) in track.events[start_idx..end_idx].iter().enumerate() {
                let absolute_idx = start_idx + relative_idx;

                match event {
                    AudioEvent::Note(note_event) => {
                        // Check if this note is cached using the pre-built HashSet (O(1) lookup, no mutex!)
                        // We built cached_note_indices earlier specifically to avoid cache locking in this hot loop
                        if cached_note_indices.contains(&absolute_idx) {
                            // Skip - already rendered directly to output buffer above
                            continue;
                        }

                        let total_duration =
                            note_event.envelope.total_duration(note_event.duration);
                        let note_end_with_release = note_event.start_time + total_duration;

                        if time >= note_event.start_time && time < note_end_with_release {
                            let time_in_note = time - note_event.start_time;
                            let envelope_amp = note_event
                                .envelope
                                .amplitude_at(time_in_note, note_event.duration);

                            // SIMD-optimized polyphonic frequency processing
                            // Process 8 frequencies at once for 3-6x speedup
                            use crate::synthesis::simd::SIMD;
                            use wide::{f32x8, f32x4};

                            let num_freqs = note_event.num_freqs;

                            // Pre-calculate pitch bend (hoisted out of frequency loop for efficiency)
                            let bend_multiplier = if note_event.pitch_bend_semitones != 0.0 {
                                let bend_progress = (time_in_note / note_event.duration).min(1.0);
                                2.0f32.powf((note_event.pitch_bend_semitones * bend_progress) / 12.0)
                            } else {
                                1.0
                            };

                            // Determine if we can use SIMD path (simple waveforms only)
                            let can_vectorize = note_event.fm_params.mod_index == 0.0
                                && note_event.custom_wavetable.is_none();

                            if can_vectorize && SIMD.width() >= 8 && num_freqs >= 8 {
                                // SIMD path: process 8 frequencies at once
                                let chunks = num_freqs / 8;
                                let bend_simd = f32x8::splat(bend_multiplier);
                                let time_simd = f32x8::splat(time_in_note);

                                for chunk_idx in 0..chunks {
                                    let base_idx = chunk_idx * 8;

                                    // Load 8 base frequencies
                                    let mut freq_array = [0.0f32; 8];
                                    freq_array.copy_from_slice(&note_event.frequencies[base_idx..base_idx+8]);
                                    let base_freqs = f32x8::from(freq_array);

                                    // Apply pitch bend to all 8 frequencies at once (SIMD)
                                    let freqs = base_freqs * bend_simd;

                                    // Calculate 8 phases at once (SIMD multiplication - this is the win!)
                                    let phases_raw = time_simd * freqs;
                                    let phases = phases_raw.to_array();

                                    // Sample waveform for each phase (wavetable lookups remain scalar)
                                    for &phase in &phases {
                                        let phase_wrapped = phase.fract();  // Wrap to [0, 1)
                                        track_value += note_event.waveform.sample(phase_wrapped) * envelope_amp;
                                    }
                                }

                                // Scalar remainder
                                for freq_idx in (chunks * 8)..num_freqs {
                                    let freq = note_event.frequencies[freq_idx] * bend_multiplier;
                                    let phase = (time_in_note * freq) % 1.0;
                                    track_value += note_event.waveform.sample(phase) * envelope_amp;
                                }
                            } else if can_vectorize && SIMD.width() >= 4 && num_freqs >= 4 {
                                // SSE path: process 4 frequencies at once
                                let chunks = num_freqs / 4;
                                let bend_simd = f32x4::splat(bend_multiplier);
                                let time_simd = f32x4::splat(time_in_note);

                                for chunk_idx in 0..chunks {
                                    let base_idx = chunk_idx * 4;

                                    // Load 4 base frequencies
                                    let mut freq_array = [0.0f32; 4];
                                    freq_array.copy_from_slice(&note_event.frequencies[base_idx..base_idx+4]);
                                    let base_freqs = f32x4::from(freq_array);

                                    // Apply pitch bend to all 4 frequencies at once (SIMD)
                                    let freqs = base_freqs * bend_simd;

                                    // Calculate 4 phases at once (SIMD multiplication - this is the win!)
                                    let phases_raw = time_simd * freqs;
                                    let phases = phases_raw.to_array();

                                    // Sample waveform for each phase (wavetable lookups remain scalar)
                                    for &phase in &phases {
                                        let phase_wrapped = phase.fract();  // Wrap to [0, 1)
                                        track_value += note_event.waveform.sample(phase_wrapped) * envelope_amp;
                                    }
                                }

                                // Scalar remainder
                                for freq_idx in (chunks * 4)..num_freqs {
                                    let freq = note_event.frequencies[freq_idx] * bend_multiplier;
                                    let phase = (time_in_note * freq) % 1.0;
                                    track_value += note_event.waveform.sample(phase) * envelope_amp;
                                }
                            } else {
                                // Scalar fallback (FM synthesis, custom wavetables, or low polyphony)
                                for freq_idx in 0..num_freqs {
                                    let freq = note_event.frequencies[freq_idx] * bend_multiplier;

                                    let sample = if note_event.fm_params.mod_index > 0.0 {
                                        note_event.fm_params.sample(
                                            freq,
                                            time_in_note,
                                            note_event.duration,
                                        )
                                    } else if let Some(ref wavetable) = note_event.custom_wavetable {
                                        let phase = (time_in_note * freq) % 1.0;
                                        wavetable.sample(phase)
                                    } else {
                                        let phase = (time_in_note * freq) % 1.0;
                                        note_event.waveform.sample(phase)
                                    };

                                    track_value += sample * envelope_amp;
                                }
                            }
                        }
                    }
                    AudioEvent::Drum(drum_event) => {
                        // Apply pitch offset: higher pitch = faster playback
                        let pitch_ratio = 2.0_f32.powf(drum_event.pitch_offset / 12.0);
                        let drum_duration = drum_event.drum_type.duration() / pitch_ratio;
                        if time >= drum_event.start_time
                            && time < drum_event.start_time + drum_duration
                        {
                            let time_in_drum = time - drum_event.start_time;
                            let sample_index = (time_in_drum * sample_rate * pitch_ratio) as usize;
                            track_value += drum_event.drum_type.sample(sample_index, sample_rate) * drum_event.velocity;
                        }
                    }
                    AudioEvent::Sample(_) => {
                        // Samples are pre-rendered above with SIMD for better performance
                        // They'll be added to track_value after this loop
                    }
                    _ => {} // Tempo/time/key signatures don't generate audio
                }
            }

            // Add pre-rendered samples (processed with SIMD above)
            track_value += sample_buffer[i];

            // Note: Cached notes are already in track_value (read from buffer at loop start)

            *sample_out = track_value;
        }

        // Apply track volume to entire buffer (SIMD-optimized, ~8x faster than per-sample!)
        if track.volume != 1.0 {
            use crate::synthesis::simd::SIMD;
            SIMD.multiply_const(buffer, track.volume);
        }

        // Apply filter to entire buffer (optimized block processing!)
        track.filter.process_buffer(buffer, sample_rate);

        // Apply effects to entire buffer (block processing!)
        track
            .effects
            .process_mono_block(buffer, sample_rate, start_time, start_sample_count);
    }

    /// Process a single track and return its stereo output (static version)
    ///
    /// This is a helper method extracted from the main mixing loop.
    /// It handles event synthesis, filtering, effects, and panning for one track.
    pub(crate) fn process_track_static(
        track: &mut Track,
        time: f32,
        sample_rate: f32,
        sample_count: u64,
    ) -> (f32, f32) {
        // Ensure events are sorted by start_time for binary search
        track.ensure_sorted();

        // Quick time-bounds check: skip entire track if current time is outside its active range
        let track_start = track.start_time();
        let track_end = track.end_time();

        // Skip track entirely if we're before it starts or after it ends
        if (time < track_start || time > track_end)
            && track.effects.delay.is_none()
            && track.effects.reverb.is_none()
        {
            return (0.0, 0.0);
        }

        let mut track_value = 0.0;
        let mut has_active_event = false;

        // Binary search to find potentially active events
        let (start_idx, end_idx) = track.find_active_range(time);

        // Process events
        for event in &track.events[start_idx..end_idx] {
            match event {
                AudioEvent::Note(note_event) => {
                    let total_duration = note_event.envelope.total_duration(note_event.duration);
                    let note_end_with_release = note_event.start_time + total_duration;

                    if time >= note_event.start_time && time < note_end_with_release {
                        has_active_event = true;
                        let time_in_note = time - note_event.start_time;
                        let envelope_amp = note_event
                            .envelope
                            .amplitude_at(time_in_note, note_event.duration);

                        for i in 0..note_event.num_freqs {
                            let base_freq = note_event.frequencies[i];

                            let freq = if note_event.pitch_bend_semitones != 0.0 {
                                let bend_progress = (time_in_note / note_event.duration).min(1.0);
                                let bend_multiplier = 2.0f32
                                    .powf((note_event.pitch_bend_semitones * bend_progress) / 12.0);
                                base_freq * bend_multiplier
                            } else {
                                base_freq
                            };

                            let sample = if note_event.fm_params.mod_index > 0.0 {
                                note_event
                                    .fm_params
                                    .sample(freq, time_in_note, note_event.duration)
                            } else if let Some(ref wavetable) = note_event.custom_wavetable {
                                let phase = (time_in_note * freq) % 1.0;
                                wavetable.sample(phase)
                            } else {
                                let phase = (time_in_note * freq) % 1.0;
                                note_event.waveform.sample(phase)
                            };

                            track_value += sample * envelope_amp;
                        }
                    }
                }
                AudioEvent::Drum(drum_event) => {
                    // Apply pitch offset: higher pitch = faster playback
                    let pitch_ratio = 2.0_f32.powf(drum_event.pitch_offset / 12.0);
                    let drum_duration = drum_event.drum_type.duration() / pitch_ratio;
                    if time >= drum_event.start_time && time < drum_event.start_time + drum_duration
                    {
                        has_active_event = true;
                        let time_in_drum = time - drum_event.start_time;
                        let sample_index = (time_in_drum * sample_rate * pitch_ratio) as usize;
                        track_value += drum_event.drum_type.sample(sample_index, sample_rate) * drum_event.velocity;
                    }
                }
                AudioEvent::Sample(sample_event) => {
                    let time_in_sample = time - sample_event.start_time;
                    let sample_duration = sample_event.sample.duration / sample_event.playback_rate;

                    if time_in_sample >= 0.0 && time_in_sample < sample_duration {
                        has_active_event = true;
                        let (sample_left, sample_right) = sample_event
                            .sample
                            .sample_at_interpolated(time_in_sample, sample_event.playback_rate);
                        track_value += (sample_left + sample_right) * 0.5 * sample_event.volume;
                    }
                }
                _ => {} // Tempo/time/key signatures don't generate audio
            }
        }

        // Skip effect processing if track has no active events and no tail effects
        if !has_active_event && track.effects.delay.is_none() && track.effects.reverb.is_none() {
            return (0.0, 0.0);
        }

        // Apply track volume
        track_value *= track.volume;

        // Apply filter
        track_value = track.filter.process(track_value, sample_rate);

        // Apply effects through the unified effect chain
        track_value = track
            .effects
            .process_mono(track_value, sample_rate, time, sample_count);

        // Apply stereo panning using constant power panning (fast trig)
        use crate::synthesis::simd::SimdLanes;
        let pan_angle = (track.pan + 1.0) * 0.25 * std::f32::consts::PI;
        let left_gain = pan_angle.fast_cos();
        let right_gain = pan_angle.fast_sin();

        (track_value * left_gain, track_value * right_gain)
    }

    /// Render the mixer to an in-memory stereo buffer
    ///
    /// Pre-renders the entire composition to a Vec of interleaved stereo samples (left, right, left, right...).
    /// This is used for efficient playback without real-time synthesis overhead.
    ///
    /// # Arguments
    /// * `sample_rate` - Sample rate in Hz
    ///
    /// # Returns
    /// A Vec of f32 samples in interleaved stereo format (left, right, left, right...)
    pub fn render_to_buffer(&mut self, sample_rate: f32) -> Vec<f32> {
        let duration = self.total_duration();
        let total_samples = (duration * sample_rate).ceil() as usize;

        // 🚀 KEY OPTIMIZATION: Pre-render all unique notes before streaming
        // This eliminates per-block cache lookups and unleashes GPU performance!
        let should_prerender = self.cache.is_some() || {
            #[cfg(feature = "gpu")]
            {
                self.gpu_synthesizer.is_some()
            }
            #[cfg(not(feature = "gpu"))]
            {
                false
            }
        };

        if should_prerender {
            self.prerender_notes(sample_rate);
        }

        // Pre-allocate buffer for interleaved stereo (2 channels)
        let mut buffer = vec![0.0; total_samples * 2];

        // Process in blocks of 512 samples for better performance
        const BLOCK_SIZE: usize = 512;
        let mut processed_samples = 0;

        while processed_samples < total_samples {
            let remaining = total_samples - processed_samples;
            let block_samples = remaining.min(BLOCK_SIZE);
            let block_frames = block_samples * 2; // stereo

            let start_time = processed_samples as f32 / sample_rate;
            let start_idx = processed_samples * 2;
            let end_idx = start_idx + block_frames;

            // Process this block
            self.process_block(
                &mut buffer[start_idx..end_idx],
                sample_rate,
                start_time,
                None,
                None,
            );

            processed_samples += block_samples;
        }

        // Clamp to valid range
        for sample in &mut buffer {
            *sample = sample.clamp(-1.0, 1.0);
        }

        buffer
    }

    /// Add a compressor to the master output
    ///
    /// Applies dynamic range compression to the final stereo mix. Master compression
    /// uses stereo-linked processing to preserve the stereo image.
    ///
    /// # Arguments
    /// * `compressor` - Compressor effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Compressor;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_compressor(Compressor::new(-10.0, 4.0, 0.01, 0.1, 2.0));
    /// ```
    pub fn master_compressor(&mut self, compressor: crate::synthesis::effects::Compressor) {
        self.master.compressor = Some(compressor);
        self.master.compute_effect_order();
    }

    /// Add a limiter to the master output
    ///
    /// Applies limiting to prevent clipping on the final stereo mix. Master limiting
    /// uses stereo-linked processing to preserve the stereo image. This is typically
    /// the last effect in the master chain.
    ///
    /// # Arguments
    /// * `limiter` - Limiter effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Limiter;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_limiter(Limiter::new(0.0, 0.01));
    /// ```
    pub fn master_limiter(&mut self, limiter: crate::synthesis::effects::Limiter) {
        self.master.limiter = Some(limiter);
        self.master.compute_effect_order();
    }

    /// Add EQ to the master output
    ///
    /// Applies 3-band equalization to the final stereo mix.
    ///
    /// # Arguments
    /// * `eq` - EQ effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::EQ;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_eq(EQ::new(1.5, 1.0, 1.2, 200.0, 3000.0));
    /// ```
    pub fn master_eq(&mut self, eq: crate::synthesis::effects::EQ) {
        self.master.eq = Some(eq);
        self.master.compute_effect_order();
    }

    /// Add parametric EQ to the master output
    ///
    /// Applies multi-band parametric equalization to the final stereo mix for
    /// precise frequency shaping and mastering.
    ///
    /// # Arguments
    /// * `parametric_eq` - ParametricEQ effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::ParametricEQ;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// let eq = ParametricEQ::new()
    ///     .band(100.0, -3.0, 0.7)  // Cut low rumble
    ///     .band(3000.0, 2.0, 1.5); // Boost presence
    /// mixer.master_parametric_eq(eq);
    /// ```
    pub fn master_parametric_eq(&mut self, parametric_eq: crate::synthesis::effects::ParametricEQ) {
        self.master.parametric_eq = Some(parametric_eq);
        self.master.compute_effect_order();
    }

    /// Add reverb to the master output
    ///
    /// Applies reverb to the final stereo mix. Use sparingly as master reverb
    /// affects the entire mix.
    ///
    /// # Arguments
    /// * `reverb` - Reverb effect configuration
    pub fn master_reverb(&mut self, reverb: crate::synthesis::effects::Reverb) {
        self.master.reverb = Some(reverb);
        self.master.compute_effect_order();
    }

    /// Add delay to the master output
    ///
    /// Applies delay to the final stereo mix.
    ///
    /// # Arguments
    /// * `delay` - Delay effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Delay;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_delay(Delay::new(0.5, 0.4, 0.3));
    /// ```
    pub fn master_delay(&mut self, delay: crate::synthesis::effects::Delay) {
        self.master.delay = Some(delay);
        self.master.compute_effect_order();
    }

    /// Add gate to the master output
    ///
    /// Applies noise gate to the final stereo mix. Useful for cutting unwanted
    /// background noise or creating rhythmic gating effects.
    ///
    /// # Arguments
    /// * `gate` - Gate effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Gate;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_gate(Gate::new(-40.0, 4.0, 0.01, 0.1));
    /// ```
    pub fn master_gate(&mut self, gate: crate::synthesis::effects::Gate) {
        self.master.gate = Some(gate);
        self.master.compute_effect_order();
    }

    /// Add saturation to the master output
    ///
    /// Applies saturation/warmth to the final stereo mix.
    ///
    /// # Arguments
    /// * `saturation` - Saturation effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Saturation;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_saturation(Saturation::new(2.0, 0.5, 1.0));
    /// ```
    pub fn master_saturation(&mut self, saturation: crate::synthesis::effects::Saturation) {
        self.master.saturation = Some(saturation);
        self.master.compute_effect_order();
    }

    /// Add bit crusher to the master output
    ///
    /// Applies bit reduction and sample rate reduction to the final stereo mix
    /// for lo-fi effects.
    ///
    /// # Arguments
    /// * `bitcrusher` - BitCrusher effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::BitCrusher;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_bitcrusher(BitCrusher::new(8.0, 2.0, 1.0));
    /// ```
    pub fn master_bitcrusher(&mut self, bitcrusher: crate::synthesis::effects::BitCrusher) {
        self.master.bitcrusher = Some(bitcrusher);
        self.master.compute_effect_order();
    }

    /// Add distortion to the master output
    ///
    /// Applies distortion to the final stereo mix.
    ///
    /// # Arguments
    /// * `distortion` - Distortion effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Distortion;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_distortion(Distortion::new(2.0, 0.5));
    /// ```
    pub fn master_distortion(&mut self, distortion: crate::synthesis::effects::Distortion) {
        self.master.distortion = Some(distortion);
        self.master.compute_effect_order();
    }

    /// Add chorus to the master output
    ///
    /// Applies chorus modulation to the final stereo mix for widening effects.
    ///
    /// # Arguments
    /// * `chorus` - Chorus effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Chorus;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_chorus(Chorus::new(0.003, 0.5, 0.3));
    /// ```
    pub fn master_chorus(&mut self, chorus: crate::synthesis::effects::Chorus) {
        self.master.chorus = Some(chorus);
        self.master.compute_effect_order();
    }

    /// Add phaser to the master output
    ///
    /// Applies phaser modulation to the final stereo mix.
    ///
    /// # Arguments
    /// * `phaser` - Phaser effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Phaser;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_phaser(Phaser::new(0.5, 0.7, 0.5, 4, 0.5));
    /// ```
    pub fn master_phaser(&mut self, phaser: crate::synthesis::effects::Phaser) {
        self.master.phaser = Some(phaser);
        self.master.compute_effect_order();
    }

    /// Add flanger to the master output
    ///
    /// Applies flanger modulation to the final stereo mix.
    ///
    /// # Arguments
    /// * `flanger` - Flanger effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Flanger;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_flanger(Flanger::new(0.5, 3.0, 0.7, 0.5));
    /// ```
    pub fn master_flanger(&mut self, flanger: crate::synthesis::effects::Flanger) {
        self.master.flanger = Some(flanger);
        self.master.compute_effect_order();
    }

    /// Add ring modulator to the master output
    ///
    /// Applies ring modulation to the final stereo mix for metallic/robotic effects.
    ///
    /// # Arguments
    /// * `ring_mod` - RingModulator effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::RingModulator;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_ring_mod(RingModulator::new(30.0, 0.5));
    /// ```
    pub fn master_ring_mod(&mut self, ring_mod: crate::synthesis::effects::RingModulator) {
        self.master.ring_mod = Some(ring_mod);
        self.master.compute_effect_order();
    }

    /// Add tremolo to the master output
    ///
    /// Applies tremolo (amplitude modulation) to the final stereo mix.
    ///
    /// # Arguments
    /// * `tremolo` - Tremolo effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::Tremolo;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_tremolo(Tremolo::new(4.0, 0.5));
    /// ```
    pub fn master_tremolo(&mut self, tremolo: crate::synthesis::effects::Tremolo) {
        self.master.tremolo = Some(tremolo);
        self.master.compute_effect_order();
    }

    /// Add auto-pan to the master output
    ///
    /// Applies automatic panning to the final stereo mix, moving the sound
    /// between left and right channels.
    ///
    /// # Arguments
    /// * `autopan` - AutoPan effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::AutoPan;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_autopan(AutoPan::new(0.25, 1.0));
    /// ```
    pub fn master_autopan(&mut self, autopan: crate::synthesis::effects::AutoPan) {
        self.master.autopan = Some(autopan);
        self.master.compute_effect_order();
    }

    /// Add a phase vocoder to the master chain for time-stretching and pitch-shifting
    ///
    /// Phase vocoder allows independent control of time and pitch using STFT analysis.
    /// Perfect for creative time/pitch manipulation with phase coherence preservation.
    ///
    /// **Note**: This is a block-based spectral effect with ~23ms latency @ 44.1kHz.
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::PhaseVocoder;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// let vocoder = PhaseVocoder::new(1.0, 7.0, 44100.0); // Perfect fifth up
    /// mixer.master_phase_vocoder(vocoder);
    /// ```
    pub fn master_phase_vocoder(&mut self, phase_vocoder: crate::synthesis::effects::PhaseVocoder) {
        self.master.phase_vocoder = Some(phase_vocoder);
        self.master.compute_effect_order();
    }

    /// Add a spectral freeze to the master chain for capturing and holding frequency spectrum
    ///
    /// Spectral freeze captures the current frequency content and holds it indefinitely,
    /// creating sustained "frozen" sounds. Perfect for ambient textures and drones.
    ///
    /// **Note**: This is a block-based spectral effect with ~23ms latency @ 44.1kHz.
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralFreeze;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// let freeze = SpectralFreeze::new(true, 0.75, 44100.0); // 75% frozen, 25% live
    /// mixer.master_spectral_freeze(freeze);
    /// ```
    pub fn master_spectral_freeze(
        &mut self,
        spectral_freeze: crate::synthesis::effects::SpectralFreeze,
    ) {
        self.master.spectral_freeze = Some(spectral_freeze);
        self.master.compute_effect_order();
    }

    /// Add a spectral gate to the master chain for frequency-selective noise gating
    ///
    /// Spectral gate applies independent gating to each frequency bin, enabling surgical
    /// noise reduction. Unlike traditional gates that gate the entire signal, spectral gate
    /// can remove hum, hiss, and unwanted frequencies while preserving the wanted signal.
    ///
    /// **Note**: This is a block-based spectral effect with ~23ms latency @ 44.1kHz.
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralGate;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// let gate = SpectralGate::new(-40.0, 0.001, 0.050, 0.0, 44100.0);
    /// mixer.master_spectral_gate(gate);
    /// ```
    pub fn master_spectral_gate(&mut self, spectral_gate: crate::synthesis::effects::SpectralGate) {
        self.master.spectral_gate = Some(spectral_gate);
        self.master.compute_effect_order();
    }

    /// Add a spectral compressor to the master chain for frequency-selective dynamic range compression
    ///
    /// Spectral compressor applies independent compression to each frequency bin, enabling
    /// multiband compression at extreme resolution (1024+ bands). This allows for surgical
    /// dynamic control that can't be achieved with traditional multiband compressors.
    ///
    /// **Note**: This is a block-based spectral effect with ~23ms latency @ 44.1kHz.
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralCompressor;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// let compressor = SpectralCompressor::new(-20.0, 4.0, 5.0, 50.0, 6.0, 44100.0);
    /// mixer.master_spectral_compressor(compressor);
    /// ```
    pub fn master_spectral_compressor(
        &mut self,
        spectral_compressor: crate::synthesis::effects::SpectralCompressor,
    ) {
        self.master.spectral_compressor = Some(spectral_compressor);
        self.master.compute_effect_order();
    }

    pub fn master_spectral_robotize(
        &mut self,
        spectral_robotize: crate::synthesis::effects::SpectralRobotize,
    ) {
        self.master.spectral_robotize = Some(spectral_robotize);
        self.master.compute_effect_order();
    }

    pub fn master_spectral_delay(
        &mut self,
        spectral_delay: crate::synthesis::effects::SpectralDelay,
    ) {
        self.master.spectral_delay = Some(spectral_delay);
        self.master.compute_effect_order();
    }

    /// Add spectral filter to the master output for frequency-domain filtering
    ///
    /// Applies filtering in the frequency domain, allowing precise control over the
    /// frequency response with minimal artifacts. Unlike time-domain filters, spectral
    /// filtering can achieve brick-wall responses and frequency-dependent effects.
    ///
    /// **Note**: This is a block-based spectral effect with ~23ms latency @ 44.1kHz.
    ///
    /// # Arguments
    /// * `spectral_filter` - SpectralFilter effect configuration
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralFilter;
    /// # use tunes::synthesis::spectral::FilterType;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// let filter = SpectralFilter::new(FilterType::LowPass, 8000.0, 1.0, 1.0, 44100.0);
    /// mixer.master_spectral_filter(filter);
    /// ```
    pub fn master_spectral_filter(
        &mut self,
        spectral_filter: crate::synthesis::effects::SpectralFilter,
    ) -> &mut Self {
        self.master.spectral_filter = Some(spectral_filter);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral shift effect to the master chain for frequency shifting
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralShift;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_shift(SpectralShift::subtle());
    /// ```
    pub fn master_spectral_shift(
        &mut self,
        spectral_shift: crate::synthesis::effects::SpectralShift,
    ) -> &mut Self {
        self.master.spectral_shift = Some(spectral_shift);
        self.master.compute_effect_order();
        self
    }

    /// Add formant shifter effect to the master chain for vocal character transformation
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::FormantShifter;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_formant_shifter(FormantShifter::male_to_female());
    /// ```
    pub fn master_formant_shifter(
        &mut self,
        formant_shifter: crate::synthesis::effects::FormantShifter,
    ) -> &mut Self {
        self.master.formant_shifter = Some(formant_shifter);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral harmonizer effect to the master chain for pitch-shifted harmonies
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralHarmonizer;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_harmonizer(SpectralHarmonizer::fifth());
    /// ```
    pub fn master_spectral_harmonizer(
        &mut self,
        spectral_harmonizer: crate::synthesis::effects::SpectralHarmonizer,
    ) -> &mut Self {
        self.master.spectral_harmonizer = Some(spectral_harmonizer);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral resonator effect to the master chain for resonant frequency peaks
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralResonator;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_resonator(SpectralResonator::bell());
    /// ```
    pub fn master_spectral_resonator(
        &mut self,
        spectral_resonator: crate::synthesis::effects::SpectralResonator,
    ) -> &mut Self {
        self.master.spectral_resonator = Some(spectral_resonator);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral panner effect to the master chain for frequency-based spatial positioning
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralPanner;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_panner(SpectralPanner::circular());
    /// ```
    pub fn master_spectral_panner(
        &mut self,
        spectral_panner: crate::synthesis::effects::SpectralPanner,
    ) -> &mut Self {
        self.master.spectral_panner = Some(spectral_panner);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral exciter effect to the master chain for harmonic enhancement
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralExciter;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_exciter(SpectralExciter::gentle());
    /// ```
    pub fn master_spectral_exciter(
        &mut self,
        spectral_exciter: crate::synthesis::effects::SpectralExciter,
    ) -> &mut Self {
        self.master.spectral_exciter = Some(spectral_exciter);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral invert effect to the master chain for frequency spectrum reversal
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralInvert;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_invert(SpectralInvert::full());
    /// ```
    pub fn master_spectral_invert(
        &mut self,
        spectral_invert: crate::synthesis::effects::SpectralInvert,
    ) -> &mut Self {
        self.master.spectral_invert = Some(spectral_invert);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral widen effect to the master chain for stereo widening
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralWiden;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_widen(SpectralWiden::wide());
    /// ```
    pub fn master_spectral_widen(
        &mut self,
        spectral_widen: crate::synthesis::effects::SpectralWiden,
    ) -> &mut Self {
        self.master.spectral_widen = Some(spectral_widen);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral morph effect to the master chain for morphing spectrum toward target shapes
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralMorph;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_morph(SpectralMorph::robot());
    /// ```
    pub fn master_spectral_morph(
        &mut self,
        spectral_morph: crate::synthesis::effects::SpectralMorph,
    ) -> &mut Self {
        self.master.spectral_morph = Some(spectral_morph);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral dynamics to the master bus for frequency-dependent compression/expansion
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralDynamics;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_dynamics(SpectralDynamics::gentle());
    /// ```
    pub fn master_spectral_dynamics(
        &mut self,
        spectral_dynamics: crate::synthesis::effects::SpectralDynamics,
    ) -> &mut Self {
        self.master.spectral_dynamics = Some(spectral_dynamics);
        self.master.compute_effect_order();
        self
    }

    /// Add spectral scramble to the master bus for glitchy frequency bin randomization
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::synthesis::effects::SpectralScramble;
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// let mut mixer = comp.into_mixer();
    /// mixer.master_spectral_scramble(SpectralScramble::glitch());
    /// ```
    pub fn master_spectral_scramble(
        &mut self,
        spectral_scramble: crate::synthesis::effects::SpectralScramble,
    ) -> &mut Self {
        self.master.spectral_scramble = Some(spectral_scramble);
        self.master.compute_effect_order();
        self
    }
}

impl Default for Mixer {
    fn default() -> Self {
        Self::new(Tempo::new(120.0))
    }
}