summaryrefslogtreecommitdiff
path: root/muse2/muse/vst_native.cpp
blob: 063d089530da8e4d330fd4c77315087287afe8b0 (plain)
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
//===================================================================
//  MusE
//  Linux Music Editor
//
//  vst_native.cpp
//  (C) Copyright 2012-2013 Tim E. Real (terminator356 on users dot sourceforge dot net)
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; version 2 of
//  the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
//===================================================================

#include "config.h"

#ifdef VST_NATIVE_SUPPORT

#include <QDir>
#include <QMenu>

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <cmath>
#include <set>
#include <string>
#include <jack/jack.h>

#include "globals.h"
#include "gconfig.h"
#include "audio.h"
#include "synth.h"
#include "jackaudio.h"
#include "midi.h"
#include "xml.h"
#include "plugin.h"
#include "popupmenu.h"
#include "pos.h"
#include "tempo.h"
#include "sync.h"
#include "al/sig.h"

#include "vst_native.h"

#define OLD_PLUGIN_ENTRY_POINT "main"
#define NEW_PLUGIN_ENTRY_POINT "VSTPluginMain"

// Enable debugging messages
//#define VST_NATIVE_DEBUG
//#define VST_NATIVE_DEBUG_PROCESS

namespace MusECore {

extern JackAudioDevice* jackAudio;

//-----------------------------------------------------------------------------------------
//   vstHostCallback
//   This must be a function, it cannot be a class method so we dispatch to various objects from here.
//-----------------------------------------------------------------------------------------

VstIntPtr VSTCALLBACK vstNativeHostCallback(AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
{
      // Is this callback for an actual instance? Hand-off to the instance if so.
      VSTPlugin* plugin;
      if(effect && effect->user)
      {
        plugin = (VSTPlugin*)(effect->user);
        return ((VstNativeSynthIF*)plugin)->hostCallback(opcode, index, value, ptr, opt);
      }

      // No instance found. So we are just scanning for plugins...
    
#ifdef VST_NATIVE_DEBUG      
      fprintf(stderr, "vstNativeHostCallback eff:%p opcode:%ld\n", effect, opcode);
#endif      
      
      switch (opcode) {
            case audioMasterAutomate:
                  // index, value, returns 0
                  return 0;

            case audioMasterVersion:
                  // vst version, currently 2 (0 for older)
                  return 2300;

            case audioMasterCurrentId:
                  // returns the unique id of a plug that's currently
                  // loading
                  return 0;

            case audioMasterIdle:
                  // call application idle routine (this will
                  // call effEditIdle for all open editors too)
                  return 0;

            case audioMasterGetTime:
                  // returns const VstTimeInfo* (or 0 if not supported)
                  // <value> should contain a mask indicating which fields are required
                  // (see valid masks above), as some items may require extensive
                  // conversions
                  return 0;

            case audioMasterProcessEvents:
                  // VstEvents* in <ptr>
                  return 0;

            case audioMasterIOChanged:
                   // numInputs and/or numOutputs has changed
                  return 0;

            case audioMasterSizeWindow:
                  // index: width, value: height
                  return 0;

            case audioMasterGetSampleRate:
                  return MusEGlobal::sampleRate;

            case audioMasterGetBlockSize:
                  return MusEGlobal::segmentSize;

            case audioMasterGetInputLatency:
                  return 0;

            case audioMasterGetOutputLatency:
                  return 0;

            case audioMasterGetCurrentProcessLevel:
                  // returns: 0: not supported,
                  // 1: currently in user thread (gui)
                  // 2: currently in audio thread (where process is called)
                  // 3: currently in 'sequencer' thread (midi, timer etc)
                  // 4: currently offline processing and thus in user thread
                  // other: not defined, but probably pre-empting user thread.
                  return 0;

            case audioMasterGetAutomationState:
                  // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
                  // offline
                  return 0;

            case audioMasterOfflineStart:
            case audioMasterOfflineRead:
                   // ptr points to offline structure, see below. return 0: error, 1 ok
                  return 0;

            case audioMasterOfflineWrite:
                  // same as read
                  return 0;

            case audioMasterOfflineGetCurrentPass:
            case audioMasterOfflineGetCurrentMetaPass:
                  return 0;

            case audioMasterGetVendorString:
                  // fills <ptr> with a string identifying the vendor (max 64 char)
                  strcpy ((char*) ptr, "MusE");
                  return 1;

            case audioMasterGetProductString:
                  // fills <ptr> with a string with product name (max 64 char)
                  strcpy ((char*) ptr, "NativeVST");
                  return 1;

            case audioMasterGetVendorVersion:
                  // returns vendor-specific version
                  return 2000;

            case audioMasterVendorSpecific:
                  // no definition, vendor specific handling
                  return 0;

            case audioMasterCanDo:
                  // string in ptr, see below
                  return 0;

            case audioMasterGetLanguage:
                  // see enum
                  return kVstLangEnglish;

            case audioMasterGetDirectory:
                  // get plug directory, FSSpec on MAC, else char*
                  return 0;

            case audioMasterUpdateDisplay:
                  // something has changed, update 'multi-fx' display
                  return 0;

            case audioMasterBeginEdit:
                  // begin of automation session (when mouse down), parameter index in <index>
                  return 0;

            case audioMasterEndEdit:
                  // end of automation session (when mouse up),     parameter index in <index>
                  return 0;

            case audioMasterOpenFileSelector:
                  // open a fileselector window with VstFileSelect* in <ptr>
                  return 0;

            case audioMasterCloseFileSelector:
                  return 0;
                  
#ifdef VST_FORCE_DEPRECATED

            case audioMasterGetSpeakerArrangement:
                  // (long)input in <value>, output in <ptr>
                  return 0;

            case audioMasterPinConnected:
                  // inquire if an input or output is beeing connected;
                  // index enumerates input or output counting from zero:
                  // value is 0 for input and != 0 otherwise. note: the
                  // return value is 0 for <true> such that older versions
                  // will always return true.
                  //return 1;
                  return 0;

            // VST 2.0 opcodes...
            case audioMasterWantMidi:
                  // <value> is a filter which is currently ignored
                  return 0;

            case audioMasterSetTime:
                  // VstTimenfo* in <ptr>, filter in <value>, not supported
                  return 0;

            case audioMasterTempoAt:
                  // returns tempo (in bpm * 10000) at sample frame location passed in <value>
                  return 0;  // TODO:

            case audioMasterGetNumAutomatableParameters:
                  return 0;

            case audioMasterGetParameterQuantization:
                     // returns the integer value for +1.0 representation,
                   // or 1 if full single float precision is maintained
                     // in automation. parameter index in <value> (-1: all, any)
                  //return 0;
                  return 1;

            case audioMasterNeedIdle:
                   // plug needs idle calls (outside its editor window)
                  return 0;

            case audioMasterGetPreviousPlug:
                   // input pin in <value> (-1: first to come), returns cEffect*
                  return 0;

            case audioMasterGetNextPlug:
                   // output pin in <value> (-1: first to come), returns cEffect*
                  return 0;

            case audioMasterWillReplaceOrAccumulate:
                   // returns: 0: not supported, 1: replace, 2: accumulate
                  //return 0;
                  return 1;

            case audioMasterSetOutputSampleRate:
                  // for variable i/o, sample rate in <opt>
                  return 0;

            case audioMasterSetIcon:
                  // void* in <ptr>, format not defined yet
                  return 0;

            case audioMasterOpenWindow:
                  // returns platform specific ptr
                  return 0;

            case audioMasterCloseWindow:
                  // close window, platform specific handle in <ptr>
                  return 0;
                  
#endif
                  
            default:
                  break;
            }

      if(MusEGlobal::debugMsg)
        fprintf(stderr, "  unknown opcode\n");

      return 0;
      }

//---------------------------------------------------------
//   loadPluginLib
//---------------------------------------------------------

static void scanVstNativeLib(QFileInfo& fi)
{
  void* handle = dlopen(fi.filePath().toAscii().constData(), RTLD_NOW);
  if (handle == NULL)
  {
    fprintf(stderr, "scanVstNativeLib: dlopen(%s) failed: %s\n", fi.filePath().toAscii().constData(), dlerror());
    return;
  }

  char buffer[128];
  QString effectName;
  QString vendorString;
  QString productString;
  int vendorVersion;
  std::vector<Synth*>::iterator is;
  int vst_version = 0;
  VstNativeSynth* new_synth = NULL;
  
  AEffect *(*getInstance)(audioMasterCallback);
  getInstance = (AEffect*(*)(audioMasterCallback))dlsym(handle, NEW_PLUGIN_ENTRY_POINT);
  if(!getInstance)
  {
    if(MusEGlobal::debugMsg)
    {
      fprintf(stderr, "VST 2.4 entrypoint \"" NEW_PLUGIN_ENTRY_POINT "\" not found in library %s, looking for \""
                      OLD_PLUGIN_ENTRY_POINT "\"\n", fi.filePath().toAscii().constData());
    }

    getInstance = (AEffect*(*)(audioMasterCallback))dlsym(handle, OLD_PLUGIN_ENTRY_POINT);
    if(!getInstance)
    {
      fprintf(stderr, "ERROR: VST entrypoints \"" NEW_PLUGIN_ENTRY_POINT "\" or \""
                      OLD_PLUGIN_ENTRY_POINT "\" not found in library\n");
      dlclose(handle);
      return;
    }
    else if(MusEGlobal::debugMsg)
    {
      fprintf(stderr, "VST entrypoint \"" OLD_PLUGIN_ENTRY_POINT "\" found\n");
    }
  }
  else if(MusEGlobal::debugMsg)
  {
    fprintf(stderr, "VST entrypoint \"" NEW_PLUGIN_ENTRY_POINT "\" found\n");
  }

  AEffect *plugin = getInstance(vstNativeHostCallback);
  if(!plugin)
  {
    fprintf(stderr, "ERROR: Failed to instantiate plugin in VST library \"%s\"\n", fi.filePath().toAscii().constData());
    dlclose(handle);
    return;
  }
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "plugin instantiated\n");

  if(plugin->magic != kEffectMagic)
  {
    fprintf(stderr, "Not a VST plugin in library \"%s\"\n", fi.filePath().toAscii().constData());
    dlclose(handle);
    return;
  }
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "plugin is a VST\n");

  if(!(plugin->flags & effFlagsHasEditor))
  {
    if(MusEGlobal::debugMsg)
      fprintf(stderr, "Plugin has no GUI\n");
  }
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "Plugin has a GUI\n");

  if(!(plugin->flags & effFlagsCanReplacing))
    fprintf(stderr, "Plugin does not support processReplacing\n");
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "Plugin supports processReplacing\n");

  plugin->dispatcher(plugin, effOpen, 0, 0, NULL, 0);
  
  buffer[0] = 0;
  plugin->dispatcher(plugin, effGetEffectName, 0, 0, buffer, 0);
  if(buffer[0])
    effectName = QString(buffer);

  buffer[0] = 0;
  plugin->dispatcher(plugin, effGetVendorString, 0, 0, buffer, 0);
  if (buffer[0])
    vendorString = QString(buffer);

  buffer[0] = 0;
  plugin->dispatcher(plugin, effGetProductString, 0, 0, buffer, 0);
  if (buffer[0])
    productString = QString(buffer);

  vendorVersion = plugin->dispatcher(plugin, effGetVendorVersion, 0, 0, NULL, 0);

  // Some (older) plugins don't have any of these strings. We only have the filename to use.
  if(effectName.isEmpty())
    effectName = fi.completeBaseName();
  if(productString.isEmpty())
    //productString = fi.completeBaseName();
    productString = effectName;
  
  // Make sure it doesn't already exist.
  for(is = MusEGlobal::synthis.begin(); is != MusEGlobal::synthis.end(); ++is)
    if((*is)->name() == effectName && (*is)->baseName() == fi.completeBaseName())
      goto _ending;
  
  // "2 = VST2.x, older versions return 0". Observed 2400 on all the ones tested so far.
  vst_version = plugin->dispatcher(plugin, effGetVstVersion, 0, 0, NULL, 0.0f);
  if(!((plugin->flags & effFlagsIsSynth) || (vst_version >= 2 && plugin->dispatcher(plugin, effCanDo, 0, 0,(void*) "receiveVstEvents", 0.0f) > 0)))
  {
    if(MusEGlobal::debugMsg)
      fprintf(stderr, "Plugin is not a synth\n");
    goto _ending;  
  }

  new_synth = new VstNativeSynth(fi, plugin, effectName, productString, vendorString, QString::number(vendorVersion)); 
  
  if(MusEGlobal::debugMsg)
    fprintf(stderr, "scanVstNativeLib: adding vst synth plugin:%s name:%s effectName:%s vendorString:%s productString:%s vstver:%d\n",
            fi.filePath().toLatin1().constData(),
            fi.completeBaseName().toLatin1().constData(),
            effectName.toLatin1().constData(),
            vendorString.toLatin1().constData(),
            productString.toLatin1().constData(),
            vst_version
            );

  MusEGlobal::synthis.push_back(new_synth);

_ending: ;
  
  //plugin->dispatcher(plugin, effMainsChanged, 0, 0, NULL, 0);
  plugin->dispatcher(plugin, effClose, 0, 0, NULL, 0);
  dlclose(handle);
}

//---------------------------------------------------------
//   scanVstDir
//---------------------------------------------------------

static void scanVstNativeDir(const QString& s)
{
      if (MusEGlobal::debugMsg)
            fprintf(stderr, "scan vst native plugin dir <%s>\n", s.toLatin1().constData());
      QDir pluginDir(s, QString("*.so"), QDir::Unsorted, QDir::Files);
      if(!pluginDir.exists())
        return;
      QStringList list = pluginDir.entryList();
      int count = list.count();
      for(int i = 0; i < count; ++i)
      {
        if(MusEGlobal::debugMsg)
          fprintf(stderr, "scanVstNativeDir: found %s\n", (s + QString("/") + list[i]).toLatin1().constData());

        QFileInfo fi(s + QString("/") + list[i]);
        scanVstNativeLib(fi);
      }
}

//---------------------------------------------------------
//   initVST_Native
//---------------------------------------------------------

void initVST_Native()
      {
      std::string s;
      const char* vstPath = getenv("VST_NATIVE_PATH");
      if (vstPath)
      {
        if (MusEGlobal::debugMsg)
            fprintf(stderr, "scan native vst: VST_NATIVE_PATH is: %s\n", vstPath);
      }
      else
      {
        if (MusEGlobal::debugMsg)
            fprintf(stderr, "scan native vst: VST_NATIVE_PATH not set\n");
      }
      
      if(!vstPath)
      {
        vstPath = getenv("VST_PATH");
        if (vstPath)
        {
          if (MusEGlobal::debugMsg)
              fprintf(stderr, "scan native vst: VST_PATH is: %s\n", vstPath);
        }
        else
        {
          if (MusEGlobal::debugMsg)
              fprintf(stderr, "scan native vst: VST_PATH not set\n");
          const char* home = getenv("HOME");
          s = std::string(home) + std::string("/vst:/usr/local/lib64/vst:/usr/local/lib/vst:/usr/lib64/vst:/usr/lib/vst");
          vstPath = s.c_str();
          if (MusEGlobal::debugMsg)
              fprintf(stderr, "scan native vst: defaulting to path: %s\n", vstPath);
        }
      }
      
      const char* p = vstPath;
      while (*p != '\0') {
            const char* pe = p;
            while (*pe != ':' && *pe != '\0')
                  pe++;

            int n = pe - p;
            if (n) {
                  char* buffer = new char[n + 1];
                  strncpy(buffer, p, n);
                  buffer[n] = '\0';
                  scanVstNativeDir(QString(buffer));
                  delete[] buffer;
                  }
            p = pe;
            if (*p == ':')
                  p++;
            }
      }

//---------------------------------------------------------
//   VstNativeSynth
//---------------------------------------------------------

VstNativeSynth::VstNativeSynth(const QFileInfo& fi, AEffect* plugin, const QString& label, const QString& desc, const QString& maker, const QString& ver)
  : Synth(fi, label, desc, maker, ver)
{
  _handle = NULL;
  _hasGui = plugin->flags & effFlagsHasEditor;
  _inports = plugin->numInputs;
  _outports = plugin->numOutputs;
  _controlInPorts = plugin->numParams;
  _inPlaceCapable = false; //(plugin->flags & effFlagsCanReplacing) && (_inports == _outports) && MusEGlobal::config.vstInPlace;
#ifndef VST_VESTIGE_SUPPORT
  _hasChunks = plugin->flags & effFlagsProgramChunks;
#else
  _hasChunks = false;
#endif
  
  _flags = 0;
  _vst_version = 0;
  _vst_version = plugin->dispatcher(plugin, effGetVstVersion, 0, 0, NULL, 0.0f);
  // "2 = VST2.x, older versions return 0". Observed 2400 on all the ones tested so far.
  if(_vst_version >= 2)
  {
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"receiveVstEvents", 0.0f) > 0)
      _flags |= canReceiveVstEvents;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"sendVstEvents", 0.0f) > 0)
      _flags |= canSendVstEvents;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"sendVstMidiEvent", 0.0f) > 0)
      _flags |= canSendVstMidiEvents;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"sendVstTimeInfo", 0.0f) > 0)
      _flags |= canSendVstTimeInfo;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"receiveVstMidiEvent", 0.0f) > 0)
      _flags |= canReceiveVstMidiEvents;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"receiveVstTimeInfo", 0.0f) > 0)
      _flags |= canReceiveVstTimeInfo;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"offline", 0.0f) > 0)
      _flags |=canProcessOffline;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"plugAsChannelInsert", 0.0f) > 0)
      _flags |= canUseAsInsert;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"plugAsSend", 0.0f) > 0)
      _flags |= canUseAsSend;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"mixDryWet", 0.0f) > 0)
      _flags |= canMixDryWet;
    if(plugin->dispatcher(plugin, effCanDo, 0, 0, (void*)"midiProgramNames", 0.0f) > 0)
      _flags |= canMidiProgramNames;
  }
}

//---------------------------------------------------------
//   incInstances
//---------------------------------------------------------

void VstNativeSynth::incInstances(int val)
{
  _instances += val;
  if(_instances == 0)
  {
    if(_handle)
    {
      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynth::incInstances no more instances, closing library\n");
      #endif

      dlclose(_handle);
    }
    _handle = NULL;
    iIdx.clear();
    oIdx.clear();
    rpIdx.clear();
    midiCtl2PortMap.clear();
    port2MidiCtlMap.clear();
  }
}

//---------------------------------------------------------
//   instantiate
//---------------------------------------------------------

AEffect* VstNativeSynth::instantiate(VstNativeSynthIF* sif)
{
  int inst_num = _instances;
  inst_num++;
  QString n;
  n.setNum(inst_num);
  QString instanceName = baseName() + "-" + n;
  QByteArray ba = info.filePath().toLatin1();
  const char* path = ba.constData();
  void* hnd = _handle;
  int vst_version;

  if(hnd == NULL)
  {
    hnd = dlopen(path, RTLD_NOW);
    if(hnd == NULL)
    {
      fprintf(stderr, "dlopen(%s) failed: %s\n", path, dlerror());
      return NULL;
    }
  }

  AEffect *(*getInstance)(audioMasterCallback);
  getInstance = (AEffect*(*)(audioMasterCallback))dlsym(hnd, NEW_PLUGIN_ENTRY_POINT);
  if(!getInstance)
  {
    if(MusEGlobal::debugMsg)
    {
      fprintf(stderr, "VST 2.4 entrypoint \"" NEW_PLUGIN_ENTRY_POINT "\" not found in library %s, looking for \""
                      OLD_PLUGIN_ENTRY_POINT "\"\n", path);
    }

    getInstance = (AEffect*(*)(audioMasterCallback))dlsym(hnd, OLD_PLUGIN_ENTRY_POINT);
    if(!getInstance)
    {
      fprintf(stderr, "ERROR: VST entrypoints \"" NEW_PLUGIN_ENTRY_POINT "\" or \""
                      OLD_PLUGIN_ENTRY_POINT "\" not found in library\n");
      dlclose(hnd);
      return NULL;
    }
    else if(MusEGlobal::debugMsg)
    {
      fprintf(stderr, "VST entrypoint \"" OLD_PLUGIN_ENTRY_POINT "\" found\n");
    }
  }
  else if(MusEGlobal::debugMsg)
  {
    fprintf(stderr, "VST entrypoint \"" NEW_PLUGIN_ENTRY_POINT "\" found\n");
  }

  AEffect *plugin = getInstance(vstNativeHostCallback);
  if(!plugin)
  {
    fprintf(stderr, "ERROR: Failed to instantiate plugin in VST library \"%s\"\n", path);
    dlclose(hnd);
    return NULL;
  }
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "plugin instantiated\n");

  if(plugin->magic != kEffectMagic)
  {
    fprintf(stderr, "Not a VST plugin in library \"%s\"\n", path);
    dlclose(hnd);
    return NULL;
  }
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "plugin is a VST\n");

  if(!(plugin->flags & effFlagsHasEditor))
  {
    if(MusEGlobal::debugMsg)
      fprintf(stderr, "Plugin has no GUI\n");
  }
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "Plugin has a GUI\n");

  if(!(plugin->flags & effFlagsCanReplacing))
    fprintf(stderr, "Plugin does not support processReplacing\n");
  else if(MusEGlobal::debugMsg)
    fprintf(stderr, "Plugin supports processReplacing\n");

  plugin->user = sif;
  plugin->dispatcher(plugin, effOpen, 0, 0, NULL, 0);

  // "2 = VST2.x, older versions return 0". Observed 2400 on all the ones tested so far.
  vst_version = plugin->dispatcher(plugin, effGetVstVersion, 0, 0, NULL, 0.0f);
  if(!((plugin->flags & effFlagsIsSynth) || (vst_version >= 2 && plugin->dispatcher(plugin, effCanDo, 0, 0,(void*) "receiveVstEvents", 0.0f) > 0)))
  {
    if(MusEGlobal::debugMsg)
      fprintf(stderr, "Plugin is not a synth\n");
    goto _error;
  }

  ++_instances;
  _handle = hnd;

  //plugin->dispatcher(plugin, effSetProgram, 0, 0, NULL, 0.0f); // REMOVE Tim. Or keep?
  return plugin;

_error:
  //plugin->dispatcher(plugin, effMainsChanged, 0, 0, NULL, 0);
  plugin->dispatcher(plugin, effClose, 0, 0, NULL, 0);
  dlclose(hnd);
  return NULL;
}

//---------------------------------------------------------
//   createSIF
//---------------------------------------------------------

SynthIF* VstNativeSynth::createSIF(SynthI* s)
      {
      VstNativeSynthIF* sif = new VstNativeSynthIF(s);
      sif->init(this);
      return sif;
      }
  
//---------------------------------------------------------
//   VstNativeSynthIF
//---------------------------------------------------------

VstNativeSynthIF::VstNativeSynthIF(SynthI* s) : SynthIF(s)
{
      _guiVisible = false;
      _gw = NULL;
      _synth = NULL;
      _plugin = NULL;
      _active = false;
      _editor = NULL;
      _inProcess = false;
       _controls = NULL;
//       controlsOut = 0;
      _audioInBuffers = NULL;
      _audioInSilenceBuf = NULL;
      _audioOutBuffers = NULL;
}

VstNativeSynthIF::~VstNativeSynthIF()
{
  // Just in case it wasn't removed or deactivate3 wasn't called etc...
  if(_plugin)
    fprintf(stderr, "ERROR: ~VstNativeSynthIF: _plugin is not NULL!\n");
  
  if(_audioOutBuffers)
  {
    unsigned long op = _synth->outPorts();
    for(unsigned long i = 0; i < op; ++i)
    {
      if(_audioOutBuffers[i])
        free(_audioOutBuffers[i]);
    }
    delete[] _audioOutBuffers;
  }

  if(_audioInBuffers)
  {
    unsigned long ip = _synth->inPorts();
    for(unsigned long i = 0; i < ip; ++i)
    {
      if(_audioInBuffers[i])
        free(_audioInBuffers[i]);
    }
    delete[] _audioInBuffers;
  }

  if(_audioInSilenceBuf)
    free(_audioInSilenceBuf);
    
  if(_controls)
    delete[] _controls;

  if(_gw)
    delete[] _gw;
}

//---------------------------------------------------------
//   init
//---------------------------------------------------------

bool VstNativeSynthIF::init(Synth* s)
      {
      _synth = (VstNativeSynth*)s;
      _plugin = _synth->instantiate(this);
      if(!_plugin)
        return false;

      queryPrograms();
      
      unsigned long outports = _synth->outPorts();
      if(outports != 0)
      {
        _audioOutBuffers = new float*[outports];
        for(unsigned long k = 0; k < outports; ++k)
        {
          int rv = posix_memalign((void**)&_audioOutBuffers[k], 16, sizeof(float) * MusEGlobal::segmentSize);
          if(rv != 0)
          {
            fprintf(stderr, "ERROR: VstNativeSynthIF::init: posix_memalign returned error:%d. Aborting!\n", rv);
            abort();
          }
          if(MusEGlobal::config.useDenormalBias)
          {
            for(unsigned q = 0; q < MusEGlobal::segmentSize; ++q)
              _audioOutBuffers[k][q] = MusEGlobal::denormalBias;
          }
          else
            memset(_audioOutBuffers[k], 0, sizeof(float) * MusEGlobal::segmentSize);
        }
      }

      unsigned long inports = _synth->inPorts();
      if(inports != 0)
      {
        _audioInBuffers = new float*[inports];
        for(unsigned long k = 0; k < inports; ++k)
        {
          int rv = posix_memalign((void**)&_audioInBuffers[k], 16, sizeof(float) * MusEGlobal::segmentSize);
          if(rv != 0)
          {
            fprintf(stderr, "ERROR: VstNativeSynthIF::init: posix_memalign returned error:%d. Aborting!\n", rv);
            abort();
          }
          if(MusEGlobal::config.useDenormalBias)
          {
            for(unsigned q = 0; q < MusEGlobal::segmentSize; ++q)
              _audioInBuffers[k][q] = MusEGlobal::denormalBias;
          }
          else
            memset(_audioInBuffers[k], 0, sizeof(float) * MusEGlobal::segmentSize);
          _iUsedIdx.push_back(false); // Start out with all false.
        }
        
        int rv = posix_memalign((void**)&_audioInSilenceBuf, 16, sizeof(float) * MusEGlobal::segmentSize);
        if(rv != 0)
        {
          fprintf(stderr, "ERROR: VstNativeSynthIF::init: posix_memalign returned error:%d. Aborting!\n", rv);
          abort();
        }
        if(MusEGlobal::config.useDenormalBias)
        {
          for(unsigned q = 0; q < MusEGlobal::segmentSize; ++q)
            _audioInSilenceBuf[q] = MusEGlobal::denormalBias;
        }
        else
          memset(_audioInSilenceBuf, 0, sizeof(float) * MusEGlobal::segmentSize);
      }

      _controls = NULL;
      _gw = NULL;
      unsigned long controlPorts = _synth->inControls();
      if(controlPorts != 0)
      {
        _controls = new Port[controlPorts];
        _gw       = new VstNativeGuiWidgets[controlPorts];
      }

      for(unsigned long i = 0; i < controlPorts; ++i)
      {
        _gw[i].pressed = false;
        
        _controls[i].idx = i;
        //float val;  // TODO
        //ladspaDefaultValue(ld, k, &val);   // FIXME TODO
        float val = _plugin->getParameter(_plugin, i);  // TODO
        _controls[i].val    = val;
        _controls[i].tmpVal = val;
        _controls[i].enCtrl  = true;

        // Support a special block for synth ladspa controllers.
        // Put the ID at a special block after plugins (far after).
        int id = genACnum(MAX_PLUGINS, i);
        const char* param_name = paramName(i);

        // TODO FIXME!
        ///float min, max;
        ///ladspaControlRange(ld, k, &min, &max);
        float min = 0.0, max = 1.0;

        CtrlList* cl;
        CtrlListList* cll = track()->controller();
        iCtrlList icl = cll->find(id);
        if (icl == cll->end())
        {
          cl = new CtrlList(id);
          cll->add(cl);
          cl->setCurVal(_controls[i].val);
          //cl->setCurVal(_plugin->getParameter(_plugin, i));
        }
        else
        {
          cl = icl->second;
          _controls[i].val = cl->curVal();
          
#ifndef VST_VESTIGE_SUPPORT
          if(dispatch(effCanBeAutomated, i, 0, NULL, 0.0f) == 1)
          {
#endif            
            double v = cl->curVal();
            if(v != _plugin->getParameter(_plugin, i))
              _plugin->setParameter(_plugin, i, v);
#ifndef VST_VESTIGE_SUPPORT
          }

  #ifdef VST_NATIVE_DEBUG
          else  
            fprintf(stderr, "VstNativeSynthIF::init %s parameter:%lu cannot be automated\n", name().toLatin1().constData(), i);
  #endif

#endif
        }
        
        cl->setRange(min, max);
        cl->setName(QString(param_name));
        //cl->setValueType(ladspaCtrlValueType(ld, k));
        cl->setValueType(ctrlValueType(i));
        //cl->setMode(ladspaCtrlMode(ld, k));
        cl->setMode(ctrlMode(i));
      }

      activate();     
      doSelectProgram(synti->_curBankH, synti->_curBankL, synti->_curProgram);
      //doSelectProgram(synti->_curProgram);
      
      return true;
      }

//---------------------------------------------------------
//   resizeEditor
//---------------------------------------------------------

bool VstNativeSynthIF::resizeEditor(int w, int h)
{
  if(!_editor || w <= 0 || h <= 0)
    return false;
  _editor->resize(w, h);
  return true;
}

//---------------------------------------------------------
//   hostCallback
//---------------------------------------------------------

VstIntPtr VstNativeSynthIF::hostCallback(VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
      {
      static VstTimeInfo _timeInfo;

#ifdef VST_NATIVE_DEBUG
      if(opcode != audioMasterGetTime)
        fprintf(stderr, "VstNativeSynthIF::hostCallback %s opcode:%ld\n", name().toLatin1().constData(), opcode);
#endif

      switch (opcode) {
            case audioMasterAutomate:
                  // index, value, returns 0
                  ///_plugin->setParameter (_plugin, index, opt);
                  guiControlChanged(index, opt);
                  return 0;

            case audioMasterVersion:
                  // vst version, currently 2 (0 for older)
                  return 2300;

            case audioMasterCurrentId:
                  // returns the unique id of a plug that's currently
                  // loading
                  ///return 0;
                  return _plugin->uniqueID;

            case audioMasterIdle:
                  // call application idle routine (this will
                  // call effEditIdle for all open editors too)
                  //_plugin->updateParamValues(false);
                  //_plugin->dispatcher(_plugin, effEditIdle, 0, 0, NULL, 0.0f);
                  ///idleEditor();  // REMOVE Tim. Or keep.
                  return 0;

            case audioMasterGetTime:
            {
                  // returns const VstTimeInfo* (or 0 if not supported)
                  // <value> should contain a mask indicating which fields are required
                  // (see valid masks above), as some items may require extensive
                  // conversions

                  // FIXME TODO: Optimizations: This may be called many times in one process call
                  //              due to our multi-run slices. Some of the (costly) info will be redundant.
                  //             So try to add some flag to try to only call some or all of this once per cycle.
                  
#ifdef VST_NATIVE_DEBUG
                  fprintf(stderr, "VstNativeSynthIF::hostCallback master time: valid: nanos:%d ppqpos:%d tempo:%d bars:%d cyclepos:%d sig:%d smpte:%d clock:%d\n",  
                    (bool)(value & kVstNanosValid),
                    (bool)(value & kVstPpqPosValid),
                    (bool)(value & kVstTempoValid),
                    (bool)(value & kVstBarsValid),
                    (bool)(value & kVstCyclePosValid),
                    (bool)(value & kVstTimeSigValid),
                    (bool)(value & kVstSmpteValid),
                    (bool)(value & kVstClockValid));
#endif
                  memset(&_timeInfo, 0, sizeof(_timeInfo));

                  unsigned int curr_frame = MusEGlobal::audio->pos().frame();
                  _timeInfo.samplePos = (double)curr_frame;
                  _timeInfo.sampleRate = (double)MusEGlobal::sampleRate;
                  _timeInfo.flags = 0;

                  Pos p(MusEGlobal::extSyncFlag.value() ? MusEGlobal::audio->tickPos() : curr_frame, MusEGlobal::extSyncFlag.value() ? true : false);

                  if(value & kVstBarsValid)
                  {
                    int p_bar, p_beat, p_tick;
                    p.mbt(&p_bar, &p_beat, &p_tick);
                    _timeInfo.barStartPos = (double)Pos(p_bar, 0, 0).tick() / (double)MusEGlobal::config.division;
                    _timeInfo.flags |= kVstBarsValid;
                  }

                  if(value & kVstTimeSigValid)
                  {
                    int z, n;
                    AL::sigmap.timesig(p.tick(), z, n);

#ifndef VST_VESTIGE_SUPPORT
                    _timeInfo.timeSigNumerator = (long)z;
                    _timeInfo.timeSigDenominator = (long)n;
#else
                    _timeInfo.timeSigNumerator = z;
                    _timeInfo.timeSigDenominator = n;
#endif
                    _timeInfo.flags |= kVstTimeSigValid;
                  }
                  
                  if(value & kVstPpqPosValid)
                  {
                    _timeInfo.ppqPos = (double)MusEGlobal::audio->tickPos() / (double)MusEGlobal::config.division;
                    _timeInfo.flags |= kVstPpqPosValid;
                  }

                  if(value & kVstTempoValid)
                  {
                    double tempo = MusEGlobal::tempomap.tempo(p.tick());
                    _timeInfo.tempo = (60000000.0 / tempo) * double(MusEGlobal::tempomap.globalTempo())/100.0;
                    _timeInfo.flags |= kVstTempoValid;
                  }
                  
#ifdef VST_NATIVE_DEBUG
                  fprintf(stderr, "VstNativeSynthIF::hostCallback master time: sample pos:%f samplerate:%f sig num:%ld den:%ld tempo:%f\n",
                    _timeInfo.samplePos, _timeInfo.sampleRate, _timeInfo.timeSigNumerator, _timeInfo.timeSigDenominator, _timeInfo.tempo);
#endif
                 
                  if(MusEGlobal::audio->isPlaying())
                    _timeInfo.flags |= (kVstTransportPlaying | kVstTransportChanged);
                  // TODO
                  //if(MusEGlobal::audio->isRecording())
                  //  _timeInfo.flags |= (kVstTransportRecording | kVstTransportChanged);
                  
                  return (long)&_timeInfo;
            }
            
            case audioMasterProcessEvents:
                  // VstEvents* in <ptr>
                  return 0;  // TODO:

            case audioMasterIOChanged:
                   // numInputs and/or numOutputs has changed
                  return 0;

            case audioMasterSizeWindow:
                  // index: width, value: height
                  if(resizeEditor(int(index), int(value)))
                    return 1; // supported.
                  return 0;

            case audioMasterGetSampleRate:
                  //return 0;
                  return MusEGlobal::sampleRate;

            case audioMasterGetBlockSize:
                  //return 0;
                  return MusEGlobal::segmentSize;

            case audioMasterGetInputLatency:
                  return 0;

            case audioMasterGetOutputLatency:
                  return 0;

            case audioMasterGetCurrentProcessLevel:
                  // returns: 0: not supported,
                  // 1: currently in user thread (gui)
                  // 2: currently in audio thread (where process is called)
                  // 3: currently in 'sequencer' thread (midi, timer etc)
                  // 4: currently offline processing and thus in user thread
                  // other: not defined, but probably pre-empting user thread.
                  if(_inProcess)
                    return 2;
                  else
                    return 1;

            case audioMasterGetAutomationState:
                  // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
                  // offline
                  return 1;   // TODO:

            case audioMasterOfflineStart:
            case audioMasterOfflineRead:
                   // ptr points to offline structure, see below. return 0: error, 1 ok
                  return 0;

            case audioMasterOfflineWrite:
                  // same as read
                  return 0;

            case audioMasterOfflineGetCurrentPass:
            case audioMasterOfflineGetCurrentMetaPass:
                  return 0;

            case audioMasterGetVendorString:
                  // fills <ptr> with a string identifying the vendor (max 64 char)
                  strcpy ((char*) ptr, "MusE");
                  return 1;

            case audioMasterGetProductString:
                  // fills <ptr> with a string with product name (max 64 char)
                  strcpy ((char*) ptr, "MusE Sequencer");
                  return 1;

            case audioMasterGetVendorVersion:
                  // returns vendor-specific version
                  return 2000;

            case audioMasterVendorSpecific:
                  // no definition, vendor specific handling
                  return 0;

            case audioMasterCanDo:
                  // string in ptr, see below
                  if(!strcmp((char*)ptr, "sendVstEvents") ||          
                     !strcmp((char*)ptr, "receiveVstMidiEvent") ||   
                     !strcmp((char*)ptr, "sendVstMidiEvent") ||
                     !strcmp((char*)ptr, "sendVstTimeInfo") ||        
                     !strcmp((char*)ptr, "sizeWindow") ||
                     !strcmp((char*)ptr, "supplyIdle"))               
                    return 1;

#if 0 //ifndef VST_VESTIGE_SUPPORT
                  else
                  if(!strcmp((char*)ptr, "openFileSelector") ||       
                     !strcmp((char*)ptr, "closeFileSelector"))        
                    return 1;
#endif
                  return 0;

            case audioMasterGetLanguage:
                  // see enum
                  //return 0;
                  return kVstLangEnglish;

            case audioMasterGetDirectory:
                  // get plug directory, FSSpec on MAC, else char*
                  return 0;

            case audioMasterUpdateDisplay:
                  // something has changed, update 'multi-fx' display

                  //_plugin->updateParamValues(false);   
                  //QApplication::processEvents();     // REMOVE Tim. Or keep. Commented in QTractor.

                  _plugin->dispatcher(_plugin, effEditIdle, 0, 0, NULL, 0.0f);  // ?
                  
                  return 0;

            case audioMasterBeginEdit:
                  // begin of automation session (when mouse down), parameter index in <index>
                  guiAutomationBegin(index);
                  return 1;  

            case audioMasterEndEdit:
                  // end of automation session (when mouse up),     parameter index in <index>
                  guiAutomationEnd(index);
                  return 1;  

#if 0 //ifndef VST_VESTIGE_SUPPORT
            case audioMasterOpenFileSelector:
                  // open a fileselector window with VstFileSelect* in <ptr>
                  return 0;
                  
            case audioMasterCloseFileSelector:
                  return 0;
#endif

#ifdef VST_FORCE_DEPRECATED
                  
            case audioMasterGetSpeakerArrangement:
                  // (long)input in <value>, output in <ptr>
                  return 0;

            case audioMasterPinConnected:
                  // inquire if an input or output is beeing connected;
                  // index enumerates input or output counting from zero:
                  // value is 0 for input and != 0 otherwise. note: the
                  // return value is 0 for <true> such that older versions
                  // will always return true.
                  //return 1;
                  return 0;

            // VST 2.0 opcodes...
            case audioMasterWantMidi:
                  // <value> is a filter which is currently ignored
                  return 0;

            case audioMasterSetTime:
                  // VstTimenfo* in <ptr>, filter in <value>, not supported
                  return 0;

            case audioMasterTempoAt:
                  // returns tempo (in bpm * 10000) at sample frame location passed in <value>
                  return 0;  // TODO:

            case audioMasterGetNumAutomatableParameters:
                  return 0;

            case audioMasterGetParameterQuantization:
                     // returns the integer value for +1.0 representation,
                   // or 1 if full single float precision is maintained
                     // in automation. parameter index in <value> (-1: all, any)
                  //return 0;
                  return 1;

            case audioMasterNeedIdle:
                   // plug needs idle calls (outside its editor window)
                  return 0;

            case audioMasterGetPreviousPlug:
                   // input pin in <value> (-1: first to come), returns cEffect*
                  return 0;

            case audioMasterGetNextPlug:
                   // output pin in <value> (-1: first to come), returns cEffect*
                  return 0;

            case audioMasterWillReplaceOrAccumulate:
                   // returns: 0: not supported, 1: replace, 2: accumulate
                  //return 0;
                  return 1;

            case audioMasterSetOutputSampleRate:
                  // for variable i/o, sample rate in <opt>
                  return 0;

            case audioMasterSetIcon:
                  // void* in <ptr>, format not defined yet
                  return 0;

            case audioMasterOpenWindow:
                  // returns platform specific ptr
                  return 0;

            case audioMasterCloseWindow:
                  // close window, platform specific handle in <ptr>
                  return 0;
#endif

                  
            default:
                  break;
            }
      return 0;
      }
      
//---------------------------------------------------------
//   idleEditor
//---------------------------------------------------------

void VstNativeSynthIF::idleEditor()
{
#ifdef VST_NATIVE_DEBUG
  fprintf(stderr, "VstNativeSynthIF::idleEditor %p\n", this);
#endif

  // REMOVE Tim. Or keep.
  //_plugin->dispatcher(_plugin, effEditIdle, 0, 0, NULL, 0.0f);
  //if(_editor)
  //  _editor->update();
}

//---------------------------------------------------------
//   guiHeartBeat
//---------------------------------------------------------

void VstNativeSynthIF::guiHeartBeat()
{
#ifdef VST_NATIVE_DEBUG
  fprintf(stderr, "VstNativeSynthIF::guiHeartBeat %p\n", this);
#endif

  // REMOVE Tim. Or keep.
  if(_plugin && _active)
  {
//#ifdef VST_FORCE_DEPRECATED   // REMOVE Tim. Or keep
    //_plugin->dispatcher(_plugin, effIdle, 0, 0, NULL, 0.0f);
//#endif
     if(_guiVisible)
     {
       _plugin->dispatcher(_plugin, effEditIdle, 0, 0, NULL, 0.0f);
       if(_editor)
         _editor->update();
     }
  }
}

//---------------------------------------------------------
//   nativeGuiVisible
//---------------------------------------------------------

bool VstNativeSynthIF::nativeGuiVisible() const
      {
      return _guiVisible;
      }

//---------------------------------------------------------
//   guiVisible
//---------------------------------------------------------

bool VstNativeSynthIF::guiVisible() const
      {
      return _gui && _gui->isVisible();
      }

//---------------------------------------------------------
//   showGui
//---------------------------------------------------------

void VstNativeSynthIF::showGui(bool v)
{
    if (v) {
            if (_gui == 0)
                makeGui();
            _gui->show();
            }
    else {
            if (_gui)
                _gui->hide();
            }
}

//---------------------------------------------------------
//   showGui
//---------------------------------------------------------

void VstNativeSynthIF::showNativeGui(bool v)
      {
      if(!(_plugin->flags & effFlagsHasEditor)) // || v == nativeGuiVisible())
            return;
      if(v)
      {
        if(_editor)
        {
          if(!_editor->isVisible())
            _editor->show();
          _editor->raise();
          _editor->activateWindow();
        }
        else
        {
          Qt::WindowFlags wflags = Qt::Window
                  | Qt::CustomizeWindowHint
                  | Qt::WindowTitleHint
                  | Qt::WindowSystemMenuHint
                  | Qt::WindowMinMaxButtonsHint
                  | Qt::WindowCloseButtonHint;
          _editor = new MusEGui::VstNativeEditor(NULL, wflags);
          _editor->open(this);
        }
      }
      else
      {
        if(_editor)
        {
          delete _editor;
          //_editor = NULL;  // No - done in editorDeleted.
        }
      }
      _guiVisible = v;
}

//---------------------------------------------------------
//   getGeometry
//---------------------------------------------------------

void VstNativeSynthIF::getGeometry(int*x, int*y, int*w, int*h) const
{
  if(!_gui)
  {
    *x=0;*y=0;*w=0;*h=0;
    return;
  }

  *x = _gui->x();
  *y = _gui->y();
  *w = _gui->width();
  *h = _gui->height();
}

//---------------------------------------------------------
//   setGeometry
//---------------------------------------------------------

void VstNativeSynthIF::setGeometry(int x, int y, int w, int h)
{
  if(!_gui)
    return;

  _gui->setGeometry(x, y, w, h);
}

//---------------------------------------------------------
//   editorOpened
//---------------------------------------------------------

void VstNativeSynthIF::getNativeGeometry(int*x, int*y, int*w, int*h) const
{
  if(!_editor)
  {
    *x=0;*y=0;*w=0;*h=0;
    return;
  }
  
  *x = _editor->x();
  *y = _editor->y();
  *w = _editor->width();
  *h = _editor->height();
}

//---------------------------------------------------------
//   editorOpened
//---------------------------------------------------------

void VstNativeSynthIF::setNativeGeometry(int x, int y, int w, int h)
{
  if(!_editor)
    return;

  _editor->setGeometry(x, y, w, h);
}

//---------------------------------------------------------
//   editorOpened
//---------------------------------------------------------

void VstNativeSynthIF::editorOpened()
{
  _guiVisible = true;
}

//---------------------------------------------------------
//   editorClosed
//---------------------------------------------------------

void VstNativeSynthIF::editorClosed()
{
  _guiVisible = false;
}

//---------------------------------------------------------
//   editorDeleted
//---------------------------------------------------------

void VstNativeSynthIF::editorDeleted()
{
  _editor = NULL;
}

//---------------------------------------------------------
//   receiveEvent
//---------------------------------------------------------

MidiPlayEvent VstNativeSynthIF::receiveEvent()
      {
      return MidiPlayEvent();
      }

//---------------------------------------------------------
//   hasGui
//---------------------------------------------------------

bool VstNativeSynthIF::hasNativeGui() const
      {
      return _plugin->flags & effFlagsHasEditor;
      }

//---------------------------------------------------------
//   channels
//---------------------------------------------------------

int VstNativeSynthIF::channels() const
      {
      return _plugin->numOutputs > MAX_CHANNELS ? MAX_CHANNELS : _plugin->numOutputs ;
      }

int VstNativeSynthIF::totalOutChannels() const
      {
      return _plugin->numOutputs;
      }

int VstNativeSynthIF::totalInChannels() const
      {
      return _plugin->numInputs;
      }

//---------------------------------------------------------
//   deactivate3
//---------------------------------------------------------

void VstNativeSynthIF::deactivate3()
      {
      if(_editor)
      {
        delete _editor;
        _editor = NULL;
        _guiVisible = false;
      }

      deactivate();
      if (_plugin) {
            _plugin->dispatcher (_plugin, effClose, 0, 0, NULL, 0);
            _plugin = NULL;
            }
      }

//---------------------------------------------------------
//   queryPrograms
//---------------------------------------------------------

void VstNativeSynthIF::queryPrograms()
{
      char buf[256];
      programs.clear();
      int num_progs = _plugin->numPrograms;
      int iOldIndex = dispatch(effGetProgram, 0, 0, NULL, 0.0f);
      bool need_restore = false;
      for(int prog = 0; prog < num_progs; ++prog)
      {
        buf[0] = 0;

//#ifndef VST_VESTIGE_SUPPORT
        // value = category. -1 = regular linear.
        if(dispatch(effGetProgramNameIndexed, prog, -1, buf, 0.0f) == 0)  
        {
//#endif
          dispatch(effSetProgram, 0, prog, NULL, 0.0f);
          dispatch(effGetProgramName, 0, 0, buf, 0.0f);
          need_restore = true;
//#ifndef VST_VESTIGE_SUPPORT
        }
//#endif

        int bankH = (prog >> 14) & 0x7f;
        int bankL = (prog >> 7) & 0x7f;
        int patch = prog & 0x7f;
        VST_Program p;
        p.name    = QString(buf);
        //p.program = prog & 0x7f;
        //p.bank    = prog << 7;
        p.program = (bankH << 16) | (bankL << 8) | patch;
        programs.push_back(p);
      }

      // Restore current program.
      if(need_restore) // && num_progs > 0)
      { 
        dispatch(effSetProgram, 0, iOldIndex, NULL, 0.0f);
        fprintf(stderr, "FIXME: VstNativeSynthIF::queryPrograms(): effGetProgramNameIndexed returned 0. Used ugly effSetProgram/effGetProgramName instead\n");
      }
}

//---------------------------------------------------------
//   doSelectProgram
//---------------------------------------------------------

void VstNativeSynthIF::doSelectProgram(int bankH, int bankL, int prog)
{
  if(!_plugin)
    return;

#ifdef VST_NATIVE_DEBUG
  fprintf(stderr, "VstNativeSynthIF::doSelectProgram bankH:%d bankL:%d prog:%d\n", bankH, bankL, prog);
#endif

  if(bankH == 0xff)
    bankH = 0;
  if(bankL == 0xff)
    bankL = 0;
  if(prog == 0xff)
    prog = 0;
  
  int p = (bankH << 14) | (bankL << 7) | prog;

  if(p >= _plugin->numPrograms)
  {
    fprintf(stderr, "VstNativeSynthIF::doSelectProgram program:%d out of range\n", p);
    return;
  }
  
  //for (unsigned short i = 0; i < instances(); ++i)
  //{
    // "host calls this before a new program (effSetProgram) is loaded"
#ifndef VST_VESTIGE_SUPPORT
    //if(dispatch(effBeginSetProgram, 0, 0, NULL, 0.0f) == 1)  // TESTED: Usually it did not acknowledge. So IGNORE it.
    dispatch(effBeginSetProgram, 0, 0, NULL, 0.0f);
    //{
#endif      
      dispatch(effSetProgram, 0, p, NULL, 0.0f);
      //dispatch(effSetProgram, 0, prog, NULL, 0.0f);
      // "host calls this after the new program (effSetProgram) has been loaded"
#ifndef VST_VESTIGE_SUPPORT
      dispatch(effEndSetProgram, 0, 0, NULL, 0.0f);
    //}
    //else
    //  fprintf(stderr, "VstNativeSynthIF::doSelectProgram bankH:%d bankL:%d prog:%d Effect did not acknowledge effBeginSetProgram\n", bankH, bankL, prog);
#endif
  //}
    
  // TODO: Is this true of VSTs? See the similar section in dssihost.cpp  // REMOVE Tim.
  //   "A plugin is permitted to re-write the values of its input control ports when select_program is called.
  //    The host should re-read the input control port values and update its own records appropriately.
  //    (This is the only circumstance in which a DSSI plugin is allowed to modify its own input ports.)"   From dssi.h
  // Need to update the automation value, otherwise it overwrites later with the last automation value.
  if(id() != -1)
  {
    const unsigned long sic = _synth->inControls();
    for(unsigned long k = 0; k < sic; ++k)
    {
      // We're in the audio thread context: no need to send a message, just modify directly.
      //synti->setPluginCtrlVal(genACnum(id(), k), _controls[k].val);
      //synti->setPluginCtrlVal(genACnum(id(), k), _plugin->getParameter(_plugin, k));
      const float v = _plugin->getParameter(_plugin, k);
      _controls[k].val = v;
      synti->setPluginCtrlVal(genACnum(id(), k), v);
    }
  }

//   // Reset parameters default value...   // TODO ? 
//   AEffect *pVstEffect = vst_effect(0);
//   if (pVstEffect) {
//           const qtractorPlugin::Params& params = qtractorPlugin::params();
//           qtractorPlugin::Params::ConstIterator param = params.constBegin();
//           for ( ; param != params.constEnd(); ++param) {
//                   qtractorPluginParam *pParam = param.value();
//                   float *pfValue = pParam->subject()->data();
//                   *pfValue = pVstEffect->getParameter(pVstEffect, pParam->index());
//                   pParam->setDefaultValue(*pfValue);
//           }
//   }
  
}

//---------------------------------------------------------
//   getPatchName
//---------------------------------------------------------

QString VstNativeSynthIF::getPatchName(int /*chan*/, int prog, bool /*drum*/) const
{
  unsigned long  program = prog & 0x7f;
  unsigned long  lbank   = (prog >> 8) & 0xff;
  unsigned long  hbank   = (prog >> 16) & 0xff;
  if (lbank == 0xff)
        lbank = 0;
  if (hbank == 0xff)
        hbank = 0;
  unsigned long p = (hbank << 16) | (lbank << 8) | program;
  unsigned long vp          = (hbank << 14) | (lbank << 7) | program;
  //if((int)vp < _plugin->numPrograms)
  if(vp < programs.size())
  {
    for(std::vector<VST_Program>::const_iterator i = programs.begin(); i != programs.end(); ++i)
    {
      if(i->program == p)
        return i->name;
    }
  }
  return "?";
}

//---------------------------------------------------------
//   populatePatchPopup
//---------------------------------------------------------

void VstNativeSynthIF::populatePatchPopup(MusEGui::PopupMenu* menu, int /*chan*/, bool /*drum*/)
{
  // The plugin can change the programs, patches etc.
  // So make sure we're up to date by calling queryPrograms.
  queryPrograms();
  
  menu->clear();

  for (std::vector<VST_Program>::const_iterator i = programs.begin(); i != programs.end(); ++i)
       {
        //int bank = i->bank;
        int prog = i->program;
        //int id   = (bank << 7) + prog;

        QAction *act = menu->addAction(i->name);
        //act->setData(id);
        act->setData(prog);
        }

}

//---------------------------------------------------------
//   getParameter
//---------------------------------------------------------

float VstNativeSynthIF::getParameter(unsigned long idx) const
      {
      if(idx >= _synth->inControls())
      {
        fprintf(stderr, "VstNativeSynthIF::getParameter param number %lu out of range of ports:%lu\n", idx, _synth->inControls());
        return 0.0;
      }

      return _plugin->getParameter(_plugin, idx);
      }

//---------------------------------------------------------
//   setParameter
//---------------------------------------------------------

void VstNativeSynthIF::setParameter(unsigned long idx, float value)
      {
      addScheduledControlEvent(idx, value, MusEGlobal::audio->curFrame());
      }

//---------------------------------------------------------
//   guiAutomationBegin
//---------------------------------------------------------

void VstNativeSynthIF::guiAutomationBegin(unsigned long param_idx)
{
  _gw[param_idx].pressed = true;
  AudioTrack* t = track();
  int plug_id = id();
  if(t && plug_id != -1)
  {
    plug_id = genACnum(plug_id, param_idx);

    //if(params[param].type == GuiParam::GUI_SLIDER)
    //{
      //double val = ((Slider*)params[param].actuator)->value();
      float val = param(param_idx);
      // FIXME TODO:
      //if (LADSPA_IS_HINT_LOGARITHMIC(params[param].hint))
      //      val = pow(10.0, val/20.0);
      //else if (LADSPA_IS_HINT_INTEGER(params[param].hint))
      //      val = rint(val);
      //plugin->setParam(param, val);
      //((DoubleLabel*)params[param].label)->setValue(val);

      //if(t)
      //{
        t->startAutoRecord(plug_id, val);
        t->setPluginCtrlVal(plug_id, val);
      //}
    //}
  //   else if(params[param].type == GuiParam::GUI_SWITCH)
  //   {
  //     float val = (float)((CheckBox*)params[param].actuator)->isChecked();
  //     plugin->setParam(param, val);
  //
  //     //if(t)
  //     //{
  //       t->startAutoRecord(plug_id, val);
  //       t->setPluginCtrlVal(plug_id, val);
  //     //}
  //   }
  }
  enableController(param_idx, false);
}

//---------------------------------------------------------
//   guiAutomationEnd
//---------------------------------------------------------

void VstNativeSynthIF::guiAutomationEnd(unsigned long param_idx)
{
  AutomationType at = AUTO_OFF;
  AudioTrack* t = track();
  if(t)
    at = t->automationType();

  int plug_id = id();
  if(t && plug_id != -1)
  {
    plug_id = genACnum(plug_id, param_idx);

    //if(params[param].type == GuiParam::GUI_SLIDER)
    //{
      //double val = ((Slider*)params[param].actuator)->value();
      float val = param(param_idx);
      // FIXME TODO:
      //if (LADSPA_IS_HINT_LOGARITHMIC(params[param].hint))
      //      val = pow(10.0, val/20.0);
      //else if (LADSPA_IS_HINT_INTEGER(params[param].hint))
      //      val = rint(val);
      t->stopAutoRecord(plug_id, val);
    //}
  }

  // Special for switch - don't enable controller until transport stopped.
  if ((at == AUTO_OFF) ||
      (at == AUTO_TOUCH)) // && (params[param].type != GuiParam::GUI_SWITCH ||  // FIXME TODO
                         //   !MusEGlobal::audio->isPlaying()) ) )
    enableController(param_idx, true);
  
  _gw[param_idx].pressed = false;
}

//---------------------------------------------------------
//   guiControlChanged
//---------------------------------------------------------

int VstNativeSynthIF::guiControlChanged(unsigned long param_idx, float value)
{
  #ifdef VST_NATIVE_DEBUG
  fprintf(stderr, "VstNativeSynthIF::guiControlChanged received oscControl port:%lu val:%f\n", param_idx, value);
  #endif

  if(param_idx >= _synth->inControls())
  {
    fprintf(stderr, "VstNativeSynthIF::guiControlChanged: port number:%lu is out of range of index list size:%lu\n", param_idx, _synth->inControls());
    return 0;
  }

  // Record automation:
  // Take care of this immediately rather than in the fifo processing.
  if(id() != -1)
  {
    unsigned long pid = genACnum(id(), param_idx);
    synti->recordAutomation(pid, value);
  }

  // Schedules a timed control change:
  ControlEvent ce;
  ce.unique = false; // Not used for native vst.
  ce.fromGui = true; // It came from the plugin's own GUI.
  ce.idx = param_idx;
  ce.value = value;
  // Don't use timestamp(), because it's circular, which is making it impossible to deal
  // with 'modulo' events which slip in 'under the wire' before processing the ring buffers.
  ce.frame = MusEGlobal::audio->curFrame();

  if(_controlFifo.put(ce))
    fprintf(stderr, "VstNativeSynthIF::guiControlChanged: fifo overflow: in control number:%lu\n", param_idx);

  enableController(param_idx, false);
  
  return 0;
}

//---------------------------------------------------------
//   write
//---------------------------------------------------------

void VstNativeSynthIF::write(int level, Xml& xml) const
{
#ifndef VST_VESTIGE_SUPPORT
  if(_synth->hasChunks())
  {
    //---------------------------------------------
    // dump current state of synth
    //---------------------------------------------
    fprintf(stderr, "%s: commencing chunk data dump, plugin api version=%d\n", name().toLatin1().constData(), _synth->vstVersion());
    unsigned long len = 0;
    void* p = 0;
    len = dispatch(effGetChunk, 0, 0, &p, 0.0); // index 0: is bank 1: is program
    if (len)
    {
      xml.tag(level++, "midistate version=\"%d\"", SYNTH_MIDI_STATE_SAVE_VERSION);
      xml.nput(level++, "<event type=\"%d\"", Sysex);
      // 10 = 2 bytes header + "VSTSAVE" + 1 byte flags (compression etc)
      xml.nput(" datalen=\"%d\">\n", len+10);
      xml.nput(level, "");
      xml.nput("%02x %02x ", (char)MUSE_SYNTH_SYSEX_MFG_ID, (char)VST_NATIVE_SYNTH_UNIQUE_ID); // Wrap in a proper header
      xml.nput("56 53 54 53 41 56 45 "); // embed a save marker "string 'VSTSAVE'
      xml.nput("%02x ", (char)0); // No flags yet, only uncompressed supported for now. TODO
      for (unsigned long int i = 0; i < len; ++i)
      {
        if (i && (((i+10) % 16) == 0))
        {
          xml.nput("\n");
          xml.nput(level, "");
        }
        xml.nput("%02x ", ((char*)(p))[i] & 0xff);
      }
      xml.nput("\n");
      xml.tag(level--, "/event");
      xml.etag(level--, "midistate");
    }
  }
#else
  fprintf(stderr, "support for vst chunks not compiled in!\n");
#endif

  //---------------------------------------------
  // dump current state of synth
  //---------------------------------------------

  int params = _plugin->numParams;
  for (int i = 0; i < params; ++i)
  {
    float f = _plugin->getParameter(_plugin, i);
    xml.floatTag(level, "param", f);
  }
}

//---------------------------------------------------------
//   getData
//---------------------------------------------------------

void VstNativeSynthIF::setVstEvent(VstMidiEvent* event, int a, int b, int c, int d)
{
  event->type         = kVstMidiType;
  event->byteSize     = 24;
  event->deltaFrames  = 0;
  event->flags        = 0;
  event->detune       = 0;
  event->noteLength   = 0;
  event->noteOffset   = 0;
  event->reserved1    = 0;
  event->reserved2    = 0;
  event->noteOffVelocity = 0;
  event->midiData[0]  = a;
  event->midiData[1]  = b;
  event->midiData[2]  = c;
  event->midiData[3]  = d;
}

//---------------------------------------------------------
//   getData
//---------------------------------------------------------

bool VstNativeSynthIF::processEvent(const MidiPlayEvent& e, VstMidiEvent* event)
{
  int type = e.type();
  int chn = e.channel();
  int a   = e.dataA();
  int b   = e.dataB();

  #ifdef VST_NATIVE_DEBUG
  fprintf(stderr, "VstNativeSynthIF::processEvent midi event type:%d chn:%d a:%d b:%d\n", type, chn, a, b);
  #endif

  switch(type)
  {
    case ME_NOTEON:
      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_NOTEON\n");
      #endif
      setVstEvent(event, (type | chn) & 0xff, a & 0x7f, b & 0x7f);
    break;
    case ME_NOTEOFF:
      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_NOTEOFF\n");
      #endif
      setVstEvent(event, (type | chn) & 0xff, a & 0x7f, 0);
    break;
    case ME_PROGRAM:
    {
      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_PROGRAM\n");
      #endif

      int bankH = (a >> 16) & 0xff;
      int bankL = (a >> 8) & 0xff;
      int prog = a & 0xff;
      synti->_curBankH = bankH;
      synti->_curBankL = bankL;
      synti->_curProgram = prog;
      doSelectProgram(bankH, bankL, prog);
      return false;  // Event pointer not filled. Return false.
    }
    break;
    case ME_CONTROLLER:
    {
      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_CONTROLLER\n");
      #endif

      if((a == 0) || (a == 32))
        return false;

      if(a == CTRL_PROGRAM)
      {
        #ifdef VST_NATIVE_DEBUG
        fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_CONTROLLER, dataA is CTRL_PROGRAM\n");
        #endif

        int bankH = (b >> 16) & 0xff;
        int bankL = (b >> 8) & 0xff;
        int prog = b & 0xff;

        synti->_curBankH = bankH;
        synti->_curBankL = bankL;
        synti->_curProgram = prog;
        doSelectProgram(bankH, bankL, prog);
        return false; // Event pointer not filled. Return false.
      }

      if(a == CTRL_PITCH)
      {
        #ifdef VST_NATIVE_DEBUG
        fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_CONTROLLER, dataA is CTRL_PITCH\n");
        #endif
        int v = b + 8192;
        setVstEvent(event, (type | chn) & 0xff, v & 0x7f, (v >> 7) & 0x7f);
        return true;
      }

      if(a == CTRL_AFTERTOUCH)
      {
        #ifdef VST_NATIVE_DEBUG
        fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_CONTROLLER, dataA is CTRL_AFTERTOUCH\n");
        #endif
        setVstEvent(event, (type | chn) & 0xff, b & 0x7f);
        return true;
      }

      if((a | 0xff)  == CTRL_POLYAFTER)
      {
        #ifdef VST_NATIVE_DEBUG
        fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_CONTROLLER, dataA is CTRL_POLYAFTER\n");
        #endif
        setVstEvent(event, (type | chn) & 0xff, a & 0x7f, b & 0x7f);
        return true;
      }

      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_CONTROLLER, dataA is:%d\n", a);
      #endif
      
      // Regular controller. Pass it on.
      setVstEvent(event, (type | chn) & 0xff, a & 0x7f, b & 0x7f);
      
      return true; 

// REMOVE Tim. Or keep. TODO For native vsts? Or not...
//      
//       const LADSPA_Descriptor* ld = dssi->LADSPA_Plugin;
// 
//       ciMidiCtl2LadspaPort ip = synth->midiCtl2PortMap.find(a);
//       // Is it just a regular midi controller, not mapped to a LADSPA port (either by the plugin or by us)?
//       // NOTE: There's no way to tell which of these controllers is supported by the plugin.
//       // For example sustain footpedal or pitch bend may be supported, but not mapped to any LADSPA port.
//       if(ip == synth->midiCtl2PortMap.end())
//       {
//         int ctlnum = a;
//         if(midiControllerType(a) != MidiController::Controller7)
//           return false;   // Event pointer not filled. Return false.
//         else
//         {
//                 #ifdef VST_NATIVE_DEBUG
//                 fprintf(stderr, "VstNativeSynthIF::processEvent non-ladspa midi event is Controller7. Current dataA:%d\n", a);
//                 #endif
//                 a &= 0x7f;
//                 ctlnum = DSSI_CC_NUMBER(ctlnum);
//         }
// 
//         // Fill the event.
//         #ifdef VST_NATIVE_DEBUG
//        fprintf(stderr, "VstNativeSynthIF::processEvent non-ladspa filling midi event chn:%d dataA:%d dataB:%d\n", chn, a, b);
//         #endif
//         snd_seq_ev_clear(event);
//         event->queue = SND_SEQ_QUEUE_DIRECT;
//         snd_seq_ev_set_controller(event, chn, a, b);
//         return true;
//       }
// 
//       unsigned long k = ip->second;
//       unsigned long i = controls[k].idx;
//       int ctlnum = DSSI_NONE;
//       if(dssi->get_midi_controller_for_port)
//         ctlnum = dssi->get_midi_controller_for_port(handle, i);
// 
//       // No midi controller for the ladspa port? Send to ladspa control.
//       if(ctlnum == DSSI_NONE)
//       {
//         // Sanity check.
//         if(k > synth->_controlInPorts)
//           return false;
// 
//         // Simple but flawed solution: Start them at 0x60000 + 0x2000 = 0x62000. Max NRPN number is 0x3fff.
//         ctlnum = k + (CTRL_NRPN14_OFFSET + 0x2000);
//       }
//       else
//       {
//         #ifdef VST_NATIVE_DEBUG
//         fprintf(stderr, "VstNativeSynthIF::processEvent plugin requests DSSI-style ctlnum:%x(h) %d(d) be mapped to control port:%lu...\n", ctlnum, ctlnum, i);
//         #endif
// 
//         int c = ctlnum;
//         // Can be both CC and NRPN! Prefer CC over NRPN.
//         if(DSSI_IS_CC(ctlnum))
//         {
//           ctlnum = DSSI_CC_NUMBER(c);
// 
//           #ifdef VST_NATIVE_DEBUG
//           fprintf(stderr, "VstNativeSynthIF::processEvent is CC ctlnum:%d\n", ctlnum);
//           #endif
// 
//           #ifdef VST_NATIVE_DEBUG
//           if(DSSI_IS_NRPN(ctlnum))
//             fprintf(stderr, "VstNativeSynthIF::processEvent is also NRPN control. Using CC.\n");
//           #endif
//         }
//         else
//         if(DSSI_IS_NRPN(ctlnum))
//         {
//           ctlnum = DSSI_NRPN_NUMBER(c) + CTRL_NRPN14_OFFSET;
// 
//           #ifdef VST_NATIVE_DEBUG
//           fprintf(stderr, "VstNativeSynthIF::processEvent is NRPN ctlnum:%x(h) %d(d)\n", ctlnum, ctlnum);
//           #endif
//         }
// 
//       }
// 
//       float val = midi2LadspaValue(ld, i, ctlnum, b);
// 
//       #ifdef VST_NATIVE_DEBUG
//       fprintf(stderr, "VstNativeSynthIF::processEvent control port:%lu port:%lu dataA:%d Converting val from:%d to ladspa:%f\n", i, k, a, b, val);
//       #endif
// 
//       // Set the ladspa port value.
//       controls[k].val = val;
// 
//       // Need to update the automation value, otherwise it overwrites later with the last automation value.
//       if(id() != -1)
//         // We're in the audio thread context: no need to send a message, just modify directly.
//         synti->setPluginCtrlVal(genACnum(id(), k), val);
// 
//       // Since we absorbed the message as a ladspa control change, return false - the event is not filled.
//       return false;
    }
    break;
    case ME_PITCHBEND:
    {
      int v = a + 8192;
      setVstEvent(event, (type | chn) & 0xff, v & 0x7f, (v >> 7) & 0x7f);
    }
    break;
    case ME_AFTERTOUCH:
      setVstEvent(event, (type | chn) & 0xff, a & 0x7f);
    break;
    case ME_POLYAFTER:
      setVstEvent(event, (type | chn) & 0xff, a & 0x7f, b & 0x7f);
    break;
    case ME_SYSEX:
      {
        #ifdef VST_NATIVE_DEBUG
        fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_SYSEX\n");
        #endif

        const unsigned char* data = e.data();
        if(e.len() >= 2)
        {
          if(data[0] == MUSE_SYNTH_SYSEX_MFG_ID)
          {
            if(data[1] == VST_NATIVE_SYNTH_UNIQUE_ID)
            {
              //if(e.len() >= 9)
              if(e.len() >= 10)
              {
                if (QString((const char*)(data + 2)).startsWith("VSTSAVE"))
                {
                  if(_synth->hasChunks())
                  {
#ifndef VST_VESTIGE_SUPPORT
                    int chunk_flags = data[9];
                    if(chunk_flags & VST_NATIVE_CHUNK_FLAG_COMPRESSED)
                      fprintf(stderr, "chunk flags:%x compressed chunks not supported yet.\n", chunk_flags);
                    else
                    {
                      fprintf(stderr, "%s: loading chunk from sysex!\n", name().toLatin1().constData());
                      // 10 = 2 bytes header + "VSTSAVE" + 1 byte flags (compression etc)
                      dispatch(effSetChunk, 0, e.len()-10, (void*)(data+10), 0.0); // index 0: is bank 1: is program
                    }
#else
                    fprintf(stderr, "support for vst chunks not compiled in!\n");
#endif
                  }
                  // Event not filled.
                  return false;
                }
              }
            }
          }
        }

        // DELETETHIS, 50 clean it up or fix it?
        /*
        // p3.3.39 Read the state of current bank and program and all input control values.
        // TODO: Needs to be better. See write().
        //else
        if (QString((const char*)e.data()).startsWith("PARAMSAVE"))
        {
          #ifdef VST_NATIVE_DEBUG
          fprintf(stderr, "VstNativeSynthIF::processEvent midi event is ME_SYSEX PARAMSAVE\n");
          #endif

          unsigned long dlen = e.len() - 9; // Minus "PARAMSAVE"
          if(dlen > 0)
          {
            //if(dlen < 2 * sizeof(unsigned long))
            if(dlen < (2 + 2 * sizeof(unsigned long))) // Version major and minor bytes, bank and program.
              fprintf(stderr, "VstNativeSynthIF::processEvent Error: PARAMSAVE data length does not include at least version major and minor, bank and program!\n");
            else
            {
              // Not required, yet.
              //char vmaj = *((char*)(e.data() + 9));  // After "PARAMSAVE"
              //char vmin = *((char*)(e.data() + 10));

              unsigned long* const ulp = (unsigned long*)(e.data() + 11);  // After "PARAMSAVE" + version major and minor.
              // TODO: TODO: Set plugin bank and program.
              _curBank = ulp[0];
              _curProgram = ulp[1];

              dlen -= (2 + 2 * sizeof(unsigned long)); // After the version major and minor, bank and program.

              if(dlen > 0)
              {
                if((dlen % sizeof(float)) != 0)
                  fprintf(stderr, "VstNativeSynthIF::processEvent Error: PARAMSAVE float data length not integral multiple of float size!\n");
                else
                {
                  const unsigned long n = dlen / sizeof(float);
                  if(n != synth->_controlInPorts)
                    fprintf(stderr, "VstNativeSynthIF::processEvent Warning: PARAMSAVE number of floats:%lu != number of controls:%lu\n", n, synth->_controlInPorts);

                  // Point to location after "PARAMSAVE", version major and minor, bank and progam.
                  float* const fp = (float*)(e.data() + 9 + 2 + 2 * sizeof(unsigned long));

                  for(unsigned long i = 0; i < synth->_controlInPorts && i < n; ++i)
                  {
                    const float v = fp[i];
                    controls[i].val = v;
                  }
                }
              }
            }
          }
          // Event not filled.
          return false;
        }
        */
        //else
        {
          // FIXME TODO: Sysex support.
          return false;

          //int len = e.len();
          //char ca[len + 2];
          //ca[0] = 0xF0;      // FIXME Stack overflow with big dumps. Use std::vector<char> or something else.
          //memcpy(ca + 1, (const char*)e.data(), len);
          //ca[len + 1] = 0xF7;
          //len += 2;

          // NOTE: There is a limit on the size of a sysex. Got this:
          // "VstNativeSynthIF::processEvent midi event is ME_SYSEX"
          // "WARNING: MIDI event of type ? decoded to 367 bytes, discarding"
          // That might be ALSA doing that.
//           snd_seq_ev_clear(event);
//           event->queue = SND_SEQ_QUEUE_DIRECT;
//           snd_seq_ev_set_sysex(event, len,
//             (unsigned char*)ca);
        }
      }
    break;
    default:
      if(MusEGlobal::debugMsg)
        fprintf(stderr, "VstNativeSynthIF::processEvent midi event unknown type:%d\n", e.type());
      // Event not filled.
      return false;
    break;
  }

  return true;
}

//---------------------------------------------------------
//   getData
//   If ports is 0, just process controllers only, not audio (do not 'run').
//---------------------------------------------------------

iMPEvent VstNativeSynthIF::getData(MidiPort* /*mp*/, MPEventList* el, iMPEvent start_event, unsigned pos, int ports, unsigned nframes, float** buffer)
{
  // We may not be using ev_buf_sz all at once - this will be just the maximum.
  const unsigned long ev_buf_sz = el->size() + synti->eventFifo.getSize();
  VstMidiEvent events[ev_buf_sz];
  char evbuf[sizeof(VstMidiEvent*) * ev_buf_sz + sizeof(VstEvents)];
  VstEvents *vst_events = (VstEvents*)evbuf;
  vst_events->numEvents = 0;
  vst_events->reserved  = 0;

  const int frameOffset = MusEGlobal::audio->getFrameOffset();
  const unsigned long syncFrame = MusEGlobal::audio->curSyncFrame();

  #ifdef VST_NATIVE_DEBUG_PROCESS
  fprintf(stderr, "VstNativeSynthIF::getData: pos:%u ports:%d nframes:%u syncFrame:%lu ev_buf_sz:%lu\n", pos, ports, nframes, syncFrame, ev_buf_sz);
  #endif

  const unsigned long nop = ((unsigned long) ports) > _synth->outPorts() ? _synth->outPorts() : ((unsigned long) ports);
  unsigned long sample = 0;

  // I read that some plugins do not like changing sample run length (compressors etc). Some are OK with it.
  // TODO: In order to support this effectively, must be user selectable, per-plugin. ENABLED for now.
  const bool usefixedrate = false;

  // For now, the fixed size is clamped to the audio buffer size.
  // TODO: We could later add slower processing over several cycles -
  //  so that users can select a small audio period but a larger control period.
  const unsigned long min_per = (usefixedrate || MusEGlobal::config.minControlProcessPeriod > nframes) ? nframes : MusEGlobal::config.minControlProcessPeriod;
  const unsigned long min_per_mask = min_per-1;   // min_per must be power of 2
  
  AudioTrack* atrack = track();
  const AutomationType at = atrack->automationType();
  const bool no_auto = !MusEGlobal::automation || at == AUTO_OFF;
  const unsigned long in_ctrls = _synth->inControls();
  CtrlListList* cll = atrack->controller();
  ciCtrlList icl_first;
  const int plug_id = id();
  if(plug_id != -1 && ports != 0)  // Don't bother if not 'running'.
    icl_first = cll->lower_bound(genACnum(plug_id, 0));

  // Inform the host callback we are in the audio thread.
  _inProcess = true;

  #ifdef VST_NATIVE_DEBUG_PROCESS
  fprintf(stderr, "VstNativeSynthIF::getData: Handling inputs...\n");
  #endif

  // Handle inputs...
  if(ports != 0)  // Don't bother if not 'running'.
  {
    if(!atrack->noInRoute())
    {
      RouteList* irl = atrack->inRoutes();
      iRoute i = irl->begin();
      if(!i->track->isMidiTrack())
      {
        const int ch     = i->channel       == -1 ? 0 : i->channel;
        const int remch  = i->remoteChannel == -1 ? 0 : i->remoteChannel;
        const int chs    = i->channels      == -1 ? 0 : i->channels;

        if((unsigned)ch < _synth->inPorts() && (unsigned)(ch + chs) <= _synth->inPorts())
        {
          const int h = remch + chs;
          for(int j = remch; j < h; ++j)
            _iUsedIdx[j] = true;

          ((AudioTrack*)i->track)->copyData(pos, chs, ch, -1, nframes, &_audioInBuffers[remch]);
        }
      }

      ++i;
      for(; i != irl->end(); ++i)
      {
        if(i->track->isMidiTrack())
          continue;

        const int ch     = i->channel       == -1 ? 0 : i->channel;
        const int remch  = i->remoteChannel == -1 ? 0 : i->remoteChannel;
        const int chs    = i->channels      == -1 ? 0 : i->channels;

        if((unsigned)ch < _synth->inPorts() && (unsigned)(ch + chs) <= _synth->inPorts())
        {
          const bool u1 = _iUsedIdx[remch];
          if(chs >= 2)
          {
            const bool u2 = _iUsedIdx[remch + 1];
            if(u1 && u2)
              ((AudioTrack*)i->track)->addData(pos, chs, ch, -1, nframes, &_audioInBuffers[remch]);
            else
            if(!u1 && !u2)
              ((AudioTrack*)i->track)->copyData(pos, chs, ch, -1, nframes, &_audioInBuffers[remch]);
            else
            {
              if(u1)
                ((AudioTrack*)i->track)->addData(pos, 1, ch, 1, nframes, &_audioInBuffers[remch]);
              else
                ((AudioTrack*)i->track)->copyData(pos, 1, ch, 1, nframes, &_audioInBuffers[remch]);

              if(u2)
                ((AudioTrack*)i->track)->addData(pos, 1, ch + 1, 1, nframes, &_audioInBuffers[remch + 1]);
              else
                ((AudioTrack*)i->track)->copyData(pos, 1, ch + 1, 1, nframes, &_audioInBuffers[remch + 1]);
            }
          }
          else
          {
              if(u1)
                ((AudioTrack*)i->track)->addData(pos, 1, ch, -1, nframes, &_audioInBuffers[remch]);
              else
                ((AudioTrack*)i->track)->copyData(pos, 1, ch, -1, nframes, &_audioInBuffers[remch]);
          }

          const int h = remch + chs;
          for(int j = remch; j < h; ++j)
            _iUsedIdx[j] = true;
        }
      }
    }
  }

  #ifdef VST_NATIVE_DEBUG_PROCESS
  fprintf(stderr, "VstNativeSynthIF::getData: Processing automation control values...\n");
  #endif

  int cur_slice = 0;
  while(sample < nframes)
  {
    unsigned long nsamp = nframes - sample;
    const unsigned long slice_frame = pos + sample;

    //
    // Process automation control values, while also determining the maximum acceptable
    //  size of this run. Further processing, from FIFOs for example, can lower the size
    //  from there, but this section determines where the next highest maximum frame
    //  absolutely needs to be for smooth playback of the controller value stream...
    //
    if(ports != 0)    // Don't bother if not 'running'.
    {
      ciCtrlList icl = icl_first;
      for(unsigned long k = 0; k < in_ctrls; ++k)
      {
        CtrlList* cl = (cll && plug_id != -1 && icl != cll->end()) ? icl->second : NULL;
        CtrlInterpolate& ci = _controls[k].interp;
        // Always refresh the interpolate struct at first, since things may have changed.
        // Or if the frame is outside of the interpolate range - and eStop is not true.  // FIXME TODO: Be sure these comparisons are correct.
        if(cur_slice == 0 || (!ci.eStop && MusEGlobal::audio->isPlaying() &&
            (slice_frame < (unsigned long)ci.sFrame || (ci.eFrame != -1 && slice_frame >= (unsigned long)ci.eFrame)) ) )
        {
          if(cl && plug_id != -1 && (unsigned long)cl->id() == genACnum(plug_id, k))
          {
            cl->getInterpolation(slice_frame, no_auto || !_controls[k].enCtrl, &ci);
            if(icl != cll->end())
              ++icl;
          }
          else
          {
            // No matching controller, or end. Just copy the current value into the interpolator.
            // Keep the current icl iterator, because since they are sorted by frames,
            //  if the IDs didn't match it means we can just let k catch up with icl.
            ci.sFrame   = 0;
            ci.eFrame   = -1;
            ci.sVal     = _controls[k].val;
            ci.eVal     = ci.sVal;
            ci.doInterp = false;
            ci.eStop    = false;
          }
        }
        else
        {
          if(ci.eStop && ci.eFrame != -1 && slice_frame >= (unsigned long)ci.eFrame)  // FIXME TODO: Get that comparison right.
          {
            // Clear the stop condition and set up the interp struct appropriately as an endless value.
            ci.sFrame   = 0; //ci->eFrame;
            ci.eFrame   = -1;
            ci.sVal     = ci.eVal;
            ci.doInterp = false;
            ci.eStop    = false;
          }
          if(cl && cll && icl != cll->end())
            ++icl;
        }

        if(!usefixedrate && MusEGlobal::audio->isPlaying())
        {
          unsigned long samps = nsamp;
          if(ci.eFrame != -1)
            samps = (unsigned long)ci.eFrame - slice_frame;
          
          if(!ci.doInterp && samps > min_per)
          {
            samps &= ~min_per_mask;
            if((samps & min_per_mask) != 0)
              samps += min_per;
          }
          else
            samps = min_per;

          if(samps < nsamp)
            nsamp = samps;

        }

        float new_val;
        if(ci.doInterp && cl)
          new_val = cl->interpolate(MusEGlobal::audio->isPlaying() ? slice_frame : pos, ci);
        else
          new_val = ci.sVal;
        if(_controls[k].val != new_val)
        {
          _controls[k].val = new_val;
#ifndef VST_VESTIGE_SUPPORT
          if(dispatch(effCanBeAutomated, k, 0, NULL, 0.0f) == 1)
          {
#endif
            if(_plugin->getParameter(_plugin, k) != new_val)
              _plugin->setParameter(_plugin, k, new_val);
#ifndef VST_VESTIGE_SUPPORT
          }
  #ifdef VST_NATIVE_DEBUG
          else
            fprintf(stderr, "VstNativeSynthIF::getData %s parameter:%lu cannot be automated\n", name().toLatin1().constData(), k);
  #endif
#endif
        }

#ifdef VST_NATIVE_DEBUG_PROCESS
        fprintf(stderr, "VstNativeSynthIF::getData k:%lu sample:%lu frame:%lu ci.eFrame:%d nsamp:%lu \n", k, sample, frame, ci.eFrame, nsamp);
#endif
        
      }
    }
    
#ifdef VST_NATIVE_DEBUG_PROCESS
      fprintf(stderr, "VstNativeSynthIF::getData sample:%lu nsamp:%lu\n", sample, nsamp);
#endif

    bool found = false;
    unsigned long frame = 0;
    unsigned long index = 0;
    unsigned long evframe;
    // Get all control ring buffer items valid for this time period...
    while(!_controlFifo.isEmpty())
    {
      ControlEvent v = _controlFifo.peek();
      // The events happened in the last period or even before that. Shift into this period with + n. This will sync with audio.
      // If the events happened even before current frame - n, make sure they are counted immediately as zero-frame.
      evframe = (syncFrame > v.frame + nframes) ? 0 : v.frame - syncFrame + nframes;

      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::getData found:%d evframe:%lu frame:%lu  event frame:%lu idx:%lu val:%f unique:%d\n",
          found, evframe, frame, v.frame, v.idx, v.value, v.unique);
      #endif

      // Protection. Observed this condition. Why? Supposed to be linear timestamps.
      if(found && evframe < frame)
      {
        fprintf(stderr, "VstNativeSynthIF::getData *** Error: evframe:%lu < frame:%lu event: frame:%lu idx:%lu val:%f unique:%d\n",
          evframe, frame, v.frame, v.idx, v.value, v.unique);

        // No choice but to ignore it.
        _controlFifo.remove();               // Done with the ring buffer's item. Remove it.
        continue;
      }

      if(evframe >= nframes                                                         // Next events are for a later period.
          || (!usefixedrate && !found && !v.unique && (evframe - sample >= nsamp))  // Next events are for a later run in this period. (Autom took prio.)
          || (found && !v.unique && (evframe - sample >= min_per))                  // Eat up events within minimum slice - they're too close.
          || (usefixedrate && found && v.unique && v.idx == index))                 // Special for dssi-vst: Fixed rate and must reply to all.
        break;
      _controlFifo.remove();               // Done with the ring buffer's item. Remove it.

      if(v.idx >= in_ctrls) // Sanity check.
        break;

      found = true;
      frame = evframe;
      index = v.idx;

      if(ports == 0)                     // Don't bother if not 'running'.
      {
        _controls[v.idx].val = v.value;   // Might as well at least update these.
// #ifndef VST_VESTIGE_SUPPORT
//         if(dispatch(effCanBeAutomated, v.idx, 0, NULL, 0.0f) == 1)
//         {
// #endif
//           if(v.value != _plugin->getParameter(_plugin, v.idx))
//             _plugin->setParameter(_plugin, v.idx, v.value);
// #ifndef VST_VESTIGE_SUPPORT
//         }
//   #ifdef VST_NATIVE_DEBUG
//         else
//           fprintf(stderr, "VstNativeSynthIF::getData %s parameter:%lu cannot be automated\n", name().toLatin1().constData(), v.idx);
//   #endif
// #endif
      }
      else
      {
        CtrlInterpolate* ci = &_controls[v.idx].interp;
        // Tell it to stop the current ramp at this frame, when it does stop, set this value:
        ci->eFrame = frame;
        ci->eVal   = v.value;
        ci->eStop  = true;
      }

      // Need to update the automation value, otherwise it overwrites later with the last automation value.
      if(plug_id != -1)
        synti->setPluginCtrlVal(genACnum(plug_id, v.idx), v.value);
    }

    if(found && !usefixedrate)  // If a control FIFO item was found, takes priority over automation controller stream.
      nsamp = frame - sample;

    if(sample + nsamp > nframes)         // Safety check.
      nsamp = nframes - sample;

    // TODO: Don't allow zero-length runs. This could/should be checked in the control loop instead.
    // Note this means it is still possible to get stuck in the top loop (at least for a while).
    if(nsamp != 0)
    {
      unsigned long nevents = 0;
      if(ports != 0)  // Don't bother if not 'running'.
      {
        // Process event list events...
        for(; start_event != el->end(); ++start_event)
        {
          #ifdef VST_NATIVE_DEBUG
          fprintf(stderr, "VstNativeSynthIF::getData eventlist event time:%d pos:%u sample:%lu nsamp:%lu frameOffset:%d\n", start_event->time(), pos, sample, nsamp, frameOffset);
          #endif

          if(start_event->time() >= (pos + sample + nsamp + frameOffset))  // frameOffset? Test again...
          {
            #ifdef VST_NATIVE_DEBUG
            fprintf(stderr, " event is for future:%lu, breaking loop now\n", start_event->time() - frameOffset - pos - sample);
            #endif
            break;
          }

          // Update hardware state so knobs and boxes are updated. Optimize to avoid re-setting existing values.
          // Same code as in MidiPort::sendEvent()
          if(synti->midiPort() != -1)
          {
            MidiPort* mp = &MusEGlobal::midiPorts[synti->midiPort()];
            if(start_event->type() == ME_CONTROLLER)
            {
              int da = start_event->dataA();
              int db = start_event->dataB();
              db = mp->limitValToInstrCtlRange(da, db);
              if(!mp->setHwCtrlState(start_event->channel(), da, db))
                continue;
            }
            else if(start_event->type() == ME_PITCHBEND)
            {
              int da = mp->limitValToInstrCtlRange(CTRL_PITCH, start_event->dataA());
              if(!mp->setHwCtrlState(start_event->channel(), CTRL_PITCH, da))
                continue;
            }
            else if(start_event->type() == ME_AFTERTOUCH)
            {
              int da = mp->limitValToInstrCtlRange(CTRL_AFTERTOUCH, start_event->dataA());
              if(!mp->setHwCtrlState(start_event->channel(), CTRL_AFTERTOUCH, da))
                continue;
            }
            else if(start_event->type() == ME_POLYAFTER)
            {
              int ctl = (CTRL_POLYAFTER & ~0xff) | (start_event->dataA() & 0x7f);
              int db = mp->limitValToInstrCtlRange(ctl, start_event->dataB());
              if(!mp->setHwCtrlState(start_event->channel(), ctl , db))
                continue;
            }
            else if(start_event->type() == ME_PROGRAM)
            {
              if(!mp->setHwCtrlState(start_event->channel(), CTRL_PROGRAM, start_event->dataA()))
                continue;
            }
          }

          // Returns false if the event was not filled. It was handled, but some other way.
          if(processEvent(*start_event, &events[nevents]))
          {
            // Time-stamp the event.
            int ft = start_event->time() - frameOffset - pos - sample;
            if(ft < 0)
              ft = 0;

            if (ft >= int(nsamp))
            {
                fprintf(stderr, "VstNativeSynthIF::getData: eventlist event time:%d out of range. pos:%d offset:%d ft:%d sample:%lu nsamp:%lu\n", start_event->time(), pos, frameOffset, ft, sample, nsamp);
                ft = nsamp - 1;
            }

            #ifdef VST_NATIVE_DEBUG
            fprintf(stderr, "VstNativeSynthIF::getData eventlist: ft:%d current nevents:%lu\n", ft, nevents);
            #endif

            vst_events->events[nevents] = (VstEvent*)&events[nevents];
            events[nevents].deltaFrames = ft;
            ++nevents;
          }
        }
      }
      
      // Now process putEvent events...
      while(!synti->eventFifo.isEmpty())
      {
        MidiPlayEvent e = synti->eventFifo.peek();

        #ifdef VST_NATIVE_DEBUG
        fprintf(stderr, "VstNativeSynthIF::getData eventFifo event time:%d\n", e.time());
        #endif

        if(e.time() >= (pos + sample + nsamp + frameOffset))
          break;

        synti->eventFifo.remove();    // Done with ring buffer's event. Remove it.
        if(ports != 0)  // Don't bother if not 'running'.
        {
          // Returns false if the event was not filled. It was handled, but some other way.
          if(processEvent(e, &events[nevents]))
          {
            // Time-stamp the event.
            int ft = e.time() - frameOffset - pos  - sample;
            if(ft < 0)
              ft = 0;
            if (ft >= int(nsamp))
            {
                fprintf(stderr, "VstNativeSynthIF::getData: eventFifo event time:%d out of range. pos:%d offset:%d ft:%d sample:%lu nsamp:%lu\n", e.time(), pos, frameOffset, ft, sample, nsamp);
                ft = nsamp - 1;
            }
            vst_events->events[nevents] = (VstEvent*)&events[nevents];
            events[nevents].deltaFrames = ft;

            ++nevents;
          }
        }
      }

      #ifdef VST_NATIVE_DEBUG_PROCESS
      fprintf(stderr, "VstNativeSynthIF::getData: Connecting and running. sample:%lu nsamp:%lu nevents:%lu\n", sample, nsamp, nevents);
      #endif

      if(ports != 0)  // Don't bother if not 'running'.
      {
        // Set the events pointer.
        if(nevents > 0)
        {
          vst_events->numEvents = nevents;
          dispatch(effProcessEvents, 0, 0, vst_events, 0.0f);
        }

        float* in_bufs[_synth->inPorts()];
        float* out_bufs[_synth->outPorts()];

        unsigned long k = 0;
        // Connect the given buffers directly to the ports, up to a max of synth ports.
        for(; k < nop; ++k)
          out_bufs[k] = buffer[k] + sample;
        // Connect the remaining ports to some local buffers (not used yet).
        const unsigned long op =_synth->outPorts();
        for(; k < op; ++k)
          out_bufs[k] = _audioOutBuffers[k] + sample;
        // Connect all inputs either to some local buffers, or a silence buffer.
        const unsigned long ip =_synth->inPorts();
        for(k = 0; k < ip; ++k)
        {
          if(_iUsedIdx[k])
          {
            _iUsedIdx[k] = false; // Reset
            in_bufs[k] = _audioInBuffers[k] + sample;
          }
          else
            in_bufs[k] = _audioInSilenceBuf + sample;
        }

        // Run the synth for a period of time. This processes events and gets/fills our local buffers...
        if((_plugin->flags & effFlagsCanReplacing) && _plugin->processReplacing)
        {
          _plugin->processReplacing(_plugin, in_bufs, out_bufs, nsamp);
        }
      }
      
      sample += nsamp;
    }

    ++cur_slice; // Slice is done. Moving on to any next slice now...
  }
  
  // Inform the host callback we will be no longer in the audio thread.
  _inProcess = false;

  return start_event;
}

//---------------------------------------------------------
//   putEvent
//---------------------------------------------------------

bool VstNativeSynthIF::putEvent(const MidiPlayEvent& ev)
      {
      #ifdef VST_NATIVE_DEBUG
      fprintf(stderr, "VstNativeSynthIF::putEvent midi event time:%d chn:%d a:%d b:%d\n", ev.time(), ev.channel(), ev.dataA(), ev.dataB());
      #endif
      
      if (MusEGlobal::midiOutputTrace)
            ev.dump();
      return synti->eventFifo.put(ev);
      }


//--------------------------------
// Methods for PluginIBase:
//--------------------------------

unsigned long VstNativeSynthIF::pluginID()                        { return (_plugin) ? _plugin->uniqueID : 0; }
int VstNativeSynthIF::id()                                        { return MAX_PLUGINS; } // Set for special block reserved for synth. 
QString VstNativeSynthIF::pluginLabel() const                     { return _synth ? QString(_synth->name()) : QString(); } // FIXME Maybe wrong
QString VstNativeSynthIF::lib() const                             { return _synth ? _synth->completeBaseName() : QString(); }
QString VstNativeSynthIF::dirPath() const                         { return _synth ? _synth->absolutePath() : QString(); }
QString VstNativeSynthIF::fileName() const                        { return _synth ? _synth->fileName() : QString(); }
void VstNativeSynthIF::enableController(unsigned long i, bool v)  { _controls[i].enCtrl = v; }
bool VstNativeSynthIF::controllerEnabled(unsigned long i) const   { return _controls[i].enCtrl;}
void VstNativeSynthIF::enableAllControllers(bool v)
{
  if(!_synth)
    return;
  const unsigned long sic = _synth->inControls();
  for(unsigned long i = 0; i < sic; ++i)
    _controls[i].enCtrl = v;
}
void VstNativeSynthIF::updateControllers() { }
void VstNativeSynthIF::activate()
{
  //for (unsigned short i = 0; i < instances(); ++i) {
  //        dispatch(i, effMainsChanged, 0, 1, NULL, 0.0f);
  dispatch(effMainsChanged, 0, 1, NULL, 0.0f);
#ifndef VST_VESTIGE_SUPPORT
  //dispatch(i, effStartProcess, 0, 0, NULL, 0.0f);
  dispatch(effStartProcess, 0, 0, NULL, 0.0f);
#endif
  //}

// REMOVE Tim. Or keep? From PluginI::activate().
//   if (initControlValues) {
//         for (unsigned long i = 0; i < controlPorts; ++i) {
//               controls[i].val = controls[i].tmpVal;
//               }
//         }
//   else {
//         // get initial control values from plugin
//         for (unsigned long i = 0; i < controlPorts; ++i) {
//               controls[i].tmpVal = controls[i].val;
//               }
//         }
  _active = true;
}
void VstNativeSynthIF::deactivate()
{
  _active = false;
  //for (unsigned short i = 0; i < instances(); ++i) {
#ifndef VST_VESTIGE_SUPPORT
  //dispatch(i, effStopProcess, 0, 0, NULL, 0.0f);
  dispatch(effStopProcess, 0, 0, NULL, 0.0f);
#endif
  //dispatch(i, effMainsChanged, 0, 0, NULL, 0.0f);
  dispatch(effMainsChanged, 0, 0, NULL, 0.0f);
  //}
}

unsigned long VstNativeSynthIF::parameters() const                { return _synth ? _synth->inControls() : 0; }
unsigned long VstNativeSynthIF::parametersOut() const             { return 0; }
void VstNativeSynthIF::setParam(unsigned long i, float val)       { setParameter(i, val); }
float VstNativeSynthIF::param(unsigned long i) const              { return getParameter(i); }
float VstNativeSynthIF::paramOut(unsigned long) const           { return 0.0; }
const char* VstNativeSynthIF::paramName(unsigned long i)          
{
  if(!_plugin)
    return 0;
  static char buf[256];
  buf[0] = 0;
  dispatch(effGetParamName, i, 0, buf, 0);
  return buf;
}

const char* VstNativeSynthIF::paramOutName(unsigned long)       { return 0; }
LADSPA_PortRangeHint VstNativeSynthIF::range(unsigned long /*i*/)     
{
  LADSPA_PortRangeHint h;
  // FIXME TODO:
  h.HintDescriptor = 0;
  h.LowerBound = 0.0;
  h.UpperBound = 1.0;
  return h;
}
LADSPA_PortRangeHint VstNativeSynthIF::rangeOut(unsigned long)  
{
  // There are no output controls.
  LADSPA_PortRangeHint h;
  h.HintDescriptor = 0;
  h.LowerBound = 0.0;
  h.UpperBound = 1.0;
  return h;
}
// FIXME TODO:
CtrlValueType VstNativeSynthIF::ctrlValueType(unsigned long /*i*/) const { return VAL_LINEAR; }
CtrlList::Mode VstNativeSynthIF::ctrlMode(unsigned long /*i*/) const     { return CtrlList::INTERPOLATE; };

} // namespace MusECore

#else  // VST_NATIVE_SUPPORT
namespace MusECore {
void initVST_Native() {}
} // namespace MusECore
#endif