beamer-vst3 0.2.0

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

use std::cell::UnsafeCell;
use std::ffi::{c_char, c_void};
use std::marker::PhantomData;
use std::slice;

use log::warn;
use vst3::{Class, ComRef, Steinberg::Vst::*, Steinberg::*};

use beamer_core::{
    AuxiliaryBuffers, Buffer, BusInfo as CoreBusInfo, BusLayout,
    BusType as CoreBusType, CachedBusConfig, CachedBusInfo, ChordInfo, ConversionBuffers,
    Descriptor, FactoryPresets, FrameRate as CoreFrameRate, HasParameters, MidiBuffer, MidiCcState,
    MidiEvent, MidiEventKind, NoPresets, NoteExpressionInt, NoteExpressionText,
    NoteExpressionValue as CoreNoteExpressionValue, ParameterStore, Config, PluginSetup,
    ProcessBufferStorage, ProcessContext as CoreProcessContext, Processor, ScaleInfo, SysEx,
    SysExOutputPool, Transport, MAX_BUSES, MAX_CHANNELS, MAX_CHORD_NAME_SIZE,
    MAX_EXPRESSION_TEXT_SIZE, MAX_SCALE_NAME_SIZE, MAX_SYSEX_SIZE,
};

use crate::factory::ComponentFactory;
use crate::util::{copy_wstring, len_wstring};
use crate::wrapper::Vst3Config;

// VST3 event type constants
const K_NOTE_ON_EVENT: u16 = 0;
const K_NOTE_OFF_EVENT: u16 = 1;
const K_DATA_EVENT: u16 = 2;
const K_POLY_PRESSURE_EVENT: u16 = 3;
const K_NOTE_EXPRESSION_VALUE_EVENT: u16 = 4;
const K_NOTE_EXPRESSION_TEXT_EVENT: u16 = 5;
const K_CHORD_EVENT: u16 = 6;
const K_SCALE_EVENT: u16 = 7;
const K_NOTE_EXPRESSION_INT_VALUE_EVENT: u16 = 8;
const K_LEGACY_MIDI_CC_OUT_EVENT: u16 = 65535;

// LegacyMIDICCOutEvent controlNumber special values
const LEGACY_CC_CHANNEL_PRESSURE: u8 = 128;
const LEGACY_CC_PITCH_BEND: u8 = 129;
const LEGACY_CC_PROGRAM_CHANGE: u8 = 130;

// DataEvent type for SysEx
const DATA_TYPE_MIDI_SYSEX: u32 = 0;

// Program change parameter ID (for preset selection, distinct from MIDI CC range)
const PROGRAM_CHANGE_PARAM_ID: u32 = 0x20000000;

// Program list ID for factory presets
const FACTORY_PRESETS_LIST_ID: i32 = 0;

// =============================================================================
// Transport Extraction
// =============================================================================

/// Helper macro for extracting optional fields based on validity flags.
/// Reduces repetitive `if state & FLAG != 0 { Some(value) } else { None }` patterns.
macro_rules! valid_if {
    ($state:expr, $flag:expr, $value:expr) => {
        if $state & $flag != 0 {
            Some($value)
        } else {
            None
        }
    };
}

/// Extract transport information from VST3 ProcessContext.
///
/// Converts VST3's validity flags to Rust's Option<T> idiom.
/// Returns a default Transport if the context pointer is null.
///
/// # Safety
///
/// The caller must ensure `context_ptr` is either null or points to a valid
/// ProcessContext struct for the duration of this call.
unsafe fn extract_transport(context_ptr: *const ProcessContext) -> Transport {
    if context_ptr.is_null() {
        return Transport::default();
    }

    let context = &*context_ptr;
    let state = context.state;

    // VST3 ProcessContext state flags
    const K_PLAYING: u32 = 1 << 1;
    const K_CYCLE_ACTIVE: u32 = 1 << 2;
    const K_RECORDING: u32 = 1 << 3;
    const K_SYSTEM_TIME_VALID: u32 = 1 << 8;
    const K_PROJECT_TIME_MUSIC_VALID: u32 = 1 << 9;
    const K_TEMPO_VALID: u32 = 1 << 10;
    const K_BAR_POSITION_VALID: u32 = 1 << 11;
    const K_CYCLE_VALID: u32 = 1 << 12;
    const K_TIME_SIG_VALID: u32 = 1 << 13;
    const K_SMPTE_VALID: u32 = 1 << 14;
    const K_CLOCK_VALID: u32 = 1 << 15;
    const K_CONT_TIME_VALID: u32 = 1 << 17;

    Transport {
        // Tempo and time signature
        tempo: valid_if!(state, K_TEMPO_VALID, context.tempo),
        time_sig_numerator: valid_if!(state, K_TIME_SIG_VALID, context.timeSigNumerator),
        time_sig_denominator: valid_if!(state, K_TIME_SIG_VALID, context.timeSigDenominator),

        // Position
        project_time_samples: Some(context.projectTimeSamples),
        project_time_beats: valid_if!(state, K_PROJECT_TIME_MUSIC_VALID, context.projectTimeMusic),
        bar_position_beats: valid_if!(state, K_BAR_POSITION_VALID, context.barPositionMusic),

        // Cycle/loop
        cycle_start_beats: valid_if!(state, K_CYCLE_VALID, context.cycleStartMusic),
        cycle_end_beats: valid_if!(state, K_CYCLE_VALID, context.cycleEndMusic),

        // Transport state (always valid)
        is_playing: state & K_PLAYING != 0,
        is_recording: state & K_RECORDING != 0,
        is_cycle_active: state & K_CYCLE_ACTIVE != 0,

        // Advanced timing
        system_time_ns: valid_if!(state, K_SYSTEM_TIME_VALID, context.systemTime),
        continuous_time_samples: valid_if!(state, K_CONT_TIME_VALID, context.continousTimeSamples), // Note: VST3 SDK typo
        samples_to_next_clock: valid_if!(state, K_CLOCK_VALID, context.samplesToNextClock),

        // SMPTE - use FrameRate::from_raw() for conversion
        smpte_offset_subframes: valid_if!(state, K_SMPTE_VALID, context.smpteOffsetSubframes),
        frame_rate: if state & K_SMPTE_VALID != 0 {
            let is_drop = context.frameRate.flags & 1 != 0;
            CoreFrameRate::from_raw(context.frameRate.framesPerSecond, is_drop)
        } else {
            None
        },
    }
}

/// Validate that a speaker arrangement doesn't exceed MAX_CHANNELS.
///
/// Returns `Ok(())` if valid, or `Err` with a descriptive message if exceeded.
fn validate_speaker_arrangement(arrangement: SpeakerArrangement) -> Result<(), String> {
    let channel_count = arrangement.count_ones() as usize;
    if channel_count > MAX_CHANNELS {
        return Err(format!(
            "Speaker arrangement has {} channels, but MAX_CHANNELS is {}",
            channel_count, MAX_CHANNELS
        ));
    }
    Ok(())
}


// =============================================================================
// Setup Extraction
// =============================================================================

/// Build plugin setup from VST3 ProcessSetup.
///
/// Creates a HostSetup with all available information, then uses the
/// `PluginSetup::extract` method to extract only what the plugin needs.
fn build_setup<S: PluginSetup>(setup: &ProcessSetup, bus_layout: &BusLayout) -> S {
    use beamer_core::{HostSetup, ProcessMode};

    // Convert VST3 process mode to our ProcessMode
    let process_mode = match setup.processMode {
        1 => ProcessMode::Offline,       // kOffline
        2 => ProcessMode::Prefetch,      // kPrefetch
        _ => ProcessMode::Realtime,      // kRealtime (0) or unknown
    };

    let host_setup = HostSetup::new(
        setup.sampleRate,
        setup.maxSamplesPerBlock as usize,
        bus_layout.clone(),
        process_mode,
    );

    S::extract(&host_setup)
}

// =============================================================================
// Plugin State Machine
// =============================================================================

// Note: beamer_core::BusInfo is imported as CoreBusInfo in the main imports
// to avoid collision with vst3::Steinberg::Vst::BusInfo used in COM interfaces.
// We use CoreBusInfo throughout this module for the beamer type.

/// Internal state machine for plugin lifecycle.
///
/// The wrapper manages two states:
/// - **Unprepared**: Descriptor exists, but audio config (sample rate) is unknown
/// - **Prepared**: Processor exists with valid audio config, ready for processing
///
/// This enables the type-safe prepare/unprepare cycle where processors cannot
/// be used until they have valid configuration.
enum PluginState<P: Descriptor> {
    /// Before setupProcessing() - definition exists but no audio config yet.
    Unprepared {
        /// The unprepared definition (holds parameters)
        plugin: P,
        /// State data received before prepare (deferred loading)
        pending_state: Option<Vec<u8>>,
    },
    /// After setupProcessing() - processor is ready for audio.
    Prepared {
        /// The prepared processor (ready for audio)
        processor: P::Processor,
        /// Cached input bus info (since Descriptor is consumed)
        input_buses: Vec<CoreBusInfo>,
        /// Cached output bus info (since Descriptor is consumed)
        output_buses: Vec<CoreBusInfo>,
    },
}

// =============================================================================
// Vst3Processor Wrapper
// =============================================================================

/// Generic VST3 processor wrapping any [`Descriptor`] implementation.
///
/// This struct implements the VST3 combined component pattern, providing
/// `IComponent`, `IAudioProcessor`, and `IEditController` interfaces that
/// delegate to the wrapped plugin.
///
/// # Two-Phase Lifecycle
///
/// The wrapper manages the plugin's two-phase lifecycle:
///
/// ```text
/// Vst3Processor::new()
///     ↓ creates Descriptor::default()
/// PluginState::Unprepared { plugin }
///     ↓ setupProcessing() calls definition.prepare(config)
/// PluginState::Prepared { processor }
///     ↓ sample rate change: processor.unprepare()
/// PluginState::Unprepared { plugin }
///     ↓ setupProcessing() again
/// PluginState::Prepared { processor }
/// ```
///
/// # Usage
///
/// ```ignore
/// use beamer_vst3::{export_vst3, Vst3Processor, Config};
///
/// #[derive(Default)]
/// struct MyPlugin { parameters: MyParameters }
/// impl Descriptor for MyPlugin { /* ... */ }
///
/// struct MyProcessor { parameters: MyParameters, sample_rate: f64 }
/// impl Processor for MyProcessor { /* ... */ }
///
/// static CONFIG: Config = Config::new("MyPlugin");
/// static VST3_CONFIG: Vst3Config = Vst3Config::new(MY_UID);
/// export_vst3!(CONFIG, VST3_CONFIG, MyPlugin);
/// ```
///
/// # Thread Safety
///
/// VST3 guarantees that `process()` is called from a single thread at a time.
/// We use `UnsafeCell` for interior mutability in `process()` since the COM
/// interface only provides `&self`.
pub struct Vst3Processor<P, Presets = NoPresets<<P as HasParameters>::Parameters>>
where
    P: Descriptor,
    Presets: FactoryPresets<Parameters = <P as HasParameters>::Parameters>,
{
    /// The plugin state machine (Unprepared or Prepared)
    state: UnsafeCell<PluginState<P>>,
    /// VST3-specific configuration reference
    vst3_config: &'static Vst3Config,
    /// Current sample rate
    sample_rate: UnsafeCell<f64>,
    /// Maximum block size
    max_block_size: UnsafeCell<usize>,
    /// Current symbolic sample size (kSample32 or kSample64)
    symbolic_sample_size: UnsafeCell<i32>,
    /// MIDI input buffer (reused each process call to avoid stack overflow)
    midi_input: UnsafeCell<MidiBuffer>,
    /// MIDI output buffer (reused each process call)
    midi_output: UnsafeCell<MidiBuffer>,
    /// SysEx output buffer pool (for VST3 DataEvent pointer stability)
    sysex_output_pool: UnsafeCell<SysExOutputPool>,
    /// Conversion buffers for f64→f32 processing
    conversion_buffers: UnsafeCell<ConversionBuffers>,
    /// Pre-allocated channel pointer storage for f32 processing
    buffer_storage_f32: UnsafeCell<ProcessBufferStorage<f32>>,
    /// Pre-allocated channel pointer storage for f64 processing
    buffer_storage_f64: UnsafeCell<ProcessBufferStorage<f64>>,
    /// MIDI CC state (created from Plugin's midi_cc_config())
    /// Framework owns this - plugin authors don't touch it
    midi_cc_state: Option<MidiCcState>,
    /// Current factory preset index (0-based, or -1 for no preset / custom state)
    /// Used for the program change parameter exposed to the host
    current_preset_index: UnsafeCell<i32>,
    /// Component handler for notifying host of parameter changes
    /// Stored as raw pointer - host manages lifetime, we just AddRef/Release
    component_handler: UnsafeCell<*mut IComponentHandler>,
    /// Marker for the plugin type and preset collection
    _marker: PhantomData<(P, Presets)>,
}

// Safety: Vst3Processor is Send because:
// - Descriptor: Send is required by the Descriptor trait
// - Processor: Send is required by the Processor trait
// - UnsafeCell contents are only accessed from VST3's guaranteed single-threaded contexts
unsafe impl<P: Descriptor, Presets> Send for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
}

// Safety: Vst3Processor is Sync because:
// - VST3 guarantees process() is called from one thread at a time
// - Parameter access through Parameters trait requires Sync
unsafe impl<P: Descriptor, Presets> Sync for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
}

impl<P: Descriptor + 'static, Presets> Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    /// Create a new VST3 processor wrapping the given plugin configuration.
    ///
    /// The wrapper starts in the Unprepared state with a default plugin instance.
    /// The processor will be created when `setupProcessing()` is called.
    pub fn new(_config: &'static Config, vst3_config: &'static Vst3Config) -> Self {
        let plugin = P::default();

        // Create MidiCcState from plugin's config (framework-managed)
        let midi_cc_state = plugin.midi_cc_config().map(|cfg| MidiCcState::from_config(&cfg));

        Self {
            state: UnsafeCell::new(PluginState::Unprepared {
                plugin,
                pending_state: None,
            }),
            vst3_config,
            sample_rate: UnsafeCell::new(44100.0),
            max_block_size: UnsafeCell::new(1024),
            symbolic_sample_size: UnsafeCell::new(SymbolicSampleSizes_::kSample32 as i32),
            midi_input: UnsafeCell::new(MidiBuffer::new()),
            midi_output: UnsafeCell::new(MidiBuffer::new()),
            sysex_output_pool: UnsafeCell::new(SysExOutputPool::with_capacity(
                vst3_config.sysex_slots,
                vst3_config.sysex_buffer_size,
            )),
            conversion_buffers: UnsafeCell::new(ConversionBuffers::new()),
            buffer_storage_f32: UnsafeCell::new(ProcessBufferStorage::new()),
            buffer_storage_f64: UnsafeCell::new(ProcessBufferStorage::new()),
            midi_cc_state,
            current_preset_index: UnsafeCell::new(0), // Default to first preset
            component_handler: UnsafeCell::new(std::ptr::null_mut()),
            _marker: PhantomData,
        }
    }

    /// Get a reference to the prepared processor.
    ///
    /// # Safety
    /// - Must only be called when no mutable reference exists.
    /// - Must only be called when in Prepared state.
    ///
    /// # Panics
    /// Panics if called when in Unprepared state (VST3 host violation).
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    unsafe fn processor(&self) -> &P::Processor {
        match &*self.state.get() {
            PluginState::Prepared { processor, .. } => processor,
            PluginState::Unprepared { .. } => {
                panic!("Attempted to access processor before setupProcessing()")
            }
        }
    }

    /// Get a mutable reference to the prepared processor.
    ///
    /// # Safety
    /// - Must only be called from contexts where VST3 guarantees single-threaded access
    ///   (e.g., process(), setupProcessing()).
    /// - Must only be called when in Prepared state.
    ///
    /// # Panics
    /// Panics if called when in Unprepared state (VST3 host violation).
    #[inline]
    #[allow(clippy::mut_from_ref)]
    unsafe fn processor_mut(&self) -> &mut P::Processor {
        match &mut *self.state.get() {
            PluginState::Prepared { processor, .. } => processor,
            PluginState::Unprepared { .. } => {
                panic!("Attempted to access processor before setupProcessing()")
            }
        }
    }

    /// Get a reference to the unprepared plugin.
    ///
    /// # Safety
    /// Must only be called when no mutable reference exists.
    ///
    /// # Panics
    /// Panics if called when in Prepared state.
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    unsafe fn unprepared_plugin(&self) -> &P {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin,
            PluginState::Prepared { .. } => {
                panic!("Attempted to access unprepared plugin after setupProcessing()")
            }
        }
    }

    /// Get a mutable reference to the unprepared plugin.
    ///
    /// # Safety
    /// Must only be called from contexts where VST3 guarantees single-threaded access.
    ///
    /// # Panics
    /// Panics if called when in Prepared state.
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    #[allow(clippy::mut_from_ref)]
    unsafe fn unprepared_plugin_mut(&self) -> &mut P {
        match &mut *self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin,
            PluginState::Prepared { .. } => {
                panic!("Attempted to access unprepared plugin after setupProcessing()")
            }
        }
    }

    /// Check if the wrapper is in prepared state.
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    unsafe fn is_prepared(&self) -> bool {
        matches!(&*self.state.get(), PluginState::Prepared { .. })
    }

    /// Try to get a reference to the unprepared plugin.
    ///
    /// Returns Some(&P) when in unprepared state, None when prepared.
    /// Use this for Plugin methods that might be called in either state.
    #[inline]
    unsafe fn try_plugin(&self) -> Option<&P> {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => Some(plugin),
            PluginState::Prepared { .. } => None,
        }
    }

    /// Try to get a mutable reference to the unprepared plugin.
    ///
    /// Returns Some(&mut P) when in unprepared state, None when prepared.
    #[inline]
    #[allow(clippy::mut_from_ref)]
    unsafe fn try_plugin_mut(&self) -> Option<&mut P> {
        match &mut *self.state.get() {
            PluginState::Unprepared { plugin, .. } => Some(plugin),
            PluginState::Prepared { .. } => None,
        }
    }

    // =========================================================================
    // Bus Info Access (works in both states)
    // =========================================================================

    /// Get input bus count (works in both states).
    #[inline]
    unsafe fn input_bus_count(&self) -> usize {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.input_bus_count(),
            PluginState::Prepared { input_buses, .. } => input_buses.len(),
        }
    }

    /// Get output bus count (works in both states).
    #[inline]
    unsafe fn output_bus_count(&self) -> usize {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.output_bus_count(),
            PluginState::Prepared { output_buses, .. } => output_buses.len(),
        }
    }

    /// Get input bus info (works in both states).
    /// Returns beamer_core::BusInfo (not vst3::BusInfo).
    #[inline]
    unsafe fn core_input_bus_info(&self, index: usize) -> Option<CoreBusInfo> {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.input_bus_info(index),
            PluginState::Prepared { input_buses, .. } => input_buses.get(index).cloned(),
        }
    }

    /// Get output bus info (works in both states).
    /// Returns beamer_core::BusInfo (not vst3::BusInfo).
    #[inline]
    unsafe fn core_output_bus_info(&self, index: usize) -> Option<CoreBusInfo> {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.output_bus_info(index),
            PluginState::Prepared { output_buses, .. } => output_buses.get(index).cloned(),
        }
    }

    // =========================================================================
    // Parameter Access (works in both states)
    // =========================================================================

    /// Get parameters (works in both states).
    ///
    /// # Safety
    /// Must only be called when no mutable reference exists.
    #[inline]
    unsafe fn parameters(&self) -> &P::Parameters {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.parameters(),
            PluginState::Prepared { processor, .. } => {
                // SAFETY: Trait bounds guarantee P::Processor::Parameters == P::Parameters.
                // Pointer cast through *const _ lets compiler verify type equality.
                &*(processor.parameters() as *const _)
            }
        }
    }

    /// Get mutable parameters (works in both states).
    ///
    /// # Safety
    /// Must only be called from contexts where VST3 guarantees single-threaded access.
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    #[allow(clippy::mut_from_ref)]
    unsafe fn parameters_mut(&self) -> &mut P::Parameters {
        match &mut *self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.parameters_mut(),
            PluginState::Prepared { processor, .. } => {
                // SAFETY: Trait bounds guarantee P::Processor::Parameters == P::Parameters.
                // Pointer cast through *mut _ lets compiler verify type equality.
                &mut *(processor.parameters_mut() as *mut _)
            }
        }
    }

    // =========================================================================
    // Processor Method Access (works in both states)
    // =========================================================================

    /// Check if plugin wants MIDI (works in both states).
    ///
    /// Queries both Descriptor (unprepared) and Processor (prepared) for MIDI support.
    #[inline]
    unsafe fn wants_midi(&self) -> bool {
        match &*self.state.get() {
            PluginState::Unprepared { plugin, .. } => plugin.wants_midi(),
            PluginState::Prepared { processor, .. } => processor.wants_midi(),
        }
    }

    /// Get latency samples (works in both states).
    ///
    /// Returns 0 when unprepared (conservative default), processor's value when prepared.
    #[inline]
    unsafe fn latency_samples(&self) -> u32 {
        match &*self.state.get() {
            PluginState::Unprepared { .. } => 0,
            PluginState::Prepared { processor, .. } => processor.latency_samples(),
        }
    }

    /// Get tail samples (works in both states).
    ///
    /// Returns 0 when unprepared (conservative default), processor's value when prepared.
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    unsafe fn tail_samples(&self) -> u32 {
        match &*self.state.get() {
            PluginState::Unprepared { .. } => 0,
            PluginState::Prepared { processor, .. } => processor.tail_samples(),
        }
    }

    /// Check if processor supports double precision (works in both states).
    ///
    /// Returns false when unprepared (conservative default), processor's value when prepared.
    #[inline]
    #[allow(dead_code)] // API method for potential future use
    unsafe fn supports_double_precision(&self) -> bool {
        match &*self.state.get() {
            PluginState::Unprepared { .. } => false,
            PluginState::Prepared { processor, .. } => processor.supports_double_precision(),
        }
    }

    // =========================================================================
    // Audio Processing Helpers
    // =========================================================================
    //
    // NOTE: process_audio_f32() and process_audio_f64_native() have similar
    // structure but cannot be deduplicated because:
    //
    // 1. VST3's ProcessData uses a C union: channelBuffers32 and channelBuffers64
    //    are separate pointer fields, not generic over sample type
    //
    // 2. Rust's type system can't easily abstract over C FFI union field access
    //    (ProcessData.__field0.channelBuffers32 vs .channelBuffers64)
    //
    // 3. A macro or trait-based abstraction would add complexity for just two
    //    concrete implementations; explicit code is clearer for maintainability
    //
    // If adding a third sample type (e.g., i32 for fixed-point), consider
    // refactoring to a macro-based approach.
    //
    // TODO: Null buffer handling - Currently we skip null channel pointers.
    // This is correct for VST3's parameter flushing (numSamples=0). Some hosts
    // may send null buffers with non-zero numSamples. Consider adding internal
    // buffer fallback like beamer-au does for instruments if this becomes an
    // issue. For now, VST3 hosts are generally compliant.
    // =========================================================================

    /// Process audio at 32-bit (f32) precision.
    ///
    /// This is the standard processing path used when the host uses kSample32.
    /// Uses pre-allocated ProcessBufferStorage - no heap allocations.
    #[inline]
    unsafe fn process_audio_f32(
        &self,
        process_data: &ProcessData,
        num_samples: usize,
        processor: &mut P::Processor,
        context: &CoreProcessContext,
    ) {
        // Get pre-allocated storage and clear for reuse (O(1), no deallocation)
        let storage = &mut *self.buffer_storage_f32.get();
        storage.clear();

        // Collect main input channel pointers (bounded by pre-allocated capacity)
        if process_data.numInputs > 0 && !process_data.inputs.is_null() {
            let bus = &*process_data.inputs;
            let num_channels = bus.numChannels as usize;
            let max_channels = storage.main_inputs.capacity();
            if num_channels > 0 && !bus.__field0.channelBuffers32.is_null() {
                let channel_ptrs =
                    slice::from_raw_parts(bus.__field0.channelBuffers32, num_channels);
                for &ptr in channel_ptrs.iter().take(max_channels) {
                    if !ptr.is_null() {
                        storage.main_inputs.push(ptr);
                    }
                }
            }
        }

        // Collect main output channel pointers (bounded by pre-allocated capacity)
        if process_data.numOutputs > 0 && !process_data.outputs.is_null() {
            let bus = &*process_data.outputs;
            let num_channels = bus.numChannels as usize;
            let max_channels = storage.main_outputs.capacity();
            if num_channels > 0 && !bus.__field0.channelBuffers32.is_null() {
                let channel_ptrs =
                    slice::from_raw_parts(bus.__field0.channelBuffers32, num_channels);
                for &ptr in channel_ptrs.iter().take(max_channels) {
                    if !ptr.is_null() {
                        storage.main_outputs.push(ptr);
                    }
                }
            }
        }

        // Collect auxiliary input channel pointers (bounded by pre-allocated capacity)
        if process_data.numInputs > 1 && !process_data.inputs.is_null() {
            let input_buses =
                slice::from_raw_parts(process_data.inputs, process_data.numInputs as usize);
            for (aux_idx, bus) in input_buses[1..].iter().enumerate() {
                if aux_idx < storage.aux_inputs.len() {
                    let num_channels = bus.numChannels as usize;
                    let max_channels = storage.aux_inputs[aux_idx].capacity();
                    if num_channels > 0 && !bus.__field0.channelBuffers32.is_null() {
                        let channel_ptrs =
                            slice::from_raw_parts(bus.__field0.channelBuffers32, num_channels);
                        for &ptr in channel_ptrs.iter().take(max_channels) {
                            if !ptr.is_null() {
                                storage.aux_inputs[aux_idx].push(ptr);
                            }
                        }
                    }
                }
            }
        }

        // Collect auxiliary output channel pointers (bounded by pre-allocated capacity)
        if process_data.numOutputs > 1 && !process_data.outputs.is_null() {
            let output_buses =
                slice::from_raw_parts(process_data.outputs, process_data.numOutputs as usize);
            for (aux_idx, bus) in output_buses[1..].iter().enumerate() {
                if aux_idx < storage.aux_outputs.len() {
                    let num_channels = bus.numChannels as usize;
                    let max_channels = storage.aux_outputs[aux_idx].capacity();
                    if num_channels > 0 && !bus.__field0.channelBuffers32.is_null() {
                        let channel_ptrs =
                            slice::from_raw_parts(bus.__field0.channelBuffers32, num_channels);
                        for &ptr in channel_ptrs.iter().take(max_channels) {
                            if !ptr.is_null() {
                                storage.aux_outputs[aux_idx].push(ptr);
                            }
                        }
                    }
                }
            }
        }

        // Create slices from pointers (safe: ProcessData lifetime covers this scope)
        let main_in_iter = storage
            .main_inputs
            .iter()
            .map(|&ptr| slice::from_raw_parts(ptr, num_samples));
        let main_out_iter = storage
            .main_outputs
            .iter()
            .map(|&ptr| slice::from_raw_parts_mut(ptr, num_samples));

        let aux_in_iter = storage.aux_inputs.iter().map(|bus| {
            bus.iter()
                .map(|&ptr| slice::from_raw_parts(ptr, num_samples))
        });
        let aux_out_iter = storage.aux_outputs.iter().map(|bus| {
            bus.iter()
                .map(|&ptr| slice::from_raw_parts_mut(ptr, num_samples))
        });

        // Construct buffers and process
        let mut buffer = Buffer::new(main_in_iter, main_out_iter, num_samples);
        let mut aux = AuxiliaryBuffers::new(aux_in_iter, aux_out_iter, num_samples);

        processor.process(&mut buffer, &mut aux, context);
    }

    /// Process audio at 64-bit (f64) precision with native plugin support.
    ///
    /// Used when host uses kSample64 and processor.supports_double_precision() is true.
    /// Uses pre-allocated ProcessBufferStorage - no heap allocations.
    #[inline]
    unsafe fn process_audio_f64_native(
        &self,
        process_data: &ProcessData,
        num_samples: usize,
        processor: &mut P::Processor,
        context: &CoreProcessContext,
    ) {
        // Get pre-allocated storage and clear for reuse (O(1), no deallocation)
        let storage = &mut *self.buffer_storage_f64.get();
        storage.clear();

        // Collect main input channel pointers (bounded by pre-allocated capacity)
        if process_data.numInputs > 0 && !process_data.inputs.is_null() {
            let bus = &*process_data.inputs;
            let num_channels = bus.numChannels as usize;
            let max_channels = storage.main_inputs.capacity();
            if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                let channel_ptrs =
                    slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                for &ptr in channel_ptrs.iter().take(max_channels) {
                    if !ptr.is_null() {
                        storage.main_inputs.push(ptr);
                    }
                }
            }
        }

        // Collect main output channel pointers (bounded by pre-allocated capacity)
        if process_data.numOutputs > 0 && !process_data.outputs.is_null() {
            let bus = &*process_data.outputs;
            let num_channels = bus.numChannels as usize;
            let max_channels = storage.main_outputs.capacity();
            if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                let channel_ptrs =
                    slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                for &ptr in channel_ptrs.iter().take(max_channels) {
                    if !ptr.is_null() {
                        storage.main_outputs.push(ptr);
                    }
                }
            }
        }

        // Collect auxiliary input channel pointers (bounded by pre-allocated capacity)
        if process_data.numInputs > 1 && !process_data.inputs.is_null() {
            let input_buses =
                slice::from_raw_parts(process_data.inputs, process_data.numInputs as usize);
            for (aux_idx, bus) in input_buses[1..].iter().enumerate() {
                if aux_idx < storage.aux_inputs.len() {
                    let num_channels = bus.numChannels as usize;
                    let max_channels = storage.aux_inputs[aux_idx].capacity();
                    if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                        let channel_ptrs =
                            slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                        for &ptr in channel_ptrs.iter().take(max_channels) {
                            if !ptr.is_null() {
                                storage.aux_inputs[aux_idx].push(ptr);
                            }
                        }
                    }
                }
            }
        }

        // Collect auxiliary output channel pointers (bounded by pre-allocated capacity)
        if process_data.numOutputs > 1 && !process_data.outputs.is_null() {
            let output_buses =
                slice::from_raw_parts(process_data.outputs, process_data.numOutputs as usize);
            for (aux_idx, bus) in output_buses[1..].iter().enumerate() {
                if aux_idx < storage.aux_outputs.len() {
                    let num_channels = bus.numChannels as usize;
                    let max_channels = storage.aux_outputs[aux_idx].capacity();
                    if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                        let channel_ptrs =
                            slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                        for &ptr in channel_ptrs.iter().take(max_channels) {
                            if !ptr.is_null() {
                                storage.aux_outputs[aux_idx].push(ptr);
                            }
                        }
                    }
                }
            }
        }

        // Create slices from pointers (safe: ProcessData lifetime covers this scope)
        let main_in_iter = storage
            .main_inputs
            .iter()
            .map(|&ptr| slice::from_raw_parts(ptr, num_samples));
        let main_out_iter = storage
            .main_outputs
            .iter()
            .map(|&ptr| slice::from_raw_parts_mut(ptr, num_samples));

        let aux_in_iter = storage.aux_inputs.iter().map(|bus| {
            bus.iter()
                .map(|&ptr| slice::from_raw_parts(ptr, num_samples))
        });
        let aux_out_iter = storage.aux_outputs.iter().map(|bus| {
            bus.iter()
                .map(|&ptr| slice::from_raw_parts_mut(ptr, num_samples))
        });

        // Construct buffers and process
        let mut buffer: Buffer<f64> = Buffer::new(main_in_iter, main_out_iter, num_samples);
        let mut aux: AuxiliaryBuffers<f64> =
            AuxiliaryBuffers::new(aux_in_iter, aux_out_iter, num_samples);

        processor.process_f64(&mut buffer, &mut aux, context);
    }

    /// Process audio at 64-bit (f64) with conversion to/from f32.
    ///
    /// Used when host uses kSample64 but processor.supports_double_precision() is false.
    /// Converts f64→f32, calls process(), converts f32→f64.
    #[inline]
    unsafe fn process_audio_f64_converted(
        &self,
        process_data: &ProcessData,
        num_samples: usize,
        processor: &mut P::Processor,
        context: &CoreProcessContext,
    ) {
        let conv = &mut *self.conversion_buffers.get();

        // Convert main input f64 → f32
        if process_data.numInputs > 0 && !process_data.inputs.is_null() {
            let input_buses = slice::from_raw_parts(process_data.inputs, 1);
            let bus = &input_buses[0];
            let num_channels = (bus.numChannels as usize).min(conv.main_input_f32.len());
            if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                let channel_ptrs = slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                for (ch, &ptr) in channel_ptrs.iter().enumerate() {
                    if !ptr.is_null() && ch < conv.main_input_f32.len() {
                        let src = slice::from_raw_parts(ptr, num_samples);
                        for (i, &s) in src.iter().enumerate() {
                            conv.main_input_f32[ch][i] = s as f32;
                        }
                    }
                }
            }
        }

        // Convert aux input f64 → f32
        for (bus_idx, aux_bus) in conv.aux_input_f32.iter_mut().enumerate() {
            let vst_bus_idx = bus_idx + 1; // aux buses start at index 1
            if process_data.numInputs as usize > vst_bus_idx && !process_data.inputs.is_null() {
                let input_buses = slice::from_raw_parts(
                    process_data.inputs,
                    process_data.numInputs as usize,
                );
                let bus = &input_buses[vst_bus_idx];
                let num_channels = (bus.numChannels as usize).min(aux_bus.len());
                if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                    let channel_ptrs = slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                    for (ch, &ptr) in channel_ptrs.iter().enumerate() {
                        if !ptr.is_null() && ch < aux_bus.len() {
                            let src = slice::from_raw_parts(ptr, num_samples);
                            for (i, &s) in src.iter().enumerate() {
                                aux_bus[ch][i] = s as f32;
                            }
                        }
                    }
                }
            }
        }

        // Build f32 buffer slices using iterators (no allocation)
        let main_input_iter = conv.main_input_f32
            .iter()
            .map(|v| &v[..num_samples]);
        let main_output_iter = conv.main_output_f32
            .iter_mut()
            .map(|v| &mut v[..num_samples]);

        let aux_input_iter = conv.aux_input_f32
            .iter()
            .map(|bus| bus.iter().map(|v| &v[..num_samples]));
        let aux_output_iter = conv.aux_output_f32
            .iter_mut()
            .map(|bus| bus.iter_mut().map(|v| &mut v[..num_samples]));

        // Construct f32 buffers and process
        let mut buffer = Buffer::new(main_input_iter, main_output_iter, num_samples);
        let mut aux = AuxiliaryBuffers::new(aux_input_iter, aux_output_iter, num_samples);

        processor.process(&mut buffer, &mut aux, context);

        // Convert main output f32 → f64
        if process_data.numOutputs > 0 && !process_data.outputs.is_null() {
            let output_buses = slice::from_raw_parts(process_data.outputs, 1);
            let bus = &output_buses[0];
            let num_channels = (bus.numChannels as usize).min(conv.main_output_f32.len());
            if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                let channel_ptrs = slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                for (ch, &ptr) in channel_ptrs.iter().enumerate() {
                    if !ptr.is_null() && ch < conv.main_output_f32.len() {
                        let dst = slice::from_raw_parts_mut(ptr, num_samples);
                        for (i, sample) in conv.main_output_f32[ch][..num_samples].iter().enumerate() {
                            dst[i] = *sample as f64;
                        }
                    }
                }
            }
        }

        // Convert aux output f32 → f64
        for (bus_idx, aux_bus) in conv.aux_output_f32.iter().enumerate() {
            let vst_bus_idx = bus_idx + 1;
            if process_data.numOutputs as usize > vst_bus_idx && !process_data.outputs.is_null() {
                let output_buses = slice::from_raw_parts(
                    process_data.outputs,
                    process_data.numOutputs as usize,
                );
                let bus = &output_buses[vst_bus_idx];
                let num_channels = (bus.numChannels as usize).min(aux_bus.len());
                if num_channels > 0 && !bus.__field0.channelBuffers64.is_null() {
                    let channel_ptrs = slice::from_raw_parts(bus.__field0.channelBuffers64, num_channels);
                    for (ch, &ptr) in channel_ptrs.iter().enumerate() {
                        if !ptr.is_null() && ch < aux_bus.len() {
                            let dst = slice::from_raw_parts_mut(ptr, num_samples);
                            for (i, sample) in aux_bus[ch][..num_samples].iter().enumerate() {
                                dst[i] = *sample as f64;
                            }
                        }
                    }
                }
            }
        }
    }
}

impl<P: Descriptor + 'static, Presets> ComponentFactory for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    fn create(config: &'static Config, vst3_config: &'static Vst3Config) -> Self {
        Self::new(config, vst3_config)
    }
}

impl<P: Descriptor + 'static, Presets> Class for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    type Interfaces = (
        IComponent,
        IAudioProcessor,
        IProcessContextRequirements,
        IEditController,
        IUnitInfo,
        IMidiMapping,
        IMidiLearn,
        IMidiMapping2,
        IMidiLearn2,
        INoteExpressionController,
        IKeyswitchController,
        INoteExpressionPhysicalUIMapping,
        IVst3WrapperMPESupport,
    );
}

// =============================================================================
// IPluginBase implementation
// =============================================================================

impl<P: Descriptor + 'static, Presets> IPluginBaseTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn initialize(&self, _context: *mut FUnknown) -> tresult {
        kResultOk
    }

    unsafe fn terminate(&self) -> tresult {
        kResultOk
    }
}

// =============================================================================
// IComponent implementation
// =============================================================================

impl<P: Descriptor + 'static, Presets> IComponentTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getControllerClassId(&self, class_id: *mut TUID) -> tresult {
        if class_id.is_null() {
            return kInvalidArgument;
        }

        // For combined component, return the controller UID if set, otherwise kNotImplemented
        if let Some(controller) = self.vst3_config.controller_uid {
            *class_id = controller;
            kResultOk
        } else {
            kNotImplemented
        }
    }

    unsafe fn setIoMode(&self, _mode: IoMode) -> tresult {
        kResultOk
    }

    unsafe fn getBusCount(&self, media_type: MediaType, dir: BusDirection) -> i32 {
        match media_type as MediaTypes {
            MediaTypes_::kAudio => match dir as BusDirections {
                BusDirections_::kInput => self.input_bus_count() as i32,
                BusDirections_::kOutput => self.output_bus_count() as i32,
                _ => 0,
            },
            MediaTypes_::kEvent => {
                // Return 1 event bus in each direction if plugin wants MIDI
                if self.wants_midi() {
                    1
                } else {
                    0
                }
            }
            _ => 0,
        }
    }

    unsafe fn getBusInfo(
        &self,
        media_type: MediaType,
        dir: BusDirection,
        index: i32,
        bus: *mut BusInfo,
    ) -> tresult {
        if bus.is_null() {
            return kInvalidArgument;
        }

        match media_type as MediaTypes {
            MediaTypes_::kAudio => {
                let info = match dir as BusDirections {
                    BusDirections_::kInput => self.core_input_bus_info(index as usize),
                    BusDirections_::kOutput => self.core_output_bus_info(index as usize),
                    _ => None,
                };

                if let Some(info) = info {
                    let bus = &mut *bus;
                    bus.mediaType = MediaTypes_::kAudio as MediaType;
                    bus.direction = dir;
                    bus.channelCount = info.channel_count as i32;
                    copy_wstring(info.name, &mut bus.name);
                    bus.busType = match info.bus_type {
                        CoreBusType::Main => BusTypes_::kMain,
                        CoreBusType::Aux => BusTypes_::kAux,
                    } as BusType;
                    bus.flags = if info.is_default_active {
                        BusInfo_::BusFlags_::kDefaultActive
                    } else {
                        0
                    };
                    kResultOk
                } else {
                    kInvalidArgument
                }
            }
            MediaTypes_::kEvent => {
                // Only index 0 for event bus, and only if plugin wants MIDI
                if index != 0 || !self.wants_midi() {
                    return kInvalidArgument;
                }

                let bus = &mut *bus;
                bus.mediaType = MediaTypes_::kEvent as MediaType;
                bus.direction = dir;
                bus.channelCount = 1; // Single event channel
                let name = match dir as BusDirections {
                    BusDirections_::kInput => "MIDI In",
                    BusDirections_::kOutput => "MIDI Out",
                    _ => "MIDI",
                };
                copy_wstring(name, &mut bus.name);
                bus.busType = BusTypes_::kMain as BusType;
                bus.flags = BusInfo_::BusFlags_::kDefaultActive;
                kResultOk
            }
            _ => kInvalidArgument,
        }
    }

    unsafe fn getRoutingInfo(
        &self,
        _in_info: *mut RoutingInfo,
        _out_info: *mut RoutingInfo,
    ) -> tresult {
        kNotImplemented
    }

    unsafe fn activateBus(
        &self,
        _media_type: MediaType,
        _dir: BusDirection,
        _index: i32,
        _state: TBool,
    ) -> tresult {
        kResultOk
    }

    unsafe fn setActive(&self, state: TBool) -> tresult {
        // set_active is only meaningful when prepared (processor exists)
        if let PluginState::Prepared { processor, .. } = &mut *self.state.get() {
            processor.set_active(state != 0);
        }
        // When unprepared, silently succeed (host may call this before setupProcessing)
        kResultOk
    }

    unsafe fn setState(&self, state: *mut IBStream) -> tresult {
        if state.is_null() {
            return kInvalidArgument;
        }

        let stream = match ComRef::from_raw(state) {
            Some(s) => s,
            None => return kInvalidArgument,
        };

        // Read all bytes from stream
        let mut buffer = Vec::new();
        let mut chunk = [0u8; 4096];
        loop {
            let mut bytes_read: i32 = 0;
            let result = stream.read(
                chunk.as_mut_ptr() as *mut c_void,
                chunk.len() as i32,
                &mut bytes_read,
            );

            if result != kResultOk || bytes_read <= 0 {
                break;
            }

            buffer.extend_from_slice(&chunk[..bytes_read as usize]);
        }

        if buffer.is_empty() {
            return kResultOk;
        }

        // Load state based on current state
        match &mut *self.state.get() {
            PluginState::Unprepared { pending_state, .. } => {
                // Store for deferred loading when prepare() is called
                *pending_state = Some(buffer);
                kResultOk
            }
            PluginState::Prepared { processor, .. } => {
                match processor.load_state(&buffer) {
                    Ok(()) => {
                        // Apply current sample rate and reset smoothers
                        use beamer_core::parameter_types::Parameters;
                        let sample_rate = *self.sample_rate.get();
                        if sample_rate > 0.0 {
                            processor.parameters_mut().set_sample_rate(sample_rate);
                        }
                        processor.parameters_mut().reset_smoothing();
                        kResultOk
                    }
                    Err(_) => kResultFalse,
                }
            }
        }
    }

    unsafe fn getState(&self, state: *mut IBStream) -> tresult {
        if state.is_null() {
            return kInvalidArgument;
        }

        // Get state from processor (only available when prepared)
        let data: Vec<u8> = match &*self.state.get() {
            PluginState::Unprepared { .. } => {
                // When unprepared, we can't save processor state
                // Return empty success (some hosts call this before prepare)
                return kResultOk;
            }
            PluginState::Prepared { processor, .. } => {
                match processor.save_state() {
                    Ok(d) => d,
                    Err(_) => return kResultFalse,
                }
            }
        };

        if data.is_empty() {
            return kResultOk;
        }

        // Write to IBStream
        let stream = match ComRef::from_raw(state) {
            Some(s) => s,
            None => return kInvalidArgument,
        };
        let mut bytes_written: i32 = 0;
        let result = stream.write(
            data.as_ptr() as *mut c_void,
            data.len() as i32,
            &mut bytes_written,
        );

        if result == kResultOk && bytes_written == data.len() as i32 {
            kResultOk
        } else {
            kResultFalse
        }
    }
}

// =============================================================================
// IAudioProcessor implementation
// =============================================================================

impl<P: Descriptor + 'static, Presets> IAudioProcessorTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn setBusArrangements(
        &self,
        inputs: *mut SpeakerArrangement,
        num_ins: i32,
        outputs: *mut SpeakerArrangement,
        num_outs: i32,
    ) -> tresult {
        // Early rejection: negative counts or bus count exceeds compile-time limits
        if num_ins < 0
            || num_outs < 0
            || num_ins as usize > MAX_BUSES
            || num_outs as usize > MAX_BUSES
        {
            return kResultFalse;
        }

        // Early rejection: null pointers with non-zero counts
        if (num_ins > 0 && inputs.is_null()) || (num_outs > 0 && outputs.is_null()) {
            return kInvalidArgument;
        }

        // Check if the requested arrangement matches our bus configuration
        if num_ins as usize != self.input_bus_count()
            || num_outs as usize != self.output_bus_count()
        {
            return kResultFalse;
        }

        // Validate each input bus
        for i in 0..num_ins as usize {
            // Early rejection: channel count exceeds compile-time limits
            let requested = *inputs.add(i);
            if validate_speaker_arrangement(requested).is_err() {
                return kResultFalse;
            }

            if let Some(info) = self.core_input_bus_info(i) {
                let expected = channel_count_to_speaker_arrangement(info.channel_count);
                if requested != expected {
                    return kResultFalse;
                }
            }
        }

        // Validate each output bus
        for i in 0..num_outs as usize {
            // Early rejection: channel count exceeds compile-time limits
            let requested = *outputs.add(i);
            if validate_speaker_arrangement(requested).is_err() {
                return kResultFalse;
            }

            if let Some(info) = self.core_output_bus_info(i) {
                let expected = channel_count_to_speaker_arrangement(info.channel_count);
                if requested != expected {
                    return kResultFalse;
                }
            }
        }

        kResultTrue
    }

    unsafe fn getBusArrangement(
        &self,
        dir: BusDirection,
        index: i32,
        arr: *mut SpeakerArrangement,
    ) -> tresult {
        if arr.is_null() {
            return kInvalidArgument;
        }

        let info = match dir as BusDirections {
            BusDirections_::kInput => self.core_input_bus_info(index as usize),
            BusDirections_::kOutput => self.core_output_bus_info(index as usize),
            _ => None,
        };

        if let Some(info) = info {
            *arr = channel_count_to_speaker_arrangement(info.channel_count);
            kResultOk
        } else {
            kInvalidArgument
        }
    }

    unsafe fn canProcessSampleSize(&self, symbolic_sample_size: i32) -> tresult {
        match symbolic_sample_size as SymbolicSampleSizes {
            SymbolicSampleSizes_::kSample32 => kResultOk,
            SymbolicSampleSizes_::kSample64 => kResultOk, // Support 64-bit via native or conversion
            _ => kNotImplemented,
        }
    }

    unsafe fn getLatencySamples(&self) -> u32 {
        self.latency_samples()
    }

    unsafe fn setupProcessing(&self, setup: *mut ProcessSetup) -> tresult {
        if setup.is_null() {
            return kInvalidArgument;
        }

        let setup = &*setup;

        // Store setup parameters
        *self.sample_rate.get() = setup.sampleRate;
        *self.max_block_size.get() = setup.maxSamplesPerBlock as usize;
        *self.symbolic_sample_size.get() = setup.symbolicSampleSize;

        // Handle state transition
        let state = &mut *self.state.get();
        match state {
            PluginState::Unprepared { plugin, pending_state } => {
                // Cache bus info before consuming the plugin
                let input_bus_count = plugin.input_bus_count();
                let output_bus_count = plugin.output_bus_count();
                let input_buses: Vec<CoreBusInfo> = (0..input_bus_count)
                    .filter_map(|i| plugin.input_bus_info(i))
                    .collect();
                let output_buses: Vec<CoreBusInfo> = (0..output_bus_count)
                    .filter_map(|i| plugin.output_bus_info(i))
                    .collect();

                let bus_layout = BusLayout::from_plugin(plugin);

                // Validate plugin's bus configuration against compile-time limits
                if let Err(msg) = CachedBusConfig::from_plugin(plugin).validate() {
                    log::error!("Plugin bus configuration exceeds limits: {}", msg);
                    return kResultFalse;
                }

                // Build the plugin setup
                let plugin_setup = build_setup::<P::Setup>(setup, &bus_layout);

                // Take ownership of the plugin and any pending state
                let plugin = std::mem::take(plugin);
                let pending = pending_state.take();

                // Prepare the processor
                let mut processor = plugin.prepare(plugin_setup);

                // Apply any pending state that was set before preparation
                if let Some(data) = pending {
                    let _ = processor.load_state(&data);
                    // Update parameters sample rate after loading
                    use beamer_core::Parameters;
                    processor.parameters_mut().set_sample_rate(setup.sampleRate);
                }

                // Pre-allocate buffer storage based on bus config
                let bus_config = CachedBusConfig::new(
                    input_buses.iter().map(CachedBusInfo::from_bus_info).collect(),
                    output_buses.iter().map(CachedBusInfo::from_bus_info).collect(),
                );
                let max_frames = setup.maxSamplesPerBlock as usize;
                *self.buffer_storage_f32.get() =
                    ProcessBufferStorage::allocate_from_config(&bus_config, max_frames);
                *self.buffer_storage_f64.get() =
                    ProcessBufferStorage::allocate_from_config(&bus_config, max_frames);

                // Pre-allocate conversion buffers for f64→f32 processing
                if setup.symbolicSampleSize == SymbolicSampleSizes_::kSample64 as i32
                    && !processor.supports_double_precision()
                {
                    *self.conversion_buffers.get() =
                        ConversionBuffers::allocate_from_buses(&input_buses, &output_buses, setup.maxSamplesPerBlock as usize);
                }

                // Update state to Prepared
                *state = PluginState::Prepared {
                    processor,
                    input_buses,
                    output_buses,
                };
            }
            PluginState::Prepared { processor, input_buses, output_buses } => {
                // Already prepared - check if sample rate changed
                let current_sample_rate = *self.sample_rate.get();
                if (current_sample_rate - setup.sampleRate).abs() > 0.001 {
                    // Sample rate changed - unprepare and re-prepare
                    let bus_layout = BusLayout {
                        main_input_channels: input_buses
                            .first()
                            .map(|b| b.channel_count)
                            .unwrap_or(2),
                        main_output_channels: output_buses
                            .first()
                            .map(|b| b.channel_count)
                            .unwrap_or(2),
                        aux_input_count: input_buses.len().saturating_sub(1),
                        aux_output_count: output_buses.len().saturating_sub(1),
                    };

                    // Take ownership of the processor
                    let old_processor = std::mem::replace(
                        processor,
                        // This placeholder will be overwritten
                        unsafe { std::mem::zeroed() },
                    );

                    // Unprepare to get the plugin back
                    let plugin = old_processor.unprepare();

                    // Build new setup and re-prepare
                    let plugin_setup = build_setup::<P::Setup>(setup, &bus_layout);
                    let new_processor = plugin.prepare(plugin_setup);

                    // Pre-allocate conversion buffers if needed
                    if setup.symbolicSampleSize == SymbolicSampleSizes_::kSample64 as i32
                        && !new_processor.supports_double_precision()
                    {
                        *self.conversion_buffers.get() =
                            ConversionBuffers::allocate_from_buses(input_buses, output_buses, setup.maxSamplesPerBlock as usize);
                    }

                    *processor = new_processor;
                }
                // If sample rate hasn't changed, nothing to do
            }
        }

        kResultOk
    }

    unsafe fn setProcessing(&self, _state: TBool) -> tresult {
        kResultOk
    }

    unsafe fn process(&self, data: *mut ProcessData) -> tresult {
        if data.is_null() {
            return kInvalidArgument;
        }

        let process_data = &*data;
        let num_samples = process_data.numSamples as usize;

        if num_samples == 0 {
            return kResultOk;
        }

        // 1. Handle incoming parameter changes from host
        if let Some(parameter_changes) = ComRef::from_raw(process_data.inputParameterChanges) {
            let parameters = self.parameters();
            let parameter_count = parameter_changes.getParameterCount();

            for i in 0..parameter_count {
                if let Some(queue) = ComRef::from_raw(parameter_changes.getParameterData(i)) {
                    let parameter_id = queue.getParameterId();
                    let point_count = queue.getPointCount();

                    if point_count > 0 {
                        let mut sample_offset = 0;
                        let mut value = 0.0;
                        // Get the last value in the queue (simplest approach)
                        if queue.getPoint(point_count - 1, &mut sample_offset, &mut value)
                            == kResultTrue
                        {
                            parameters.set_normalized(parameter_id, value);
                        }
                    }
                }
            }
        }

        // 2. Handle MIDI events (reuse pre-allocated buffer to avoid stack overflow)
        let midi_input = &mut *self.midi_input.get();
        midi_input.clear();

        if let Some(event_list) = ComRef::from_raw(process_data.inputEvents) {
            let event_count = event_list.getEventCount();

            for i in 0..event_count {
                let mut event: Event = std::mem::zeroed();
                if event_list.getEvent(i, &mut event) == kResultOk {
                    if let Some(midi_event) = convert_vst3_to_midi(&event) {
                        midi_input.push(midi_event);
                    }
                }
            }
        }

        // 2.5. Convert MIDI CC parameter changes to MIDI events
        // This handles the VST3 IMidiMapping flow where DAWs send CC/pitch bend
        // as parameter changes instead of raw MIDI events.
        // Uses framework-owned MidiCcState.
        if let Some(parameter_changes) = ComRef::from_raw(process_data.inputParameterChanges) {
            if let Some(cc_state) = self.midi_cc_state.as_ref() {
                let parameter_count = parameter_changes.getParameterCount();

                for i in 0..parameter_count {
                    if let Some(queue) = ComRef::from_raw(parameter_changes.getParameterData(i)) {
                        let parameter_id = queue.getParameterId();

                        // Check if this is a MIDI CC parameter
                        if let Some(controller) = MidiCcState::parameter_id_to_controller(parameter_id) {
                            if cc_state.has_controller(controller) {
                                let point_count = queue.getPointCount();

                                // Process all points for sample-accurate timing
                                for j in 0..point_count {
                                    let mut sample_offset: i32 = 0;
                                    let mut value: f64 = 0.0;

                                    if queue.getPoint(j, &mut sample_offset, &mut value) == kResultOk {
                                        let midi_event = convert_cc_parameter_to_midi(
                                            controller,
                                            value as f32,
                                            sample_offset as u32,
                                        );
                                        midi_input.push(midi_event);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Check for MIDI input buffer overflow (once per block)
        if midi_input.has_overflowed() {
            warn!(
                "MIDI input buffer overflow: {} events max, some events were dropped",
                beamer_core::midi::MAX_MIDI_EVENTS
            );
        }

        // Clear and prepare MIDI output buffer and SysEx pool
        let midi_output = &mut *self.midi_output.get();
        midi_output.clear();
        let sysex_pool = &mut *self.sysex_output_pool.get();

        // Clear pool FIRST so next_slot is reset to 0 before draining fallback
        sysex_pool.clear();

        // With heap fallback enabled, emit any overflow messages from previous block first.
        // These allocate slots starting from 0; new plugin output will append after them.
        #[cfg(feature = "sysex-heap-fallback")]
        if sysex_pool.has_fallback() {
            if let Some(event_list) = ComRef::from_raw(process_data.outputEvents) {
                for sysex_data in sysex_pool.take_fallback() {
                    // Allocate from pool (succeeds since we just cleared it)
                    if let Some((ptr, len)) = sysex_pool.allocate(&sysex_data) {
                        let mut event: Event = std::mem::zeroed();
                        event.busIndex = 0;
                        event.sampleOffset = 0; // Delayed message, emit at start of block
                        event.ppqPosition = 0.0;
                        event.flags = 0;
                        event.r#type = K_DATA_EVENT;
                        event.__field0.data.r#type = DATA_TYPE_MIDI_SYSEX;
                        event.__field0.data.size = len as u32;
                        event.__field0.data.bytes = ptr;
                        let _ = event_list.addEvent(&mut event);
                    }
                }
            }
            // Log that we recovered from overflow
            warn!(
                "SysEx fallback: emitted delayed messages from previous block overflow"
            );
        }
        // NOTE: Don't clear again - fallback events occupy slots 0..N, new events append after

        // Process MIDI events (process_midi is on Processor)
        let processor = self.processor_mut();
        processor.process_midi(midi_input.as_slice(), midi_output);

        // Write output MIDI events
        if let Some(event_list) = ComRef::from_raw(process_data.outputEvents) {
            for midi_event in midi_output.iter() {
                if let Some(mut vst3_event) = convert_midi_to_vst3(midi_event, sysex_pool) {
                    let _ = event_list.addEvent(&mut vst3_event);
                }
            }
        }

        // Check for MIDI buffer overflow (once per block)
        if midi_output.has_overflowed() {
            warn!(
                "MIDI output buffer overflow: {} events reached capacity, some events were dropped",
                midi_output.len()
            );
        }

        // Check for SysEx pool overflow (once per block)
        if sysex_pool.has_overflowed() {
            warn!(
                "SysEx output pool overflow: {} slots exhausted, some SysEx messages were dropped",
                sysex_pool.capacity()
            );
        }

        // 3. Extract transport info from VST3 ProcessContext
        let transport = extract_transport(process_data.processContext);
        let sample_rate = *self.sample_rate.get();
        let context = if let Some(cc_state) = self.midi_cc_state.as_ref() {
            CoreProcessContext::with_midi_cc(sample_rate, num_samples, transport, cc_state)
        } else {
            CoreProcessContext::new(sample_rate, num_samples, transport)
        };

        // 4. Process audio based on sample size
        let symbolic_sample_size = *self.symbolic_sample_size.get();
        let processor = self.processor_mut();

        if symbolic_sample_size == SymbolicSampleSizes_::kSample64 as i32 {
            // 64-bit processing path
            if processor.supports_double_precision() {
                // Native f64: extract f64 buffers and call process_f64()
                self.process_audio_f64_native(process_data, num_samples, processor, &context);
            } else {
                // Conversion: f64→f32, process, f32→f64
                self.process_audio_f64_converted(process_data, num_samples, processor, &context);
            }
        } else {
            // 32-bit processing path (default)
            self.process_audio_f32(process_data, num_samples, processor, &context);
        }

        kResultOk
    }

    unsafe fn getTailSamples(&self) -> u32 {
        // tail_samples and bypass_ramp_samples are on Processor
        match &*self.state.get() {
            PluginState::Unprepared { .. } => 0,
            PluginState::Prepared { processor, .. } => {
                processor.tail_samples().saturating_add(processor.bypass_ramp_samples())
            }
        }
    }
}

impl<P: Descriptor + 'static, Presets> IProcessContextRequirementsTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getProcessContextRequirements(&self) -> u32 {
        // Request all available transport information from host.
        // These flags tell the host which ProcessContext fields we need.
        // See VST3 SDK: IProcessContextRequirements interface
        const K_NEED_SYSTEM_TIME: u32 = 1 << 0;
        const K_NEED_CONTINUOUS_TIME_SAMPLES: u32 = 1 << 1;
        const K_NEED_PROJECT_TIME_MUSIC: u32 = 1 << 2;
        const K_NEED_BAR_POSITION_MUSIC: u32 = 1 << 3;
        const K_NEED_CYCLE_MUSIC: u32 = 1 << 4;
        const K_NEED_SAMPLES_TO_NEXT_CLOCK: u32 = 1 << 5;
        const K_NEED_TEMPO: u32 = 1 << 6;
        const K_NEED_TIME_SIGNATURE: u32 = 1 << 7;
        const K_NEED_FRAME_RATE: u32 = 1 << 9;
        const K_NEED_TRANSPORT_STATE: u32 = 1 << 10;

        K_NEED_SYSTEM_TIME
            | K_NEED_CONTINUOUS_TIME_SAMPLES
            | K_NEED_PROJECT_TIME_MUSIC
            | K_NEED_BAR_POSITION_MUSIC
            | K_NEED_CYCLE_MUSIC
            | K_NEED_SAMPLES_TO_NEXT_CLOCK
            | K_NEED_TEMPO
            | K_NEED_TIME_SIGNATURE
            | K_NEED_FRAME_RATE
            | K_NEED_TRANSPORT_STATE
    }
}

// =============================================================================
// IEditController implementation
// =============================================================================

impl<P: Descriptor + 'static, Presets> IEditControllerTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn setComponentState(&self, _state: *mut IBStream) -> tresult {
        // For combined component, state is handled by IComponent::setState
        kResultOk
    }

    unsafe fn setState(&self, _state: *mut IBStream) -> tresult {
        kResultOk
    }

    unsafe fn getState(&self, _state: *mut IBStream) -> tresult {
        kResultOk
    }

    unsafe fn getParameterCount(&self) -> i32 {
        let user_parameters = self.parameters().count();
        // MIDI CC state is framework-owned, always available
        let cc_parameters = self
            .midi_cc_state
            .as_ref()
            .map(|s| s.enabled_count())
            .unwrap_or(0);
        // Add program change parameter if we have factory presets
        let preset_parameter = if Presets::count() > 0 { 1 } else { 0 };
        (user_parameters + cc_parameters + preset_parameter) as i32
    }

    unsafe fn getParameterInfo(&self, parameter_index: i32, info: *mut ParameterInfo) -> tresult {
        if info.is_null() {
            return kInvalidArgument;
        }

        let parameters = self.parameters();
        let user_parameter_count = parameters.count();

        // User-defined parameters first
        if (parameter_index as usize) < user_parameter_count {
            if let Some(parameter_info) = parameters.info(parameter_index as usize) {
                let info = &mut *info;
                info.id = parameter_info.id;
                copy_wstring(parameter_info.name, &mut info.title);
                copy_wstring(parameter_info.short_name, &mut info.shortTitle);
                copy_wstring(parameter_info.units, &mut info.units);
                info.stepCount = parameter_info.step_count;
                info.defaultNormalizedValue = parameter_info.default_normalized;
                info.unitId = parameter_info.group_id;
                info.flags = {
                    let mut flags = 0;
                    if parameter_info.flags.can_automate {
                        flags |= ParameterInfo_::ParameterFlags_::kCanAutomate;
                    }
                    if parameter_info.flags.is_bypass {
                        flags |= ParameterInfo_::ParameterFlags_::kIsBypass;
                    }
                    // List parameters (enums) - display as dropdown with text labels
                    if parameter_info.flags.is_list {
                        flags |= ParameterInfo_::ParameterFlags_::kIsList;
                    }
                    // Hidden parameters (MIDI CC emulation)
                    if parameter_info.flags.is_hidden {
                        flags |= ParameterInfo_::ParameterFlags_::kIsHidden;
                    }
                    flags
                };
                return kResultOk;
            }
            return kInvalidArgument;
        }

        // Hidden MIDI CC parameters (framework-owned state)
        let cc_parameter_count = self
            .midi_cc_state
            .as_ref()
            .map(|s| s.enabled_count())
            .unwrap_or(0);

        if let Some(cc_state) = self.midi_cc_state.as_ref() {
            let cc_index = (parameter_index as usize) - user_parameter_count;
            if cc_index < cc_parameter_count {
                if let Some(parameter_info) = cc_state.info(cc_index) {
                    let info = &mut *info;
                    info.id = parameter_info.id;
                    copy_wstring(parameter_info.name, &mut info.title);
                    copy_wstring(parameter_info.short_name, &mut info.shortTitle);
                    copy_wstring(parameter_info.units, &mut info.units);
                    info.stepCount = parameter_info.step_count;
                    info.defaultNormalizedValue = parameter_info.default_normalized;
                    info.unitId = parameter_info.group_id;
                    // Hidden + automatable
                    info.flags = ParameterInfo_::ParameterFlags_::kCanAutomate
                        | ParameterInfo_::ParameterFlags_::kIsHidden;
                    return kResultOk;
                }
            }
        }

        // Program change parameter for factory presets (after all other parameters)
        let preset_count = Presets::count();
        if preset_count > 0 {
            let preset_param_index = user_parameter_count + cc_parameter_count;
            if parameter_index as usize == preset_param_index {
                let info = &mut *info;
                info.id = PROGRAM_CHANGE_PARAM_ID;
                copy_wstring("Program", &mut info.title);
                copy_wstring("Prg", &mut info.shortTitle);
                copy_wstring("", &mut info.units);
                info.stepCount = (preset_count - 1) as i32; // Discrete steps
                info.defaultNormalizedValue = 0.0; // First preset is default
                info.unitId = 0; // Root unit
                // Program change + list (shows preset names in host)
                info.flags = ParameterInfo_::ParameterFlags_::kIsProgramChange
                    | ParameterInfo_::ParameterFlags_::kIsList;
                return kResultOk;
            }
        }

        kInvalidArgument
    }

    unsafe fn getParamStringByValue(
        &self,
        id: u32,
        value_normalized: f64,
        string: *mut String128,
    ) -> tresult {
        if string.is_null() {
            return kInvalidArgument;
        }

        // Handle program change parameter (preset names)
        if id == PROGRAM_CHANGE_PARAM_ID {
            let preset_count = Presets::count();
            if preset_count > 0 {
                // Convert normalized value to preset index
                let step_count = (preset_count - 1).max(1) as f64;
                let preset_index = (value_normalized * step_count).round() as usize;
                let preset_index = preset_index.min(preset_count - 1);

                if let Some(preset_info) = Presets::info(preset_index) {
                    copy_wstring(preset_info.name, &mut *string);
                    return kResultOk;
                }
            }
            copy_wstring("", &mut *string);
            return kResultOk;
        }

        let parameters = self.parameters();
        let display = parameters.normalized_to_string(id, value_normalized);
        copy_wstring(&display, &mut *string);
        kResultOk
    }

    unsafe fn getParamValueByString(
        &self,
        id: u32,
        string: *mut TChar,
        value_normalized: *mut f64,
    ) -> tresult {
        if string.is_null() || value_normalized.is_null() {
            return kInvalidArgument;
        }

        let len = len_wstring(string as *const TChar);
        if let Ok(s) = String::from_utf16(slice::from_raw_parts(string as *const u16, len)) {
            // Handle program change parameter (preset name to value)
            if id == PROGRAM_CHANGE_PARAM_ID {
                let preset_count = Presets::count();
                // Find preset by name
                for i in 0..preset_count {
                    if let Some(preset_info) = Presets::info(i) {
                        if preset_info.name == s {
                            let step_count = (preset_count - 1).max(1) as f64;
                            *value_normalized = (i as f64) / step_count;
                            return kResultOk;
                        }
                    }
                }
                return kInvalidArgument;
            }

            let parameters = self.parameters();
            if let Some(value) = parameters.string_to_normalized(id, &s) {
                *value_normalized = value;
                return kResultOk;
            }
        }
        kInvalidArgument
    }

    unsafe fn normalizedParamToPlain(&self, id: u32, value_normalized: f64) -> f64 {
        // Handle program change parameter (normalized to index)
        if id == PROGRAM_CHANGE_PARAM_ID {
            let preset_count = Presets::count();
            if preset_count > 0 {
                let step_count = (preset_count - 1).max(1) as f64;
                return (value_normalized * step_count).round();
            }
            return 0.0;
        }
        self.parameters().normalized_to_plain(id, value_normalized)
    }

    unsafe fn plainParamToNormalized(&self, id: u32, plain_value: f64) -> f64 {
        // Handle program change parameter (index to normalized)
        if id == PROGRAM_CHANGE_PARAM_ID {
            let preset_count = Presets::count();
            if preset_count > 1 {
                let step_count = (preset_count - 1) as f64;
                return plain_value / step_count;
            }
            return 0.0;
        }
        self.parameters().plain_to_normalized(id, plain_value)
    }

    unsafe fn getParamNormalized(&self, id: u32) -> f64 {
        // Check if this is a MIDI CC parameter
        if MidiCcState::is_midi_cc_parameter(id) {
            if let Some(cc_state) = self.midi_cc_state.as_ref() {
                return cc_state.get_normalized(id);
            }
        }

        // Check if this is the program change parameter
        if id == PROGRAM_CHANGE_PARAM_ID {
            let preset_count = Presets::count();
            if preset_count > 1 {
                let current_index = *self.current_preset_index.get();
                let step_count = (preset_count - 1) as f64;
                return (current_index as f64) / step_count;
            } else if preset_count == 1 {
                return 0.0;
            }
            return 0.0;
        }

        self.parameters().get_normalized(id)
    }

    unsafe fn setParamNormalized(&self, id: u32, value: f64) -> tresult {
        // Check if this is a MIDI CC parameter
        if MidiCcState::is_midi_cc_parameter(id) {
            if let Some(cc_state) = self.midi_cc_state.as_ref() {
                cc_state.set_normalized(id, value);
                return kResultOk;
            }
        }

        // Check if this is the program change parameter (preset selection)
        if id == PROGRAM_CHANGE_PARAM_ID {
            let preset_count = Presets::count();
            if preset_count > 0 {
                // Convert normalized value to preset index
                // stepCount = preset_count - 1, so index = round(value * stepCount)
                let step_count = (preset_count - 1) as f64;
                let preset_index = (value * step_count).round() as usize;
                let preset_index = preset_index.min(preset_count - 1);

                // Always apply unconditionally - never skip with "if changed" guard.
                // Hosts may re-send the same preset index (e.g., user clicks preset 0
                // when it's already selected), and skipping would break preset 0 on
                // fresh load when current_preset_index is initialized to 0.
                Presets::apply(preset_index, self.parameters());

                // Store the current preset index
                *self.current_preset_index.get() = preset_index as i32;

                // Notify host that parameter values changed so UI refreshes
                let handler = *self.component_handler.get();
                if !handler.is_null() {
                    ((*(*handler).vtbl).restartComponent)(
                        handler,
                        RestartFlags_::kParamValuesChanged,
                    );
                }

                return kResultOk;
            }
            return kInvalidArgument;
        }

        self.parameters().set_normalized(id, value);
        kResultOk
    }

    unsafe fn setComponentHandler(&self, handler: *mut IComponentHandler) -> tresult {
        let handler_ptr = self.component_handler.get();
        let old_handler = *handler_ptr;

        // Release old handler if present
        if !old_handler.is_null() {
            let unknown = old_handler as *mut FUnknown;
            ((*(*unknown).vtbl).release)(unknown);
        }

        // Store and AddRef new handler if present
        if !handler.is_null() {
            let unknown = handler as *mut FUnknown;
            ((*(*unknown).vtbl).addRef)(unknown);
        }

        *handler_ptr = handler;
        kResultOk
    }

    unsafe fn createView(&self, name: *const c_char) -> *mut IPlugView {
        if name.is_null() {
            return std::ptr::null_mut();
        }

        // Check if this is an "editor" view request
        let name_str = std::ffi::CStr::from_ptr(name).to_str().unwrap_or("");
        if name_str != "editor" {
            return std::ptr::null_mut();
        }

        // TODO: Integrate WebView editor via EditorDelegate in Phase 2
        // For now, return null (no editor)
        std::ptr::null_mut()
    }
}

// =============================================================================
// IUnitInfo implementation (VST3 Unit/Group hierarchy)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IUnitInfoTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getUnitCount(&self) -> i32 {
        use beamer_core::parameter_groups::ParameterGroups;
        self.parameters().group_count() as i32
    }

    unsafe fn getUnitInfo(&self, unit_index: i32, info: *mut UnitInfo) -> tresult {
        if info.is_null() || unit_index < 0 {
            return kInvalidArgument;
        }

        use beamer_core::parameter_groups::ParameterGroups;
        let parameters = self.parameters();

        if let Some(group_info) = parameters.group_info(unit_index as usize) {
            let info = &mut *info;
            info.id = group_info.id;
            info.parentUnitId = group_info.parent_id;
            // Assign program list to root unit if we have presets
            info.programListId = if group_info.id == 0 && Presets::count() > 0 {
                FACTORY_PRESETS_LIST_ID
            } else {
                kNoProgramListId
            };
            copy_wstring(group_info.name, &mut info.name);
            kResultOk
        } else {
            kInvalidArgument
        }
    }

    unsafe fn getProgramListCount(&self) -> i32 {
        if Presets::count() > 0 {
            1 // One program list for factory presets
        } else {
            0
        }
    }

    unsafe fn getProgramListInfo(
        &self,
        list_index: i32,
        info: *mut ProgramListInfo,
    ) -> tresult {
        if info.is_null() {
            return kInvalidArgument;
        }

        // Only support our single factory presets list
        if list_index != 0 || Presets::count() == 0 {
            return kInvalidArgument;
        }

        let info = &mut *info;
        info.id = FACTORY_PRESETS_LIST_ID;
        info.programCount = Presets::count() as i32;
        copy_wstring("Factory Presets", &mut info.name);

        kResultOk
    }

    unsafe fn getProgramName(&self, list_id: i32, program_index: i32, name: *mut String128) -> tresult {
        if name.is_null() {
            return kInvalidArgument;
        }

        // Only support our factory presets list
        if list_id != FACTORY_PRESETS_LIST_ID {
            return kInvalidArgument;
        }

        if let Some(preset_info) = Presets::info(program_index as usize) {
            copy_wstring(preset_info.name, &mut *name);
            kResultOk
        } else {
            kInvalidArgument
        }
    }

    unsafe fn getProgramInfo(
        &self,
        _list_id: i32,
        _program_index: i32,
        _attribute_id: *const c_char,
        _attribute_value: *mut String128,
    ) -> tresult {
        kNotImplemented
    }

    unsafe fn hasProgramPitchNames(&self, _list_id: i32, _program_index: i32) -> tresult {
        kResultFalse
    }

    unsafe fn getProgramPitchName(
        &self,
        _list_id: i32,
        _program_index: i32,
        _midi_pitch: i16,
        _name: *mut String128,
    ) -> tresult {
        kNotImplemented
    }

    unsafe fn getSelectedUnit(&self) -> i32 {
        0 // Return root unit
    }

    unsafe fn selectUnit(&self, _unit_id: i32) -> tresult {
        kResultOk // Accept but ignore unit selection
    }

    unsafe fn getUnitByBus(
        &self,
        _media_type: MediaType,
        _dir: BusDirection,
        _bus_index: i32,
        _channel: i32,
        _unit_id: *mut i32,
    ) -> tresult {
        kNotImplemented
    }

    unsafe fn setUnitProgramData(
        &self,
        _list_or_unit_id: i32,
        _program_index: i32,
        _data: *mut IBStream,
    ) -> tresult {
        kNotImplemented
    }
}

// =============================================================================
// IMidiMapping implementation (VST3 SDK 3.8.0)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IMidiMappingTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getMidiControllerAssignment(
        &self,
        bus_index: i32,
        channel: i16,
        midi_controller_number: i16,
        id: *mut u32,
    ) -> tresult {
        if id.is_null() {
            return kInvalidArgument;
        }

        let controller = midi_controller_number as u8;

        // 1. First check plugin's custom mappings (only available in unprepared state)
        if let Some(plugin) = self.try_plugin() {
            if let Some(parameter_id) = plugin.midi_cc_to_parameter(bus_index, channel, controller) {
                *id = parameter_id;
                return kResultOk;
            }
        }

        // 2. Check framework-owned MIDI CC state (omni channel - ignore channel parameter)
        if let Some(cc_state) = self.midi_cc_state.as_ref() {
            if cc_state.has_controller(controller) {
                *id = MidiCcState::parameter_id(controller);
                return kResultOk;
            }
        }

        kResultFalse
    }
}

// =============================================================================
// IMidiLearn implementation (VST3 SDK 3.8.0)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IMidiLearnTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn onLiveMIDIControllerInput(
        &self,
        bus_index: i32,
        channel: i16,
        midi_cc: i16,
    ) -> tresult {
        // on_midi_learn is on Plugin, only available in unprepared state
        if let Some(plugin) = self.try_plugin_mut() {
            if plugin.on_midi_learn(bus_index, channel, midi_cc as u8) {
                return kResultOk;
            }
        }
        kResultFalse
    }
}

// =============================================================================
// IMidiMapping2 implementation (VST3 SDK 3.8.0 - MIDI 2.0)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IMidiMapping2Trait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getNumMidi1ControllerAssignments(&self, direction: BusDirections) -> u32 {
        // Only support input direction
        if direction != BusDirections_::kInput {
            return 0;
        }
        // midi1_assignments is on Plugin, only available in unprepared state
        self.try_plugin()
            .map(|p| p.midi1_assignments().len() as u32)
            .unwrap_or(0)
    }

    unsafe fn getMidi1ControllerAssignments(
        &self,
        direction: BusDirections,
        list: *const Midi1ControllerParamIDAssignmentList,
    ) -> tresult {
        if list.is_null() || direction != BusDirections_::kInput {
            return kInvalidArgument;
        }

        // midi1_assignments is on Plugin, only available in unprepared state
        let Some(plugin) = self.try_plugin() else {
            return kResultFalse;
        };
        let assignments = plugin.midi1_assignments();
        let list_ref = &*list;

        if (list_ref.count as usize) < assignments.len() {
            return kResultFalse;
        }

        if assignments.is_empty() {
            return kResultOk;
        }

        let map = slice::from_raw_parts_mut(list_ref.map, assignments.len());
        for (i, a) in assignments.iter().enumerate() {
            map[i] = Midi1ControllerParamIDAssignment {
                pId: a.assignment.parameter_id,
                busIndex: a.assignment.bus_index,
                channel: a.assignment.channel,
                controller: a.controller as i16,
            };
        }

        kResultOk
    }

    unsafe fn getNumMidi2ControllerAssignments(&self, direction: BusDirections) -> u32 {
        // Only support input direction
        if direction != BusDirections_::kInput {
            return 0;
        }
        // midi2_assignments is on Plugin, only available in unprepared state
        self.try_plugin()
            .map(|p| p.midi2_assignments().len() as u32)
            .unwrap_or(0)
    }

    unsafe fn getMidi2ControllerAssignments(
        &self,
        direction: BusDirections,
        list: *const Midi2ControllerParamIDAssignmentList,
    ) -> tresult {
        if list.is_null() || direction != BusDirections_::kInput {
            return kInvalidArgument;
        }

        // midi2_assignments is on Plugin, only available in unprepared state
        let Some(plugin) = self.try_plugin() else {
            return kResultFalse;
        };
        let assignments = plugin.midi2_assignments();
        let list_ref = &*list;

        if (list_ref.count as usize) < assignments.len() {
            return kResultFalse;
        }

        if assignments.is_empty() {
            return kResultOk;
        }

        let map = slice::from_raw_parts_mut(list_ref.map, assignments.len());
        for (i, a) in assignments.iter().enumerate() {
            map[i] = Midi2ControllerParamIDAssignment {
                pId: a.assignment.parameter_id,
                busIndex: a.assignment.bus_index,
                channel: a.assignment.channel,
                controller: Midi2Controller {
                    bank: a.controller.bank,
                    registered: if a.controller.registered { 1 } else { 0 },
                    index: a.controller.index,
                    reserved: 0,
                },
            };
        }

        kResultOk
    }
}

// =============================================================================
// IMidiLearn2 implementation (VST3 SDK 3.8.0 - MIDI 2.0)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IMidiLearn2Trait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn onLiveMidi1ControllerInput(
        &self,
        bus_index: i32,
        channel: u8,
        midi_cc: i16,
    ) -> tresult {
        if let Some(plugin) = self.try_plugin_mut() {
            if plugin.on_midi1_learn(bus_index, channel, midi_cc as u8) {
                return kResultOk;
            }
        }
        kResultFalse
    }

    unsafe fn onLiveMidi2ControllerInput(
        &self,
        bus_index: i32,
        channel: u8,
        midi_cc: Midi2Controller,
    ) -> tresult {
        if let Some(plugin) = self.try_plugin_mut() {
            let controller = beamer_core::Midi2Controller {
                bank: midi_cc.bank,
                registered: midi_cc.registered != 0,
                index: midi_cc.index,
            };
            if plugin.on_midi2_learn(bus_index, channel, controller) {
                return kResultOk;
            }
        }
        kResultFalse
    }
}

// =============================================================================
// INoteExpressionController implementation (VST3 SDK 3.5.0)
// =============================================================================

impl<P: Descriptor + 'static, Presets> INoteExpressionControllerTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getNoteExpressionCount(&self, bus_index: i32, channel: i16) -> i32 {
        self.try_plugin()
            .map(|p| p.note_expression_count(bus_index, channel) as i32)
            .unwrap_or(0)
    }

    unsafe fn getNoteExpressionInfo(
        &self,
        bus_index: i32,
        channel: i16,
        note_expression_index: i32,
        info: *mut NoteExpressionTypeInfo,
    ) -> tresult {
        if info.is_null() {
            return kInvalidArgument;
        }

        let Some(plugin) = self.try_plugin() else {
            return kInvalidArgument;
        };
        if let Some(expr_info) =
            plugin.note_expression_info(bus_index, channel, note_expression_index as usize)
        {
            let vst_info = &mut *info;
            vst_info.typeId = expr_info.type_id;
            copy_wstring(expr_info.title_str(), &mut vst_info.title);
            copy_wstring(expr_info.short_title_str(), &mut vst_info.shortTitle);
            copy_wstring(expr_info.units_str(), &mut vst_info.units);
            vst_info.unitId = expr_info.unit_id;
            vst_info.valueDesc.minimum = expr_info.value_desc.minimum;
            vst_info.valueDesc.maximum = expr_info.value_desc.maximum;
            vst_info.valueDesc.defaultValue = expr_info.value_desc.default_value;
            vst_info.valueDesc.stepCount = expr_info.value_desc.step_count;
            vst_info.associatedParameterId = expr_info.associated_parameter_id as u32;
            vst_info.flags = expr_info.flags.0;
            kResultOk
        } else {
            kInvalidArgument
        }
    }

    unsafe fn getNoteExpressionStringByValue(
        &self,
        bus_index: i32,
        channel: i16,
        id: NoteExpressionTypeID,
        value_normalized: NoteExpressionValue,
        string: *mut String128,
    ) -> tresult {
        if string.is_null() {
            return kInvalidArgument;
        }

        let Some(plugin) = self.try_plugin() else {
            return kInvalidArgument;
        };
        let display = plugin.note_expression_value_to_string(bus_index, channel, id, value_normalized);
        copy_wstring(&display, &mut *string);
        kResultOk
    }

    unsafe fn getNoteExpressionValueByString(
        &self,
        bus_index: i32,
        channel: i16,
        id: NoteExpressionTypeID,
        string: *const TChar,
        value_normalized: *mut NoteExpressionValue,
    ) -> tresult {
        if string.is_null() || value_normalized.is_null() {
            return kInvalidArgument;
        }

        let len = len_wstring(string);
        if let Ok(s) = String::from_utf16(slice::from_raw_parts(string, len)) {
            if let Some(plugin) = self.try_plugin() {
                if let Some(value) = plugin.note_expression_string_to_value(bus_index, channel, id, &s) {
                    *value_normalized = value;
                    return kResultOk;
                }
            }
        }
        kResultFalse
    }
}

// =============================================================================
// IKeyswitchController implementation (VST3 SDK 3.5.0)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IKeyswitchControllerTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getKeyswitchCount(&self, bus_index: i32, channel: i16) -> i32 {
        self.try_plugin()
            .map(|p| p.keyswitch_count(bus_index, channel) as i32)
            .unwrap_or(0)
    }

    unsafe fn getKeyswitchInfo(
        &self,
        bus_index: i32,
        channel: i16,
        keyswitch_index: i32,
        info: *mut KeyswitchInfo,
    ) -> tresult {
        if info.is_null() {
            return kInvalidArgument;
        }

        let Some(plugin) = self.try_plugin() else {
            return kInvalidArgument;
        };
        if let Some(ks_info) =
            plugin.keyswitch_info(bus_index, channel, keyswitch_index as usize)
        {
            let vst_info = &mut *info;
            vst_info.typeId = ks_info.type_id;
            copy_wstring(ks_info.title_str(), &mut vst_info.title);
            copy_wstring(ks_info.short_title_str(), &mut vst_info.shortTitle);
            vst_info.keyswitchMin = ks_info.keyswitch_min;
            vst_info.keyswitchMax = ks_info.keyswitch_max;
            vst_info.keyRemapped = ks_info.key_remapped;
            vst_info.unitId = ks_info.unit_id;
            vst_info.flags = ks_info.flags;
            kResultOk
        } else {
            kInvalidArgument
        }
    }
}

// =============================================================================
// INoteExpressionPhysicalUIMapping implementation (VST3 SDK 3.6.11)
// =============================================================================

impl<P: Descriptor + 'static, Presets> INoteExpressionPhysicalUIMappingTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn getPhysicalUIMapping(
        &self,
        bus_index: i32,
        channel: i16,
        list: *mut PhysicalUIMapList,
    ) -> tresult {
        if list.is_null() {
            return kInvalidArgument;
        }

        let Some(plugin) = self.try_plugin() else {
            return kInvalidArgument;
        };
        let mappings = plugin.physical_ui_mappings(bus_index, channel);
        let list_ref = &mut *list;

        // Fill in the mappings up to the provided count
        let fill_count = (list_ref.count as usize).min(mappings.len());
        if fill_count > 0 && !list_ref.map.is_null() {
            let map_slice = slice::from_raw_parts_mut(list_ref.map, fill_count);
            for (i, mapping) in mappings.iter().take(fill_count).enumerate() {
                map_slice[i].physicalUITypeID = mapping.physical_ui_type_id;
                map_slice[i].noteExpressionTypeID = mapping.note_expression_type_id;
            }
        }

        kResultOk
    }
}

// =============================================================================
// IVst3WrapperMPESupport implementation (VST3 SDK 3.6.12)
// =============================================================================

impl<P: Descriptor + 'static, Presets> IVst3WrapperMPESupportTrait for Vst3Processor<P, Presets>
where
    Presets: FactoryPresets<Parameters = P::Parameters>,
{
    unsafe fn enableMPEInputProcessing(&self, state: TBool) -> tresult {
        if let Some(plugin) = self.try_plugin_mut() {
            if plugin.enable_mpe_input_processing(state != 0) {
                return kResultOk;
            }
        }
        kResultFalse
    }

    unsafe fn setMPEInputDeviceSettings(
        &self,
        master_channel: i32,
        member_begin_channel: i32,
        member_end_channel: i32,
    ) -> tresult {
        if let Some(plugin) = self.try_plugin_mut() {
            let settings = beamer_core::MpeInputDeviceSettings {
                master_channel,
                member_begin_channel,
                member_end_channel,
            };
            if plugin.set_mpe_input_device_settings(settings) {
                return kResultOk;
            }
        }
        kResultFalse
    }
}

// =============================================================================
// Helper functions
// =============================================================================

/// Convert UTF-16 slice to UTF-8, writing into a fixed-size buffer.
///
/// Returns the number of bytes written. Handles BMP characters (most common)
/// and replaces non-BMP surrogates with replacement character.
fn utf16_to_utf8(utf16: &[u16], utf8_buf: &mut [u8]) -> usize {
    let mut utf8_pos = 0;

    for &code_unit in utf16 {
        if code_unit == 0 {
            // Null terminator
            break;
        }

        // Calculate how many UTF-8 bytes this character needs
        let (bytes_needed, char_value) = if code_unit < 0x80 {
            // ASCII (1 byte)
            (1, code_unit as u32)
        } else if code_unit < 0x800 {
            // 2-byte UTF-8
            (2, code_unit as u32)
        } else if (0xD800..=0xDFFF).contains(&code_unit) {
            // Surrogate pair (non-BMP) - simplified: use replacement char
            // Full implementation would need to look ahead for the low surrogate
            (3, 0xFFFD) // Unicode replacement character
        } else {
            // 3-byte UTF-8 (most non-ASCII BMP characters)
            (3, code_unit as u32)
        };

        // Check if we have room
        if utf8_pos + bytes_needed > utf8_buf.len() {
            break;
        }

        // Encode to UTF-8
        match bytes_needed {
            1 => {
                utf8_buf[utf8_pos] = char_value as u8;
            }
            2 => {
                utf8_buf[utf8_pos] = (0xC0 | (char_value >> 6)) as u8;
                utf8_buf[utf8_pos + 1] = (0x80 | (char_value & 0x3F)) as u8;
            }
            3 => {
                utf8_buf[utf8_pos] = (0xE0 | (char_value >> 12)) as u8;
                utf8_buf[utf8_pos + 1] = (0x80 | ((char_value >> 6) & 0x3F)) as u8;
                utf8_buf[utf8_pos + 2] = (0x80 | (char_value & 0x3F)) as u8;
            }
            _ => unreachable!(),
        }

        utf8_pos += bytes_needed;
    }

    utf8_pos
}

/// Convert a channel count to the corresponding VST3 speaker arrangement.
fn channel_count_to_speaker_arrangement(channel_count: u32) -> SpeakerArrangement {
    match channel_count {
        1 => SpeakerArr::kMono,
        2 => SpeakerArr::kStereo,
        // For other channel counts, create a bitmask with that many speakers
        n => (1u64 << n) - 1,
    }
}

/// Convert a MIDI CC parameter value to a MidiEvent.
///
/// This is used to convert parameter changes from IMidiMapping back to MIDI events.
/// The controller number determines the event type:
/// - 0-127: Standard MIDI CC (ControlChange)
/// - 128: Channel Aftertouch (ChannelPressure)
/// - 129: Pitch Bend (PitchBend)
fn convert_cc_parameter_to_midi(controller: u8, normalized_value: f32, sample_offset: u32) -> MidiEvent {
    match controller {
        LEGACY_CC_PITCH_BEND => {
            // Pitch bend: 0.0-1.0 normalized → -1.0 to 1.0
            let bend = normalized_value * 2.0 - 1.0;
            MidiEvent::pitch_bend(sample_offset, 0, bend)
        }
        LEGACY_CC_CHANNEL_PRESSURE => {
            // Channel aftertouch: 0.0-1.0
            MidiEvent::channel_pressure(sample_offset, 0, normalized_value)
        }
        cc => {
            // Standard CC: 0.0-1.0
            MidiEvent::control_change(sample_offset, 0, cc, normalized_value)
        }
    }
}

/// Convert a VST3 Event to a MIDI event.
///
/// Returns None for unsupported event types.
unsafe fn convert_vst3_to_midi(event: &Event) -> Option<MidiEvent> {
    let sample_offset = event.sampleOffset as u32;

    match event.r#type {
        K_NOTE_ON_EVENT => {
            let note_on = &event.__field0.noteOn;
            // Use pitch as note_id when host sends -1
            let note_id = if note_on.noteId == -1 {
                note_on.pitch as i32
            } else {
                note_on.noteId
            };
            Some(MidiEvent::note_on(
                sample_offset,
                note_on.channel as u8,
                note_on.pitch as u8,
                note_on.velocity,
                note_id,
                note_on.tuning,
                note_on.length,
            ))
        }
        K_NOTE_OFF_EVENT => {
            let note_off = &event.__field0.noteOff;
            // Use pitch as note_id when host sends -1
            let note_id = if note_off.noteId == -1 {
                note_off.pitch as i32
            } else {
                note_off.noteId
            };
            Some(MidiEvent::note_off(
                sample_offset,
                note_off.channel as u8,
                note_off.pitch as u8,
                note_off.velocity,
                note_id,
                note_off.tuning,
            ))
        }
        K_POLY_PRESSURE_EVENT => {
            let poly = &event.__field0.polyPressure;
            // Use pitch as note_id when host sends -1
            let note_id = if poly.noteId == -1 {
                poly.pitch as i32
            } else {
                poly.noteId
            };
            Some(MidiEvent::poly_pressure(
                sample_offset,
                poly.channel as u8,
                poly.pitch as u8,
                poly.pressure,
                note_id,
            ))
        }
        K_DATA_EVENT => {
            let data_event = &event.__field0.data;
            // Only handle SysEx data type
            if data_event.r#type == DATA_TYPE_MIDI_SYSEX {
                let mut sysex = SysEx::new();
                let copy_len = (data_event.size as usize).min(MAX_SYSEX_SIZE);
                if copy_len > 0 && !data_event.bytes.is_null() {
                    let src = std::slice::from_raw_parts(data_event.bytes, copy_len);
                    sysex.data[..copy_len].copy_from_slice(src);
                    sysex.len = copy_len as u16;
                }
                Some(MidiEvent {
                    sample_offset,
                    event: MidiEventKind::SysEx(Box::new(sysex)),
                })
            } else {
                None
            }
        }
        K_NOTE_EXPRESSION_VALUE_EVENT => {
            let expr = &event.__field0.noteExpressionValue;
            Some(MidiEvent {
                sample_offset,
                event: MidiEventKind::NoteExpressionValue(CoreNoteExpressionValue {
                    note_id: expr.noteId,
                    expression_type: expr.typeId,
                    value: expr.value,
                }),
            })
        }
        K_NOTE_EXPRESSION_INT_VALUE_EVENT => {
            let expr = &event.__field0.noteExpressionIntValue;
            Some(MidiEvent {
                sample_offset,
                event: MidiEventKind::NoteExpressionInt(NoteExpressionInt {
                    note_id: expr.noteId,
                    expression_type: expr.typeId,
                    value: expr.value,
                }),
            })
        }
        K_NOTE_EXPRESSION_TEXT_EVENT => {
            let expr = &event.__field0.noteExpressionText;
            let mut text_event = NoteExpressionText {
                note_id: expr.noteId,
                expression_type: expr.typeId,
                text: [0u8; MAX_EXPRESSION_TEXT_SIZE],
                text_len: 0,
            };
            // Convert UTF-16 to UTF-8
            let text_len = expr.textLen as usize;
            if !expr.text.is_null() && text_len > 0 {
                let text_slice = std::slice::from_raw_parts(expr.text, text_len);
                let utf8_len = utf16_to_utf8(text_slice, &mut text_event.text);
                text_event.text_len = utf8_len as u8;
            }
            Some(MidiEvent {
                sample_offset,
                event: MidiEventKind::NoteExpressionText(text_event),
            })
        }
        K_CHORD_EVENT => {
            let chord = &event.__field0.chord;
            let mut info = ChordInfo {
                root: chord.root as i8,
                bass_note: chord.bassNote as i8,
                mask: chord.mask as u16,
                name: [0u8; MAX_CHORD_NAME_SIZE],
                name_len: 0,
            };
            // Convert UTF-16 to UTF-8
            let text_len = chord.textLen as usize;
            if !chord.text.is_null() && text_len > 0 {
                let text_slice = std::slice::from_raw_parts(chord.text, text_len);
                let utf8_len = utf16_to_utf8(text_slice, &mut info.name);
                info.name_len = utf8_len as u8;
            }
            Some(MidiEvent {
                sample_offset,
                event: MidiEventKind::ChordInfo(info),
            })
        }
        K_SCALE_EVENT => {
            let scale = &event.__field0.scale;
            let mut info = ScaleInfo {
                root: scale.root as i8,
                mask: scale.mask as u16,
                name: [0u8; MAX_SCALE_NAME_SIZE],
                name_len: 0,
            };
            // Convert UTF-16 to UTF-8
            let text_len = scale.textLen as usize;
            if !scale.text.is_null() && text_len > 0 {
                let text_slice = std::slice::from_raw_parts(scale.text, text_len);
                let utf8_len = utf16_to_utf8(text_slice, &mut info.name);
                info.name_len = utf8_len as u8;
            }
            Some(MidiEvent {
                sample_offset,
                event: MidiEventKind::ScaleInfo(info),
            })
        }
        K_LEGACY_MIDI_CC_OUT_EVENT => {
            let cc_event = &event.__field0.midiCCOut;
            let channel = cc_event.channel as u8;

            match cc_event.controlNumber {
                0..=127 => {
                    // Standard Control Change
                    Some(MidiEvent::control_change(
                        sample_offset,
                        channel,
                        cc_event.controlNumber,
                        cc_event.value as f32 / 127.0,
                    ))
                }
                LEGACY_CC_CHANNEL_PRESSURE => Some(MidiEvent::channel_pressure(
                    sample_offset,
                    channel,
                    cc_event.value as f32 / 127.0,
                )),
                LEGACY_CC_PITCH_BEND => {
                    // Pitch bend: 14-bit value split across value (LSB) and value2 (MSB)
                    // Cast to u8 first to avoid sign extension issues
                    let lsb = (cc_event.value as u8) as u16;
                    let msb = (cc_event.value2 as u8) as u16;
                    let raw = (msb << 7) | (lsb & 0x7F);
                    let normalized = (raw as f32 - 8192.0) / 8192.0;
                    Some(MidiEvent::pitch_bend(sample_offset, channel, normalized))
                }
                LEGACY_CC_PROGRAM_CHANGE => Some(MidiEvent::program_change(
                    sample_offset,
                    channel,
                    cc_event.value as u8,
                )),
                _ => None, // Unknown control number
            }
        }
        _ => None, // Unsupported event type
    }
}

/// Convert a MIDI event to a VST3 Event.
///
/// The `sysex_pool` parameter provides stable storage for SysEx data during the
/// process() call, ensuring the pointers remain valid until the host processes them.
///
/// Note: ChordInfo, ScaleInfo, and NoteExpressionText are primarily input events
/// (DAW → plugin) and are not output.
fn convert_midi_to_vst3(midi: &MidiEvent, sysex_pool: &mut SysExOutputPool) -> Option<Event> {
    let mut event: Event = unsafe { std::mem::zeroed() };
    event.busIndex = 0;
    event.sampleOffset = midi.sample_offset as i32;
    event.ppqPosition = 0.0;
    event.flags = 0;

    // Note: Writing to union fields is safe in Rust, only reading requires unsafe
    match &midi.event {
        MidiEventKind::NoteOn(note_on) => {
            event.r#type = K_NOTE_ON_EVENT;
            event.__field0.noteOn.channel = note_on.channel as i16;
            event.__field0.noteOn.pitch = note_on.pitch as i16;
            event.__field0.noteOn.velocity = note_on.velocity;
            event.__field0.noteOn.noteId = note_on.note_id;
            event.__field0.noteOn.tuning = note_on.tuning;
            event.__field0.noteOn.length = note_on.length;
        }
        MidiEventKind::NoteOff(note_off) => {
            event.r#type = K_NOTE_OFF_EVENT;
            event.__field0.noteOff.channel = note_off.channel as i16;
            event.__field0.noteOff.pitch = note_off.pitch as i16;
            event.__field0.noteOff.velocity = note_off.velocity;
            event.__field0.noteOff.noteId = note_off.note_id;
            event.__field0.noteOff.tuning = note_off.tuning;
        }
        MidiEventKind::PolyPressure(poly) => {
            event.r#type = K_POLY_PRESSURE_EVENT;
            event.__field0.polyPressure.channel = poly.channel as i16;
            event.__field0.polyPressure.pitch = poly.pitch as i16;
            event.__field0.polyPressure.pressure = poly.pressure;
            event.__field0.polyPressure.noteId = poly.note_id;
        }
        MidiEventKind::ControlChange(cc) => {
            event.r#type = K_LEGACY_MIDI_CC_OUT_EVENT;
            event.__field0.midiCCOut.controlNumber = cc.controller;
            event.__field0.midiCCOut.channel = cc.channel as i8;
            event.__field0.midiCCOut.value = (cc.value * 127.0) as i8;
            event.__field0.midiCCOut.value2 = 0;
        }
        MidiEventKind::PitchBend(pb) => {
            event.r#type = K_LEGACY_MIDI_CC_OUT_EVENT;
            event.__field0.midiCCOut.controlNumber = LEGACY_CC_PITCH_BEND;
            event.__field0.midiCCOut.channel = pb.channel as i8;
            // Convert -1.0..1.0 to 14-bit value (0-16383, center at 8192)
            let raw = ((pb.value * 8192.0) + 8192.0).clamp(0.0, 16383.0) as i16;
            event.__field0.midiCCOut.value = (raw & 0x7F) as i8;
            event.__field0.midiCCOut.value2 = ((raw >> 7) & 0x7F) as i8;
        }
        MidiEventKind::ChannelPressure(cp) => {
            event.r#type = K_LEGACY_MIDI_CC_OUT_EVENT;
            event.__field0.midiCCOut.controlNumber = LEGACY_CC_CHANNEL_PRESSURE;
            event.__field0.midiCCOut.channel = cp.channel as i8;
            event.__field0.midiCCOut.value = (cp.pressure * 127.0) as i8;
            event.__field0.midiCCOut.value2 = 0;
        }
        MidiEventKind::ProgramChange(pc) => {
            event.r#type = K_LEGACY_MIDI_CC_OUT_EVENT;
            event.__field0.midiCCOut.controlNumber = LEGACY_CC_PROGRAM_CHANGE;
            event.__field0.midiCCOut.channel = pc.channel as i8;
            event.__field0.midiCCOut.value = pc.program as i8;
            event.__field0.midiCCOut.value2 = 0;
        }
        MidiEventKind::NoteExpressionValue(expr) => {
            event.r#type = K_NOTE_EXPRESSION_VALUE_EVENT;
            event.__field0.noteExpressionValue.noteId = expr.note_id;
            event.__field0.noteExpressionValue.typeId = expr.expression_type;
            event.__field0.noteExpressionValue.value = expr.value;
        }
        MidiEventKind::NoteExpressionInt(expr) => {
            event.r#type = K_NOTE_EXPRESSION_INT_VALUE_EVENT;
            event.__field0.noteExpressionIntValue.noteId = expr.note_id;
            event.__field0.noteExpressionIntValue.typeId = expr.expression_type;
            event.__field0.noteExpressionIntValue.value = expr.value;
        }
        MidiEventKind::SysEx(sysex) => {
            // Allocate a slot in the pool for stable pointer storage
            if let Some((ptr, len)) = sysex_pool.allocate(sysex.as_slice()) {
                event.r#type = K_DATA_EVENT;
                event.__field0.data.r#type = DATA_TYPE_MIDI_SYSEX;
                event.__field0.data.size = len as u32;
                event.__field0.data.bytes = ptr;
            } else {
                // Pool is full, drop this SysEx
                return None;
            }
        }
        // ChordInfo/ScaleInfo are DAW → plugin only (chord track metadata).
        // Plugins receive these from the DAW but don't generate them.
        MidiEventKind::ChordInfo(_) => return None,
        MidiEventKind::ScaleInfo(_) => return None,

        // TODO: NoteExpressionText output not yet implemented.
        // Some vocal/granular synths emit phoneme or waveform text data.
        // Implementation would require a UTF-8→UTF-16 buffer pool (like SysEx)
        // to provide stable pointers for the host. Low priority but valid use case.
        MidiEventKind::NoteExpressionText(_) => return None,
    }

    Some(event)
}