summaryrefslogtreecommitdiff
path: root/muse2/muse/dssihost.cpp
blob: 923192b44b872209f33f5ade2a61ec519328347d (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
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
//=============================================================================
//  MusE
//  Linux Music Editor
//  $Id: dssihost.cpp,v 1.15.2.16 2009/12/15 03:39:58 terminator356 Exp $
//
//  Copyright (C) 1999-2011 by Werner Schweer and others
//
//  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 DSSI_SUPPORT

// Turn on debugging messages
//#define DSSI_DEBUG 

// Support vst state saving/loading with vst chunks. 
//#define DSSI_VST_CHUNK_SUPPORT    

#include <string.h>
#include <signal.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/stat.h>
//#include <dssi.h>
//#include <alsa/asoundlib.h>

#include <QDir>
#include <QFileInfo>
//#include <QMenu>

#include "dssihost.h"
#include "synth.h"
#include "audio.h"
#include "jackaudio.h"
//#include "../driver/jackaudio.h"  // p4.0.2
#include "midi.h"
#include "midiport.h"
#include "stringparam.h"
#include "plugin.h"
#include "controlfifo.h"
//#include "al/al.h"
//#include "al/xml.h"
#include "xml.h"
#include "song.h"
//#include "midictrl.h"
//#include "ladspaplugin.h"

#include "app.h"
#include "globals.h"
#include "globaldefs.h"
//#include "al/dsp.h"
#include "gconfig.h"
#include "popupmenu.h"


/*
static lo_server_thread serverThread;
static char osc_path_tmp[1024];
static char* url;

//---------------------------------------------------------
//   oscError
//---------------------------------------------------------

static void oscError(int num, const char *msg, const char *path)
      {
      fprintf(stderr, "MusE: liblo server error %d in path %s: %s\n",
          num, path, msg);
      }

//---------------------------------------------------------
//   oscDebugHandler
//---------------------------------------------------------

static int oscDebugHandler(const char* path, const char* types, lo_arg** argv,
   int argc, void*, void*)
      {
      printf("MusE: got unhandled OSC message:\n   path: <%s>\n", path);
      for (int i = 0; i < argc; i++) {
            printf("   arg %d '%c' ", i, types[i]);
            lo_arg_pp(lo_type(types[i]), argv[i]);
            printf("\n");
            }
      return 1;
      }

//---------------------------------------------------------
//   oscUpdate
//---------------------------------------------------------

int DssiSynthIF::oscUpdate(lo_arg **argv)
      {
      const char *url = (char *)&argv[0]->s;

      if (uiTarget)
            lo_address_free(uiTarget);
      char* host = lo_url_get_hostname(url);
      char* port = lo_url_get_port(url);
      uiTarget   = lo_address_new(host, port);
      free(host);
      free(port);

      if (uiOscPath)
            free(uiOscPath);
      uiOscPath = lo_url_get_path(url);
      int pl = strlen(uiOscPath);

      if (uiOscControlPath)
            free(uiOscControlPath);
      uiOscControlPath = (char *)malloc(pl + 10);
      sprintf(uiOscControlPath, "%s/control", uiOscPath);

      if (uiOscConfigurePath)
            free(uiOscConfigurePath);
      uiOscConfigurePath = (char *)malloc(pl + 12);
      sprintf(uiOscConfigurePath, "%s/configure", uiOscPath);

      if (uiOscProgramPath)
            free(uiOscProgramPath);
      uiOscProgramPath = (char *)malloc(pl + 10);
      sprintf(uiOscProgramPath, "%s/program", uiOscPath);

      if (uiOscShowPath)
            free(uiOscShowPath);
      uiOscShowPath = (char *)malloc(pl + 10);
      sprintf(uiOscShowPath, "%s/show", uiOscPath);

      // At this point a more substantial host might also call
      // configure() on the UI to set any state that it had remembered
      // for the plugin instance.  But we don't remember state for
      // plugin instances (see our own configure() implementation in
      // osc_configure_handler), and so we have nothing to send except
      // the optional project directory.
      

      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::oscUpdate synth name:%s url:%s uiTarget:%p uiOscPath:%s uiOscConfigurePath:%s museProject:%s\n", synti->name().ascii(), url, uiTarget, uiOscPath, uiOscConfigurePath, museProject.ascii());
      #endif
      
      //lo_send(uiTarget, uiOscConfigurePath, "ss",
         //DSSI_PROJECT_DIRECTORY_KEY, song->projectPath().toAscii().data());
      lo_send(uiTarget, uiOscConfigurePath, "ss",
         DSSI_PROJECT_DIRECTORY_KEY, museProject.ascii());

#if 0
      // Send current bank/program  (-FIX- another race...) 
      if (instance->pendingProgramChange < 0) {
            unsigned long bank = instance->currentBank;
            unsigned long program = instance->currentProgram;
            instance->uiNeedsProgramUpdate = 0;
            if (instance->uiTarget) {
                  lo_send(instance->uiTarget, instance->ui_osc_program_path, "ii", bank, program);
                  }
            }

      // Send control ports 
      for (i = 0; i < instance->plugin->controlIns; i++) {
            int in = i + instance->firstControlIn;
            int port = pluginControlInPortNumbers[in];
            lo_send(instance->uiTarget, instance->ui_osc_control_path, "if", port,
               pluginControlIns[in]);
            // Avoid overloading the GUI if there are lots and lots of ports 
            if ((i+1) % 50 == 0)
                  usleep(300000);
            }
#endif
      return 0;
      }

//---------------------------------------------------------
//   oscMessageHandler
//---------------------------------------------------------

int oscMessageHandler(const char* path, const char* types, lo_arg** argv,
   int argc, void* data, void* user_data)
      {
      const char* p = path;
      
      #ifdef DSSI_DEBUG 
      if(argc) 
      {
          printf("oscMessageHandler: path:%s argc:%d\n", path, argc);
          for(int i = 0; i < argc; ++i) 
          {
            printf(" ");
            lo_arg_pp((lo_type)types[i], argv[i]);
          }
          printf("\n");
      } 
      else 
      {
          printf("%s\n", path);
          printf("oscMessageHandler: no args, path:%s\n", path);
      }
      #endif  
        
      if (strncmp(p, "/dssi/", 6))
            return oscDebugHandler(path, types, argv, argc, data, user_data);
      
      p += 6;
      //p = strrchr(p, "/");

      SynthIList* sl = song->syntis();
      DssiSynthIF* instance = 0;
      SynthI* synti = 0;

      #ifdef DSSI_DEBUG 
      fprintf(stderr, "oscMessageHandler: song->syntis() size:%d\n", sl->size());
      #endif
        
      for(int retry = 0; retry < 5; ++retry) 
      {
        #ifdef DSSI_DEBUG 
        fprintf(stderr, "oscMessageHandler: search retry number:%d ...\n", retry);
        #endif
        
        //if(uiOscPath)
        //  break;
      
        for(iSynthI si = sl->begin(); si != sl->end(); ++si) 
        {
          #ifdef DSSI_DEBUG 
          fprintf(stderr, "oscMessageHandler: searching for synth p:%s: checking instances:%s\n", p, (*si)->name().ascii());
          #endif
          
          //int l = strlen((*si)->name().toAscii().data());
          //if (!strncmp(p, (*si)->name().toAscii().data(), l)) {
          //int l = strlen((*si)->name().ascii());
          const char* sub = strstr(p, (*si)->name().ascii());
          
          //if(!strncmp(p, (*si)->name().ascii(), l)) 
          if(sub != NULL) 
          {
            synti = *si;
            instance = (DssiSynthIF*)(synti->sif());
            
            //p += l;
            p = sub + strlen((*si)->name().ascii());
            
            break;
          }
        }
        if(instance)
          break;
          
        sleep(1);
      }
      
      if(!instance)
      {
        fprintf(stderr, "oscMessageHandler: error: no instance\n");
        return oscDebugHandler(path, types, argv, argc, data, user_data);
      }
      
      if (*p != '/' || *(p + 1) == 0)
      {
        fprintf(stderr, "oscMessageHandler: error: end or no /\n");
        return oscDebugHandler(path, types, argv, argc, data, user_data);
      }
            
      ++p;

      #ifdef DSSI_DEBUG 
      fprintf(stderr, "oscMessageHandler: method:%s\n", p);
      #endif
      
      if (!strcmp(p, "configure") && argc == 2 && !strcmp(types, "ss"))
            return instance->oscConfigure(argv);
      else if (!strcmp(p, "control") && argc == 2 && !strcmp(types, "if"))
            return instance->oscControl(argv);
      else if (!strcmp(p, "midi") && argc == 1 && !strcmp(types, "m"))
            return instance->oscMidi(argv);
      else if (!strcmp(p, "program") && argc == 2 && !strcmp(types, "ii"))
            return instance->oscProgram(argv);
      else if (!strcmp(p, "update") && argc == 1 && !strcmp(types, "s"))
            return instance->oscUpdate(argv);
      else if (!strcmp(p, "exiting") && argc == 0)
            return instance->oscExiting(argv);
      return oscDebugHandler(path, types, argv, argc, data, user_data);
      }
*/

//---------------------------------------------------------
//   scanDSSILib
//---------------------------------------------------------

static void scanDSSILib(QFileInfo& fi) // ddskrjo removed const for argument
      {
      //void* handle = dlopen(fi.filePath().toAscii().data(), RTLD_NOW);
      void* handle = dlopen(fi.filePath().toLatin1().constData(), RTLD_NOW);
      //void* handle = dlopen(fi.absFilePath().toLatin1().constData(), RTLD_NOW);
      
      if (handle == 0) {
            fprintf(stderr, "scanDSSILib: dlopen(%s) failed: %s\n",
              //fi.filePath().toAscii().data(), dlerror());
              fi.filePath().toLatin1().constData(), dlerror());
              //fi.absFilePath().toLatin1().constData(), dlerror());
              
            return;
            }
      DSSI_Descriptor_Function dssi = (DSSI_Descriptor_Function)dlsym(handle, "dssi_descriptor");

      if (!dssi) 
      {
          /*
          const char *txt = dlerror();
          if (txt) 
          {
            fprintf(stderr,
                "Unable to find dssi_descriptor() function in plugin "
                "library file \"%s\": %s.\n"
                "Are you sure this is a DSSI plugin file?\n",
                //fi.filePath().toAscii().data(),
                fi.filePath().ascii(),
                //fi.absFilePath().toLatin1().constData(),
                
                txt);
            dlclose(handle);
            exit(1);
          }
          */
        dlclose(handle);
        return;
      }
      else
      {
        //const DSSI_Descriptor* descr;
        for (int i = 0;; ++i) 
        {
          const DSSI_Descriptor* descr;
          
          // CRAPPY PLUGIN ALERT: 
          // Out of many plugins, with several, Valgrind says something in here is allocated with new. 
          descr = dssi(i);
          if (descr == 0)
                break;
          
          #ifdef DSSI_DEBUG 
          fprintf(stderr, "scanDSSILib: name:%s inPlaceBroken:%d\n", descr->LADSPA_Plugin->Name, LADSPA_IS_INPLACE_BROKEN(descr->LADSPA_Plugin->Properties));
          #endif
          
          // Listing synths only while excluding effect plugins:
          // Do the exact opposite of what dssi-vst.cpp does for listing ladspa plugins.
          // That way we cover all bases - effect plugins and synths. 
          // Non-synths will show up in the ladspa effect dialog, while synths will show up here...
          // There should be nothing left out...
          if(descr->run_synth ||                  
            descr->run_synth_adding ||
            descr->run_multiple_synths ||
            descr->run_multiple_synths_adding) 
          {
            const QString label(descr->LADSPA_Plugin->Label);
            
            // Make sure it doesn't already exist.
            std::vector<Synth*>::iterator is;
            for(is = synthis.begin(); is != synthis.end(); ++is)
            {
              Synth* s = *is;
              //#ifdef DSSI_DEBUG 
              //  fprintf(stderr, "scanDSSILib: name:%s listname:%s lib:%s listlib:%s\n", 
              //          label.toLatin1().constData(), s->name().toLatin1().constData(), fi.baseName(true).toLatin1().constData(), s->baseName().toLatin1().constData());
              //#endif

              if(s->name() == label && s->baseName() == fi.completeBaseName())
                break;
            }
            if(is != synthis.end())
              continue;
            
            DssiSynth* s = new DssiSynth(fi, descr);
            
            if(debugMsg)
            {
              fprintf(stderr, "scanDSSILib: name:%s listname:%s lib:%s listlib:%s\n", 
                      label.toLatin1().constData(), s->name().toLatin1().constData(), fi.completeBaseName().toLatin1().constData(), s->baseName().toLatin1().constData());
              int ai = 0, ao = 0, ci = 0, co = 0;
              for(unsigned long pt = 0; pt < descr->LADSPA_Plugin->PortCount; ++pt)
              {
                LADSPA_PortDescriptor pd = descr->LADSPA_Plugin->PortDescriptors[pt];
                if(LADSPA_IS_PORT_INPUT(pd) && LADSPA_IS_PORT_AUDIO(pd))
                  ai++;
                else  
                if(LADSPA_IS_PORT_OUTPUT(pd) && LADSPA_IS_PORT_AUDIO(pd))
                  ao++;
                else  
                if(LADSPA_IS_PORT_INPUT(pd) && LADSPA_IS_PORT_CONTROL(pd))
                  ci++;
                else  
                if(LADSPA_IS_PORT_OUTPUT(pd) && LADSPA_IS_PORT_CONTROL(pd))
                  co++;
              }  
              fprintf(stderr, "audio ins:%d outs:%d control ins:%d outs:%d\n", ai, ao, ci, co);
            }
            
            synthis.push_back(s);
          }
          //else
          //{
            // NOTE: Just a test
            //QFileInfo ffi(fi);
            //plugins.add(&ffi, LADSPA_Descriptor_Function(NULL), descr->LADSPA_Plugin, false);
            //plugins.add(&ffi, descr, false);
          //}
        }
      }  
      dlclose(handle);
      }

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

static void scanDSSIDir(QString& s) // ddskrjo removed const for argument
{
      if(debugMsg)
        //printf("scan DSSI plugin dir <%s>\n", s.toAscii().data());
        printf("scanDSSIDir: scan DSSI plugin dir <%s>\n", s.toLatin1().constData());

#ifdef __APPLE__
      QDir pluginDir(s, QString("*.dylib"), QDir::Unsorted, QDir::Files);
#else
      QDir pluginDir(s, QString("*.so"), QDir::Unsorted, QDir::Files);
#endif
      if(!pluginDir.exists())
        return;

      //const QFileInfoList list = pluginDir.entryInfoList();
      //for (int i = 0; i < list.size(); ++i) {
      	//QFileInfo fi = list.at(i);
            //scanDSSILib(fi);
            //}
      
      QStringList list = pluginDir.entryList();
      for(int i = 0; i < list.count(); ++i) 
      {
        if(debugMsg)
          printf("scanDSSIDir: found %s\n", (s + QString("/") + list[i]).toLatin1().constData());

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

//---------------------------------------------------------
//   initDSSI
//---------------------------------------------------------

void initDSSI()
      {
      const char* dssiPath = getenv("DSSI_PATH");
      if (dssiPath == 0)
            dssiPath = "/usr/local/lib64/dssi:/usr/lib64/dssi:/usr/local/lib/dssi:/usr/lib/dssi";

      //const char* ladspaPath = getenv("LADSPA_PATH");
      //if (ladspaPath == 0)
      //      ladspaPath = "/usr/local/lib64/ladspa:/usr/lib64/ladspa:/usr/local/lib/ladspa:/usr/lib/ladspa";
      
      const char* p = dssiPath;
      //QString pth = QString(dssiPath) + QString(":") + QString(ladspaPath);
      //const char* p = pth.toLatin1().constData();
      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';
                  QString tmpStr(buffer);
                  scanDSSIDir(tmpStr);
                  delete[] buffer;
                  }
            p = pe;
            if (*p == ':')
                  p++;
            }
      
      // Create OSC thread
      //serverThread = lo_server_thread_new(0, oscError);
      //snprintf(osc_path_tmp, 31, "/dssi");
      //char* tmp = lo_server_thread_get_url(serverThread);
      //url = (char *)malloc(strlen(tmp) + strlen(osc_path_tmp));
      //sprintf(url, "%s%s", tmp, osc_path_tmp + 1);
      //free(tmp);
      //lo_server_thread_add_method(serverThread, 0, 0, oscMessageHandler, 0);
      //lo_server_thread_start(serverThread);
      }

//---------------------------------------------------------
//   DssiSynth
//   Synth.label   =  plug.Label 
//   Synth.descr   =  plug.Name
//   Synth.maker   =  plug.maker 
//   Synth.version =  nil (no such field in ladspa, maybe try copyright instead)
//---------------------------------------------------------

DssiSynth::DssiSynth(QFileInfo& fi, const DSSI_Descriptor* d) : // ddskrjo removed const from QFileInfo
  //Synth(fi, label, descr, maker, ver) 
  Synth(fi, QString(d->LADSPA_Plugin->Label), QString(d->LADSPA_Plugin->Name), QString(d->LADSPA_Plugin->Maker), QString()) 
{
  df = 0;
  handle = 0;
  dssi = 0;
  _hasGui = false;
  
  const LADSPA_Descriptor* descr = d->LADSPA_Plugin;
  
  _portCount = descr->PortCount;
  //_portDescriptors = 0;
  //if(_portCount)
  //  _portDescriptors = new LADSPA_PortDescriptor[_portCount];
  
  _inports = 0;
  _outports = 0;
  _controlInPorts = 0;
  _controlOutPorts = 0;
  for(unsigned long k = 0; k < _portCount; ++k) 
  {
    LADSPA_PortDescriptor pd = descr->PortDescriptors[k];
    //_portDescriptors[k] = pd;
    if(pd & LADSPA_PORT_AUDIO)
    {
      if(pd & LADSPA_PORT_INPUT)
        ++_inports;
      else
      if(pd & LADSPA_PORT_OUTPUT)
        ++_outports;
    }    
    else
    if(pd & LADSPA_PORT_CONTROL)
    {
      if(pd & LADSPA_PORT_INPUT)
        ++_controlInPorts;
      else
      if(pd & LADSPA_PORT_OUTPUT)
        ++_controlOutPorts;
    }    
  }
  
  _inPlaceCapable = !LADSPA_IS_INPLACE_BROKEN(descr->Properties);
  
  // Hack: Special flag required for example for control processing.
  _isDssiVst = fi.completeBaseName() == QString("dssi-vst");
  // Hack: Blacklist vst plugins in-place, configurable for now. 
  if ((_inports != _outports) || (_isDssiVst && !config.vstInPlace))
        _inPlaceCapable = false;
}

DssiSynth::~DssiSynth() 
{ 

}

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

SynthIF* DssiSynth::createSIF(SynthI* synti)
{
      if (_instances == 0) 
      {
        //handle = dlopen(info.filePath().toAscii().data(), RTLD_NOW);
        handle = dlopen(info.filePath().toLatin1().constData(), RTLD_NOW);
        //handle = dlopen(info.absFilePath().toLatin1().constData(), RTLD_NOW);
        
        if (handle == 0) 
        {
              fprintf(stderr, "DssiSynth::createSIF dlopen(%s) failed: %s\n",
                //info.filePath().toAscii().data(), dlerror());
                info.filePath().toLatin1().constData(), dlerror());
                //info.absFilePath().toLatin1().constData(), dlerror());
                
              return 0;
        }
        df = (DSSI_Descriptor_Function)dlsym(handle, "dssi_descriptor");

        if (!df) {
              const char *txt = dlerror();
              fprintf(stderr,
                  "Unable to find dssi_descriptor() function in plugin "
                  "library file \"%s\": %s.\n"
                  "Are you sure this is a DSSI plugin file?\n",
                  //info.filePath().toAscii().data(),
                  info.filePath().toLatin1().constData(),
                  //info.absFilePath().toLatin1().constData(),
                  
                  txt ? txt : "?");
              dlclose(handle);
              handle = 0;
              return 0;
              }
        for (int i = 0;; ++i) 
        {
          dssi = df(i);
          if (dssi == 0)
            break;
          QString label(dssi->LADSPA_Plugin->Label);
          if (label == _name)
            break;
        }

        if(dssi != 0)
        {
          _inports    = 0;
          _outports   = 0;
          _controlInPorts = 0;
          _controlOutPorts = 0;

          ///pIdx.clear(); 
          ///opIdx.clear();
          
          iIdx.clear(); 
          oIdx.clear(); 
          rpIdx.clear();
          iUsedIdx.clear();
          midiCtl2PortMap.clear();
          port2MidiCtlMap.clear();
          //synti->_guiUpdateControls.clear();
          
          const LADSPA_Descriptor* descr = dssi->LADSPA_Plugin;
          //#ifdef DSSI_DEBUG 
          //  printf("DssiSynth::createSIF ladspa plugin PortCount:%lu\n", d->PortCount);
          //#endif
          
          _portCount = descr->PortCount;
          
          for (unsigned long k = 0; k < _portCount; ++k) 
          {
            LADSPA_PortDescriptor pd = descr->PortDescriptors[k];
            
            #ifdef DSSI_DEBUG 
            printf("DssiSynth::createSIF ladspa plugin Port:%lu Name:%s descriptor:%x\n", k, descr->PortNames[k], pd);
            #endif
            
            if (LADSPA_IS_PORT_AUDIO(pd)) 
            {
              if (LADSPA_IS_PORT_INPUT(pd)) 
              {
                ++_inports;
                iIdx.push_back(k);
                iUsedIdx.push_back(false); // Start out with all false.
              }
              else if (LADSPA_IS_PORT_OUTPUT(pd)) 
              {
                ++_outports;
                oIdx.push_back(k);
              }
              
              rpIdx.push_back((unsigned long)-1);
            }
            else if (LADSPA_IS_PORT_CONTROL(pd)) 
            {
              if (LADSPA_IS_PORT_INPUT(pd)) 
              {
                rpIdx.push_back(_controlInPorts);
                ++_controlInPorts;
                ///pIdx.push_back(k);
                // Set to false at first.
                //synti->_guiUpdateControls.push_back(false);
              }
              else if (LADSPA_IS_PORT_OUTPUT(pd))
              {
                rpIdx.push_back((unsigned long)-1);
                ++_controlOutPorts;
                ///opIdx.push_back(k);
              }
            }
          }
          
          _inPlaceCapable = !LADSPA_IS_INPLACE_BROKEN(descr->Properties);
          // Hack: Special flag required for example for control processing.
          _isDssiVst = info.completeBaseName() == QString("dssi-vst");
          // Hack: Blacklist vst plugins in-place, configurable for now. 
          if((_inports != _outports) || (_isDssiVst && !config.vstInPlace))
            _inPlaceCapable = false;
        }  
      }  
      
      if (dssi == 0) 
      {
        //fprintf(stderr, "cannot found DSSI synti %s\n", _name.toAscii().data());
        fprintf(stderr, "cannot find DSSI synti %s\n", _name.toLatin1().constData());
        dlclose(handle);
        handle = 0;
        df     = 0;
        return 0;
      }
      
      DssiSynthIF* sif = new DssiSynthIF(synti);
      ++_instances;
      sif->init(this);

      //_plugin->incInstances(1);



//      static char oscUrl[1024];
      //snprintf(oscUrl, 1024, "%s/%s", url, synti->name().toAscii().data());
      //snprintf(oscUrl, 1024, "%s/%s", url, synti->name().toLatin1().constData());
//      snprintf(oscUrl, 1024, "%s/%s/%s", url, info.baseName().toLatin1().constData(), synti->name().toLatin1().constData());
      //QString guiPath(info.path() + "/" + info.baseName());
      QString guiPath(info.path() + "/" + info.baseName());
      QDir guiDir(guiPath, "*", QDir::Unsorted, QDir::Files);
      _hasGui = guiDir.exists();
      
      //sif->initGui();
      
      return sif;
}

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

//bool DssiSynthIF::guiVisible() const
bool DssiSynthIF::nativeGuiVisible() const
      {
      //return _guiVisible;
      #ifdef OSC_SUPPORT
      return _oscif.oscGuiVisible();
      #endif
      return false;
      }

bool DssiSynthIF::guiVisible() const
      {
      //return _guiVisible;
      //return false;
      return _gui && _gui->isVisible();
      }

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

//void DssiSynthIF::showGui(bool v)    
void DssiSynthIF::showNativeGui(bool v)
      {
      #ifdef OSC_SUPPORT
      
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::showGui(): v:%d visible:%d\n", v, guiVisible());
      #endif
      
      _oscif.oscShowGui(v);
      
      #endif // OSC_SUPPORT
      
      /*
      if (v == guiVisible())
            return;
      
      //if(guiPid == -1)
      if((guiQProc == 0) || (!guiQProc->isRunning()))
      {
        // We need an indicator that update was called - update must have been called to get new path etc...
        // If the process is not running this path is invalid, right?
        if(uiOscPath)
          free(uiOscPath);
        uiOscPath = 0;  
          
        #ifdef DSSI_DEBUG 
        printf("DssiSynthIF::showGui(): No QProcess or process not running. Starting gui...\n");
        #endif
        
        initGui();
      }  
      
      //for (int i = 0; i < 5; ++i) {
      for (int i = 0; i < 10; ++i) {    // Give it a wee bit more time?
            if (uiOscPath)
                  break;
            sleep(1);
            }
      if (uiOscPath == 0) {
            printf("DssiSynthIF::showGui(): no uiOscPath. Error: Timeout - synth gui did not start within 10 seconds.\n");
            return;
            }
      
      char uiOscGuiPath[strlen(uiOscPath)+6];
      sprintf(uiOscGuiPath, "%s/%s", uiOscPath, v ? "show" : "hide");
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::showGui(): Sending show/hide uiOscGuiPath:%s\n", uiOscGuiPath);
      #endif
      
      lo_send(uiTarget, uiOscGuiPath, "");
      _guiVisible = v;
      */
      }

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

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

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

//MidiEvent DssiSynthIF::receiveEvent()
//      {
//      return MidiEvent();
//      }
MidiPlayEvent DssiSynthIF::receiveEvent()
      {
      return MidiPlayEvent();
      }

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

bool DssiSynthIF::init(DssiSynth* s)
      {
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::init\n");
      #endif
      
      synth = s;
      const DSSI_Descriptor* dssi = synth->dssi;
      const LADSPA_Descriptor* ld = dssi->LADSPA_Plugin;
      handle = ld->instantiate(ld, sampleRate);

      #ifdef OSC_SUPPORT
      _oscif.oscSetSynthIF(this);
      #endif
      
      queryPrograms();

      int inports = synth->_inports;
      if(inports != 0)
      {
        audioInBuffers = new float*[inports];
        for(int k = 0; k < inports; ++k)
        {
          //audioInBuffers[k] = new LADSPA_Data[segmentSize];
          //posix_memalign((void**)(audioInBuffers + k), 16, sizeof(float) * segmentSize);
          posix_memalign((void**)&audioInBuffers[k], 16, sizeof(float) * segmentSize);
          memset(audioInBuffers[k], 0, sizeof(float) * segmentSize);
          ld->connect_port(handle, synth->iIdx[k], audioInBuffers[k]);
        }  
      }
      
      int outports = synth->_outports;
      if(outports != 0)
      {
        audioOutBuffers = new float*[outports];
        for(int k = 0; k < outports; ++k)
        {
          //audioOutBuffers[k] = new LADSPA_Data[segmentSize];
          //posix_memalign((void**)(audioOutBuffers + k), 16, sizeof(float) * segmentSize);
          posix_memalign((void**)&audioOutBuffers[k], 16, sizeof(float) * segmentSize);
          memset(audioOutBuffers[k], 0, sizeof(float) * segmentSize);
          ld->connect_port(handle, synth->oIdx[k], audioOutBuffers[k]);
          //printf("DssiSynthIF::init output port name: %s\n", ld->PortNames[synth->oIdx[k]]); // out1, out2, out3 etc
        }  
      }
      
      int controlPorts = synth->_controlInPorts;
      int controlOutPorts = synth->_controlOutPorts;
      
      if(controlPorts != 0)
        controls = new Port[controlPorts];
      else
        controls = 0;
          
      if(controlOutPorts != 0)
        controlsOut = new Port[controlOutPorts];
      else
        controlsOut = 0;

      synth->midiCtl2PortMap.clear();
      synth->port2MidiCtlMap.clear();
      synti->_guiUpdateControls.clear();
      synti->_guiUpdateProgram = false;
                
/*      
      for (int k = 0; k < controlPorts; ++k) {
                int i = synth->pIdx[k];
                controls[k].idx = i;    // p4.0.20
                //controls[k].val = ladspaDefaultValue(ld, i);
                ladspaDefaultValue(ld, i, &controls[k].val);
		
                // Set to false at first.
                synti->_guiUpdateControls.push_back(false);
              
                #ifdef DSSI_DEBUG 
                printf("DssiSynthIF::init control port:%d port idx:%d name:%s\n", k, i, ld->PortNames[i]);
                #endif
                
                // This code is duplicated in ::getControllerInfo()
                //
                
                int ctlnum = DSSI_NONE;
                if(dssi->get_midi_controller_for_port)
                  ctlnum = dssi->get_midi_controller_for_port(handle, i);
                
                // No controller number? Try to give it a unique one...
                if(ctlnum == DSSI_NONE)
                {
                  // FIXME: Be more careful. Must make sure to pick numbers not already chosen or which WILL BE chosen.
                  // Simple but flawed solution: Start them at 0x60000 + 0x2000 = 0x62000. Max NRPN number is 0x3fff.
                  // TODO: Update: Actually we want to try to use CC Controller7 controllers if possible (or a choice) because what if
                  //  the user's controller hardware doesn't support RPN?
                  // If CC Controller7 is chosen we must make sure to use only non-common numbers. An already limited range
                  //  of 127 now becomes narrower. See the cool document midi-controllers.txt in the DSSI source for a 
                  //  nice roundup of numbers and how to choose them and how they relate to synths and DSSI synths etc. !
                  ctlnum = CTRL_NRPN14_OFFSET + 0x2000 + k; 
                }
                else
                {
                  int c = ctlnum;
                  // Can be both CC and NRPN! Prefer CC over NRPN.
                  if(DSSI_IS_CC(ctlnum))
                  {
                    #ifdef DSSI_DEBUG 
                    printf("DssiSynthIF::init is CC control\n");
                    #endif
                    
                    ctlnum = DSSI_CC_NUMBER(c);
                    #ifdef DSSI_DEBUG 
                    if(DSSI_IS_NRPN(ctlnum))
                      printf("DssiSynthIF::init is also NRPN control. Using CC.\n");
                    #endif  
                  }
                  else
                  if(DSSI_IS_NRPN(ctlnum))
                  {
                    #ifdef DSSI_DEBUG 
                    printf("DssiSynthIF::init  is NRPN control\n");
                    #endif
                    
                    ctlnum = DSSI_NRPN_NUMBER(c) + CTRL_NRPN14_OFFSET;
                  }  
                    
                }
                
                #ifdef DSSI_DEBUG 
                printf("DssiSynthIF::init inserting to midiCtl2PortMap: ctlnum:%d k:%d\n", ctlnum, k);
                #endif
                
                // We have a controller number! Insert it and the DSSI port number into both maps.
                synth->midiCtl2PortMap.insert(std::pair<int, int>(ctlnum, k));
                synth->port2MidiCtlMap.insert(std::pair<int, int>(k, ctlnum));
                ld->connect_port(handle, i, &controls[k].val);
            }

      for (int k = 0; k < controlOutPorts; ++k) {
                int i = synth->opIdx[k];
                controlsOut[k].idx = i;    // p4.0.20
    
                #ifdef DSSI_DEBUG 
                printf("DssiSynthIF::init control output port:%d port idx:%d name:%s\n", k, i, ld->PortNames[i]);
                #endif
                    
                //  - Control outs are not handled but still must be connected to something.
                ld->connect_port(handle, i, &controlsOut[k].val);
            }
*/
      // p4.0.20
      int cip = 0;
      int cop = 0;
      for (unsigned long k = 0; k < synth->_portCount; ++k) 
      {
        LADSPA_PortDescriptor pd = ld->PortDescriptors[k];
        
        #ifdef DSSI_DEBUG 
        printf("DssiSynth::init ladspa plugin Port:%lu Name:%s descriptor:%x\n", k, ld->PortNames[k], pd);
        #endif
        
        if (LADSPA_IS_PORT_CONTROL(pd)) 
        {
          if (LADSPA_IS_PORT_INPUT(pd)) 
          {
            controls[cip].idx = k;    
            float val;
            ladspaDefaultValue(ld, k, &val);
            controls[cip].val    = val;
            controls[cip].tmpVal = val;
            controls[cip].enCtrl  = true;
            controls[cip].en2Ctrl = true;
            
            // Set to false at first.
            synti->_guiUpdateControls.push_back(false);
          
            #ifdef DSSI_DEBUG 
            printf("DssiSynthIF::init control port:%d port idx:%d name:%s\n", cip, k, ld->PortNames[k]);
            #endif
            
            // This code is duplicated in ::getControllerInfo()
            //
            
            int ctlnum = DSSI_NONE;
            if(dssi->get_midi_controller_for_port)
              ctlnum = dssi->get_midi_controller_for_port(handle, k);
            
            // No controller number? Try to give it a unique one...
            if(ctlnum == DSSI_NONE)
            {
              // FIXME: Be more careful. Must make sure to pick numbers not already chosen or which WILL BE chosen.
              // Simple but flawed solution: Start them at 0x60000 + 0x2000 = 0x62000. Max NRPN number is 0x3fff.
              // TODO: Update: Actually we want to try to use CC Controller7 controllers if possible (or a choice) because what if
              //  the user's controller hardware doesn't support RPN?
              // If CC Controller7 is chosen we must make sure to use only non-common numbers. An already limited range
              //  of 127 now becomes narrower. See the cool document midi-controllers.txt in the DSSI source for a 
              //  nice roundup of numbers and how to choose them and how they relate to synths and DSSI synths etc. !
              ctlnum = CTRL_NRPN14_OFFSET + 0x2000 + cip; 
            }
            else
            {
              int c = ctlnum;
              // Can be both CC and NRPN! Prefer CC over NRPN.
              if(DSSI_IS_CC(ctlnum))
              {
                #ifdef DSSI_DEBUG 
                printf("DssiSynthIF::init is CC control\n");
                #endif
                
                ctlnum = DSSI_CC_NUMBER(c);
                #ifdef DSSI_DEBUG 
                if(DSSI_IS_NRPN(ctlnum))
                  printf("DssiSynthIF::init is also NRPN control. Using CC.\n");
                #endif  
              }
              else
              if(DSSI_IS_NRPN(ctlnum))
              {
                #ifdef DSSI_DEBUG 
                printf("DssiSynthIF::init  is NRPN control\n");
                #endif
                
                ctlnum = DSSI_NRPN_NUMBER(c) + CTRL_NRPN14_OFFSET;
              }  
                
            }
            
            #ifdef DSSI_DEBUG 
            printf("DssiSynthIF::init inserting to midiCtl2PortMap: ctlnum:%d k:%d\n", ctlnum, cip);
            #endif
            
            // We have a controller number! Insert it and the DSSI port number into both maps.
            synth->midiCtl2PortMap.insert(std::pair<int, int>(ctlnum, cip));
            synth->port2MidiCtlMap.insert(std::pair<int, int>(cip, ctlnum));
            
            // Support a special block for dssi synth ladspa controllers. p4.0.20
            // Put the ID at a special block after plugins (far after).
            int id = genACnum(MAX_PLUGINS, cip);
            const char* name = ld->PortNames[k];
            float min, max;
            ladspaControlRange(ld, k, &min, &max);
            CtrlList* cl;
            CtrlListList* cll = ((AudioTrack*)synti)->controller();
            iCtrlList icl = cll->find(id);
            if (icl == cll->end())
            {
              cl = new CtrlList(id);
              cll->add(cl);
              cl->setCurVal(controls[cip].val);
            }
            else 
            {
              cl = icl->second;
              controls[cip].val = cl->curVal();
            }
            cl->setRange(min, max);
            cl->setName(QString(name));
            cl->setValueType(ladspaCtrlValueType(ld, k));
            cl->setMode(ladspaCtrlMode(ld, k));
            
            ld->connect_port(handle, k, &controls[cip].val);
            
            ++cip;
          }
          else if (LADSPA_IS_PORT_OUTPUT(pd))
          {
            controlsOut[cop].idx = k;
            controlsOut[cop].val    = 0.0;
            controlsOut[cop].tmpVal = 0.0;
            controlsOut[cop].enCtrl  = false;
            controlsOut[cop].en2Ctrl = false;

            #ifdef DSSI_DEBUG 
            printf("DssiSynthIF::init control output port:%d port idx:%d name:%s\n", cop, k, ld->PortNames[k]);
            #endif
            
            //  Control outs are not handled but still must be connected to something.
            ld->connect_port(handle, k, &controlsOut[cop].val);
            
            ++cop;
          }
        }
      }
          
      
      /*
      // Add the LADSPA controllers to the audio track controller list. p4.0.20
      //int controller = plugin->parameters();
      int controller = controlPorts;
      for (int i = 0; i < controller; ++i) 
      {
        //int id = genACnum(idx, i);
        // Put the ID at a special block after plugins (far after).
        int id = genACnum(MAX_PLUGINS, i);
        const char* name = plugin->paramName(i);
        synth->dssi->LADSPA_Plugin->PortNames[controls[i].idx]
        float min, max;
        plugin->range(i, &min, &max);
        CtrlValueType t = plugin->valueType();
        CtrlList* cl = new CtrlList(id);
        cl->setRange(min, max);
        cl->setName(QString(name));
        cl->setValueType(t);
        LADSPA_PortRangeHint range = plugin->range(i);
        if(LADSPA_IS_HINT_TOGGLED(range.HintDescriptor))
          cl->setMode(CtrlList::DISCRETE);
        else  
          cl->setMode(CtrlList::INTERPOLATE);
        cl->setCurVal(plugin->param(i));
        addController(cl);
      }
      */
      
      if (ld->activate)
            ld->activate(handle);

      // Set current configuration values.
      if(dssi->configure) 
      {
        char *rv = dssi->configure(handle, DSSI_PROJECT_DIRECTORY_KEY,
            museProject.toLatin1().constData()); //song->projectPath()
        
        if(rv)
        {
          fprintf(stderr, "MusE: Warning: plugin doesn't like project directory: \"%s\"\n", rv);
          free(rv);
        }          
        
        for(ciStringParamMap r = synti->_stringParamMap.begin(); r != synti->_stringParamMap.end(); ++r) 
        {
          rv = 0;
          rv = dssi->configure(handle, r->first.c_str(), r->second.c_str());
          if(rv)
          {
            fprintf(stderr, "MusE: Warning: plugin config key: %s value: %s \"%s\"\n", r->first.c_str(), r->second.c_str(), rv);
            free(rv);
          }  
        }
      }
            
      // Set current program.
      if(dssi->select_program)
        dssi->select_program(handle, synti->_curBankL, synti->_curProgram);
      
      //
      // For stored initial control values, let SynthI::initInstance() take care of that via ::setParameter().
      //
        
      return true;
      }

//---------------------------------------------------------
//   DssiSynthIF
//---------------------------------------------------------

DssiSynthIF::DssiSynthIF(SynthI* s)
   : SynthIF(s)
      {
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::DssiSynthIF\n");
      #endif
      
      synth = 0;
      handle = NULL;
      controls = 0;
      controlsOut = 0;
      
      //_curBank = 0;
      //_curProgram = 0;
      
      //#ifdef OSC_SUPPORT
      //_oscif.setSynthIF(this);
      //#endif
      
      //_guiVisible = false;
      //uiTarget = 0;
      //uiOscShowPath = 0;
      //uiOscControlPath = 0;
      //uiOscConfigurePath = 0;
      //uiOscProgramPath = 0;
      //uiOscPath = 0;
      //guiPid = -1;
      //guiQProc = 0;
      
      audioInBuffers = 0;
      audioOutBuffers = 0;
      }

//---------------------------------------------------------
//   ~DssiSynthIF
//---------------------------------------------------------

DssiSynthIF::~DssiSynthIF()
{
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::~DssiSynthIF\n");
      #endif
      
      if(synth)
      {
        #ifdef DSSI_DEBUG 
        printf("DssiSynthIF::~DssiSynthIF synth:%p\n", synth);
        #endif
        
        if(synth->dssi)
        {
          #ifdef DSSI_DEBUG 
          printf("DssiSynthIF::~DssiSynthIF synth->dssi:%p\n", synth->dssi);
          #endif
       
          if(synth->dssi->LADSPA_Plugin)
          {
            #ifdef DSSI_DEBUG 
            printf("DssiSynthIF::~DssiSynthIFsynth->dssi->LADSPA_Plugin:%p\n", synth->dssi->LADSPA_Plugin);
            #endif
          }
        }
      }
      
      if(synth && synth->dssi && synth->dssi->LADSPA_Plugin)
      {
        const DSSI_Descriptor* dssi = synth->dssi;
        const LADSPA_Descriptor* descr = dssi->LADSPA_Plugin;

        #ifdef DSSI_DEBUG 
        printf("DssiSynthIF::~DssiSynthIF checking cleanup function exists\n");
        #endif
        
        if(descr->cleanup)
        {
          #ifdef DSSI_DEBUG 
          printf("DssiSynthIF::~DssiSynthIF calling cleanup function\n");
          #endif
            
          descr->cleanup(handle);
        }    
      }
      
      /*
      //if (guiPid != -1)
      //      kill(guiPid, SIGHUP);
      if(guiQProc)
      {
        if(guiQProc->isRunning())
        {
          #ifdef DSSI_DEBUG 
          printf("DssiSynthIF::~DssiSynthIF killing guiQProc\n");
          #endif
          
          guiQProc->kill();
        }  
        
        //delete guiQProc;
      }
      
      if(uiOscShowPath)
        free(uiOscShowPath);
      if(uiOscControlPath)
        free(uiOscControlPath);
      if(uiOscConfigurePath)
        free(uiOscConfigurePath);
      if(uiOscProgramPath)
        free(uiOscProgramPath);
      if(uiOscPath)
        free(uiOscPath);
      if(uiTarget)
        lo_address_free(uiTarget);
      */
      
      if(audioInBuffers)
      {
        //for(int i = 0; i < synth->_inports; ++i)
        //{
        //  if(audioInBuffers[i])
        //    delete[] audioInBuffers[i];
        //}  
        for(unsigned long i = 0; i < synth->_inports; ++i) 
        {
          if(audioInBuffers[i])
            free(audioInBuffers[i]);
        }
        delete[] audioInBuffers;
      }  
      
      if(audioOutBuffers)
      {
        //for(int i = 0; i < synth->_outports; ++i)
        //{
        //  if(audioOutBuffers[i])
        //    delete[] audioOutBuffers[i];
        //}  
        for(unsigned long i = 0; i < synth->_outports; ++i) 
        {
          if(audioOutBuffers[i])
            free(audioOutBuffers[i]);
        }
        delete[] audioOutBuffers;
      }  
      
      if(controls)
        delete[] controls;
        
      if(controlsOut)
        delete[] controlsOut;
}

int DssiSynthIF::oldMidiStateHeader(const unsigned char** data) const 
{
  static unsigned char const d[2] = {MUSE_SYNTH_SYSEX_MFG_ID, DSSI_SYNTH_UNIQUE_ID};
  *data = &d[0];
  return 2; 
}
        
//---------------------------------------------------------
//   getParameter
//---------------------------------------------------------

float DssiSynthIF::getParameter(unsigned long n) const
{
  if(n >= synth->_controlInPorts)
  {
    printf("DssiSynthIF::getParameter param number %lu out of range of ports:%lu\n", n, synth->_controlInPorts);
    return 0.0;
  }
  
  if(!controls)
    return 0.0;
  
  return controls[n].val;
}
//---------------------------------------------------------
//   getParameter
//---------------------------------------------------------

float DssiSynthIF::getParameterOut(unsigned long n) const
{
  if(n >= synth->_controlOutPorts)
  {
    printf("DssiSynthIF::getParameterOut param number %lu out of range of ports:%lu\n", n, synth->_controlOutPorts);
    return 0.0;
  }

  if(!controlsOut)
    return 0.0;

  return controlsOut[n].val;
}

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

void DssiSynthIF::setParameter(unsigned long n, float v)
{
  if(n >= synth->_controlInPorts)
  {
    printf("DssiSynthIF::setParameter param number %lu out of range of ports:%lu\n", n, synth->_controlInPorts);
    return;
  }
  
  //if(!controls)
  //  return;
  //controls[n].val = v;
  // p4.0.21
  ControlEvent ce;
  ce.unique = false;
  ce.idx = n;
  ce.value = v;
  // Time-stamp the event. This does a possibly slightly slow call to gettimeofday via timestamp().
  //  timestamp() is more or less an estimate of the current frame. (This is exactly how ALSA events 
  //  are treated when they arrive in our ALSA driver.) 
  //ce.frame = audio->timestamp();  
  // p4.0.23 timestamp() is circular, which is making it impossible to deal with 'modulo' events which 
  //  slip in 'under the wire' before processing the ring buffers. So try this linear timestamp instead:
  ce.frame = audio->curFrame();  
  if(_controlFifo.put(ce))
  {
    fprintf(stderr, "DssiSynthIF::setParameter: fifo overflow: in control number:%lu\n", n);
  }
  
  // Notify that changes are to be sent upon heartbeat.
  // TODO: No, at least not for now. So far, setParameter is only called during loading of stored params,
  //  and we don't want this interfering with oscUpdate which also sends the values.
  //synti->_guiUpdateControls[n] = true;
}

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

//void DssiSynthIF::write(Xml&) const
void DssiSynthIF::write(int level, Xml& xml) const
{
      //bool vstsaved = false;

#ifdef DSSI_VST_CHUNK_SUPPORT
      if(synth->dssi->getCustomData)
      {
        //---------------------------------------------
        // dump current state of synth
        //---------------------------------------------
        printf("dumping DSSI custom data! %p\n", synth->dssi->getCustomData);
  
        // this is only needed and supported if
        // we are talking to a VST plugin at the other end.
        std::string name = synth->dssi->LADSPA_Plugin->Name;
        if ((name.length()> 4) && name.substr(name.length() - 4) == " VST")
        {
          printf("is vst plugin, commencing data dump, apiversion=%d!\n", synth->dssi->DSSI_API_Version);
          unsigned long len = 0;
          void* p = 0;
          synth->dssi->getCustomData(handle,&p, &len);
          if (len) {
                //xml.tag(level++, "midistate");
                xml.tag(level++, "midistate version=\"%d\"", SYNTH_MIDI_STATE_SAVE_VERSION);         // p4.0.27
                xml.nput(level++, "<event type=\"%d\"", Sysex);
                //xml.nput(" datalen=\"%d\">\n", len+7 /*VSTSAVE*/);
                xml.nput(" datalen=\"%d\">\n", len+9 /* 2 bytes header + "VSTSAVE" */);
                xml.nput(level, "");
                xml.nput("%02x %02x ", (char)MUSE_SYNTH_SYSEX_MFG_ID, (char)DSSI_SYNTH_UNIQUE_ID);   // p4.0.27 Wrap in a proper header
                xml.nput("56 53 54 53 41 56 45 "); // embed a save marker "string 'VSTSAVE'
                for (long unsigned int i = 0; i < len; ++i) {
                      //if (i && (((i+7) % 16) == 0)) {
                      if (i && (((i+9) % 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");
                //vstsaved = true;
                }
        }        
      }
#else
      printf("support for vst chunks not compiled in!\n");
#endif

      /*
      // p3.3.39 Store the state of current program and bank and all input control values, but only if VSTSAVE above didn't do it already! 
      // TODO: Not quite good enough, we would want to store all controls for EACH program, not just the current one. 
      // Need to modify controls array to be inside a program array and act as a cache when the user changes a control on a particular program.
      if(!vstsaved)
      {
        if(synth->_controlInPorts)
        {
          // TODO: Hmm, what if these sizes change (platform etc.)? Hard code? Not good - need to store complete value.
          const int fs = sizeof(float);
          const int uls = sizeof(unsigned long);
          
          // Data length: Version major and minor bytes, bank + program, and controllers. 
          const unsigned long len = 2 + 2 * uls + synth->_controlInPorts * fs; 
          
          unsigned long prog = _curBank; 
          unsigned long bnk = _curProgram;
          
          xml.tag(level++, "midistate");
          xml.nput(level++, "<event type=\"%d\"", Sysex);
          xml.nput(" datalen=\"%d\">\n", len+9); //  "PARAMSAVE" length + data length.
          xml.nput(level, "");
          xml.nput("50 41 52 41 4d 53 41 56 45 "); // Embed a save marker string "PARAMSAVE".
          
          unsigned long i = 9;
          
          // Store PARAMSAVE version major...
          char uc = DSSI_PARAMSAVE_VERSION_MAJOR;
          if(i && ((i % 16) == 0)) 
          {
            xml.nput("\n");
            xml.nput(level, "");
          }
          xml.nput("%02x ", uc & 0xff);
          ++i;
          
          // Store PARAMSAVE version minor...
          uc = DSSI_PARAMSAVE_VERSION_MINOR;
          if(i && ((i % 16) == 0)) 
          {
            xml.nput("\n");
            xml.nput(level, "");
          }
          xml.nput("%02x ", uc & 0xff);
          ++i;
          
          // Store bank...
          void* p = &bnk;
          for(int j = 0; j < uls; ++j)
          {
            if(i && ((i % 16) == 0)) 
            {
              xml.nput("\n");
              xml.nput(level, "");
            }
            xml.nput("%02x ", ((char*)(p))[j] & 0xff);
            ++i;
          }  
          
          // Store program...
          p = &prog;
          for(int j = 0; j < uls; ++j)
          {
            if(i && ((i % 16) == 0)) 
            {
              xml.nput("\n");
              xml.nput(level, "");
            }
            xml.nput("%02x ", ((char*)(p))[j] & 0xff);
            ++i;
          }  
          
          // Store controls...
          for(unsigned long c = 0; c < synth->_controlInPorts; ++c)
          {
            float v = controls[c].val;
            p = &v;
            for(int j = 0; j < fs; ++j)
            {
              if(i && ((i % 16) == 0)) 
              {
                xml.nput("\n");
                xml.nput(level, "");
              }
              xml.nput("%02x ", ((char*)(p))[j] & 0xff);
              ++i;
            }  
          }
          xml.nput("\n");
          xml.tag(level--, "/event");
          xml.etag(level--, "midistate");
        }
      }
      */
      
      // Store controls as parameters...
      for(unsigned long c = 0; c < synth->_controlInPorts; ++c)
      {
        float f = controls[c].val;
        xml.floatTag(level, "param", f);
        //xml.tag(level, "param name=\"%s\" val=\"%s\"/", name, r->first.c_str(), r->second.c_str());
      }  
}

//---------------------------------------------------------
//   preProcessAlways
//---------------------------------------------------------

void DssiSynthIF::preProcessAlways()
{

}

//---------------------------------------------------------
//   processEvent
//   Return true if event pointer filled.
//--------------------------------------------------------

bool DssiSynthIF::processEvent(const MidiPlayEvent& e, snd_seq_event_t* event)
{
  const DSSI_Descriptor* dssi = synth->dssi;
  
  int chn = e.channel();
  int a   = e.dataA();
  int b   = e.dataB();
  //for sysex
  //QByteArray ba = QByteArray((const char*)e.data(), e.len());
  //we must had 0xF0 at the beginning and 0xF7 at the end of e.data()
  //ba.push_front(0xF0);
  //ba.push_back(0xF7);
  
  //QByteArray ba();
  ////ba.assign((const char*)e.data(), e.len());
  ////ba.duplicate((const char*)e.data(), e.len());
  ////ba.setRawData((const char*)e.data(), e.len());
  //int len = e.len() + 2;
  
  int len = e.len();
  char ca[len + 2];
  
  ca[0] = 0xF0;
  memcpy(ca + 1, (const char*)e.data(), len);
  ca[len + 1] = 0xF7;

  len += 2;

  //snd_seq_event_t* event = &events[nevents];
  //event->queue = SND_SEQ_QUEUE_DIRECT;

  #ifdef DSSI_DEBUG 
  fprintf(stderr, "DssiSynthIF::processEvent midi event type:%d chn:%d a:%d b:%d\n", e.type(), chn, a, b);
  #endif
  
  switch(e.type()) 
  {
    case ME_NOTEON:
      #ifdef DSSI_DEBUG 
      fprintf(stderr, "DssiSynthIF::processEvent midi event is ME_NOTEON\n");
      #endif
          
      snd_seq_ev_clear(event); 
      event->queue = SND_SEQ_QUEUE_DIRECT;
      if(b)
        snd_seq_ev_set_noteon(event, chn, a, b);
      else
        snd_seq_ev_set_noteoff(event, chn, a, 0);
    break;
    case ME_NOTEOFF:
      snd_seq_ev_clear(event); 
      event->queue = SND_SEQ_QUEUE_DIRECT;
      snd_seq_ev_set_noteoff(event, chn, a, 0);
    break;
    case ME_PROGRAM:
    {
      #ifdef DSSI_DEBUG 
      fprintf(stderr, "DssiSynthIF::processEvent midi event is ME_PROGRAM\n");
      #endif
      
      int bank = (a >> 8) & 0xff;
      int prog = a & 0xff;
      //_curBank = bank;
      //_curProgram = prog;
      synti->_curBankH = 0;
      synti->_curBankL = bank;
      synti->_curProgram = prog;
      
      if(dssi->select_program)
      {
        dssi->select_program(handle, bank, prog);
        // Notify that changes are to be sent upon heartbeat.
        synti->_guiUpdateProgram = true;
      }  
      // Event pointer not filled. Return false.
      return false;
    }    
    break;
    case ME_CONTROLLER:
    {
      #ifdef DSSI_DEBUG 
      fprintf(stderr, "DssiSynthIF::processEvent midi event is ME_CONTROLLER\n");
      #endif
      
      if((a == 0) || (a == 32))
        return false;
        
      if(a == CTRL_PROGRAM) 
      {
        #ifdef DSSI_DEBUG 
        fprintf(stderr, "DssiSynthIF::processEvent midi event is ME_CONTROLLER, dataA is CTRL_PROGRAM\n");
        #endif
        
        int bank = (b >> 8) & 0xff;
        int prog = b & 0xff;
        
        //_curBank = bank;
        //_curProgram = prog;
        synti->_curBankH = 0;
        synti->_curBankL = bank;
        synti->_curProgram = prog;
        
        if(dssi->select_program)
        {
          dssi->select_program(handle, bank, prog);
          // Notify that changes are to be sent upon heartbeat.
          synti->_guiUpdateProgram = true;
        }  
        // Event pointer not filled. Return false.
        return false;
      }
          
      if(a == CTRL_PITCH) 
      {
        #ifdef DSSI_DEBUG 
        fprintf(stderr, "DssiSynthIF::processEvent midi event is ME_CONTROLLER, dataA is CTRL_PITCH\n");
        #endif
        
        b &= 0x3fff;
        snd_seq_ev_clear(event); 
        event->queue = SND_SEQ_QUEUE_DIRECT;
        snd_seq_ev_set_pitchbend(event, chn, b);
        // Event pointer filled. Return true.
        return true;
      }
          
      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())
      {
        // p3.3.39 Changed to return false because of crashes with unknown controllers when switching a midi track 
        //  among different dssi synths and regular synths etc. For example high RPN offset numbers (set by another 
        //  device selected into the midi port before selecting this synth) were passing through here when in fact 
        //  the particular synth had no such midi controllers. 
        // ========================== No, that leaves out regular controllers like footpedal
        //#ifdef DSSI_DEBUG 
        //fprintf(stderr, "DssiSynthIF::processEvent dataA:%d not found in map (not a ladspa controller). Ignoring.\n", a);
        //#endif
        //return false;
        
        //#ifdef DSSI_DEBUG 
        //fprintf(stderr, "DssiSynthIF::processEvent dataA:%d not found in map (not a ladspa controller). Filling event as regular controller.\n", a);
        //#endif
        //snd_seq_ev_set_controller(event, chn, a, b);
        //return true;
        
        int ctlnum = a;
        //switch(midiControllerType(a))
        if(midiControllerType(a) != MidiController::Controller7)
          return false;   // Event pointer not filled. Return false.
        else  
        {
          /*
          case MidiController::NRPN14:
          case MidiController::Controller14:
          case MidiController::Pitch:
          case MidiController::Program:
          case MidiController::RPN:
          case MidiController::RPN14:
          case MidiController::NRPN:
                #ifdef DSSI_DEBUG 
                fprintf(stderr, "DssiSynthIF::processEvent non-ladspa midi event controller unsupported. DataA:%d\n", a);
                #endif
                return false;
          */
          
          //case MidiController::Controller7:
                #ifdef DSSI_DEBUG 
                //fprintf(stderr, "DssiSynthIF::processEvent midi event is Controller7. Changing to DSSI_CC type. Current dataA:%d\n", a);
                fprintf(stderr, "DssiSynthIF::processEvent non-ladspa midi event is Controller7. Current dataA:%d\n", a);
                #endif  
                //a = DSSI_CC(a);
                a &= 0x7f;
                ctlnum = DSSI_CC_NUMBER(ctlnum);
          //      break;
          
          /*
          case MidiController::NRPN14:
                #ifdef DSSI_DEBUG 
                //  fprintf(stderr, "DssiSynthIF::processEvent midi event is NRPN. Changing to DSSI_NRPN type. Current dataA:%d\n", a);
                fprintf(stderr, "DssiSynthIF::processEvent non-ladspa midi event is NRPN. Current dataA:%d\n", a);
                #endif  
                //a = DSSI_NRPN(a - CTRL_NRPN14_OFFSET);
                a &= 0x3fff;
                ctlnum = DSSI_NRPN_NUMBER(ctlnum);
                break;
          case MidiController::Controller14:
                a &= 0x7f;
                break;
          case MidiController::Pitch:
                // Should be caught above!
                #ifdef DSSI_DEBUG 
                //fprintf(stderr, "DssiSynthIF::processEvent non-ladspa midi event is Pitch. DataA:%d\n", a);
                fprintf(stderr, "DssiSynthIF::processEvent Error! non-ladspa midi event is Pitch. Should have been caught already! DataA:%d\n", a);
                #endif
                //a &= 0x3fff;
                //snd_seq_ev_set_pitchbend(event, chn, b);
                // Event pointer filled. Return true.
                //return true;
                // Event pointer not filled. Return false.
                return false;
          case MidiController::Program:
                // Should be caught above!
                #ifdef DSSI_DEBUG 
                fprintf(stderr, "DssiSynthIF::processEvent Error! non-ladspa midi event is Program. Should have been caught already! DataA:%d\n", a);
                #endif
                return false;
          case MidiController::RPN:
          case MidiController::RPN14:
          case MidiController::NRPN:
          default: 
                #ifdef DSSI_DEBUG 
                fprintf(stderr, "DssiSynthIF::processEvent non-ladspa midi event is RPN, RPN14, or NRPN type. DataA:%d\n", a);
                #endif
                break;      
          */      
        }
        
        // Verify it's the same number.
        //if(ctlnum != a)
        //{
        //  #ifdef DSSI_DEBUG 
        //  printf("DssiSynthIF::processEvent Error! non-ladspa midi ctlnum:%d != event dataA:%d\n", ctlnum, a);
        //  #endif
          // Event not filled. Return false.
          
          // TEMP: TODO: Turn on later
          //return false;
        //}  
        
        // Fill the event.
        #ifdef DSSI_DEBUG 
        printf("DssiSynthIF::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;
      }
      
      //int num = ip->first;
      unsigned long k = ip->second;
      
      ///unsigned long i = synth->pIdx[k];
      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;
          
        // TODO: If necessary... choose non-existing numbers...
        //for(int k = 0; k < controlPorts; ++k) 
        //{
        //  int i = synth->pIdx[k];
        //}
        
        // Simple but flawed solution: Start them at 0x60000 + 0x2000 = 0x62000. Max NRPN number is 0x3fff.
        ctlnum = k + (CTRL_NRPN14_OFFSET + 0x2000);
      }  
      // p3.3.39
      else
      {
        #ifdef DSSI_DEBUG 
        printf("DssiSynthIF::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 DSSI_DEBUG 
          printf("DssiSynthIF::processEvent is CC ctlnum:%d\n", ctlnum);
          #endif
          
          #ifdef DSSI_DEBUG 
          if(DSSI_IS_NRPN(ctlnum))
            printf("DssiSynthIF::processEvent is also NRPN control. Using CC.\n");
          #endif  
        }
        else
        if(DSSI_IS_NRPN(ctlnum))
        {
          ctlnum = DSSI_NRPN_NUMBER(c) + CTRL_NRPN14_OFFSET;
          
          #ifdef DSSI_DEBUG 
          printf("DssiSynthIF::processEvent is NRPN ctlnum:%x(h) %d(d)\n", ctlnum, ctlnum);
          #endif
        }  
      
      }
      
      //{  
        float val = midi2LadspaValue(ld, i, ctlnum, b); 
        
        #ifdef DSSI_DEBUG 
        //fprintf(stderr, "DssiSynthIF::processEvent No midi controller for control port:%d port:%d dataA:%d Converting val from:%d to ladspa:%f\n", i, k, a, b, val);
        fprintf(stderr, "DssiSynthIF::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;
        // FIXME: Testing - Works but is this safe in a RT process callback? Try hooking into gui heartbeat timer instead...
        //lo_send(uiTarget, uiOscControlPath, "if", i, val);
        // Notify that changes are to be sent upon heartbeat.
        synti->_guiUpdateControls[k] = true;
        
        // Since we absorbed the message as a ladspa control change, return false - the event is not filled.
        return false;
      //}
    }
    break;
    case ME_PITCHBEND:
      snd_seq_ev_clear(event); 
      event->queue = SND_SEQ_QUEUE_DIRECT;
      snd_seq_ev_set_pitchbend(event, chn, a);
    break;
    case ME_AFTERTOUCH:
      snd_seq_ev_clear(event); 
      event->queue = SND_SEQ_QUEUE_DIRECT;
      snd_seq_ev_set_chanpress(event, chn, a);
    break;
    case ME_SYSEX: 
      {
        #ifdef DSSI_DEBUG 
        fprintf(stderr, "DssiSynthIF::processEvent midi event is ME_SYSEX\n");
        #endif
        
        // Changed p4.0.27
        const unsigned char* data = e.data();
        if(e.len() >= 2)
        {
          if(data[0] == MUSE_SYNTH_SYSEX_MFG_ID)
          {
            if(data[1] == DSSI_SYNTH_UNIQUE_ID)
            {
              if(e.len() >= 9)
              {
                //if (QString((const char*)e.data()).startsWith("VSTSAVE")) {
                if (QString((const char*)(data + 2)).startsWith("VSTSAVE")) {
#ifdef DSSI_VST_CHUNK_SUPPORT
                  if(dssi->setCustomData)
                  {
                    //printf("loading chunk from sysex %s!\n", e.data()+7);
                    printf("loading chunk from sysex %s!\n", data+9);
                    //dssi->setCustomData(handle, e.data()+7 /* len of str*/,e.len()-7);
                    dssi->setCustomData(handle, (unsigned char*)(data+9) /* len of str*/,e.len()-9);
                  } 
#else
                  printf("support for vst chunks not compiled in!\n");
#endif
                  // Event not filled.
                  return false;
                }  
              }  
            }  
          }  
        }
        /*
        // 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 DSSI_DEBUG 
          fprintf(stderr, "DssiSynthIF::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.
              printf("DssiSynthIF::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)
                  printf("DssiSynthIF::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)
                    printf("DssiSynthIF::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
        {
          // NOTE: There is a limit on the size of a sysex. Got this: 
          // "DssiSynthIF::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*)ba.data());
            (unsigned char*)ca);
        }
      }  
    break;
    default:
      if(debugMsg)
        fprintf(stderr, "DssiSynthIF::processEvent midi event unknown type:%d\n", e.type());
      // Event not filled.
      return false;
    break;
  }
  
  return true;
}

#if 0

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

//void DssiSynthIF::getData(MidiEventList* el, unsigned pos, int ch, unsigned samples, float** data)
iMPEvent DssiSynthIF::getData(MidiPort* /*mp*/, MPEventList* el, iMPEvent i, unsigned pos, int ports, unsigned n, float** buffer)
{
  //#ifdef DSSI_DEBUG 
  //  fprintf(stderr, "DssiSynthIF::getData elsize:%d pos:%d ports:%d samples:%d processed already?:%d\n", el->size(), pos, ports, n, synti->processed());
  //#endif
  
  //BEGIN: Process midi events
  
  // FIXME: Add 10(?) for good luck in case volatile size changes (increments) while we're processing.
  //unsigned long nevents = el->size();
  unsigned long nevents = el->size() + synti->eventFifo.getSize() + 10; 

  /*
  while (!synti->eventFifo.isEmpty()) {
        MidiEvent event = synti->eventFifo.get();
        printf("Dssi: FIFO\n");
        }
  */
  
  snd_seq_event_t events[nevents];
  memset(events, 0, sizeof(events));
  nevents = 0;

  unsigned endPos = pos + n;
  int frameOffset = audio->getFrameOffset();
  
  //iMPEvent i = el->begin();     // Removed p4.0.15
  
  // Process event list events...
  for(; i != el->end(); ++i) 
  {
    if(i->time() >= (endPos + frameOffset))  // NOTE: frameOffset? Tested, examined printouts of times: Seems OK for playback.
      break;
      
    #ifdef DSSI_DEBUG 
    fprintf(stderr, "DssiSynthIF::getData eventlist event time:%d\n", i->time());
    #endif
    
    // p3.3.39 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 = &midiPorts[synti->midiPort()];
      if(i->type() == ME_CONTROLLER) 
      {
        int da = i->dataA();
        int db = i->dataB();
        db = mp->limitValToInstrCtlRange(da, db);
        if(!mp->setHwCtrlState(i->channel(), da, db))
          continue;
        //mp->setHwCtrlState(i->channel(), da, db);
      }
      else
      if(i->type() == ME_PITCHBEND) 
      {
        int da = mp->limitValToInstrCtlRange(CTRL_PITCH, i->dataA());
        if(!mp->setHwCtrlState(i->channel(), CTRL_PITCH, da))
          continue;
        //mp->setHwCtrlState(i->channel(), CTRL_PITCH, da);
      }
      else
      if(i->type() == ME_PROGRAM) 
      {
        if(!mp->setHwCtrlState(i->channel(), CTRL_PROGRAM, i->dataA()))
          continue;
        //mp->setHwCtrlState(i->channel(), CTRL_PROGRAM, i->dataA());
      }
    }
        
    if(processEvent(*i, &events[nevents]))
    {
      // Time-stamp the event.   p4.0.15 Tim.
      int ft = i->time() - frameOffset - pos;
      if(ft < 0)
        ft = 0;
      if (ft >= (int)segmentSize) 
      {
        printf("DssiSynthIF::getData: eventlist event time:%d out of range. pos:%d offset:%d ft:%d (seg=%d)\n", i->time(), pos, frameOffset, ft, segmentSize);
        ///if (ft > (int)segmentSize)
          ft = segmentSize - 1;
      }
      // "Each event is timestamped relative to the start of the block, (mis)using the ALSA "tick time" field as a frame count. 
      //  The host is responsible for ensuring that events with differing timestamps are already ordered by time."  -  From dssi.h
      events[nevents].time.tick = ft;
      
      ++nevents;
    }  
  }
  
  // Now process putEvent events...
  while(!synti->eventFifo.isEmpty()) 
  {
    MidiPlayEvent e = synti->eventFifo.get();  
    
    #ifdef DSSI_DEBUG 
    fprintf(stderr, "DssiSynthIF::getData eventFifo event time:%d\n", e.time());
    #endif
    
    // Maybe TODO: 
    //if(e.time() >= (endPos + frameOffset))  
    //  break;
    
    if(processEvent(e, &events[nevents]))
    {
      // Time-stamp the event.   p4.0.15 Tim.
      int ft = e.time() - frameOffset - pos;
      if(ft < 0)
        ft = 0;
      if (ft >= (int)segmentSize) 
      {
        printf("DssiSynthIF::getData: eventFifo event time:%d out of range. pos:%d offset:%d ft:%d (seg=%d)\n", e.time(), pos, frameOffset, ft, segmentSize);
        ///if (ft > (int)segmentSize)
          ft = segmentSize - 1;
      }
      // "Each event is timestamped relative to the start of the block, (mis)using the ALSA "tick time" field as a frame count. 
      //  The host is responsible for ensuring that events with differing timestamps are already ordered by time."  -  From dssi.h
      events[nevents].time.tick = ft;
      
      ++nevents;
    }  
  }
  
  // Now process OSC gui input control fifo events.
  // It is probably more important that these are processed last so that they take precedence over all other
  //  events because OSC + DSSI/DSSI-VST are fussy about receiving feedback via these control ports, from GUI changes.
  #ifdef OSC_SUPPORT
  unsigned long ctls = synth->_controlInPorts;
  for(unsigned long k = 0; k < ctls; ++k)
  {
    OscControlFifo* cfifo = _oscif.oscFifo(k);
    if(!cfifo)
      continue;
      
    // If there are 'events' in the fifo, get exactly one 'event' per control per process cycle...
    // TODO: The OSC events are now time-stamped. Split up the processing below between parameter changes
    //        and get rid of this slooow control processing!   p4.0.15
    if(!cfifo->isEmpty()) 
    {
      OscControlValue v = cfifo->get();  
      
      #ifdef DSSI_DEBUG 
      fprintf(stderr, "DssiSynthIF::getData OscControlFifo event input control number:%lu value:%f\n", k, v.value);
      #endif
      
      // Set the ladspa control port value.
      controls[k].val = v.value;
      
      // TODO: (From plugin module, adapt for synth if/when our own plugin gui is added to synths).
      // Need to update the automation value, otherwise the block above overwrites with the last automation value.
      ///if(_track)
      ///{
        // Since we are now in the audio thread context, there's no need to send a message,
        //  just modify directly.
        //audio->msgSetPluginCtrlVal(this, genACnum(_id, i), controls[i].val);
      ///  _track->setPluginCtrlVal(k, v.value)
      ///}  
    }
  }  
  #endif

  ///el->erase(el->begin(), i);      // Removed p4.0.15 Let SynthI::getData() do this.
  
  //END: Process midi events
  
  //BEGIN: Run the synth
  // All ports must be connected to something!
  
  // First, copy the given input buffers to our local input buffers.
  unsigned long np, k;
  //np = portsin > synth->_inports ? synth->_inports : portsin;
  //for(k = 0; k < np; ++k)
  //  memcpy(audioInBuffers[k], inbuffer[k], sizeof(float) * n);
  //for(; k < portsin; ++k)
  //  memset(audioInBuffers[k], 0, sizeof(float) * n);
  
  // Watch our limits.
  //willyfoobar-2011-02-13
  //old code//np = ports > synth->_outports ? synth->_outports : ports;
  np = ((unsigned long) ports) > synth->_outports ? synth->_outports : ((unsigned long) ports);
  
  const DSSI_Descriptor* dssi = synth->dssi;
  const LADSPA_Descriptor* descr = dssi->LADSPA_Plugin;
  k = 0;
  // Connect the given buffers directly to the ports, up to a max of synth ports.
  for(; k < np; ++k)
    descr->connect_port(handle, synth->oIdx[k], buffer[k]);
  // Connect the remaining ports to some local buffers (not used yet).
  for(; k < synth->_outports; ++k)
    descr->connect_port(handle, synth->oIdx[k], audioOutBuffers[k]);
  
  /*
  //
  // p3.3.39 Handle inputs...
  //
  //if((song->bounceTrack != this) && !noInRoute()) 
  if(!((AudioTrack*)synti)->noInRoute()) 
  {
    RouteList* irl = ((AudioTrack*)synti)->inRoutes();
    iRoute i = irl->begin();
    if(!i->track->isMidiTrack())
    {
      //if(debugMsg)
        printf("DssiSynthIF::getData: Error: First route is a midi track route!\n");
    }
    else
    {
      int ch     = i->channel       == -1 ? 0 : i->channel;
      int remch  = i->remoteChannel == -1 ? 0 : i->remoteChannel;
      int chs    = i->channels      == -1 ? 0 : i->channels;
      
      // TODO:
      //if(ch >= synth->_inports)
      //iUsedIdx[ch] = true;
      //if(chs == 2)
      //  iUsedIdx[ch + 1] = true;
      
      //((AudioTrack*)i->track)->copyData(framePos, channels, nframe, bp);
      ((AudioTrack*)i->track)->copyData(pos, ports, 
                                      //(i->track->type() == Track::AUDIO_SOFTSYNTH && i->channel != -1) ? i->channel : 0, 
                                      i->channel, 
                                      i->channels,
                                      n, bp);
    }
    
    //unsigned pos, int ports, unsigned n, float** buffer    
    
    ++i;
    for(; i != irl->end(); ++i)
    {
      if(i->track->isMidiTrack())
      {
        //if(debugMsg)
          printf("DssiSynthIF::getData: Error: Route is a midi track route!\n");
        continue;
      }
      //((AudioTrack*)i->track)->addData(framePos, channels, nframe, bp);
      ((AudioTrack*)i->track)->addData(framePos, channels, 
                                        //(i->track->type() == Track::AUDIO_SOFTSYNTH && i->channel != -1) ? i->channel : 0, 
                                        i->channel, 
                                        i->channels,
                                        nframe, bp);
    }
  }  
  */  
    
  //#ifdef DSSI_DEBUG 
  //if(nevents)
  //  fprintf(stderr, "DssiSynthIF::getData run nevents:%d\n", nevents);
  //#endif
  
  // Run the synth for one segment. This processes events and gets/fills our local buffers...
  if(synth->dssi->run_synth)
  {
    synth->dssi->run_synth(handle, n, events, nevents);
    
    // NOTE: Just a test
    //for(int m = 0; m < n; ++m)
    //{
    //  synth->dssi->run_synth(handle, 1, events, nevents);
    //}  

  }  
  else if (synth->dssi->run_multiple_synths) 
  {
    snd_seq_event_t* ev = events;
    synth->dssi->run_multiple_synths(1, &handle, n, &ev, &nevents);
  }
  //END: Run the synth
  
  return i;
}

#else

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

//void DssiSynthIF::getData(MidiEventList* el, unsigned pos, int ch, unsigned samples, float** data)
iMPEvent DssiSynthIF::getData(MidiPort* /*mp*/, MPEventList* el, iMPEvent i, unsigned pos, int ports, unsigned n, float** buffer)
{
  //#ifdef DSSI_DEBUG 
  //  fprintf(stderr, "DssiSynthIF::getData elsize:%d pos:%d ports:%d samples:%d processed already?:%d\n", el->size(), pos, ports, n, synti->processed());
  //#endif
  
  // Grab the control ring buffer size now.
  //const int cbsz = _controlFifo.getSize(); 
  
  // We may not be using nevents all at once - this will be just the maximum. 
  unsigned long nevents = el->size() + synti->eventFifo.getSize(); 
  snd_seq_event_t events[nevents];
  // No, do this in processEvent.
  //memset(events, 0, sizeof(events)); 
  
  //nevents = 0;

  //unsigned long endPos = pos + n;
  int frameOffset = audio->getFrameOffset();
  unsigned long syncFrame = audio->curSyncFrame();  
  
  // All ports must be connected to something!
  unsigned long nop, k;
  // First, copy the given input buffers to our local input buffers.
  //np = portsin > synth->_inports ? synth->_inports : portsin;
  //for(k = 0; k < np; ++k)
  //  memcpy(audioInBuffers[k], inbuffer[k], sizeof(float) * n);
  //for(; k < portsin; ++k)
  //  memset(audioInBuffers[k], 0, sizeof(float) * n);
  
  // Watch our limits.
  //willyfoobar-2011-02-13
  //old code//np = ports > synth->_outports ? synth->_outports : ports;
  nop = ((unsigned long) ports) > synth->_outports ? synth->_outports : ((unsigned long) ports);
  // TODO Number of inports requested?
  //nip = ((unsigned long) iports) > synth->_inports ? synth->_inports : ((unsigned long) iports);
  
  const DSSI_Descriptor* dssi = synth->dssi;
  const LADSPA_Descriptor* descr = dssi->LADSPA_Plugin;
  unsigned long sample = 0;
  int loopcount = 0;      // REMOVE Tim.
  
  // To remember the last retrieved value of each AudioTrack controller. 
  //float prev_ctrl_values[synth->_controlInPorts];
  
  // NOTE Tested: Variable run-lengths worked superbly for LADSPA and DSSI synths. But DSSI-VST definitely 
  //  does NOT like changing sample run length. It crashes the plugin and Wine (but MusE keeps running!). 
  // Furthermore, it resizes the shared memory (mmap, remap) upon each run length DIFFERENT from the last. 
  // And all of this done through client-server communications. It doesn't seem designed for this technique.
  //
  // So we could support an alternate technique: A fixed control processing rate, in number of samples. 
  //
  // Allow user to choose either a fixed rate or these 'packets' for LADSPA and DSSI plugins/synths, 
  //  but make fixed-rate MANDATORY for DSSI-VST plugins and synths.
  // 
  // Or K.I.S.S - Just use fixed rates only, but allow it to be changed. I'm worried about libraries and
  //  plugins other than DSSI-VST. What if they need the fixed-rate, too?
  // How to tell, and manage it all...?
  // But this 'packet' method sure seems to work nicely so far, so we'll throw it in...
  //
  // Must make this detectable for dssi vst synths, just like the plugins' in-place blacklist.
  //const bool usefixedrate = true;      
  const bool usefixedrate = synth->_isDssiVst;  // Try this.
  // TODO Make this number a global setting.
  // Note for dssi-vst this MUST equal audio period. It doesn't like broken-up runs (it stutters), 
  //  even with fixed sizes. Could be a Wine + Jack thing, wanting a full Jack buffer's length.
  //unsigned long fixedsize = 2048;   
  unsigned long fixedsize = n;     
  
  // 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. 
  if(fixedsize > n)
    fixedsize = n;
  
  unsigned long min_per = config.minControlProcessPeriod;  
  if(min_per > n)
    min_per = n;
      
  // Process automation control values now.
  // TODO: This needs to be respect frame resolution. Put this inside the sample loop below.
  if(automation && synti && synti->automationType() != AUTO_OFF && id() != -1)
  {
    for(unsigned long k = 0; k < synth->_controlInPorts; ++k)
    {
      if(controls[k].enCtrl && controls[k].en2Ctrl )
        controls[k].val = synti->pluginCtrlVal(genACnum(id(), k));
    }      
  }
        
  while(sample < n)
  {
    //unsigned long nsamp = n;
    //unsigned long nsamp = n - sample;
    unsigned long nsamp = usefixedrate ? fixedsize : n - sample;
    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...
    //for(int m = 0; m < cbsz; ++m)   // Doesn't like this. Why?
    while(!_controlFifo.isEmpty())
    {
      //ControlValue v = _controlFifo.get(); 
      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 = (pos + frameOffset > v.frame + n) ? 0 : v.frame - pos - frameOffset + n; 
      evframe = (syncFrame > v.frame + n) ? 0 : v.frame - syncFrame + n; 
      // Protection. Observed this condition. Why? Supposed to be linear timestamps.
      if(found && evframe < frame)
      {
        printf("DssiSynthIF::getData *** Error: evframe:%lu < frame:%lu idx:%lu val:%f unique:%d\n", 
          evframe, v.frame, v.idx, v.value, v.unique); 
        // Just make it equal to the current frame so it gets processed right away.
        evframe = frame;  
      }    
      
      //printf("DssiSynthIF::getData ctrl dssi:%d idx:%lu frame:%lu val:%f unique:%d evframe:%lu\n", 
      //        synth->_isDssiVst, v.idx, v.frame, v.value, v.unique, evframe);   // REMOVE Tim.
      // Process only items in this time period. Make sure to process all
      //  subsequent items which have the same frame. 
      //if(v.frame >= (endPos + frameOffset) || (found && v.frame != frame))  
      //if(v.frame < sample || v.frame >= (sample + nsamp) || (found && v.frame != frame))  
      //if(v.frame < sample || v.frame >= (endPos + frameOffset) || (found && v.frame != frame))  
      //if(v.frame < startPos || v.frame >= (endPos + frameOffset)  
      //if(evframe < sample || evframe >= n  
      //if(evframe < sample || evframe >= (n + frameOffset)
      if(evframe >= n
         //|| (found && v.frame != frame)  
         //|| (!usefixedrate && found && !v.unique && v.frame != frame)  
         //|| (found && !v.unique && evframe != frame)  
         // Not enough requested samples to satisfy minimum setting? Keep going.
         || (found && !v.unique && (evframe - sample >= min_per))  
         // dssi-vst needs them serialized and accounted for, no matter what. This works with fixed rate 
         //  because nsamp is constant. But with packets, we need to guarantee at least one-frame spacing. 
         // Although we likely won't be using packets with dssi-vst, so it's OK for now.
         //|| (found && v.idx == index))  
         //|| (usefixedrate && found && v.idx == index))  // Try this.
         || (usefixedrate && found && v.unique && v.idx == index))  // 
        break;
      _controlFifo.remove();               // Done with the ring buffer's item. Remove it.
      if(v.idx >= synth->_controlInPorts) // Sanity check.
        break;
      found = true;
      //frame = v.frame;
      frame = evframe;
      index = v.idx;
      // Set the ladspa control port value.
      controls[v.idx].val = v.value;
    }
    
    // Process automation control values now.
    //if(automation && synti && synti->automationType() != AUTO_OFF && id() != -1)
    //{
    //  for(unsigned long k = 0; k < synth->_controlInPorts; ++k)
    //  {
    //    if(controls[k].enCtrl && controls[k].en2Ctrl )
    //      controls[k].val = synti->pluginCtrlVal(genACnum(id(), k));
    //  }      
    //}
    
    //if(found)
    if(found && !usefixedrate)
      //nsamp = frame - sample + 1;
      nsamp = frame - sample;
    if(sample + nsamp >= n)         // Safety check.
      nsamp = n - sample; 
    
    //printf("DssiSynthIF::getData n:%d frame:%lu sample:%lu nsamp:%lu pos:%d fOffset:%d syncFrame:%lu loopcount:%d\n", 
    //       n, frame, sample, nsamp, pos, frameOffset, syncFrame, loopcount);   // REMOVE Tim.
    
    // TODO: TESTING: 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)
      continue;
      
    nevents = 0;
    // Process event list events...
    for(; i != el->end(); ++i) 
    {
      //if(i->time() >= (endPos + frameOffset))  // NOTE: frameOffset? Tested, examined printouts of times: Seems OK for playback.
      if(i->time() >= (pos + sample + nsamp + frameOffset))  // frameOffset? Test again...
        break;
        
      #ifdef DSSI_DEBUG 
      fprintf(stderr, "DssiSynthIF::getData eventlist event time:%d\n", i->time());
      #endif
      
      // p3.3.39 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 = &midiPorts[synti->midiPort()];
        if(i->type() == ME_CONTROLLER) 
        {
          int da = i->dataA();
          int db = i->dataB();
          db = mp->limitValToInstrCtlRange(da, db);
          if(!mp->setHwCtrlState(i->channel(), da, db))
            continue;
          //mp->setHwCtrlState(i->channel(), da, db);
        }
        else
        if(i->type() == ME_PITCHBEND) 
        {
          int da = mp->limitValToInstrCtlRange(CTRL_PITCH, i->dataA());
          if(!mp->setHwCtrlState(i->channel(), CTRL_PITCH, da))
            continue;
          //mp->setHwCtrlState(i->channel(), CTRL_PITCH, da);
        }
        else
        if(i->type() == ME_PROGRAM) 
        {
          if(!mp->setHwCtrlState(i->channel(), CTRL_PROGRAM, i->dataA()))
            continue;
          //mp->setHwCtrlState(i->channel(), CTRL_PROGRAM, i->dataA());
        }
      }
          
      // Returns false if the event was not filled. It was handled, but some other way.
      if(processEvent(*i, &events[nevents]))
      {
        // Time-stamp the event.   p4.0.15 Tim.
        int ft = i->time() - frameOffset - pos;
        if(ft < 0)
          ft = 0;
        //if (ft >= (int)segmentSize) 
        if (ft >= int(sample + nsamp)) 
        {
          //printf("DssiSynthIF::getData: eventlist event time:%d out of range. pos:%d offset:%d ft:%d (seg=%d)\n", i->time(), pos, frameOffset, ft, segmentSize);
          printf("DssiSynthIF::getData: eventlist event time:%d out of range. pos:%d offset:%d ft:%d sample:%lu nsamp:%lu\n", i->time(), pos, frameOffset, ft, sample, nsamp);
          ///if (ft > (int)segmentSize)
            //ft = segmentSize - 1;
            ft = sample + nsamp - 1;
        }
        // "Each event is timestamped relative to the start of the block, (mis)using the ALSA "tick time" field as a frame count. 
        //  The host is responsible for ensuring that events with differing timestamps are already ordered by time."  -  From dssi.h
        events[nevents].time.tick = ft;
        
        ++nevents;
      }  
    }
    
    // Now process putEvent events...
    while(!synti->eventFifo.isEmpty()) 
    {
      //MidiPlayEvent e = synti->eventFifo.get();  
      MidiPlayEvent e = synti->eventFifo.peek();  
      
      #ifdef DSSI_DEBUG 
      fprintf(stderr, "DssiSynthIF::getData eventFifo event time:%d\n", e.time());
      #endif
      
      //if(e.time() >= (endPos + frameOffset))  
      if(e.time() >= (pos + sample + nsamp + frameOffset))  
        break;
      
      synti->eventFifo.remove();    // Done with ring buffer's event. Remove it.
      // Returns false if the event was not filled. It was handled, but some other way.
      if(processEvent(e, &events[nevents]))
      {
        // Time-stamp the event.   p4.0.15 Tim.
        int ft = e.time() - frameOffset - pos;
        if(ft < 0)
          ft = 0;
        //if (ft >= (int)segmentSize) 
        if (ft >= int(sample + nsamp)) 
        {
          //printf("DssiSynthIF::getData: eventFifo event time:%d out of range. pos:%d offset:%d ft:%d (seg=%d)\n", e.time(), pos, frameOffset, ft, segmentSize);
          printf("DssiSynthIF::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);
          ///if (ft > (int)segmentSize)
            //ft = segmentSize - 1;
            ft = sample + nsamp - 1;
        }
        // "Each event is timestamped relative to the start of the block, (mis)using the ALSA "tick time" field as a frame count. 
        //  The host is responsible for ensuring that events with differing timestamps are already ordered by time."  -  From dssi.h
        events[nevents].time.tick = ft;
        
        ++nevents;
      }  
    }
    
    /*
    //
    // p3.3.39 Handle inputs...
    //
    //if((song->bounceTrack != this) && !noInRoute()) 
    if(!((AudioTrack*)synti)->noInRoute()) 
    {
      RouteList* irl = ((AudioTrack*)synti)->inRoutes();
      iRoute i = irl->begin();
      if(!i->track->isMidiTrack())
      {
        //if(debugMsg)
          printf("DssiSynthIF::getData: Error: First route is a midi track route!\n");
      }
      else
      {
        int ch     = i->channel       == -1 ? 0 : i->channel;
        int remch  = i->remoteChannel == -1 ? 0 : i->remoteChannel;
        int chs    = i->channels      == -1 ? 0 : i->channels;
        
        // TODO:
        //if(ch >= synth->_inports)
        //iUsedIdx[ch] = true;
        //if(chs == 2)
        //  iUsedIdx[ch + 1] = true;
        
        //((AudioTrack*)i->track)->copyData(framePos, channels, nframe, bp);
        ((AudioTrack*)i->track)->copyData(pos, ports, 
                                        //(i->track->type() == Track::AUDIO_SOFTSYNTH && i->channel != -1) ? i->channel : 0, 
                                        i->channel, 
                                        i->channels,
                                        n, bp);
      }
      
      //unsigned pos, int ports, unsigned n, float** buffer    
      
      ++i;
      for(; i != irl->end(); ++i)
      {
        if(i->track->isMidiTrack())
        {
          //if(debugMsg)
            printf("DssiSynthIF::getData: Error: Route is a midi track route!\n");
          continue;
        }
        //((AudioTrack*)i->track)->addData(framePos, channels, nframe, bp);
        ((AudioTrack*)i->track)->addData(framePos, channels, 
                                          //(i->track->type() == Track::AUDIO_SOFTSYNTH && i->channel != -1) ? i->channel : 0, 
                                          i->channel, 
                                          i->channels,
                                          nframe, bp);
      }
    }  
    */  
      
    k = 0;
    // Connect the given buffers directly to the ports, up to a max of synth ports.
    for(; k < nop; ++k)
      descr->connect_port(handle, synth->oIdx[k], buffer[k] + sample);
    // Connect the remaining ports to some local buffers (not used yet).
    for(; k < synth->_outports; ++k)
      descr->connect_port(handle, synth->oIdx[k], audioOutBuffers[k] + sample);
    // Just connect all inputs to some local buffers (not used yet). TODO: Support inputs. 
    for(k = 0; k < synth->_inports; ++k)
      descr->connect_port(handle, synth->iIdx[k], audioInBuffers[k] + sample);
    
    // Run the synth for a period of time. This processes events and gets/fills our local buffers...
    if(synth->dssi->run_synth)
    {
      synth->dssi->run_synth(handle, nsamp, events, nevents);
    }  
    else if (synth->dssi->run_multiple_synths) 
    {
      snd_seq_event_t* ev = events;
      synth->dssi->run_multiple_synths(1, &handle, nsamp, &ev, &nevents);
    }
    //else 
    //if(synth->dssi->LADSPA_Plugin->run)         
    //{
    //  // Just a test, worked OK.
    //  synth->dssi->LADSPA_Plugin->run(handle, nsamp);     
    //}
    
    sample += nsamp;
    loopcount++;       // REMOVE Tim.
  }
  
  return i;
}
#endif

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

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


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

void DssiSynth::incInstances(int val)
{
      _instances += val;
      if (_instances == 0) 
      {
            if (handle)
            {
              #ifdef DSSI_DEBUG 
              fprintf(stderr, "DssiSynth::incInstances no more instances, closing library\n");
              #endif
              
              dlclose(handle);
            }
            handle = 0;
            dssi = NULL;
            df   = NULL;
            ///pIdx.clear(); 
            ///opIdx.clear();
            iIdx.clear(); 
            oIdx.clear(); 
            rpIdx.clear();
            iUsedIdx.clear();
            midiCtl2PortMap.clear();
            port2MidiCtlMap.clear();
            //synti->_guiUpdateControls.clear();
      }
}

//---------------------------------------------------------
//   initGui
//---------------------------------------------------------
bool DssiSynthIF::initGui()
{
      #ifdef OSC_SUPPORT
      return _oscif.oscInitGui();
      #endif
      
      return true;
      
      /*
      // Are we already running? We don't want to allow another process do we...
      if((guiQProc != 0) && (guiQProc->isRunning()))
        return true;
        
      //
      //  start gui
      //
      static char oscUrl[1024];
      //snprintf(oscUrl, 1024, "%s/%s", url, synti->name().toAscii().data());
      //snprintf(oscUrl, 1024, "%s/%s", url, synti->name().toLatin1().constData());
      snprintf(oscUrl, 1024, "%s/%s/%s", url, synth->info.baseName().toLatin1().constData(), synti->name().toLatin1().constData());

      //QString guiPath(info.path() + "/" + info.baseName());
      QString guiPath(synth->info.dirPath() + "/" + synth->info.baseName());

      QDir guiDir(guiPath, "*", QDir::Unsorted, QDir::Files);
      if (guiDir.exists()) 
      {
            //const QFileInfoList list = guiDir.entryInfoList();
            QStringList list = guiDir.entryList();
            
            //for (int i = 0; i < list.size(); ++i) {
            for (unsigned int i = 0; i < list.count(); ++i) 
            {
                
                //QFileInfo fi = list.at(i);
                QFileInfo fi(guiPath + QString("/") + list[i]);
                  
                  QString gui(fi.filePath());
                  if (gui.contains('_') == 0)
                        continue;
                  struct stat buf;
                  
                  //if (stat(gui.toAscii().data(), &buf)) {
                  if (stat(gui.toLatin1().constData(), &buf)) {
                  
                        perror("stat failed");
                        continue;
                        }

                  #ifdef DSSI_DEBUG 
                  fprintf(stderr, "DssiSynthIF::initGui  %s %s %s %s\n",
                      //fi.filePath().toAscii().data(),
                      //fi.fileName().toAscii().data(),
                      fi.filePath().toLatin1().constData(),
                      //fi.fileName().toLatin1().constData(),
                      
                      oscUrl,
                      
                      synth->info.filePath().toLatin1().constData(),
                      
                      //name().toAscii().data(),
                      synth->name().toLatin1().constData());
                  #endif
                      
                  if ((S_ISREG(buf.st_mode) || S_ISLNK(buf.st_mode)) &&
                     (buf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) 
                  {
                        // Changed by T356.
                        // fork + execlp were causing the processes to remain after closing gui, requiring manual kill.
                        // Changed to QProcess, works OK now. 
                        //if((guiPid = fork()) == 0) 
                        {
                              // No QProcess created yet? Do it now. Only once per SynthIF instance. Exists until parent destroyed.
                              if(guiQProc == 0)
                                guiQProc = new QProcess(muse);                        
                              
                              // Don't forget this, he he...
                              guiQProc->clearArguments();
                              
                              guiQProc->addArgument(fi.filePath());
                              //guiQProc->addArgument(fi.fileName()); // No conventional 'Arg0' here.
                              guiQProc->addArgument(QString(oscUrl));
                              guiQProc->addArgument(synth->info.filePath());
                              guiQProc->addArgument(synth->name());
                              guiQProc->addArgument(QString("channel 1"));
                              
                              #ifdef DSSI_DEBUG 
                              fprintf(stderr, "DssiSynthIF::initGui starting QProcess\n");
                              #endif
                                
                              if(guiQProc->start() == TRUE)
                              {
                                #ifdef DSSI_DEBUG 
                                fprintf(stderr, "DssiSynthIF::initGui started QProcess\n");
                                #endif
                                
                                //guiPid = guiQProc->processIdentifier();
                              }
                              else
                              {
                              
                                // execlp(
                                        // fi.filePath().toAscii().data(),
                                        // fi.fileName().toAscii().data(),
                                //        fi.filePath().toLatin1().constData(),
                                //        fi.fileName().toLatin1().constData(),
                                        
                                //        oscUrl,
                                        
                                        // info.filePath().toAscii().data(),
                                        // name().toAscii().data(),
                                //        synth->info.filePath().toLatin1().constData(),
                                //        synth->name().toLatin1().constData(),
                                        
                                //        "channel 1", (void*)0);
                                        
                                fprintf(stderr, "exec %s %s %s %s failed: %s\n",
                                        // fi.filePath().toAscii().data(),
                                        // fi.fileName().toAscii().data(),
                                        fi.filePath().toLatin1().constData(),
                                        fi.fileName().toLatin1().constData(),
                                        oscUrl,
                                        //  name().toAscii().data(),
                                        synth->name().toLatin1().constData(),
                                        strerror(errno));
                                        
                                // It's Ok, Keep going. So nothing happens. So what. The timeout in showGui will just leave.
                                // Maybe it's a 'busy' issue somewhere - allow to try again later + save work now.
                                // exit(1);
                                
                              }
                              
                              #ifdef DSSI_DEBUG 
                              fprintf(stderr, "DssiSynthIF::initGui after QProcess\n");
                              #endif
                        }
                  }
            }
            //synth->_hasGui = true;
      }
      else {
            printf("%s: no dir for dssi gui found: %s\n",
               //name().toAscii().data(), guiPath.toAscii().data());
               synth->name().toLatin1().constData(), guiPath.toLatin1().constData());
            
            //synth->_hasGui = false;
            }
            
  return true;          
  */
}

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

void DssiSynthIF::guiHeartBeat()
{
  #ifdef OSC_SUPPORT
  // Update the gui's program if needed.
  if(synti->_guiUpdateProgram)
  {
    _oscif.oscSendProgram(synti->_curProgram, synti->_curBankL);
    synti->_guiUpdateProgram = false;
  }
  
  // Update the gui's controls if needed.
  unsigned long ports = synth->_controlInPorts;
  if(ports > synti->_guiUpdateControls.size())
    return;
  for(unsigned long i = 0; i < ports; ++i)
  {
    if(synti->_guiUpdateControls[i])
    {
      ///unsigned long k = synth->pIdx[i];
      ///_oscif.oscSendControl(k, controls[i].val);
      _oscif.oscSendControl(controls[i].idx, controls[i].val);
    
      // Reset.
      synti->_guiUpdateControls[i] = false;
    }
  }
  #endif
}

#ifdef OSC_SUPPORT
//---------------------------------------------------------
//   oscUpdate
//---------------------------------------------------------

int DssiSynthIF::oscUpdate()
{
      // Send project directory.
      _oscif.oscSendConfigure(DSSI_PROJECT_DIRECTORY_KEY, museProject.toLatin1().constData());  // song->projectPath()
      
      // Send current string configuration parameters.
      //StringParamMap& map = synti->_stringParamMap;
      int i = 0;
      for(ciStringParamMap r = synti->_stringParamMap.begin(); r != synti->_stringParamMap.end(); ++r) 
      {
        _oscif.oscSendConfigure(r->first.c_str(), r->second.c_str());
        // Avoid overloading the GUI if there are lots and lots of params. 
        if((i+1) % 50 == 0)
          usleep(300000);
        ++i;      
      }  
      
      // Send current bank and program.
      //unsigned long bank, prog;
      //synti->currentProg(&prog, &bank, 0);
      //_oscif.oscSendProgram(prog, bank);
      _oscif.oscSendProgram(synti->_curProgram, synti->_curBankL);
      
      // Send current control values.
      unsigned long ports = synth->_controlInPorts;
      for(unsigned long i = 0; i < ports; ++i) 
      {
        ///unsigned long k = synth->pIdx[i];
        ///_oscif.oscSendControl(k, controls[i].val);
        _oscif.oscSendControl(controls[i].idx, controls[i].val);
        
        // Avoid overloading the GUI if there are lots and lots of ports. 
        if((i+1) % 50 == 0)
          usleep(300000);
      }
      
      
#if 0
      /* Send current bank/program  (-FIX- another race...) */
      if (instance->pendingProgramChange < 0) {
            unsigned long bank = instance->currentBank;
            unsigned long program = instance->currentProgram;
            instance->uiNeedsProgramUpdate = 0;
            if (instance->uiTarget) {
                  lo_send(instance->uiTarget, instance->ui_osc_program_path, "ii", bank, program);
                  }
            }

      /* Send control ports */
      for (i = 0; i < instance->plugin->controlIns; i++) {
            int in = i + instance->firstControlIn;
            int port = pluginControlInPortNumbers[in];
            lo_send(instance->uiTarget, instance->ui_osc_control_path, "if", port,
               pluginControlIns[in]);
            /* Avoid overloading the GUI if there are lots and lots of ports */
            if ((i+1) % 50 == 0)
                  usleep(300000);
            }
#endif
      return 0;
}

//---------------------------------------------------------
//   oscProgram
//---------------------------------------------------------

int DssiSynthIF::oscProgram(unsigned long program, unsigned long bank)
      {
      //int bank    = argv[0]->i;
      //int program = argv[1]->i;
      
      int ch      = 0;        // TODO: ??
      
      int port    = synti->midiPort();        
      
      //_curBank = bank;
      //_curProgram = program;
      synti->_curBankH = 0;
      synti->_curBankL = bank;
      synti->_curProgram = program;
      
      bank    &= 0xff;
      program &= 0xff;
      
      //MidiEvent event(0, ch, ME_CONTROLLER, CTRL_PROGRAM, (bank << 8) + program);
      
      if(port != -1)
      {
        //MidiPlayEvent event(0, port, ch, ME_CONTROLLER, CTRL_PROGRAM, (bank << 8) + program);
        MidiPlayEvent event(0, port, ch, ME_PROGRAM, (bank << 8) + program, 0);
      
        #ifdef DSSI_DEBUG 
        fprintf(stderr, "DssiSynthIF::oscProgram midi event chn:%d a:%d b:%d\n", event.channel(), event.dataA(), event.dataB());
        #endif
        
        midiPorts[port].sendEvent(event);
      }
      
      
      
      //synti->playMidiEvent(&event); // TODO
      //
      //MidiDevice* md = dynamic_cast<MidiDevice*>(synti);
      //if(md)
      //  md->putEvent(event);
      //
      //synti->putEvent(event); 
      
      return 0;
      }

//---------------------------------------------------------
//   oscControl
//---------------------------------------------------------

int DssiSynthIF::oscControl(unsigned long port, float value)
      {
  //int port = argv[0]->i;
  //LADSPA_Data value = argv[1]->f;

  #ifdef DSSI_DEBUG 
  printf("DssiSynthIF::oscControl received oscControl port:%lu val:%f\n", port, value);    
  #endif
  
  //int controlPorts = synth->_controlInPorts;
  
  //if(port >= controlPorts)
  //if(port < 0 || port >= synth->rpIdx.size())
  if(port >= synth->rpIdx.size())
  {
    //fprintf(stderr, "DssiSynthIF::oscControl: port number:%d is out of range of number of ports:%d\n", port, controlPorts);
    fprintf(stderr, "DssiSynthIF::oscControl: port number:%lu is out of range of index list size:%zd\n", port, synth->rpIdx.size());
    return 0;
  }
  
  // Convert from DSSI port number to control input port index.
  unsigned long cport = synth->rpIdx[port];
  
  if((int)cport == -1)
  {
    fprintf(stderr, "DssiSynthIF::oscControl: port number:%lu is not a control input\n", port);
    return 0;
  }
  
  // p3.3.39 Set the DSSI control input port's value.
  // Observations: With a native DSSI synth like LessTrivialSynth, the native GUI's controls do not change the sound at all
  //  ie. they don't update the DSSI control port values themselves. 
  // Hence in response to the call to this oscControl, sent by the native GUI, it is required to that here.
///  controls[cport].val = value;
  // DSSI-VST synths however, unlike DSSI synths, DO change their OWN sound in response to their gui controls.
  // AND this function is called. 
  // Despite the descrepency we are STILL required to update the DSSI control port values here 
  //  because dssi-vst is WAITING FOR A RESPONSE. (A CHANGE in the control port value). 
  // It will output something like "...4 events expected..." and count that number down as 4 actual control port value CHANGES
  //  are done here in response. Normally it says "...0 events expected..." when MusE is the one doing the DSSI control changes.
  //
  // NOTE: NOTE: This line in RemoteVSTServer::setParameter(int p, float v) in dssi-vst-server.cpp :
  //
  //  " if (tv.tv_sec > m_lastGuiComms.tv_sec + 10) "
  //
  //  explains an observation that after ten seconds, the server automatically clears the expected number to 0.
  // You can't send any 'new' values until either you a): send all the expected events or b): wait ten seconds.
  // (Because the server simply ignores the 'expected' messages.)
  //
  // Well, at least here are the fifos. Try this ...
  /*
  OscControlFifo* cfifo = _oscif.oscFifo(cport); 
  if(cfifo)
  {
    OscControlValue cv;
    //cv.idx = cport;
    cv.value = value;
    // Time-stamp the event. Looks like no choice but to use the (possibly slow) call to gettimeofday via timestamp(),
    //  because these are asynchronous events arriving from OSC.  timestamp() is more or less an estimate of the
    //  current frame. (This is exactly how ALSA events are treated when they arrive in our ALSA driver.) p4.0.15 Tim. 
    cv.frame = audio->timestamp();  
    if(cfifo->put(cv))
    {
      fprintf(stderr, "DssiSynthIF::oscControl: fifo overflow: in control number:%lu\n", cport);
    }
  }
  */
  // p4.0.21
  ControlEvent ce;
  ce.unique = synth->_isDssiVst;    // Special for messages from vst gui to host - requires processing every message.
  ce.idx = cport;
  ce.value = value;
  // Time-stamp the event. This does a possibly slightly slow call to gettimeofday via timestamp().
  //  timestamp() is more or less an estimate of the current frame. (This is exactly how ALSA events 
  //  are treated when they arrive in our ALSA driver.) 
  //ce.frame = audio->timestamp();  
  // p4.0.23 timestamp() is circular, which is making it impossible to deal with 'modulo' events which 
  //  slip in 'under the wire' before processing the ring buffers. So try this linear timestamp instead:
  ce.frame = audio->curFrame();  
  if(_controlFifo.put(ce))
  {
    fprintf(stderr, "DssiSynthIF::oscControl: fifo overflow: in control number:%lu\n", cport);
  }
  
   
  //const DSSI_Descriptor* dssi = synth->dssi;
  //const LADSPA_Descriptor* ld = dssi->LADSPA_Plugin;
  
  ciMidiCtl2LadspaPort ip = synth->port2MidiCtlMap.find(cport);
  if(ip != synth->port2MidiCtlMap.end())
  {
    // TODO: TODO: Update midi MusE's midi controller knobs, sliders, boxes etc with a call to the midi port's setHwCtrlState() etc.
    // But first we need a ladspa2MidiValue() function!  ... 
    //
    //
    //float val = ladspa2MidiValue(ld, i, ?, ?); 
  
  }

#if 0
      int port = argv[0]->i;
      LADSPA_Data value = argv[1]->f;

      if (port < 0 || port > instance->plugin->descriptor->LADSPA_Plugin->PortCount) {
            fprintf(stderr, "MusE: OSC: %s port number (%d) is out of range\n",
               instance->friendly_name, port);
            return 0;
            }
      if (instance->pluginPortControlInNumbers[port] == -1) {
            fprintf(stderr, "MusE: OSC: %s port %d is not a control in\n",
               instance->friendly_name, port);
            return 0;
            }
      pluginControlIns[instance->pluginPortControlInNumbers[port]] = value;
      if (verbose) {
            printf("MusE: OSC: %s port %d = %f\n",
               instance->friendly_name, port, value);
            }
#endif
      return 0;
      }

/*
//---------------------------------------------------------
//   oscExiting
//---------------------------------------------------------

int DssiSynthIF::oscExiting(lo_arg**)
      {
      //printf("not impl.: oscExiting\n");
      
      // The gui is gone now, right?
      _guiVisible = false;
      
      //const DSSI_Descriptor* dssi = synth->dssi;
      //const LADSPA_Descriptor* ld = dssi->LADSPA_Plugin;
      //if(ld->deactivate) 
      //  ld->deactivate(handle);
      
      if (uiOscPath == 0) {
            printf("DssiSynthIF::oscExiting(): no uiOscPath\n");
            return 1;
            }
      char uiOscGuiPath[strlen(uiOscPath)+6];
        
      sprintf(uiOscGuiPath, "%s/%s", uiOscPath, "quit");
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::oscExiting(): sending quit to uiOscGuiPath:%s\n", uiOscGuiPath);
      #endif
      
      lo_send(uiTarget, uiOscGuiPath, "");
      
#if 0
      int i;

      if (verbose) {
            printf("MusE: OSC: got exiting notification for instance %d\n",
               instance->number);
            }

      if (instance->plugin) {

            // !!! No, this isn't safe -- plugins deactivated in this way
            //  would still be included in a run_multiple_synths call unless
            //  we re-jigged the instance array at the same time -- leave it
            //  for now
            //if (instance->plugin->descriptor->LADSPA_Plugin->deactivate) {
            //      instance->plugin->descriptor->LADSPA_Plugin->deactivate
            //         (instanceHandles[instance->number]);
            //      }
            // Leave this flag though, as we need it to determine when to exit 
            instance->inactive = 1;
            }

      // Do we have any plugins left running? 

      for (i = 0; i < instance_count; ++i) {
            if (!instances[i].inactive)
                  return 0;
            }

      if (verbose) {
            printf("MusE: That was the last remaining plugin, exiting...\n");
            }
      exiting = 1;
#endif
      return 0;
      }
*/

//---------------------------------------------------------
//   oscMidi
//---------------------------------------------------------

int DssiSynthIF::oscMidi(int a, int b, int c)
      {
      //int a = argv[0]->m[1];
      //int b = argv[0]->m[2];
      //int c = argv[0]->m[3];
      
      if (a == ME_NOTEOFF) {
            a = ME_NOTEON;
            c = 0;
            }
      int channel = 0;        // TODO: ??
      
      int port    = synti->midiPort();        
      
      //MidiEvent event(0, channel, a, b, c);
      
      if(port != -1)
      {
        MidiPlayEvent event(0, port, channel, a, b, c);
      
        #ifdef DSSI_DEBUG 
        printf(stderr, "DssiSynthIF::oscMidi midi event chn:%d a:%d b:%d\n", event.channel(), event.dataA(), event.dataB());  
        #endif
        
        midiPorts[port].sendEvent(event);
      }
      
      //synti->playMidiEvent(&event); // TODO
      //
      //MidiDevice* md = dynamic_cast<MidiDevice*>(synti);
      //if(md)
      //  md->putEvent(event);
      //
      //synti->putEvent(event); 
      //
      
      return 0;
      }

//---------------------------------------------------------
//   oscConfigure
//---------------------------------------------------------

int DssiSynthIF::oscConfigure(const char *key, const char *value)
      {
      //const char *key = (const char *)&argv[0]->s;
      //const char *value = (const char *)&argv[1]->s;

      // This is pretty much the simplest legal implementation of
      // configure in a DSSI host. 

      // The host has the option to remember the set of (key,value)
      // pairs associated with a particular instance, so that if it
      // wants to restore the "same" instance on another occasion it can
      // just call configure() on it for each of those pairs and so
      // restore state without any input from a GUI.  Any real-world GUI
      // host will probably want to do that.  This host doesn't have any
      // concept of restoring an instance from one run to the next, so
      // we don't bother remembering these at all. 

      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::oscConfigure synth name:%s key:%s value:%s\n", synti->name().toLatin1().constData(), key, value);
      #endif
      
      // Add or modify the configuration map item.
      synti->_stringParamMap.set(key, value);
      
      if (!strncmp(key, DSSI_RESERVED_CONFIGURE_PREFIX,
         strlen(DSSI_RESERVED_CONFIGURE_PREFIX))) {
            fprintf(stderr, "MusE: OSC: UI for plugin '%s' attempted to use reserved configure key \"%s\", ignoring\n",
               //synti->name().toAscii().data(), key);
               synti->name().toLatin1().constData(), key);
               
            return 0;
            }

      if (!synth->dssi->configure)
            return 0;

      char* message = synth->dssi->configure(handle, key, value);
      if (message) {
            printf("MusE: on configure '%s' '%s', plugin '%s' returned error '%s'\n",
               //key, value, synti->name().toAscii().data(), message);
               key, value, synti->name().toLatin1().constData(), message);
            
            free(message);
            }

      // also call back on UIs for plugins other than the one
      // that requested this:
      // if (n != instance->number && instances[n].uiTarget) {
      //      lo_send(instances[n].uiTarget,
      //      instances[n].ui_osc_configure_path, "ss", key, value);
      //      }

      // configure invalidates bank and program information, so
      //  we should do this again now: 
      queryPrograms();
      return 0;
      }
#endif // OSC_SUPPORT

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

void DssiSynthIF::queryPrograms()
      {
      for (std::vector<DSSI_Program_Descriptor>::const_iterator i = programs.begin();
         i != programs.end(); ++i) {
            free((void*)(i->Name));
            }
      programs.clear();

      //if (!(synth->dssi->get_program && synth->dssi->select_program))
      if (!synth->dssi->get_program)
            return;

      for (int i = 0;; ++i) {
            const DSSI_Program_Descriptor* pd = synth->dssi->get_program(handle, i);
            if (pd == 0)
                  break;
            DSSI_Program_Descriptor d;
            d.Name    = strdup(pd->Name);
            d.Program = pd->Program;
            d.Bank    = pd->Bank;
            programs.push_back(d);
            }
      }

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

//QString DssiSynthIF::getPatchName(int, int prog)
const char* DssiSynthIF::getPatchName(int /*chan*/, int prog, MType /*type*/, bool /*drum*/)
      {
      unsigned program = prog & 0x7f;
      int lbank   = (prog >> 8) & 0xff;
      int hbank   = (prog >> 16) & 0xff;

      if (lbank == 0xff)
            lbank = 0;
      if (hbank == 0xff)
            hbank = 0;
      unsigned bank = (hbank << 8) + lbank;

      for (std::vector<DSSI_Program_Descriptor>::const_iterator i = programs.begin();
         i != programs.end(); ++i) {
            if (i->Bank == bank && i->Program ==program)
                  return i->Name;
            }
      return "?";
      }

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

//void DssiSynthIF::populatePatchPopup(QMenu* menu, int)
void DssiSynthIF::populatePatchPopup(PopupMenu* menu, int /*ch*/, MType /*type*/, 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<DSSI_Program_Descriptor>::const_iterator i = programs.begin();
         i != programs.end(); ++i) {
            int bank = i->Bank;
            int prog = i->Program;
            int id   = (bank << 16) + prog;
            
            QAction *act = menu->addAction(QString(i->Name));
            act->setData(id);
            }
      }

int DssiSynthIF::getControllerInfo(int id, const char** name, int* ctrl, int* min, int* max, int* initval)
{
  int controlPorts = synth->_controlInPorts;
  if(id >= controlPorts)
  //if(id >= midiCtl2PortMap.size())
    return 0;

  const DSSI_Descriptor* dssi = synth->dssi;
  const LADSPA_Descriptor* ld = dssi->LADSPA_Plugin;
  
  // Hmm, <map> has a weird [] operator. Would it work?
  // For now just use duplicate code found in ::init()
  //iMidiCtl2LadspaPort ip = midiCtl2PortMap[id];
  //int ctlnum = ip->first;
  //int k = ip->second;
  
  ///int i = synth->pIdx[id];
  //int i = synth->pIdx[k];
  //int i = controls[id].idx;
  unsigned long i = controls[id].idx;   // p4.0.21
  
  //ladspaDefaultValue(ld, i, &controls[id].val);
  
  #ifdef DSSI_DEBUG 
  printf("DssiSynthIF::getControllerInfo control port:%d port idx:%d name:%s\n", id, i, ld->PortNames[i]);
  #endif
  
  int ctlnum = DSSI_NONE;
  if(dssi->get_midi_controller_for_port)
    ctlnum = dssi->get_midi_controller_for_port(handle, i);
  
  
  // No controller number? Give it one.
  if(ctlnum == DSSI_NONE)
  {
    // TODO: If neccesary... choose non-existing numbers...
    //for(int k = 0; k < controlPorts; ++k) 
    //{
    //  int i = synth->pIdx[k];
    //}
    
    // Simple but flawed solution: Start them at 0x60000 + 0x2000 = 0x62000. Max NRPN number is 0x3fff.
    ctlnum = CTRL_NRPN14_OFFSET + 0x2000 + id;
  }
  else
  {
    #ifdef DSSI_DEBUG 
    printf("DssiSynthIF::getControllerInfo ctlnum:%d\n", ctlnum);
    #endif
     
    int c = ctlnum;
    // Can be both CC and NRPN! Prefer CC over NRPN.
    if(DSSI_IS_CC(ctlnum))
    {
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::getControllerInfo is CC control\n");
      #endif
      
      ctlnum = DSSI_CC_NUMBER(c);
      
      #ifdef DSSI_DEBUG 
      if(DSSI_IS_NRPN(ctlnum))
        printf("DssiSynthIF::getControllerInfo is also NRPN control. Using CC.\n");
      #endif  
    }
    else
    if(DSSI_IS_NRPN(ctlnum))
    {
      #ifdef DSSI_DEBUG 
      printf("DssiSynthIF::getControllerInfo is NRPN control\n");
      #endif
      
      ctlnum = DSSI_NRPN_NUMBER(c) + CTRL_NRPN14_OFFSET;
    }  
  }
  
  int def = CTRL_VAL_UNKNOWN;
  if(ladspa2MidiControlValues(ld, i, ctlnum, min, max, &def))
    *initval = def;
  else
    *initval = CTRL_VAL_UNKNOWN;
    
  #ifdef DSSI_DEBUG 
  printf("DssiSynthIF::getControllerInfo passed ctlnum:%d min:%d max:%d initval:%d\n", ctlnum, *min, *max, *initval);
  #endif
  
  *ctrl = ctlnum;
  *name =  ld->PortNames[i];
  return ++id;

  /*
  // ...now create midi controllers for ports which did not define them ...
  for(int k = 0; k < controlPorts; ++k) 
  {
    int i = synth->pIdx[k];
    //controls[k].val = ladspaDefaultValue(ld, i);
    ladspaDefaultValue(ld, i, &controls[k].val);
    
    printf("DssiSynthIF::getControllerInfo #2 control port:%d port idx:%d name:%s\n", k, i, ld->PortNames[i]);
    
    if(!dssi->get_midi_controller_for_port || (dssi->get_midi_controller_for_port(handle, i) == DSSI_NONE))
    {
      int ctlnum;
      //printf("DssiSynthIF::getControllerInfo #2 midi controller number:%d\n", ctlnum);
      printf("DssiSynthIF::getControllerInfo #2 creating MidiController number:%d\n", ctlnum);
      MidiController* mc = ladspa2MidiController(ld, i, ctlnum); 
      // Add to MidiInstrument controller list.
      if(mc)
      {
        printf("DssiSynthIF::getControllerInfo #2 adding MidiController to instrument\n");
        ((MidiInstrument*)synti)->controller()->add(mc);
      }  
    }
    else
    {
    
    }
  }
  */

}

int DssiSynthIF::channels() const 
{ 
    //willyfoobar-2011-02-13
    //!! either change return type to unsigend long or do this change
    //old code //return synth->_outports > MAX_CHANNELS ? MAX_CHANNELS : synth->_outports; 
    return ((int)synth->_outports) > MAX_CHANNELS ? MAX_CHANNELS : ((int)synth->_outports) ;
}

int DssiSynthIF::totalOutChannels() const 
{ 
  return synth->_outports; 
}

int DssiSynthIF::totalInChannels() const 
{ 
  return synth->_inports; 
}

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

bool DssiSynthIF::on() const                                 { return true; }  // Synth is not part of a rack plugin chain. Always on.
void DssiSynthIF::setOn(bool /*val*/)                        { }   
//int DssiSynthIF::pluginID()                                  { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->UniqueID : 0; } 
unsigned long DssiSynthIF::pluginID()                        { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->UniqueID : 0; }   
//int DssiSynthIF::id()                                        { return 0; } // Synth is not part of a rack plugin chain. Always 0.
int DssiSynthIF::id()                                        { return MAX_PLUGINS; } // Set for special block reserved for dssi synth. p4.0.20
QString DssiSynthIF::pluginLabel() const                     { return (synth && synth->dssi) ? QString(synth->dssi->LADSPA_Plugin->Label) : QString(); } 
QString DssiSynthIF::name() const                            { return synti->name(); }
QString DssiSynthIF::lib() const                             { return synth ? synth->completeBaseName() : QString(); }
QString DssiSynthIF::dirPath() const                         { return synth ? synth->absolutePath() : QString(); }
QString DssiSynthIF::fileName() const                        { return synth ? synth->fileName() : QString(); }
AudioTrack* DssiSynthIF::track()                             { return (AudioTrack*)synti; }
//void DssiSynthIF::enableController(int i, bool v)            { controls[i].enCtrl = v; } 
//bool DssiSynthIF::controllerEnabled(int i) const             { return controls[i].enCtrl; }  
//bool DssiSynthIF::controllerEnabled2(int i) const            { return controls[i].en2Ctrl; }   
void DssiSynthIF::enableController(unsigned long i, bool v)  { controls[i].enCtrl = v; } 
bool DssiSynthIF::controllerEnabled(unsigned long i) const   { return controls[i].enCtrl; }  
bool DssiSynthIF::controllerEnabled2(unsigned long i) const  { return controls[i].en2Ctrl; }   
void DssiSynthIF::updateControllers()                        { }
void DssiSynthIF::writeConfiguration(int /*level*/, Xml& /*xml*/)        { }
bool DssiSynthIF::readConfiguration(Xml& /*xml*/, bool /*readPreset*/) { return false; }

//int DssiSynthIF::parameters() const                          { return synth ? synth->_controlInPorts : 0; }
//void DssiSynthIF::setParam(int i, double val)                { setParameter(i, val); }
//double DssiSynthIF::param(int i) const                       { return getParameter(i); }
//const char* DssiSynthIF::paramName(int i)                    { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->PortNames[controls[i].idx] : 0; }
//LADSPA_PortRangeHint DssiSynthIF::range(int i)               { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->PortRangeHints[i] : 0; }
//LADSPA_PortRangeHint DssiSynthIF::range(int i)               { return synth->dssi->LADSPA_Plugin->PortRangeHints[controls[i].idx]; }
unsigned long DssiSynthIF::parameters() const                { return synth ? synth->_controlInPorts : 0; }
unsigned long DssiSynthIF::parametersOut() const             { return synth ? synth->_controlOutPorts : 0; }
void DssiSynthIF::setParam(unsigned long i, float val)       { setParameter(i, val); }
float DssiSynthIF::param(unsigned long i) const              { return getParameter(i); }
float DssiSynthIF::paramOut(unsigned long i) const           { return getParameterOut(i); }
const char* DssiSynthIF::paramName(unsigned long i)          { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->PortNames[controls[i].idx] : 0; }
const char* DssiSynthIF::paramOutName(unsigned long i)       { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->PortNames[controlsOut[i].idx] : 0; }
//LADSPA_PortRangeHint DssiSynthIF::range(unsigned long i)     { return (synth && synth->dssi) ? synth->dssi->LADSPA_Plugin->PortRangeHints[i] : 0; }
LADSPA_PortRangeHint DssiSynthIF::range(unsigned long i)     { return synth->dssi->LADSPA_Plugin->PortRangeHints[controls[i].idx]; }
LADSPA_PortRangeHint DssiSynthIF::rangeOut(unsigned long i)  { return synth->dssi->LADSPA_Plugin->PortRangeHints[controlsOut[i].idx]; }
CtrlValueType DssiSynthIF::ctrlValueType(unsigned long i) const { return ladspaCtrlValueType(synth->dssi->LADSPA_Plugin, controls[i].idx); }
CtrlList::Mode DssiSynthIF::ctrlMode(unsigned long i) const     { return ladspaCtrlMode(synth->dssi->LADSPA_Plugin, controls[i].idx); };


#else //DSSI_SUPPORT
void initDSSI() {}
#endif