summaryrefslogtreecommitdiff
path: root/audio.c
blob: f0cf3a042f6ef8a8f9abd020bc8cd65899d97193 (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
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
/* Audio hardware handlers (OSS, ALSA, Sun, Windows, Mac OSX, Jack, HPUX, NetBSD, OpenBSD, pulseaudio, portaudio) 
 *
 * In many cases, only callback driven transfers are supported, so ideally we'd have:
 * int mus_audio_playback(caller_data, start_func, fill_func, end_func)
 *   returns error indication or MUS_NO_ERROR
 *   calls start_func at startup: void start(caller_data, ...)?
 *   each times it needs a bufferfull, calls fill_func: bool fill(caller_data, void *buf, buf_size_in_samples, buf_data_type)
 *     perhaps returns false to signal normal quit?
 *   at end (either via fill or some interrupt), calls end(caller_data, ...)?
 */

/*
 * layout of this file:
 *    error handlers
 *    OSS
 *    ALSA
 *    Sun
 *    Windows 95/98
 *    OSX
 *    JACK
 *    HPUX
 *    OpenBSD
 *    NetBSD
 *    PulseAudio (in progress?)
 *    PortAudio
 */

/*
 * int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size)
 * int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size)
 * int mus_audio_write(int line, char *buf, int bytes)
 * int mus_audio_close(int line)
 * int mus_audio_read(int line, char *buf, int bytes)
 * int mus_audio_initialize(void) does whatever is needed to get set up
 * char *mus_audio_moniker(void) returns some brief description of the overall audio setup (don't free return string).
 */

#include "mus-config.h"

#if USE_SND && __APPLE__ && USE_MOTIF
  #undef USE_MOTIF
  #define USE_NO_GUI 1
  /* Xt's Boolean (/usr/include/X11/Intrinsic.h = char) collides with MacTypes.h Boolean, (actually,
   *   unsigned char in /Developer/SDKs/MacOSX10.4u.sdk/System/Library/Frameworks/CoreFoundation.framework/Versions/A/Headers/CFBase.h)
   *   but we want snd.h for other stuff, so, if Motif is in use, don't load its headers at this time
   *   perhaps we could use the -funsigned-char switch in gcc
   */
#endif

#if USE_SND && __APPLE__ && HAVE_RUBY
  /* if using Ruby, OpenTransport.h T_* definitions collide with Ruby's -- it isn't needed here, so... */
  #define REDEFINE_HAVE_RUBY 1
  #undef HAVE_RUBY
#endif

#if USE_SND
  #include "snd.h"
#else
  #define PRINT_BUFFER_SIZE 512
  #define LABEL_BUFFER_SIZE 64
#endif

#if USE_SND && __APPLE__
  #define USE_MOTIF 1
  #undef USE_NO_GUI
  #if REDEFINE_HAVE_RUBY
    #define HAVE_RUBY 1
  #endif
#endif

#include <math.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#ifndef _MSC_VER
  #include <unistd.h>
#endif
#include <string.h>

#ifdef __APPLE__
#include <CoreServices/CoreServices.h>
#include <CoreAudio/CoreAudio.h>
/* these pull in stdbool.h apparently, so they have to precede sndlib.h */
#endif

/* #define HAVE_JACK_IN_LINUX (MUS_JACK && __linux__) */
/* using JACK on GNU/linux, GNU/kFreeBSD and GNU/Hurd is all the same */
#if ((defined __linux__) || ((defined __FreeBSD_kernel__) && (defined __GLIBC__)) || (defined __GNU__))
  #define HAVE_JACK_IN_LINUX MUS_JACK
#else
  #define HAVE_JACK_IN_LINUX 0
#endif

#include "_sndlib.h"
#include "sndlib-strings.h"

#if WITH_AUDIO

enum {MUS_AUDIO_IGNORED, MUS_AUDIO_DUPLEX_DEFAULT, MUS_AUDIO_LINE_OUT,
      MUS_AUDIO_LINE_IN, MUS_AUDIO_MICROPHONE, MUS_AUDIO_SPEAKERS, MUS_AUDIO_DIGITAL_OUT,
      MUS_AUDIO_DAC_OUT, MUS_AUDIO_MIXER, MUS_AUDIO_AUX_OUTPUT
};


#define mus_standard_error(Error_Type, Error_Message) \
  mus_print("%s\n  [%s[%d] %s]", Error_Message, __FILE__, __LINE__, __func__)

#define mus_standard_io_error(Error_Type, IO_Func, IO_Name) \
  mus_print("%s %s: %s\n  [%s[%d] %s]", IO_Func, IO_Name, strerror(errno), __FILE__, __LINE__, __func__)


static char *version_name = NULL;
static bool audio_initialized = false;




/* ------------------------------- OSS ----------------------------------------- */

/* Thanks to Yair K. for OSS v4 changes.  22-Jan-08 */

#if (HAVE_OSS || HAVE_ALSA || HAVE_JACK_IN_LINUX)
/* actually it's not impossible that someday we'll have ALSA but not OSS... */
#define AUDIO_OK 1

#include <sys/ioctl.h>
#include <sys/soundcard.h>

#if ((SOUND_VERSION > 360) && (defined(OSS_SYSINFO)))
  #define NEW_OSS 1
#endif

#define MUS_OSS_WRITE_RATE     SNDCTL_DSP_SPEED
#define MUS_OSS_WRITE_CHANNELS SNDCTL_DSP_CHANNELS
#define MUS_OSS_SET_FORMAT     SNDCTL_DSP_SETFMT
#define MUS_OSS_GET_FORMATS    SNDCTL_DSP_GETFMTS

#define DAC_NAME "/dev/dsp"
#define MIXER_NAME "/dev/mixer"
/* some programs use /dev/audio */

/* there can be more than one sound card installed, and a card can be handled through
 * more than one /dev/dsp device, so we can't use a global dac device here.
 * The caller has to keep track of the various cards (via AUDIO_SYSTEM) --
 * I toyed with embedding all that in mus_audio_open_output and mus_audio_write, but
 * decided it's better to keep them explicit -- the caller may want entirely
 * different (non-synchronous) streams going to the various cards.  This same
 * code (AUDIO_SYSTEM(n)->devn) should work in Windoze (see below), and
 * might work on the Mac -- something for a rainy day...
 */

#define return_error_exit(Message_Type, Audio_Line, Ur_Message) \
  do { \
       char *Message; Message = Ur_Message; \
       if (Audio_Line != -1) \
          linux_audio_close(Audio_Line); \
       if ((Message) && (strlen(Message) > 0)) \
         { \
           mus_print("%s\n  [%s[%d] %s]", \
                     Message, \
                     __FILE__, __LINE__, __func__); \
           free(Message); \
         } \
       else mus_print("%s\n  [%s[%d] %s]", \
                      mus_error_type_to_string(Message_Type), \
                      __FILE__, __LINE__, __func__); \
       return(MUS_ERROR); \
     } while (false)

static int FRAGMENTS = 4;
static int FRAGMENT_SIZE = 12;
static bool fragments_locked = false;

/* defaults here are FRAGMENTS 16 and FRAGMENT_SIZE 12; these values however
 * cause about a .5 second delay, which is not acceptable in "real-time" situations.
 *
 * this changed 22-May-01: these are causing more trouble than they're worth
 */

static void oss_mus_oss_set_buffers(int num, int size) {FRAGMENTS = num; FRAGMENT_SIZE = size; fragments_locked = true;}

#define MAX_SOUNDCARDS 8
#define MAX_DSPS 8
#define MAX_MIXERS 8
/* there can be (apparently) any number of mixers and dsps per soundcard, but 8 is enough! */

static int *audio_fd = NULL; 
static int *audio_open_ctr = NULL; 
static int *audio_dsp = NULL; 
static int *audio_mixer = NULL; 
static int *audio_mode = NULL; 

static int sound_cards = 0;
#ifdef NEW_OSS
  static int new_oss_running = 0;
#endif
static char *dev_name = NULL;

static char *oss_mus_audio_moniker(void)
{
  if (!version_name) version_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  if (SOUND_VERSION < 361)
    {
      char version[LABEL_BUFFER_SIZE];
      snprintf(version, LABEL_BUFFER_SIZE, "%d", SOUND_VERSION);
      snprintf(version_name, LABEL_BUFFER_SIZE, "OSS %c.%c.%c", version[0], version[1], version[2]);
    }
  else
    snprintf(version_name, LABEL_BUFFER_SIZE, "OSS %x.%x.%x", 
		 (SOUND_VERSION >> 16) & 0xff, 
		 (SOUND_VERSION >> 8) & 0xff, 
		 SOUND_VERSION & 0xff);
  return(version_name);
}

static char *dac_name(int sys, int offset)
{
  if ((sys < sound_cards) && (audio_mixer[sys] >= -1))
    {
      snprintf(dev_name, LABEL_BUFFER_SIZE, "%s%d", DAC_NAME, audio_dsp[sys] + offset);
      return(dev_name);
    }
  return((char *)DAC_NAME);
}

#define MIXER_SIZE SOUND_MIXER_NRDEVICES
static int **mixer_state = NULL;
static int *init_srate = NULL, *init_chans = NULL, *init_format = NULL;

static int oss_mus_audio_initialize(void) 
{
  /* here we need to set up the map of /dev/dsp and /dev/mixer to a given system */
  /* since this info is not passed to us by OSS, we have to work at it... */
  /* for the time being, I'll ignore auxiliary dsp and mixer ports (each is a special case) */
  int amp, old_mixer_amp, old_dsp_amp, new_mixer_amp;
  int devmask;
#ifdef NEW_OSS
  int status, ignored;
  oss_sysinfo sysinfo;
  static mixer_info mixinfo;
  int sysinfo_ok = 0;
#endif
  if (!audio_initialized)
    {
      int i, num_mixers, num_dsps, nmix, ndsp, err = 0, fd = -1, responsive_field;
      audio_initialized = true;
      audio_fd = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_open_ctr = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_dsp = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_mixer = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      audio_mode = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      dev_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
      init_srate = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      init_chans = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      init_format = (int *)calloc(MAX_SOUNDCARDS, sizeof(int));
      mixer_state = (int **)calloc(MAX_SOUNDCARDS, sizeof(int *));
      for (i = 0; i < MAX_SOUNDCARDS; i++) mixer_state[i] = (int *)calloc(MIXER_SIZE, sizeof(int));
      for (i = 0; i < MAX_SOUNDCARDS; i++)
	{
	  audio_fd[i] = -1;
	  audio_open_ctr[i] = 0;
	  audio_dsp[i] = -1;
	  audio_mixer[i] = -1;
	}

      num_mixers = MAX_MIXERS;
      num_dsps = MAX_DSPS;
#ifdef NEW_OSS
      fd = open(DAC_NAME, O_WRONLY | O_NONBLOCK, 0);
      if (fd == -1) fd = open(MIXER_NAME, O_RDONLY | O_NONBLOCK, 0);
      if (fd != -1)
	{
	  status = ioctl(fd, OSS_GETVERSION, &ignored);
	  new_oss_running = (status == 0);
	  if (new_oss_running)
	    {
	      status = ioctl(fd, OSS_SYSINFO, &sysinfo);
	      sysinfo_ok = (status == 0);
	    }
	  if ((new_oss_running) && (sysinfo_ok))
	    {
	      num_mixers = sysinfo.nummixers;
	      num_dsps = sysinfo.numaudios;
	    }
	  close(fd);
	}
#endif

      /* need to get which /dev/dsp lines match which /dev/mixer lines,
       *   find out how many separate systems (soundcards) are available,
       *   fill the audio_dsp and audio_mixer arrays with the system-related numbers,
       * since we have no way to tell from OSS info which mixers/dsps are the
       *   main ones, we'll do some messing aound to try to deduce this info.
       * for example, SB uses two dsp ports and two mixers per card, whereas
       *  Ensoniq uses 2 dsps and 1 mixer.
       * 
       * the data we are gathering here:
       *   int audio_dsp[MAX_SOUNDCARDS] -> main_dsp_port[n] (-1 => no such system dsp)
       *   int audio_mixer[MAX_SOUNDCARDS] -> main_mixer_port[n]
       *   int sound_cards = 0 -> usable systems
       * all auxiliary ports are currently ignored (SB equalizer, etc)
       */
      sound_cards = 0;
      ndsp = 0;
      nmix = 0;
      while ((nmix < num_mixers) && 
	     (ndsp < num_dsps))
	{
	  char dname[LABEL_BUFFER_SIZE];
	  int md;
	  /* for each mixer, find associated main dsp (assumed to be first in /dev/dsp ordering) */
	  /*   if mixer's dsp overlaps or we run out of dsps first, ignore it (aux mixer) */
	  /* our by-guess-or-by-gosh method here is to try to open the mixer.
	   *   if that fails, quit (if very first, try at least to get the dsp setup)
	   *   find volume field, if none, go on, else read current volume
	   *   open next unchecked dsp, try to set volume, read current, if different we found a match -- set and go on.
	   *     if no change, move to next dsp and try again, if no more dsps, quit (checking for null case as before)
	   */
	  snprintf(dname, LABEL_BUFFER_SIZE, "%s%d", MIXER_NAME, nmix);
	  md = open(dname, O_RDWR, 0);
	  if (md == -1)
	    {
	      if (errno == EBUSY) 
		{
		  mus_print("%s is busy: can't access it [%s[%d] %s]", 
			    dname,
			    __FILE__, __LINE__, __func__); 
		  nmix++;
		  continue;
		}
	      else break;
	    }
	  snprintf(dname, LABEL_BUFFER_SIZE, "%s%d", DAC_NAME, ndsp);
	  fd = open(dname, O_RDWR | O_NONBLOCK, 0);
	  if (fd == -1) fd = open(dname, O_RDONLY | O_NONBLOCK, 0);
 	  if (fd == -1) fd = open(dname, O_WRONLY | O_NONBLOCK, 0); /* some output devices need this */
	  if (fd == -1)
	    {
	      close(md); 
	      if (errno == EBUSY) /* in linux /usr/include/asm-generic/errno-base.h */
		{
		  fprintf(stderr, "%s is busy: can't access it\n", dname); 
		  ndsp++;
		  continue;
		}
	      else 
		{
		  if ((errno != ENXIO) && (errno != ENODEV) && (errno != ENOENT))
		    fprintf(stderr, "%s: %s! ", dname, strerror(errno));
		  break;
		}
	    }
#ifdef NEW_OSS				  
	  status = ioctl(md, SOUND_MIXER_INFO, &mixinfo);
#endif
	  err = ioctl(md, SOUND_MIXER_READ_DEVMASK, &devmask);
	  responsive_field = SOUND_MIXER_VOLUME;
	  for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
	    if ((1 << i) & devmask)
	      {
		responsive_field = i;
		break;
	      }
	  if (!err)
	    {
	      err = ioctl(md, MIXER_READ(responsive_field), &old_mixer_amp);
	      if (!err)
		{
		  err = ioctl(fd, MIXER_READ(responsive_field), &old_dsp_amp);
		  if ((!err) && (old_dsp_amp == old_mixer_amp))
		    {
		      if (old_mixer_amp == 0) amp = 50; else amp = 0; /* 0..100 */
		      err = ioctl(fd, MIXER_WRITE(responsive_field), &amp);
		      if (!err)
			{
			  err = ioctl(md, MIXER_READ(responsive_field), &new_mixer_amp);
			  if (!err)
			    {
			      if (new_mixer_amp == amp)
				{
				  /* found one! */
				  audio_dsp[sound_cards] = ndsp; ndsp++;
				  audio_mixer[sound_cards] = nmix; nmix++;
				  sound_cards++;
				}
			      else ndsp++;
			      err = ioctl(fd, MIXER_WRITE(responsive_field), &old_dsp_amp);
			    }
			  else nmix++;
			}
		      else ndsp++;
		    }
		  else ndsp++;
		}
	      else nmix++;
	    }
	  else nmix++;
	  close(fd);
	  close(md);
	}
      if (sound_cards == 0)
	{
 	  fd = open(DAC_NAME, O_WRONLY | O_NONBLOCK, 0);
	  if (fd != -1)
	    {
	      sound_cards = 1;
	      audio_dsp[0] = 0;
	      audio_mixer[0] = -2; /* hmmm -- need a way to see /dev/dsp as lonely outpost */
	      close(fd);
 	      fd = open(MIXER_NAME, O_RDONLY | O_NONBLOCK, 0);
	      if (fd == -1)
		audio_mixer[0] = -3;
	      else close(fd);
	    }
	}
    }
  return(MUS_NO_ERROR);
}

static int linux_audio_open(const char *pathname, int flags, mode_t mode, int system)
{
  /* sometimes this is simply searching for a device (so failure is not a mus_error) */
  if (audio_fd[system] == -1) 
    {
      audio_fd[system] = open(pathname, flags, mode);
      audio_open_ctr[system] = 0;
    }
  else audio_open_ctr[system]++;
  return(audio_fd[system]);
}

static int linux_audio_open_with_error(const char *pathname, int flags, mode_t mode, int system)
{
  int fd;
  static bool already_warned = false;
  if ((system < 0) ||
      (system >= MAX_SOUNDCARDS))
    return(-1);

  fd = linux_audio_open(pathname, flags, mode, system);
  if ((fd == -1) &&
      (!already_warned))
    {
      already_warned = true;
      mus_standard_io_error(MUS_AUDIO_CANT_OPEN,
			    ((mode == O_RDONLY) ? "open read" : 
			     (mode == O_WRONLY) ? "open write" : "open read/write"),
			    pathname);
    }
  return(fd);
}

static int find_system(int line)
{
  int i;
  for (i = 0; i < sound_cards; i++)
    if (line == audio_fd[i])
      return(i);
  return(MUS_ERROR);
}

static int linux_audio_close(int fd)
{
  if (fd != -1)
    {
      int err = 0, sys;
      sys = find_system(fd);
      if (sys != -1)
	{
	  if (audio_open_ctr[sys] > 0) 
	    audio_open_ctr[sys]--;
	  else 
	    {
	      err = close(fd);
	      audio_open_ctr[sys] = 0;
	      audio_fd[sys] = -1;
	    }
	}
      else err = close(fd);
      if (err) return_error_exit(MUS_AUDIO_CANT_CLOSE, -1,
				 mus_format("close %d failed: %s",
					    fd, strerror(errno)));
    }
  /* is this an error? */
  return(MUS_NO_ERROR);
}

static int to_oss_sample_type(mus_sample_t snd_format)
{
  switch (snd_format)
    {
    case MUS_BYTE:    return(AFMT_S8);     
    case MUS_BSHORT:  return(AFMT_S16_BE); 
    case MUS_UBYTE:   return(AFMT_U8);     
    case MUS_MULAW:   return(AFMT_MU_LAW); 
    case MUS_ALAW:    return(AFMT_A_LAW);  
    case MUS_LSHORT:  return(AFMT_S16_LE); 
    case MUS_UBSHORT: return(AFMT_U16_BE); 
    case MUS_ULSHORT: return(AFMT_U16_LE); 
#ifdef NEW_OSS
    case MUS_LINT:    return(AFMT_S32_LE); 
    case MUS_BINT:    return(AFMT_S32_BE); 
#endif
    default: break;
    }
  return(MUS_ERROR);
}

static bool fragment_set_failed = false;

static int oss_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  int oss_sample_type, buffer_info, audio_out = -1, sys, dev;
  char *dev_name;
#ifndef NEW_OSS
  int stereo;
#endif
  sys = MUS_AUDIO_SYSTEM(ur_dev);
  dev = MUS_AUDIO_DEVICE(ur_dev);
  oss_sample_type = to_oss_sample_type(samp_type); 
  if (oss_sample_type == MUS_ERROR) 
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d (%s) not available",
				 samp_type, 
				 mus_sample_type_name(samp_type)));

  if (dev == MUS_AUDIO_DEFAULT)
    audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, 0), 
					    O_WRONLY, 0, sys);
  else audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, (dev == MUS_AUDIO_AUX_OUTPUT) ? 1 : 0), 
					       O_RDWR, 0, sys);
  if (audio_out == -1) return(MUS_ERROR);

  /* ioctl(audio_out, SNDCTL_DSP_RESET, 0); */ /* causes clicks */
  if ((fragments_locked) && 
      (!(fragment_set_failed)) &&
      ((dev == MUS_AUDIO_DUPLEX_DEFAULT) || 
       (size != 0))) /* only set if user has previously called set_oss_buffers */
    {
      buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
      if (ioctl(audio_out, SNDCTL_DSP_SETFRAGMENT, &buffer_info) == -1)
        {
          /* older Linuces (or OSS's?) refuse to handle the fragment reset if O_RDWR used --
           * someone at OSS forgot to update the version number when this was fixed, so
           * I have no way to get around this except to try and retry...
           */
          linux_audio_close(audio_out);
          audio_out = linux_audio_open_with_error(dev_name = dac_name(sys, (dev == MUS_AUDIO_AUX_OUTPUT) ? 1 : 0), 
						  O_WRONLY, 0, sys);
	  if (audio_out == -1) return(MUS_ERROR);
          buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
          if (ioctl(audio_out, SNDCTL_DSP_SETFRAGMENT, &buffer_info) == -1) 
	    {
	      char *tmp;
	      tmp = mus_format("can't set %s fragments to: %d x %d",
			       dev_name, FRAGMENTS, FRAGMENT_SIZE); /* not an error if ALSA OSS-emulation */
	      fprintf(stderr, "%s\n", tmp);
	      fragment_set_failed = true;
	      free(tmp);
	    }
        }
    }
  if ((ioctl(audio_out, MUS_OSS_SET_FORMAT, &oss_sample_type) == -1) || 
      (oss_sample_type != to_oss_sample_type(samp_type)))
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_out,
		      mus_format("sample type %d (%s) not available on %s",
				 samp_type, 
				 mus_sample_type_name(samp_type), 
				 dev_name));
#ifdef NEW_OSS
  if (ioctl(audio_out, MUS_OSS_WRITE_CHANNELS, &chans) == -1) 
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_out,
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#else
  if (chans == 2) stereo = 1; else stereo = 0;
  if ((ioctl(audio_out, SNDCTL_DSP_STEREO, &stereo) == -1) || 
      ((chans == 2) && (stereo == 0)))
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_out,
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#endif
  if (ioctl(audio_out, MUS_OSS_WRITE_RATE, &srate) == -1) 
    return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, audio_out,
		      mus_format("can't set srate of %s to %d",
				 dev_name, srate));
  /* http://www.4front-tech.com/pguide/audio.html says this order has to be followed */
  return(audio_out);
}

static int oss_mus_audio_write(int line, char *buf, int bytes)
{
  int err;
  if (line < 0) return(-1);
  errno = 0;
  err = write(line, buf, bytes);
  if (err != bytes)
    {
      if (errno != 0)
	return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
			  mus_format("write error: %s", strerror(errno)));
      else return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
			     mus_format("wrote %d bytes of requested %d", err, bytes));
    }
  return(MUS_NO_ERROR);
}

static int oss_mus_audio_close(int line)
{
  return(linux_audio_close(line));
}

static int oss_mus_audio_read(int line, char *buf, int bytes)
{
  int err;
  if (line < 0) return(-1);
  errno = 0;
  err = read(line, buf, bytes);
  if (err != bytes) 
    {
      if (errno != 0)
	return_error_exit(MUS_AUDIO_READ_ERROR, -1,
			  mus_format("read error: %s", strerror(errno)));
      else return_error_exit(MUS_AUDIO_READ_ERROR, -1,
			     mus_format("read %d bytes of requested %d", err, bytes));
    }
  return(MUS_NO_ERROR);
}

static char *oss_unsrc(int srcbit)
{
  if (srcbit == 0)
    return(mus_strdup("none"));
  else
    {
      bool need_and = false;
      char *buf;
      buf = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
      if (srcbit & SOUND_MASK_MIC) {need_and = true; strcat(buf, "mic");}
      if (srcbit & SOUND_MASK_LINE) {if (need_and) strcat(buf, " and "); need_and = true; strcat(buf, "line in");}
      if (srcbit & SOUND_MASK_CD) {if (need_and) strcat(buf, " and "); strcat(buf, "cd");}
      return(buf);
    }
}


static int oss_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size)
{
  /* dev can be MUS_AUDIO_DEFAULT or MUS_AUDIO_DUPLEX_DEFAULT as well as the obvious others */
  int audio_fd = -1, oss_sample_type, buffer_info, sys, dev, srcbit, cursrc, err;
  char *dev_name;
#ifndef NEW_OSS
  int stereo;
#endif
  sys = MUS_AUDIO_SYSTEM(ur_dev);
  dev = MUS_AUDIO_DEVICE(ur_dev);
  oss_sample_type = to_oss_sample_type(samp_type);
  if (oss_sample_type == MUS_ERROR)
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d (%s) not available",
				 samp_type, 
				 mus_sample_type_name(samp_type)));

  if (((dev == MUS_AUDIO_DEFAULT) || (dev == MUS_AUDIO_DUPLEX_DEFAULT)) && (sys == 0))
    audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), 
				O_RDWR, 0, sys);
  else audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), O_RDONLY, 0, sys);
  if (audio_fd == -1)
    {
      if (dev == MUS_AUDIO_DUPLEX_DEFAULT)
	return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, -1,
		       mus_format("can't open %s: %s",
				  dev_name, strerror(errno)));
      if ((audio_fd = linux_audio_open(dev_name = dac_name(sys, 0), O_RDONLY, 0, sys)) == -1)
        {
          if ((errno == EACCES) || (errno == ENOENT))
	    return_error_exit(MUS_AUDIO_NO_READ_PERMISSION, -1,
			      mus_format("can't open %s: %s\n  to get input in Linux, we need read permission on /dev/dsp",
					 dev_name, 
					 strerror(errno)));
          else return_error_exit(MUS_AUDIO_NO_INPUT_AVAILABLE, -1,
				 mus_format("can't open %s: %s",
					    dev_name, 
					    strerror(errno)));
        }
    }
#ifdef SNDCTL_DSP_SETDUPLEX
  else 
    ioctl(audio_fd, SNDCTL_DSP_SETDUPLEX, &err); /* not always a no-op! */
#endif
  /* need to make sure the desired recording source is active -- does this actually have any effect? */
  switch (dev)
    {
    case MUS_AUDIO_MICROPHONE: srcbit = SOUND_MASK_MIC;                   break;
    case MUS_AUDIO_LINE_IN:    srcbit = SOUND_MASK_LINE;                  break;
    case MUS_AUDIO_DUPLEX_DEFAULT: 
    case MUS_AUDIO_DEFAULT:    srcbit = SOUND_MASK_LINE | SOUND_MASK_MIC; break;
    default:                   srcbit = 0;                                break;

    }
  ioctl(audio_fd, MIXER_READ(SOUND_MIXER_RECSRC), &cursrc);
  srcbit = (srcbit | cursrc);
  ioctl(audio_fd, MIXER_WRITE(SOUND_MIXER_RECSRC), &srcbit);
  ioctl(audio_fd, MIXER_READ(SOUND_MIXER_RECSRC), &cursrc);
  if (cursrc != srcbit)
    {
      char *str1, *str2;
      str1 = oss_unsrc(srcbit);
      str2 = oss_unsrc(cursrc);
      mus_print("weird: tried to set recorder source to %s, but got %s?", str1, str2);
      free(str1);
      free(str2);
    }
  if ((fragments_locked) && (requested_size != 0))
    {
      buffer_info = (FRAGMENTS << 16) | (FRAGMENT_SIZE);
      ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &buffer_info);
    }
  if ((ioctl(audio_fd, MUS_OSS_SET_FORMAT, &oss_sample_type) == -1) ||
      (oss_sample_type != to_oss_sample_type(samp_type)))
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
		      mus_format("can't set %s sample type to %d (%s)",
				 dev_name, samp_type, 
				 mus_sample_type_name(samp_type)));
#ifdef NEW_OSS
  if (ioctl(audio_fd, MUS_OSS_WRITE_CHANNELS, &chans) == -1) 
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#else
  if (chans == 2) stereo = 1; else stereo = 0;
  if ((ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) == -1) || 
      ((chans == 2) && (stereo == 0))) 
    return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
		      mus_format("can't get %d channels on %s",
				 chans, dev_name));
#endif
  if (ioctl(audio_fd, MUS_OSS_WRITE_RATE, &srate) == -1) 
    return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, audio_fd,
		      mus_format("can't set srate to %d on %s",
				 srate, dev_name));
  return(audio_fd);
}


#if (!HAVE_ALSA) && (!HAVE_JACK_IN_LINUX)
static int oss_sample_types(int ur_dev, mus_sample_t *val)
{
  int fd, samp_types = 0, sys, ind;

  sys = MUS_AUDIO_SYSTEM(ur_dev);
  /* dev = MUS_AUDIO_DEVICE(ur_dev); */

  fd = open(dac_name(sys, 0), O_WRONLY, 0);
  if (fd == -1) fd = open(DAC_NAME, O_WRONLY, 0);
  if (fd == -1) 
    {
      return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
			mus_format("can't open %s: %s",
				   DAC_NAME, strerror(errno)));
      return(MUS_ERROR);
    }
  
  ioctl(fd, MUS_OSS_GET_FORMATS, &samp_types);
  ind = 1;
  if (samp_types & (to_oss_sample_type(MUS_BSHORT)))  val[ind++] = MUS_BSHORT;
  if (samp_types & (to_oss_sample_type(MUS_LSHORT)))  val[ind++] = MUS_LSHORT;
  if (samp_types & (to_oss_sample_type(MUS_MULAW)))   val[ind++] = MUS_MULAW;
  if (samp_types & (to_oss_sample_type(MUS_ALAW)))    val[ind++] = MUS_ALAW;
  if (samp_types & (to_oss_sample_type(MUS_BYTE)))    val[ind++] = MUS_BYTE;
  if (samp_types & (to_oss_sample_type(MUS_UBYTE)))   val[ind++] = MUS_UBYTE;
  if (samp_types & (to_oss_sample_type(MUS_UBSHORT))) val[ind++] = MUS_UBSHORT;
  if (samp_types & (to_oss_sample_type(MUS_ULSHORT))) val[ind++] = MUS_ULSHORT;
  val[0] = (mus_sample_t)(ind - 1);
  return(MUS_NO_ERROR);
}
#endif




/* ------------------------------- ALSA, OSS, Jack-in-Linux ----------------------------------- */

static int api = MUS_ALSA_API;
int mus_audio_api(void) {return(api);}

/* hopefully first call to sndlib will be this... */
static int probe_api(void);
static int (*vect_mus_audio_initialize)(void);

/* FIXME: add a suitable default for all other vectors
   so that a call happening before mus_audio_initialize
   can be detected */
/* I don't think this is necessary -- documentation discusses this
 * (mus_sound_initialize calls mus_audio_initialize)
 */

/* vectors for the rest of the sndlib api */
static void  (*vect_mus_oss_set_buffers)(int num, int size);
static char* (*vect_mus_audio_moniker)(void);
static int   (*vect_mus_audio_open_output)(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
static int   (*vect_mus_audio_open_input)(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
static int   (*vect_mus_audio_write)(int id, char *buf, int bytes);
static int   (*vect_mus_audio_read)(int id, char *buf, int bytes);
static int   (*vect_mus_audio_close)(int id);

/* vectors for the rest of the sndlib api */
int mus_audio_initialize(void) 
{
  return(probe_api());
}

void mus_oss_set_buffers(int num, int size) 
{
  vect_mus_oss_set_buffers(num, size);
}

#if HAVE_ALSA 
static char* alsa_mus_audio_moniker(void);
#endif

char* mus_audio_moniker(void) 
{
#if (HAVE_OSS && HAVE_ALSA)
  char *both_names;
  both_names = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
  /* need to be careful here since these use the same constant buffer */
  strcpy(both_names, oss_mus_audio_moniker());
  strcat(both_names, ", ");
  strcat(both_names, alsa_mus_audio_moniker());
  return(both_names); /* tiny memory leak ... */
#else
  return(vect_mus_audio_moniker());
#endif
}

int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  return(vect_mus_audio_open_output(ur_dev, srate, chans, samp_type, size));
}

int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size) 
{
  return(vect_mus_audio_open_input(ur_dev, srate, chans, samp_type, requested_size));
}

int mus_audio_write(int id, char *buf, int bytes) 
{
  return(vect_mus_audio_write(id, buf, bytes));
}

int mus_audio_read(int id, char *buf, int bytes) 
{
  return(vect_mus_audio_read(id, buf, bytes));
}

int mus_audio_close(int id) 
{
  return(vect_mus_audio_close(id));
}

#if HAVE_JACK_IN_LINUX
  static int jack_mus_audio_initialize(void);
#endif

#if (!HAVE_ALSA)
static int probe_api(void) 
{
#if HAVE_JACK_IN_LINUX
  {
    int jackprobe = jack_mus_audio_initialize();
    if (jackprobe == MUS_ERROR)
      {
#endif
  /* go for the oss api */
  api = MUS_OSS_API;
  vect_mus_audio_initialize = oss_mus_audio_initialize;
  vect_mus_oss_set_buffers = oss_mus_oss_set_buffers;
  vect_mus_audio_moniker = oss_mus_audio_moniker;
  vect_mus_audio_open_output = oss_mus_audio_open_output;
  vect_mus_audio_open_input = oss_mus_audio_open_input;
  vect_mus_audio_write = oss_mus_audio_write;
  vect_mus_audio_read = oss_mus_audio_read;
  vect_mus_audio_close = oss_mus_audio_close;
  return(vect_mus_audio_initialize());
#if HAVE_JACK_IN_LINUX
      }
    return(jackprobe);
  }
#endif
}
#endif

#endif


/* ------------------------------- ALSA ----------------------------------------- */
/*
 * Changed the names of the environment variables to use MUS, not SNDLIB.
 * reformatted and reorganized to be like the rest of the code
 * changed default device to "default"
 *    -- Bill 3-Feb-06
 *
 * error handling (mus_error) changed by Bill 14-Nov-02
 * 0.5 support removed by Bill 24-Mar-02
 *
 * changed for 0.9.x api by Fernando Lopez-Lezcano <nando@ccrma.stanford.edu>
 *
 *  sndlib "exports" only one soundcard with two directions (if they are available),
 *  and only deals with the alsa library pcm's. It does not scan for available
 *  cards and devices at the hardware level. Which device it uses can be defined by:
 *
 *  - setting variables in the environment (searched for in the following order):
 *    MUS_ALSA_PLAYBACK_DEVICE
 *       defines the name of the playback device
 *    MUS_ALSA_CAPTURE_DEVICE
 *       defines the name of the capture device
 *    MUS_ALSA_DEVICE
 *       defines the name of the playback and capture device
 *    use the first two if the playback and capture devices are different or the
 *    third if they are the same. 
 *  - if no variables are found in the environment sndlib tries to probe for a
 *    default device named "sndlib" (in alsa 0.9 devices are configured in 
 *    /usr/share/alsa/alsa.conf or in ~/.asoundrc)
 *  - if "sndlib" is not a valid device "hw:0,0" was used [but now it looks for "default"] (which by default should
 *    point to the first device of the first card
 *
 *  Some default settings are controllable through the environment as well:
 *    MUS_ALSA_BUFFER_SIZE = size of each buffer in frames
 *    MUS_ALSA_BUFFERS = number of buffers
 *
 * changed 18-Sep-00 by Bill: new error handling: old mus_audio_error folded into
 *  mus_error; mus_error itself should be used only for "real" errors -- things
 *  that can cause a throw (a kind of global jump elsewhere); use mus_print for informational
 *  stuff -- in Snd, mus_print will also save everything printed in the error dialog.
 *  In a few cases, I tried to fix the code to unwind before mus_error, and in others
 *  I've changed mus_error to mus_print, but some of these may be mistaken.
 *  Look for ?? below for areas where I'm not sure I rewrote code correctly.
 *
 * changed for 0.6.x api by Paul Barton-Davis, pbd@op.net
 *
 * changed for 0.5.x api by Fernando Lopez-Lezcano, nando@ccrma.stanford.edu
 *   04-10-2000:
 *     based on original 0.4.x code by Paul Barton-Davis (not much left of it :-)
 *     also Bill's code and Jaroslav Kysela (aplay.c and friends)
 *
 * Changes:
 * 04/25/2000: finished major rework, snd-dac now automatically decides which
 *             device or devices it uses for playback. Multiple device use is
 *             for now restricted to only two at most (more changes in Bill's
 *             needed to be able to support more). Four channel playback in 
 *             Ensoniq AudioPCI and relatives possible (with proper settings
 *             of the mixer) as well as using two separate cards. 
 * 04/11/2000: added reporting of alsa sound formats
*/

#if HAVE_ALSA

#if (!HAVE_OSS)
#define AUDIO_OK 1
#endif

#include <sys/ioctl.h>

#if HAVE_ALSA
  #include <alsa/asoundlib.h>
#else
  #include <sys/asoundlib.h>
#endif

#if SND_LIB_VERSION < ((0<<16)|(6<<8)|(0))
  #error ALSA version is too old -- audio.c needs 0.9 or later
#endif

/* prototypes for the alsa sndlib functions */
static int   alsa_mus_audio_initialize(void);
static void  alsa_mus_oss_set_buffers(int num, int size);
static int   alsa_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
static int   alsa_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
static int   alsa_mus_audio_write(int id, char *buf, int bytes);
static int   alsa_mus_audio_read(int id, char *buf, int bytes);
static int   alsa_mus_audio_close(int id);

/* decide which api to activate */

static int probe_api(void) 
{
#if HAVE_JACK_IN_LINUX
  int jackprobe;
  jackprobe = jack_mus_audio_initialize();
  if (jackprobe == MUS_ERROR)
    {
#endif
    int card = -1;
    if ((snd_card_next(&card) >= 0) && (card >= 0))
      {
	/* the alsa library has detected one or more cards */
	api = MUS_ALSA_API;
	vect_mus_audio_initialize = alsa_mus_audio_initialize;
	vect_mus_oss_set_buffers = alsa_mus_oss_set_buffers;
	vect_mus_audio_moniker = alsa_mus_audio_moniker;
	vect_mus_audio_open_output = alsa_mus_audio_open_output;
	vect_mus_audio_open_input = alsa_mus_audio_open_input;
	vect_mus_audio_write = alsa_mus_audio_write;
	vect_mus_audio_read = alsa_mus_audio_read;
	vect_mus_audio_close = alsa_mus_audio_close;
      } 
    else 
      {
	/* go for the oss api */
        api = MUS_OSS_API;
	vect_mus_audio_initialize = oss_mus_audio_initialize;
	vect_mus_oss_set_buffers = oss_mus_oss_set_buffers;
	vect_mus_audio_moniker = oss_mus_audio_moniker;
	vect_mus_audio_open_output = oss_mus_audio_open_output;
	vect_mus_audio_open_input = oss_mus_audio_open_input;
	vect_mus_audio_write = oss_mus_audio_write;
	vect_mus_audio_read = oss_mus_audio_read;
	vect_mus_audio_close = oss_mus_audio_close;
      }
    /* will the _real_ mus_audio_initialize please stand up? */
    return(vect_mus_audio_initialize());
#if HAVE_JACK_IN_LINUX
    }
  return(jackprobe);
#endif
}

/* convert a sndlib sample type to an alsa sample type */

static snd_pcm_format_t to_alsa_format(mus_sample_t snd_format)
{
  switch (snd_format) 
    {
    case MUS_BYTE:     return(SND_PCM_FORMAT_S8); 
    case MUS_UBYTE:    return(SND_PCM_FORMAT_U8); 
    case MUS_MULAW:    return(SND_PCM_FORMAT_MU_LAW); 
    case MUS_ALAW:     return(SND_PCM_FORMAT_A_LAW); 
    case MUS_BSHORT:   return(SND_PCM_FORMAT_S16_BE); 
    case MUS_LSHORT:   return(SND_PCM_FORMAT_S16_LE); 
    case MUS_UBSHORT:  return(SND_PCM_FORMAT_U16_BE); 
    case MUS_ULSHORT:  return(SND_PCM_FORMAT_U16_LE); 
    case MUS_B24INT:   return(SND_PCM_FORMAT_S24_BE); 
    case MUS_L24INT:   return(SND_PCM_FORMAT_S24_LE); 
    case MUS_BINT:     return(SND_PCM_FORMAT_S32_BE); 
    case MUS_LINT:     return(SND_PCM_FORMAT_S32_LE); 
    case MUS_BINTN:    return(SND_PCM_FORMAT_S32_BE); 
    case MUS_LINTN:    return(SND_PCM_FORMAT_S32_LE); 
    case MUS_BFLOAT:   return(SND_PCM_FORMAT_FLOAT_BE); 
    case MUS_LFLOAT:   return(SND_PCM_FORMAT_FLOAT_LE); 
    case MUS_BDOUBLE:  return(SND_PCM_FORMAT_FLOAT64_BE); 
    case MUS_LDOUBLE:  return(SND_PCM_FORMAT_FLOAT64_LE); 
    default: break;
    }
  return((snd_pcm_format_t)MUS_ERROR);
}

/* FIXME: this is not taking yet into account the 
 * number of bits that a given alsa format is actually
 * using... 
 */

static mus_sample_t to_mus_sample_type(int alsa_format) 
{
  /* alsa format definitions from asoundlib.h (0.9 cvs 6/27/2001) */
  switch (alsa_format)
    {
    case SND_PCM_FORMAT_S8:         return(MUS_BYTE);
    case SND_PCM_FORMAT_U8:         return(MUS_UBYTE);
    case SND_PCM_FORMAT_S16_LE:     return(MUS_LSHORT);
    case SND_PCM_FORMAT_S16_BE:     return(MUS_BSHORT);
    case SND_PCM_FORMAT_U16_LE:     return(MUS_ULSHORT);
    case SND_PCM_FORMAT_U16_BE:     return(MUS_UBSHORT);
    case SND_PCM_FORMAT_S24_LE:     return(MUS_L24INT);
    case SND_PCM_FORMAT_S24_BE:     return(MUS_B24INT);
    case SND_PCM_FORMAT_S32_LE:     return(MUS_LINTN); /* 32bit normalized plays 24bit and 16bit files with same amplitude bound (for 24 bit cards) */
    case SND_PCM_FORMAT_S32_BE:     return(MUS_BINTN);
    case SND_PCM_FORMAT_FLOAT_LE:   return(MUS_LFLOAT);
    case SND_PCM_FORMAT_FLOAT_BE:   return(MUS_BFLOAT);
    case SND_PCM_FORMAT_FLOAT64_LE: return(MUS_LDOUBLE);
    case SND_PCM_FORMAT_FLOAT64_BE: return(MUS_BDOUBLE);
    case SND_PCM_FORMAT_MU_LAW:     return(MUS_MULAW);
    case SND_PCM_FORMAT_A_LAW:      return(MUS_ALAW);
    /* formats with no translation in snd */
    case SND_PCM_FORMAT_U24_LE:
    case SND_PCM_FORMAT_U24_BE:
    case SND_PCM_FORMAT_U32_LE:
    case SND_PCM_FORMAT_U32_BE:
    case SND_PCM_FORMAT_IEC958_SUBFRAME_LE:
    case SND_PCM_FORMAT_IEC958_SUBFRAME_BE:
    case SND_PCM_FORMAT_IMA_ADPCM:
    case SND_PCM_FORMAT_MPEG:
    case SND_PCM_FORMAT_GSM:
    case SND_PCM_FORMAT_SPECIAL:
    default:
      return(MUS_UNKNOWN_SAMPLE);
    }
}

/* convert a sndlib device into an alsa device number and channel
 * [has to be coordinated with following function!] 
 */

/* very simplistic approach, device mapping should also depend
 * on which card we're dealing with, digital i/o devices should
 * be identified as such and so on 
 */

/* NOTE: in the Delta1010 digital i/o is just a pair of channels
 * in the 10 channel playback frame or 12 channel capture frame,
 * how do we specify that???
 */

static int to_alsa_device(int dev, int *adev, snd_pcm_stream_t *achan)
{
  switch (dev) 
    {
      /* default values are a problem because the concept does
       * not imply a direction (playback or capture). This works
       * fine as long as both directions of a device are symetric,
       * the Midiman 1010, for example, has 10 channel frames for
       * playback and 12 channel frames for capture and breaks 
       * the recorder (probes the default, defaults to output, 
       * uses the values for input). 
       */
    case MUS_AUDIO_DEFAULT:
    case MUS_AUDIO_DUPLEX_DEFAULT:
    case MUS_AUDIO_LINE_OUT:
      /* analog output */
      (*adev) = 0;
      (*achan) = SND_PCM_STREAM_PLAYBACK;
      break;

    case MUS_AUDIO_AUX_OUTPUT:
      /* extra analog output */
      (*adev) = 1;
      (*achan) = SND_PCM_STREAM_PLAYBACK;
      break;

    case MUS_AUDIO_DAC_OUT:
      /* analog outputs */
      (*adev) = 2;
      (*achan) = SND_PCM_STREAM_PLAYBACK;
      break;

    case MUS_AUDIO_MICROPHONE:
    case MUS_AUDIO_LINE_IN:
      /* analog input */
      (*adev) = 0;
      (*achan) = SND_PCM_STREAM_CAPTURE;
      break;

    default:
      return(MUS_ERROR);
      break;
    }
  return(0);
}

/* convert an alsa device into a sndlib device 
 * [has to be coordinated with previous function!] 
 *
 * naming here is pretty much arbitrary. We have to have
 * a bidirectional mapping between sndlib devices and
 * alsa devices and that's just not possible (I think). 
 * This stopgap mapping ignores digital input and output
 * devices - how to differentiate them in alsa?
 */

static int to_sndlib_device(int dev, int channel) 
{
  switch (channel) 
    {
    case SND_PCM_STREAM_PLAYBACK:
      switch (dev) 
	{
	  /* works only for the first three outputs */
	case 0: return(MUS_AUDIO_LINE_OUT);
	case 1: return(MUS_AUDIO_AUX_OUTPUT);
	case 2: return(MUS_AUDIO_DAC_OUT);
	default:
	  return(MUS_ERROR);
	}
    case SND_PCM_STREAM_CAPTURE:
      switch (dev) 
	{
	case 0: return(MUS_AUDIO_LINE_IN);
	default:
	  return(MUS_ERROR);
	}
      break;
    }
  return(MUS_ERROR);
}


static int alsa_mus_error(int type, char *message)
{
  if (message)
    {
      mus_print("%s", message);
      free(message);
    }
  return(MUS_ERROR);
}


/* dump current hardware and software configuration */

static void alsa_dump_configuration(char *name, snd_pcm_hw_params_t *hw_params, snd_pcm_sw_params_t *sw_params)
{
  int err; 
  char *str;
  snd_output_t *buf;

#if (SND_LIB_MAJOR == 0) || ((SND_LIB_MAJOR == 1) && (SND_LIB_MINOR == 0) && (SND_LIB_SUBMINOR < 8))
  return; /* avoid Alsa bug */
#endif

  err = snd_output_buffer_open(&buf);
  if (err < 0) 
    mus_print("could not open dump buffer: %s", snd_strerror(err));
  else 
    {
      size_t len;
      if (hw_params) 
	{
	  snd_output_puts(buf, "hw_params status of ");
	  snd_output_puts(buf, name);
	  snd_output_puts(buf, "\n");
	  err = snd_pcm_hw_params_dump(hw_params, buf);
	  if (err < 0) 
	    mus_print("snd_pcm_hw_params_dump: %s", snd_strerror(err));
	}
      if (sw_params) 
	{
	  snd_output_puts(buf, "sw_params status of ");
	  snd_output_puts(buf, name);
	  snd_output_puts(buf, "\n");
	  err = snd_pcm_sw_params_dump(sw_params, buf);
	  if (err < 0) 
	    mus_print("snd_pcm_hw_params_dump: %s", snd_strerror(err));
	}
      snd_output_putc(buf, '\0');
      len = snd_output_buffer_string(buf, &str);
      if (len > 1) 
	mus_print("status of %s\n%s", name, str);
      snd_output_close(buf);
    }
}

/* get hardware params for a pcm */

static snd_pcm_hw_params_t *alsa_get_hardware_params(const char *name, snd_pcm_stream_t stream, int mode)
{
  int err;
  snd_pcm_t *handle;
  if ((err = snd_pcm_open(&handle, name, stream, mode | SND_PCM_NONBLOCK)) != 0) 
    {
      alsa_mus_error(MUS_AUDIO_CANT_OPEN, 
		     mus_format("open pcm %s for stream %d: %s",
				name, stream, snd_strerror(err)));
      return(NULL);
    }
  else 
    {
      snd_pcm_hw_params_t *params;
      params = (snd_pcm_hw_params_t *)calloc(1, snd_pcm_hw_params_sizeof());
      if (!params) 
	{
	  snd_pcm_close(handle);
	  alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			 mus_format("could not allocate memory for hardware params"));
	} 
      else 
	{
	  err = snd_pcm_hw_params_any(handle, params);
	  if (err < 0) 
	    {
	      snd_pcm_close(handle);
	      alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			     mus_format("snd_pcm_hw_params_any: pcm %s, stream %d, error: %s",
					name, stream, snd_strerror(err)));
	    } 
	  else 
	    {
	      snd_pcm_close(handle);
	      return(params);
	    }
	}
    }
  return(NULL);
}

/* allocate software params structure */

static snd_pcm_sw_params_t *alsa_get_software_params(void)
{
  snd_pcm_sw_params_t *params = NULL;
  params = (snd_pcm_sw_params_t *)calloc(1, snd_pcm_sw_params_sizeof());
  if (!params) 
    {
      alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
		     mus_format("could not allocate memory for software params"));
    } 
  return(params);
}

/* probe a device name against the list of available pcm devices */

static bool alsa_probe_device_name(const char *name)
{
  snd_config_t *conf;
  snd_config_iterator_t pos, next;
  int err;
  
  err = snd_config_update();
  if (err < 0) 
    {
      mus_print("snd_config_update: %s", snd_strerror(err));
      return(false);
    }

  err = snd_config_search(snd_config, "pcm", &conf);
  if (err < 0) 
    {
      mus_print("snd_config_search: %s", snd_strerror(err));
      return(false);
    }

  snd_config_for_each(pos, next, conf) 
    {
      snd_config_t *c = snd_config_iterator_entry(pos);
      const char *id;
      int err = snd_config_get_id(c, &id);
      if (err == 0) {
	int result = strncmp(name, id, strlen(id));
	if (result == 0 &&
	    (name[strlen(id)] == '\0' || name[strlen(id)] == ':')) 
	  {
	    return(true);
	  }
      }
    }
  return(false);
}

/* check a device name against the list of available pcm devices */

static int alsa_check_device_name(const char *name)
{
  if (!alsa_probe_device_name(name)) 
    {
      return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
			    mus_format("alsa could not find device \"%s\" in configuration", 
				       name)));
    } 
  return(MUS_NO_ERROR);
}


/* set scheduling priority to SCHED_FIFO 
 * this will only work if the program that uses sndlib is run as root or is suid root 
 */

/* whether we want to trace calls 
 *
 * set to "1" to print function trace information in the 
 * snd error window
 */

static int alsa_trace = 0;

/* this should go away as it is oss specific */

static int fragment_size = 512; 
static int fragments = 4;

static void alsa_mus_oss_set_buffers(int num, int size) 
{
  fragments = num; 
  fragment_size = size; 
}

/* total number of soundcards in our setup, set by initialize_audio */

/* static int sound_cards = 0; */

/* return the number of cards that are available */

/* return the type of driver we're dealing with */

static char *alsa_mus_audio_moniker(void)
{
  if (!version_name) version_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  snprintf(version_name, LABEL_BUFFER_SIZE, "ALSA %s", SND_LIB_VERSION_STR);
  return(version_name);
}

/* handles for both directions of the virtual device */

static snd_pcm_t *handles[2] = {NULL, NULL};

/* hardware and software parameter sctructure pointers */

static snd_pcm_hw_params_t *alsa_hw_params[2] = {NULL, NULL}; /* avoid bogus free */
static snd_pcm_sw_params_t *alsa_sw_params[2] = {NULL, NULL};

/* some defaults */

static int alsa_open_mode = SND_PCM_ASYNC;
static int alsa_buffers = 3;
/* size of buffer in number of samples per channel, 
 * at 44100 approximately 5.9mSecs
 */
static int alsa_samples_per_channel = 1024;
static snd_pcm_access_t alsa_interleave = SND_PCM_ACCESS_RW_INTERLEAVED;
static int alsa_max_capture_channels = 32;

/* first default name for pcm configuration */

static char *alsa_sndlib_device_name = (char *)"sndlib";

/* second default for playback and capture: hardware pcm, first card, first device */
/* pcms used by sndlib, playback and capture */

static char *alsa_playback_device_name = NULL;
static char *alsa_capture_device_name = NULL;



/* -------- tie these names into scheme/ruby -------- */

static int alsa_get_max_buffers(void)
{
  uint32_t max_periods = 0, max_rec_periods = 0;
  int dir = 0;

  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
    snd_pcm_hw_params_get_periods_max(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &max_periods, &dir);

  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_periods_max(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &max_rec_periods, &dir);

      if (max_periods > max_rec_periods) 
	max_periods = max_rec_periods;
    }
  return(max_periods);
}

static int alsa_get_min_buffers(void)
{
  uint32_t min_periods = 0, min_rec_periods = 0;
  int dir = 0;
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
    snd_pcm_hw_params_get_periods_min(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &min_periods, &dir);

  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_periods_min(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &min_rec_periods, &dir);

      if (min_periods < min_rec_periods) 
	min_periods = min_rec_periods;
    }
  return(min_periods);
}

static int alsa_clamp_buffers(int bufs)
{
  int minb, maxb;
  minb = alsa_get_min_buffers();
  maxb = alsa_get_max_buffers();
  if (bufs > maxb)
    bufs = maxb;
  if (bufs < minb)
    bufs = minb;
  return(bufs);
}

static snd_pcm_uframes_t alsa_get_min_buffer_size(void)
{
  snd_pcm_uframes_t min_buffer_size = 0, min_rec_buffer_size = 0;
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
    snd_pcm_hw_params_get_buffer_size_min(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &min_buffer_size);

  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_buffer_size_min(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &min_rec_buffer_size);
      if (min_buffer_size < min_rec_buffer_size) 
	min_buffer_size = min_rec_buffer_size;
    }
  return(min_buffer_size);
}

static snd_pcm_uframes_t alsa_get_max_buffer_size(void)
{
  snd_pcm_uframes_t max_buffer_size = 0, max_rec_buffer_size = 0;
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK])
    snd_pcm_hw_params_get_buffer_size_max(alsa_hw_params[SND_PCM_STREAM_PLAYBACK], &max_buffer_size);

  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_hw_params_get_buffer_size_max(alsa_hw_params[SND_PCM_STREAM_CAPTURE], &max_rec_buffer_size);
      if (max_buffer_size > max_rec_buffer_size) 
	max_buffer_size = max_rec_buffer_size;
    }
  return(max_buffer_size);
}

static snd_pcm_uframes_t alsa_clamp_buffer_size(snd_pcm_uframes_t buf_size)
{
  snd_pcm_uframes_t minb, maxb;
  minb = alsa_get_min_buffer_size();
  maxb = alsa_get_max_buffer_size();
  if (buf_size > maxb)
    buf_size = maxb;
  if (buf_size < minb)
    buf_size = minb;
  return(buf_size);
}

static bool alsa_set_playback_parameters(void)
{
  /* playback stream parameters */
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK]) free(alsa_hw_params[SND_PCM_STREAM_PLAYBACK]);
  alsa_hw_params[SND_PCM_STREAM_PLAYBACK] = alsa_get_hardware_params(alsa_playback_device_name, SND_PCM_STREAM_PLAYBACK, alsa_open_mode);
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK]) 
    {
      snd_pcm_uframes_t size;
      int old_buffers;
      old_buffers = alsa_buffers;
      if (alsa_sw_params[SND_PCM_STREAM_PLAYBACK]) free(alsa_sw_params[SND_PCM_STREAM_PLAYBACK]);
      alsa_sw_params[SND_PCM_STREAM_PLAYBACK] = alsa_get_software_params();
      sound_cards = 1;
      alsa_buffers = alsa_clamp_buffers(alsa_buffers);
      if (alsa_buffers <= 0)
	{
	  alsa_buffers = old_buffers;
	  return(false);
	}
      size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
      if (size <= 0) return(false);
      alsa_samples_per_channel = size / alsa_buffers;
    }
  return(alsa_hw_params[SND_PCM_STREAM_PLAYBACK] && alsa_sw_params[SND_PCM_STREAM_PLAYBACK]);
}

static bool alsa_set_capture_parameters(void)
{  
  /* capture stream parameters */
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) free(alsa_hw_params[SND_PCM_STREAM_CAPTURE]);
  alsa_hw_params[SND_PCM_STREAM_CAPTURE] = alsa_get_hardware_params(alsa_capture_device_name, SND_PCM_STREAM_CAPTURE, alsa_open_mode);
  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    {
      snd_pcm_uframes_t size;
      int old_buffers;
      old_buffers = alsa_buffers;
      if (alsa_sw_params[SND_PCM_STREAM_CAPTURE]) free(alsa_sw_params[SND_PCM_STREAM_CAPTURE]);
      alsa_sw_params[SND_PCM_STREAM_CAPTURE] = alsa_get_software_params();
      sound_cards = 1;
      alsa_buffers = alsa_clamp_buffers(alsa_buffers);
      if (alsa_buffers <= 0)
	{
	  alsa_buffers = old_buffers;
	  return(false);
	}
      size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
      if (size <= 0) return(false);
      alsa_samples_per_channel = size / alsa_buffers;
    }
  return(alsa_hw_params[SND_PCM_STREAM_CAPTURE] && alsa_sw_params[SND_PCM_STREAM_CAPTURE]);
}


char *mus_alsa_playback_device(void) {return(alsa_playback_device_name);}
char *mus_alsa_set_playback_device(const char *name) 
{
  if (alsa_check_device_name(name) == MUS_NO_ERROR)
    {
      char *old_name = alsa_playback_device_name;
      alsa_playback_device_name = mus_strdup(name); 
      if (!alsa_set_playback_parameters())
	{
	  alsa_playback_device_name = old_name; /* try to back out of the mistake */
	  alsa_set_playback_parameters();
	}
    }
  return(alsa_playback_device_name);
}

char *mus_alsa_capture_device(void) {return(alsa_capture_device_name);}
char *mus_alsa_set_capture_device(const char *name) 
{
  if (alsa_check_device_name(name) == MUS_NO_ERROR)
    {
      char *old_name = alsa_capture_device_name;
      alsa_capture_device_name = mus_strdup(name); 
      if (!alsa_set_capture_parameters())
	{
	  alsa_capture_device_name = old_name;
	  alsa_set_capture_parameters();
	}
    }
  return(alsa_capture_device_name);
}

char *mus_alsa_device(void) {return(alsa_sndlib_device_name);}
char *mus_alsa_set_device(const char *name) 
{
  if (alsa_check_device_name(name) == MUS_NO_ERROR)
    {
      alsa_sndlib_device_name = mus_strdup(name);
      mus_alsa_set_playback_device(name);
      mus_alsa_set_capture_device(name);
    }
  return(alsa_sndlib_device_name);
}

int mus_alsa_buffer_size(void) {return(alsa_samples_per_channel);}
int mus_alsa_set_buffer_size(int size) 
{
  snd_pcm_uframes_t bsize;
  if (alsa_buffers == 0) alsa_buffers = 1;
  if (size > 0)
    {
      bsize = alsa_clamp_buffer_size((snd_pcm_uframes_t)(size * alsa_buffers));
      alsa_samples_per_channel = bsize / alsa_buffers;
    }
  return(alsa_samples_per_channel);
}

int mus_alsa_buffers(void) {return(alsa_buffers);}
int mus_alsa_set_buffers(int num) 
{
  snd_pcm_uframes_t size;
  if (num > 0)
    {
      alsa_buffers = alsa_clamp_buffers(num);
      if (alsa_buffers > 0)
	{
	  size = alsa_clamp_buffer_size((snd_pcm_uframes_t)(alsa_samples_per_channel * alsa_buffers));
	  alsa_samples_per_channel = size / alsa_buffers;
	}
    }
  return(alsa_buffers);
}

static bool alsa_squelch_warning = false;
bool mus_alsa_squelch_warning(void) {return(alsa_squelch_warning);}
bool mus_alsa_set_squelch_warning(bool val) 
{
  alsa_squelch_warning = val; 
  return(val);
}




/* get a device name from the environment */

static char *alsa_get_device_from_env(const char *name)
{
  char *string = getenv(name);
  if (string) 
    if (alsa_check_device_name(string) == MUS_NO_ERROR) 
      return(string);
  return(NULL);
}

/* get an integer from the environment */

static int alsa_get_int_from_env(const char *name, int *value, int min, int max)
{
  char *string = getenv(name);
  if (string) 
    {
      char *end;
      long int result = strtol(string, &end, 10);
      if (((min != -1) && (max != -1)) &&
	  (result < min || result > max)) 
	{
	  return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
				mus_format("%s ignored: out of range, value=%d, min=%d, max=%d",
					   name, (int)result, min, max)));
	} 
      else 
	{
	  if (errno == ERANGE) 
	    {
	      return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
				    mus_format("%s ignored: strlol conversion out of range",
					       name)));
	    } 
	  else 
	    {
	      if ((*string != '\0') && (*end == '\0'))
		{
		  *value = (int)result;
		  return(MUS_NO_ERROR);
		} 
	      else 
		{
		  return(alsa_mus_error(MUS_AUDIO_CANT_READ, 
					mus_format("%s ignored: value is \"%s\", not an integer",
						   name, string)));
		}
	    }
	}
    }
  return(MUS_ERROR);
}

/* initialize the audio subsystem */

/* define environment variable names */
#define MUS_ALSA_PLAYBACK_DEVICE_ENV_NAME "MUS_ALSA_PLAYBACK_DEVICE"
#define MUS_ALSA_CAPTURE_DEVICE_ENV_NAME  "MUS_ALSA_CAPTURE_DEVICE"
#define MUS_ALSA_DEVICE_ENV_NAME          "MUS_ALSA_DEVICE"
#define MUS_ALSA_BUFFERS_ENV_NAME         "MUS_ALSA_BUFFERS"
#define MUS_ALSA_BUFFER_SIZE_ENV_NAME     "MUS_ALSA_BUFFER_SIZE"
#define MUS_ALSA_TRACE_ENV_NAME           "MUS_ALSA_TRACE"

static int alsa_mus_audio_initialize(void) 
{
  char *name = NULL;
  char *pname;
  char *cname;
  int value = 0, alsa_buffer_size = 0;

  if (audio_initialized) 
    return(0);

  sound_cards = 0;

  /* get trace flag from environment */
  if (alsa_get_int_from_env(MUS_ALSA_TRACE_ENV_NAME, &value, 0, 1) == MUS_NO_ERROR) 
    alsa_trace = value;

  /* try to get device names from environment */
  pname = alsa_get_device_from_env(MUS_ALSA_PLAYBACK_DEVICE_ENV_NAME);
  if ((pname) && (alsa_probe_device_name(pname)))
    alsa_playback_device_name = pname;

  cname = alsa_get_device_from_env(MUS_ALSA_CAPTURE_DEVICE_ENV_NAME);
  if ((cname) && (alsa_probe_device_name(cname)))
    alsa_capture_device_name = cname;
    
  name = alsa_get_device_from_env(MUS_ALSA_DEVICE_ENV_NAME);
  if ((name) && (alsa_probe_device_name(name)))
    {
      if (!alsa_playback_device_name) 
	alsa_playback_device_name = name;

      if (!alsa_capture_device_name) 
	alsa_capture_device_name = name;

      alsa_sndlib_device_name = name;
    }

  /* now check that we have a plausible name */
  if (!alsa_probe_device_name(alsa_sndlib_device_name))
    {
      alsa_sndlib_device_name = (char *)"default";
      if (!alsa_probe_device_name(alsa_sndlib_device_name))
	{
	  alsa_sndlib_device_name = (char *)"plughw:0";
	  if (!alsa_probe_device_name(alsa_sndlib_device_name))
	    alsa_sndlib_device_name = (char *)"hw:0";
	}
    }
    
  /* if no device name set yet, try for special sndlib name first */
  if (!alsa_playback_device_name) 
    {
      if (alsa_probe_device_name(alsa_sndlib_device_name)) 
	alsa_playback_device_name = alsa_sndlib_device_name;
      else alsa_playback_device_name = (char *)"hw:0";
    }

  if (!alsa_capture_device_name) 
    {
      if (alsa_probe_device_name(alsa_sndlib_device_name)) 
	alsa_capture_device_name = alsa_sndlib_device_name;
      else alsa_capture_device_name = (char *)"hw:0";
    }

  alsa_get_int_from_env(MUS_ALSA_BUFFERS_ENV_NAME, &alsa_buffers, -1, -1);
  alsa_get_int_from_env(MUS_ALSA_BUFFER_SIZE_ENV_NAME, &alsa_buffer_size, -1, -1);

  if ((alsa_buffer_size > 0) && (alsa_buffers > 0))
    alsa_samples_per_channel = alsa_buffer_size / alsa_buffers;

  if (!alsa_set_playback_parameters())
    {
      /* somehow we got a device that passed muster with alsa_probe_device_name, but doesn't return hw params! */
      alsa_playback_device_name = (char *)"plughw:0";
      if (!alsa_set_playback_parameters())
	{
	  alsa_playback_device_name = (char *)"hw:0";
	  if (!alsa_set_playback_parameters())
	    return(MUS_ERROR);
	}
    }

  if (!alsa_set_capture_parameters())
    {
      alsa_capture_device_name = (char *)"plughw:0";
      if (!alsa_set_capture_parameters())
	{
	  alsa_capture_device_name = (char *)"hw:0";
	  if (!alsa_set_capture_parameters())
	    return(MUS_ERROR);
	}
    }

  if ((!alsa_hw_params[SND_PCM_STREAM_CAPTURE]) ||
      (!alsa_hw_params[SND_PCM_STREAM_PLAYBACK]))
    return(MUS_ERROR);

  audio_initialized = true;
  return(0);
}

/* open an input or output stream */

static int alsa_audio_open(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  int device, alsa_device;
  snd_pcm_format_t alsa_format;
  snd_pcm_stream_t alsa_stream;
  char *alsa_name;
  int frames, periods;
  int err;
  snd_pcm_t *handle;
  snd_pcm_hw_params_t *hw_params = NULL;
  snd_pcm_sw_params_t *sw_params = NULL;
  
  if ((!audio_initialized) && 
      (mus_audio_initialize() != MUS_NO_ERROR))
    return(MUS_ERROR);
  if (chans <= 0) return(MUS_ERROR);
  
  if (alsa_trace) 
    mus_print("%s: %x rate=%d, chans=%d, format=%d:%s, size=%d", 
	      __func__, ur_dev, srate, chans, samp_type, 
	      mus_sample_type_to_string(samp_type), size);

  /* card = MUS_AUDIO_SYSTEM(ur_dev); */
  device = MUS_AUDIO_DEVICE(ur_dev);

  if ((err = to_alsa_device(device, &alsa_device, &alsa_stream)) < 0) 
    {
      return(alsa_mus_error(MUS_AUDIO_DEVICE_NOT_AVAILABLE, 
			    mus_format("%s: cannot translate device %d to alsa",
				       snd_strerror(err), device)));
    }
  if ((alsa_format = to_alsa_format(samp_type)) == (snd_pcm_format_t)MUS_ERROR) 
    {
      return(alsa_mus_error(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, 
			    mus_format("could not change %s<%d> to alsa format", 
				       mus_sample_type_to_string(samp_type), samp_type)));
    }

  alsa_name = (alsa_stream == SND_PCM_STREAM_PLAYBACK) ? alsa_playback_device_name : alsa_capture_device_name;
  if ((err = snd_pcm_open(&handle, alsa_name, alsa_stream, alsa_open_mode)) != 0) 
    {
      /* snd_pcm_close(handle); */
      /* this segfaults in some versions of ALSA */
      return(alsa_mus_error(MUS_AUDIO_CANT_OPEN, 
			    mus_format("open pcm %s stream %s: %s",
				       alsa_name, snd_pcm_stream_name(alsa_stream), 
				       snd_strerror(err))));
    }
  handles[alsa_stream] = handle;
  hw_params = alsa_hw_params[alsa_stream];
  sw_params = alsa_sw_params[alsa_stream];
  if ((err = snd_pcm_hw_params_any(handle, hw_params)) < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: no parameter configurations available for %s", 
				       snd_strerror(err), alsa_name)));
    }

  err = snd_pcm_hw_params_set_access(handle, hw_params, alsa_interleave);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: access type %s not available", 
				       snd_strerror(err), alsa_name, snd_pcm_access_name(alsa_interleave))));
    }

  periods = alsa_buffers;
  err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0);
  if (err < 0) 
    {
      uint32_t minp, maxp;
      int dir;
      snd_pcm_hw_params_get_periods_min(hw_params, &minp, &dir);
      snd_pcm_hw_params_get_periods_max(hw_params, &maxp, &dir);
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set number of periods to %d, min is %d, max is %d", 
				       snd_strerror(err), alsa_name, periods, (int)minp, (int)maxp)));
    }

  frames = size / chans / mus_bytes_per_sample(samp_type);

  err = snd_pcm_hw_params_set_buffer_size(handle, hw_params, frames * periods);
  if (err < 0) 
    {
      snd_pcm_uframes_t minp, maxp;
      snd_pcm_hw_params_get_buffer_size_min(hw_params, &minp);
      snd_pcm_hw_params_get_buffer_size_max(hw_params, &maxp);
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set buffer size to %d periods of %d frames; \
total requested buffer size is %d frames, minimum allowed is %d, maximum is %d", 
				       snd_strerror(err), alsa_name, periods, frames, periods * frames, (int)minp, (int)maxp)));
    }

  err = snd_pcm_hw_params_set_format(handle, hw_params, alsa_format);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set format to %s", 
				       snd_strerror(err), alsa_name, snd_pcm_format_name(alsa_format))));
    }

  err = snd_pcm_hw_params_set_channels(handle, hw_params, chans);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: %s: cannot set channels to %d", 
				       snd_strerror(err), alsa_name, chans)));
    }

  {
    uint32_t new_rate;
    new_rate = srate;
    /* r is uint32_t so it can't be negative */
    err = snd_pcm_hw_params_set_rate_near(handle, hw_params, &new_rate, 0);
    if ((new_rate != (uint32_t)srate) && (!alsa_squelch_warning))
      {
	mus_print("%s: could not set rate to exactly %d, set to %d instead",
		  alsa_name, srate, new_rate);
      }
  }

  err = snd_pcm_hw_params(handle, hw_params);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: cannot set hardware parameters for %s", 
				       snd_strerror(err), alsa_name)));
    }

  snd_pcm_sw_params_current(handle, sw_params);
  err = snd_pcm_sw_params(handle, sw_params);
  if (err < 0) 
    {
      snd_pcm_close(handle);
      handles[alsa_stream] = NULL;
      alsa_dump_configuration(alsa_name, hw_params, sw_params);
      return(alsa_mus_error(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE, 
			    mus_format("%s: cannot set software parameters for %s", 
				       snd_strerror(err), alsa_name)));
    }

  /* for now the id for the stream is the direction identifier, that is
     not a problem because we only advertise one card with two devices */
  return(alsa_stream);
}

/* sndlib support for opening output devices */

static int alsa_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  return(alsa_audio_open(ur_dev, srate, chans, samp_type, size));
}

/* sndlib support for opening input devices */

static int alsa_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  return(alsa_audio_open(ur_dev, srate, chans, samp_type, size));
}

/* sndlib support for closing a device */

/* to force it to stop, snd_pcm_drop */

static bool xrun_warned = false;

static int alsa_mus_audio_close(int id)
{
  xrun_warned = false;
  if (id == MUS_ERROR) return(MUS_ERROR);
  if (alsa_trace) mus_print( "%s: %d", __func__, id); 
  if (handles[id]) 
    {
      int err;
      err = snd_pcm_drain(handles[id]);
      if (err != 0) 
	mus_print("snd_pcm_drain: %s", snd_strerror(err)); 

      err = snd_pcm_close(handles[id]);
      if (err != 0) 
	return(alsa_mus_error(MUS_AUDIO_CANT_CLOSE, 
			      mus_format("snd_pcm_close: %s", 
					 snd_strerror(err)))); 
      handles[id] = NULL;
    }
  return(MUS_NO_ERROR);
}

/* recover from underruns or overruns */

static int recover_from_xrun(int id)
{
  int err;
  snd_pcm_status_t *status;
  snd_pcm_state_t state;
  snd_pcm_status_alloca(&status);
  err = snd_pcm_status(handles[id], status);
  if (err < 0) 
    {
      mus_print("%s: snd_pcm_status: %s", __func__, snd_strerror(err));
      return(MUS_ERROR);
    }
  state = snd_pcm_status_get_state(status);
  if (state == SND_PCM_STATE_XRUN) 
    {
      if (!xrun_warned)
	{
	  xrun_warned = true;
	  mus_print("[under|over]run detected");
	}
      err = snd_pcm_prepare(handles[id]);
      if (err < 0) 
	mus_print("snd_pcm_prepare: %s", snd_strerror(err));
      else return(MUS_NO_ERROR);
    }
  else mus_print("%s: error, current state is %s", __func__, snd_pcm_state_name(state));
  return(MUS_ERROR);
}

/* sndlib support for writing a buffer to an output device */

static int alsa_mus_audio_write(int id, char *buf, int bytes)
{
  snd_pcm_sframes_t status;
  ssize_t frames;
  if (id == MUS_ERROR) return(MUS_ERROR);
  frames = snd_pcm_bytes_to_frames(handles[id], bytes);
  status = snd_pcm_writei(handles[id], buf, frames);
  if ((status == -EAGAIN) || 
      ((status >= 0) && (status < frames)))
    snd_pcm_wait(handles[id], 1000);
  else
    {
      if (status == -EPIPE) 
	return(recover_from_xrun(id));
      else 
	{
	  if (status < 0) 
	    {
	      mus_print("snd_pcm_writei: %s", snd_strerror(status));
	      return(MUS_ERROR);
	    }
	}
    }
  return(MUS_NO_ERROR);
}

/* sndlib support for reading a buffer from an input device */

static int alsa_mus_audio_read(int id, char *buf, int bytes)
{
  snd_pcm_sframes_t status;
  ssize_t frames;
  if (id == MUS_ERROR) return(MUS_ERROR);
  frames = snd_pcm_bytes_to_frames(handles[id], bytes);
  status = snd_pcm_readi(handles[id], buf, frames);
  if ((status == -EAGAIN) || 
      ((status >= 0) && (status < frames)))
    snd_pcm_wait(handles[id], 1000);
  else 
    {
      if (status == -EPIPE) 
	return(recover_from_xrun(id));
      else 
	{
	  if (status < 0) 
	    {
	      mus_print("snd_pcm_readi: %s", snd_strerror(status));
	      return(MUS_ERROR);
	    }
	}
    }
  return(MUS_NO_ERROR);
}

/* read state of the audio hardware */

static int alsa_chans(int ur_dev, int *info)
{
  int card;
  int device;
  int alsa_device = 0;
  snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;

  if ((!audio_initialized) && 
      (mus_audio_initialize() != MUS_NO_ERROR))
    return(MUS_ERROR);
  
  card = MUS_AUDIO_SYSTEM(ur_dev);
  device = MUS_AUDIO_DEVICE(ur_dev);
  to_alsa_device(device, &alsa_device, &alsa_stream);

  if (card > 0 || alsa_device > 0) 
    return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));

  if ((alsa_stream == SND_PCM_STREAM_CAPTURE) &&
      (alsa_capture_device_name) &&
      (strcmp(alsa_capture_device_name, "default") == 0))
    {
      if (info)
	info[0] = 2;
      else return(2);
    }

  {
    uint32_t max_channels = 0;
    snd_pcm_hw_params_get_channels_max(alsa_hw_params[alsa_stream], &max_channels);

    if ((alsa_stream == SND_PCM_STREAM_CAPTURE) &&
	(max_channels > (uint32_t)alsa_max_capture_channels))
      {
	/* limit number of capture channels to a reasonable maximum, if the user
	   specifies a plug pcm as the capture pcm then the returned number of channels
	   would be MAXINT (or whatever the name is for a really big number). At this
	   point there is no support in the alsa api to distinguish between default
	   parameters or those that have been set by a user on purpose, of for querying
	   the hardware pcm device that is hidden by the plug device to see what is the
	   real number of channels for the device we are dealing with. We could also try
	   to flag this as an error to the user and exit the program */
	max_channels = alsa_max_capture_channels;
      }

    if (info)
      {
	uint32_t tmp = 0;
	info[0] = max_channels;
	snd_pcm_hw_params_get_channels_min(alsa_hw_params[alsa_stream], &tmp); 
	info[1] = tmp;
	info[2] = max_channels;
      }

    return(max_channels);
  }
}


static int alsa_sample_types(int ur_dev, int chan, mus_sample_t *val)
{
  int card;
  int device;
  int alsa_device = 0;
  snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;
  
  if ((!audio_initialized) && 
      (mus_audio_initialize() != MUS_NO_ERROR))
    return(MUS_ERROR);
  
  card = MUS_AUDIO_SYSTEM(ur_dev);
  device = MUS_AUDIO_DEVICE(ur_dev);
  to_alsa_device(device, &alsa_device, &alsa_stream);

  if (card > 0 || alsa_device > 0) 
    return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));

  {
    int f, format;
    snd_pcm_format_mask_t *mask;

    snd_pcm_format_mask_alloca(&mask);
    snd_pcm_hw_params_get_format_mask(alsa_hw_params[alsa_stream], mask); 

    for (format = 0, f = 1; format < SND_PCM_FORMAT_LAST; format++) 
      {
	int err;
	err = snd_pcm_format_mask_test(mask, (snd_pcm_format_t)format);
	if (err > 0) 
	  {
	    if ((f < chan) && 
		(to_mus_sample_type(format) != MUS_UNKNOWN_SAMPLE))
	      val[f++] = to_mus_sample_type(format);
	  }
      }
    val[0] = (mus_sample_t)(f - 1);
  }
  
  return(MUS_NO_ERROR);
}

#endif /* HAVE_ALSA */



/* -------------------------------- SUN -------------------------------- */
/*
 * Thanks to Seppo Ingalsuo for several bugfixes.
 * record case improved after perusal of Snack 1.6/src/jkAudio_sun.c
 */

/* apparently input other than 8000 is 16-bit, 8000 is (?) mulaw */

#if (defined(__sun) || defined(__SVR4)) && (!(defined(AUDIO_OK)))
#define AUDIO_OK 1

#include <sys/types.h>
#ifdef SUNOS
  #include <stropts.h>
#endif
#include <sys/filio.h>

#ifdef SUNOS
#include <sun/audioio.h>
#else
#include <sys/audioio.h>
#endif

#include <sys/mixer.h>

int mus_audio_initialize(void) {return(MUS_NO_ERROR);}

#define DAC_NAME "/dev/audio"
#define AUDIODEV_ENV "AUDIODEV"

#define return_error_exit(Error_Type, Audio_Line, Ur_Error_Message) \
  do { char *Error_Message; Error_Message = Ur_Error_Message; \
    if (Audio_Line != -1) close(Audio_Line); \
    if (Error_Message) \
      {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
    else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
    return(MUS_ERROR); \
  } while (false)

char *mus_audio_moniker(void) 
{
#ifndef AUDIO_DEV_AMD
  struct audio_device ad;
#else
  int ad;
#endif
  int audio_fd, err;
  char *dev_name;
  if (getenv(AUDIODEV_ENV)) 
    dev_name = getenv(AUDIODEV_ENV); 
  else dev_name = (char *)DAC_NAME;
  audio_fd = open(dev_name, O_RDONLY | O_NONBLOCK, 0);
  if (audio_fd == -1) 
    {
      audio_fd = open("/dev/audioctl", O_RDONLY | O_NONBLOCK, 0);
      if (audio_fd == -1) return("sun probably");
    }
  err = ioctl(audio_fd, AUDIO_GETDEV, &ad); 
  if (err == -1) 
    {
      close(audio_fd); 
      return("sun?");
    }
  mus_audio_close(audio_fd);

  if (!version_name) version_name = (char *)calloc(PRINT_BUFFER_SIZE, sizeof(char));
#ifndef AUDIO_DEV_AMD
  snprintf(version_name, LABEL_BUFFER_SIZE, "audio: %s (%s)", ad.name, ad.version);
#else
  switch (ad)
    {
    case AUDIO_DEV_AMD:        snprintf(version_name, LABEL_BUFFER_SIZE, "audio: amd");        break;
  #ifdef AUDIO_DEV_CS4231
    case AUDIO_DEV_CS4231:     snprintf(version_name, LABEL_BUFFER_SIZE, "audio: cs4231");     break;
  #endif
    case AUDIO_DEV_SPEAKERBOX: snprintf(version_name, LABEL_BUFFER_SIZE, "audio: speakerbox"); break;
    case AUDIO_DEV_CODEC:      snprintf(version_name, LABEL_BUFFER_SIZE, "audio: codec");      break;
    default:                   snprintf(version_name, LABEL_BUFFER_SIZE, "audio: unknown");    break;
    }
#endif
  return(version_name);
}

static int to_sun_sample_type(mus_sample_t samp_type)
{
  switch (samp_type)
    {
#if MUS_LITTLE_ENDIAN
    case MUS_LSHORT: /* Solaris on Intel? */
#else
    case MUS_BSHORT: 
#endif
      return(AUDIO_ENCODING_LINEAR); 
      break;
    case MUS_BYTE: 
#if defined(AUDIO_ENCODING_LINEAR8)
      return(AUDIO_ENCODING_LINEAR8); break;
#else
      return(AUDIO_ENCODING_LINEAR);
      break;
#endif
    case MUS_MULAW: return(AUDIO_ENCODING_ULAW); break;
    case MUS_ALAW:  return(AUDIO_ENCODING_ALAW); break;
      /* there's also AUDIO_ENCODING_DVI */

    default: break;
    }
  return(MUS_ERROR);
}

int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  struct audio_info info;
  char *dev_name;
  int encode, bits, dev;
  int audio_fd, err;
  dev = MUS_AUDIO_DEVICE(ur_dev);
  encode = to_sun_sample_type(samp_type);
  if (encode == MUS_ERROR) 
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d (%s) not available",
				 samp_type, 
				 mus_sample_type_name(samp_type)));
  if (getenv(AUDIODEV_ENV)) 
    dev_name = getenv(AUDIODEV_ENV); 
  else dev_name = (char *)DAC_NAME;
  if (dev != MUS_AUDIO_DUPLEX_DEFAULT)
    audio_fd = open(dev_name, O_WRONLY, 0);
  else audio_fd = open(dev_name, O_RDWR, 0);
  if (audio_fd == -1) 
    return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
		      mus_format("can't open output %s: %s",
				 dev_name, strerror(errno)));
  AUDIO_INITINFO(&info);
  if (dev == MUS_AUDIO_LINE_OUT)
    info.play.port = AUDIO_LINE_OUT;
  else
    {
      if (dev == MUS_AUDIO_SPEAKERS)
	/* OR may not be available */
	info.play.port = AUDIO_SPEAKER | AUDIO_HEADPHONE;
      else 
	info.play.port = AUDIO_SPEAKER;
    }
  info.play.sample_rate = srate; 
  info.play.channels = chans;
  bits = 8 * mus_bytes_per_sample(samp_type);
  info.play.precision = bits;
  info.play.encoding = encode;
  err = ioctl(audio_fd, AUDIO_SETINFO, &info); 
  if (err == -1) 
    {
      ioctl(audio_fd, AUDIO_GETINFO, &info); 

      if ((int)info.play.channels != chans) 
	return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
			  mus_format("can't set output %s channels to %d",
				     dev_name, chans));
      
      if (((int)info.play.precision != bits) || 
	  ((int)info.play.encoding != encode)) 
	return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
			  mus_format("can't set output %s sample type to %d bits, %d encode (%s)",
				     dev_name,
				     bits, encode, 
				     mus_sample_type_name(samp_type)));
      
      if ((int)info.play.sample_rate != srate) 
	return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
			  mus_format("can't set output %s srate to %d",
				     dev_name, srate));
    }
  /* man audio sez the play.buffer_size field is not currently supported */
  /* but since the default buffer size is 8180! we need ioctl(audio_fd, I_SETSIG, ...) */
#ifdef SUNOS
  ioctl(audio_fd, I_FLUSH, FLUSHR);
#endif
  return(audio_fd);
}

int mus_audio_write(int line, char *buf, int bytes)
{
  if (write(line, buf, bytes) != bytes) 
    return_error_exit(MUS_AUDIO_WRITE_ERROR, -1,
		      mus_format("write error: %s", strerror(errno)));
  return(MUS_NO_ERROR);
}

int mus_audio_close(int line)
{
  write(line, (char *)NULL, 0);
  close(line);
  return(MUS_NO_ERROR);
}

int mus_audio_read(int line, char *buf, int bytes)
{
  int total = 0;
  char *curbuf;
  /* ioctl(line, AUDIO_DRAIN, NULL) */
  /* this seems to return 8-12 bytes fewer than requested -- perverse! */
  /* should I buffer data internally? */

  /* apparently we need to loop here ... */
  curbuf = buf;
  while (total < bytes)
    {
      int bytes_available;
      ioctl(line, FIONREAD, &bytes_available);
      if (bytes_available > 0)
	{
	  int bytes_read;
	  if ((total + bytes_available) > bytes) bytes_available = bytes - total;
	  bytes_read = read(line, curbuf, bytes_available);
	  if (bytes_read > 0)
	    {
	      total += bytes_read;
	      curbuf = (char *)(buf + total);
	    }
	  /* else return anyway?? */
	}
    }
  return(MUS_NO_ERROR);
}

int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  struct audio_info info;
  int indev, encode, bits, dev, audio_fd, err;
  char *dev_name;
  dev = MUS_AUDIO_DEVICE(ur_dev);
  encode = to_sun_sample_type(samp_type);
  bits = 8 * mus_bytes_per_sample(samp_type);
  if (encode == -1) 
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d bits, %d encode (%s) not available",
				 bits, encode, 
				 mus_sample_type_name(samp_type)));
  if (getenv(AUDIODEV_ENV)) 
    dev_name = getenv(AUDIODEV_ENV); 
  else dev_name = (char *)DAC_NAME;
  if (dev != MUS_AUDIO_DUPLEX_DEFAULT)
    audio_fd = open(dev_name, O_RDONLY, 0);
  else audio_fd = open(dev_name, O_RDWR, 0);
  if (audio_fd == -1) 
    return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
		      mus_format("can't open input %s: %s",
				 dev_name, strerror(errno)));
  AUDIO_INITINFO(&info);
  /*  ioctl(audio_fd, AUDIO_GETINFO, &info); */
  info.record.sample_rate = srate;
  info.record.channels = chans;
  err = ioctl(audio_fd, AUDIO_SETINFO, &info); 
  if (err == -1) 
    return_error_exit(MUS_AUDIO_CANT_OPEN, audio_fd,
		      mus_format("can't set srate %d and chans %d for input %s",
				 srate, chans,
				 dev_name));
  ioctl(audio_fd, AUDIO_GETINFO, &info);
  if (info.record.sample_rate != (uint32_t)srate) 
    mus_print("%s[%d]: sampling rate: %d != %d\n", 
	      __FILE__, __LINE__, 
	      info.record.sample_rate, srate);
  if (info.record.channels != (uint32_t)chans) 
    mus_print("%s[%d]: channels: %d != %d\n", 
	      __FILE__, __LINE__, 
	      info.record.channels, chans);

  info.record.precision = bits; /* was play, changed 10-Jul-03 thanks to J�rgen Keil */
  info.record.encoding = encode;
  err = ioctl(audio_fd, AUDIO_SETINFO, &info); 
  if (err == -1) 
    return_error_exit(MUS_AUDIO_CANT_OPEN, audio_fd,
		      mus_format("can't set bits %d, encode %d (sample type %s) for input %s",
				 bits, encode, mus_sample_type_name(samp_type),
				 dev_name));
  ioctl(audio_fd, AUDIO_GETINFO, &info);

  /* these cannot be OR'd */
  if (dev == MUS_AUDIO_LINE_IN) 
    indev = AUDIO_LINE_IN; 
  else indev = AUDIO_MICROPHONE;
  info.record.port = indev;
  err = ioctl(audio_fd, AUDIO_SETINFO, &info); 
  if (err == -1) 
    return_error_exit(MUS_AUDIO_CANT_WRITE, audio_fd,
		      mus_format("can't set record.port to %d for %s",
				 indev, dev_name));
  err = ioctl(audio_fd, AUDIO_GETINFO, &info);
  if (err == -1) 
    return_error_exit(MUS_AUDIO_CANT_READ, audio_fd,
		      mus_format("can't getinfo on input %s (line: %d)",
				 dev_name, 
				 audio_fd));
  else 
    {
      if ((int)info.record.port != indev) 
	return_error_exit(MUS_AUDIO_DEVICE_NOT_AVAILABLE, audio_fd,
			  mus_format("confusion in record.port: %d != %d (%s)",
				     (int)info.record.port, indev,
				     dev_name));
      if ((int)info.record.channels != chans) 
	return_error_exit(MUS_AUDIO_CHANNELS_NOT_AVAILABLE, audio_fd,
			  mus_format("confusion in record.channels: %d != %d (%s)",
				     (int)info.record.channels, chans,
				     dev_name));
      if (((int)info.record.precision != bits) || 
	  ((int)info.record.encoding != encode)) 
	return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, audio_fd,
			  mus_format("confusion in record.precision|encoding: %d != %d or %d != %d (%s)",
				     (int)info.record.precision, bits,
				     (int)info.record.encoding, encode,
				     dev_name));
    }
  /* this may be a bad idea */
  info.record.buffer_size = size;
  err = ioctl(audio_fd, AUDIO_SETINFO, &info); 
  if (err == -1) 
    return_error_exit(MUS_AUDIO_CANT_WRITE, audio_fd,
		      mus_format("can't set buffer size to %d on input %s",
				 size,
				 dev_name));
  return(audio_fd);
}

#if 0
/* pause can be implemented with play.pause and record.pause */

static const char *sun_sample_type_name(mus_sample_t samp_type)
{
  switch (samp_type)
    {
#ifdef AUDIO_ENCODING_ALAW
    case AUDIO_ENCODING_ALAW: return("alaw"); break;
#endif
#ifdef AUDIO_ENCODING_ULAW
    case AUDIO_ENCODING_ULAW: return("ulaw"); break;
#endif
#ifdef AUDIO_ENCODING_DVI
    case AUDIO_ENCODING_DVI: return("dvi adpcm"); break;
#endif
#ifdef AUDIO_ENCODING_LINEAR8
    case AUDIO_ENCODING_LINEAR8: return("linear"); break;
#else
  #ifdef AUDIO_ENCODING_PCM8
    case AUDIO_ENCODING_PCM8: return("linear"); break;
  #endif
#endif
#ifdef AUDIO_ENCODING_LINEAR
    case AUDIO_ENCODING_LINEAR: return("linear"); break;
#else
  #ifdef AUDIO_ENCODING_PCM16
    case AUDIO_ENCODING_PCM16: return("linear"); break;
  #endif
#endif
#ifdef AUDIO_ENCODING_NONE
    case AUDIO_ENCODING_NONE: return("not audio"); break; /* dbri interface configured for something else */
#endif      
    }
  return("unknown");
}

static const char *sun_in_device_name(int dev)
{
  if (dev == AUDIO_MICROPHONE) return("microphone");
  if (dev == AUDIO_LINE_IN) return("line in");
  if (dev == AUDIO_INTERNAL_CD_IN) return("cd");
  if (dev == (AUDIO_MICROPHONE | AUDIO_LINE_IN)) return("microphone + line in");
  if (dev == (AUDIO_MICROPHONE | AUDIO_LINE_IN | AUDIO_INTERNAL_CD_IN)) return("microphone + line in + cd");
  if (dev == (AUDIO_MICROPHONE | AUDIO_INTERNAL_CD_IN)) return("microphone + cd");
  if (dev == (AUDIO_LINE_IN | AUDIO_INTERNAL_CD_IN)) return("line in + cd");
  return("unknown");
}

static const char *sun_out_device_name(int dev)
{
  if (dev == AUDIO_SPEAKER) return("speakers");
  if (dev == AUDIO_LINE_OUT) return("line out");
  if (dev == AUDIO_HEADPHONE) return("headphones");
  if (dev == (AUDIO_SPEAKER | AUDIO_LINE_OUT)) return("speakers + line out");
  if (dev == (AUDIO_SPEAKER | AUDIO_LINE_OUT | AUDIO_HEADPHONE)) return("speakers + line out + headphones");
  if (dev == (AUDIO_SPEAKER | AUDIO_HEADPHONE)) return("speakers + headphones");
  if (dev == (AUDIO_LINE_OUT | AUDIO_HEADPHONE)) return("line out + headphones");
  return("unknown");
}


static char *sun_vol_name = NULL;
static char *sun_volume_name(float vol, int balance, int chans)
{
  if (!sun_vol_name) sun_vol_name = (char *)calloc(LABEL_BUFFER_SIZE, sizeof(char));
  if (chans != 2)
    snprintf(sun_vol_name, LABEL_BUFFER_SIZE, "%.3f", vol);
  else 
    {
      snprintf(sun_vol_name, LABEL_BUFFER_SIZE, "%.3f %.3f",
		   vol * (float)(AUDIO_RIGHT_BALANCE - balance) / (float)AUDIO_RIGHT_BALANCE,
		   vol * (float)balance / (float)AUDIO_RIGHT_BALANCE);
    }
  return(sun_vol_name);
}

#endif
#endif



/* ------------------------------- WINDOZE ----------------------------------------- */

#if defined(_MSC_VER) && (!(defined(__CYGWIN__)))
#define AUDIO_OK 1

#include <windows.h>
#include <mmsystem.h>

#define BUFFER_FILLED 1
#define BUFFER_EMPTY 2

#define OUTPUT_LINE 1
#define INPUT_LINE 2

#define SOUND_UNREADY 0
#define SOUND_INITIALIZED 1
#define SOUND_RUNNING 2

static int buffer_size = 1024;
static int db_state[2];
static int sound_state = 0;
static int current_chans = 1;
static int current_datum_size = 2;
static int current_buf = 0;
WAVEHDR wh[2];
HWAVEOUT fd;
HWAVEIN record_fd;
WAVEHDR rec_wh;
static int rec_state = SOUND_UNREADY;

static MMRESULT win_in_err = 0, win_out_err = 0;
static char errstr[128], getstr[128];

static char *win_err_buf = NULL;
static mus_print_handler_t *old_handler;

static void win_mus_print(char *msg)
{
  if ((win_in_err == 0) && (win_out_err == 0))
    (*old_handler)(msg);
  else
    {
      if (win_in_err) 
	waveInGetErrorText(win_in_err, getstr, PRINT_BUFFER_SIZE);
      else waveOutGetErrorText(win_out_err, getstr, PRINT_BUFFER_SIZE);
      snprintf(errstr, PRINT_BUFFER_SIZE, "%s [%s]", msg, getstr);
      (*old_handler)(errstr);
    }
}

static void start_win_print(void)
{
  if (old_handler != win_mus_print)
    old_handler = mus_print_set_handler(win_mus_print);
}

static void end_win_print(void)
{
  if (old_handler == win_mus_print)
    mus_print_set_handler(NULL);
  else mus_print_set_handler(old_handler);
}

#define return_error_exit(Error_Type, Ur_Error_Message) \
  do { char *Error_Message; Error_Message = Ur_Error_Message; \
    if (Error_Message) \
      {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
    else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
    end_win_print(); \
    return(MUS_ERROR); \
  } while (false)



DWORD CALLBACK next_buffer(HWAVEOUT w, UINT msg, DWORD user_data, DWORD p1, DWORD p2)
{
  if (msg == WOM_DONE)
    {
      db_state[current_buf] = BUFFER_EMPTY;
    }
  return(0);
}

int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  WAVEFORMATEX wf;
  int dev;
  start_win_print();
  dev = MUS_AUDIO_DEVICE(ur_dev);
  wf.nChannels = chans;
  current_chans = chans;
  wf.wFormatTag = WAVE_FORMAT_PCM;
  wf.cbSize = 0;
  if (samp_type == MUS_UBYTE) 
    {
      wf.wBitsPerSample = 8;
      current_datum_size = 1;
    }
  else 
    {
      wf.wBitsPerSample = 16;
      current_datum_size = 2;
    }
  wf.nSamplesPerSec = srate;
  wf.nBlockAlign = chans * current_datum_size;
  wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
#if _MSC_VER
  win_out_err = waveOutOpen(&fd, WAVE_MAPPER, &wf, (DWORD (*)(HWAVEOUT,UINT,DWORD,DWORD,DWORD))next_buffer, 0, CALLBACK_FUNCTION); 
#else
  win_out_err = waveOutOpen(&fd, WAVE_MAPPER, &wf, (DWORD)next_buffer, 0, CALLBACK_FUNCTION); 
#endif
  /* 0 here = user_data above, other case = WAVE_FORMAT_QUERY */
  if (win_out_err) 
    return_error_exit(MUS_AUDIO_DEVICE_NOT_AVAILABLE,
		      mus_format("can't open %d", dev));
  waveOutPause(fd);
  if (size <= 0) 
    buffer_size = 1024; 
  else buffer_size = size;
  wh[0].dwBufferLength = buffer_size * current_datum_size;
  wh[0].dwFlags = 0;
  wh[0].dwLoops = 0;
  wh[0].lpData = (char *)calloc(wh[0].dwBufferLength, sizeof(char));
  if ((wh[0].lpData) == 0) 
    {
      waveOutClose(fd); 
      return_error_exit(MUS_AUDIO_SIZE_NOT_AVAILABLE,
			mus_format("can't allocate buffer size %d for output %d", buffer_size, dev));
    }
  win_out_err = waveOutPrepareHeader(fd, &(wh[0]), sizeof(WAVEHDR));
  if (win_out_err) 
    {
      free(wh[0].lpData); 
      waveOutClose(fd);  
      return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
			mus_format("can't setup output 'header' for %d", dev));
    }
  db_state[0] = BUFFER_EMPTY;
  wh[1].dwBufferLength = buffer_size * current_datum_size;
  wh[1].dwFlags = 0;
  wh[1].dwLoops = 0;
  wh[1].lpData = (char *)calloc(wh[0].dwBufferLength, sizeof(char));
  if ((wh[1].lpData) == 0) 
    {
      free(wh[0].lpData); 
      waveOutClose(fd); 
      return_error_exit(MUS_AUDIO_SIZE_NOT_AVAILABLE,
			mus_format("can't allocate buffer size %d for output %d", buffer_size, dev));
    }
  win_out_err = waveOutPrepareHeader(fd, &(wh[1]), sizeof(WAVEHDR));
  if (win_out_err) 
    {
      waveOutUnprepareHeader(fd, &(wh[0]), sizeof(WAVEHDR)); 
      free(wh[0].lpData); 
      free(wh[1].lpData); 
      waveOutClose(fd);  
      return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
			mus_format("can't setup output 'header' for %d", dev));
    }
  db_state[1] = BUFFER_EMPTY;
  sound_state = SOUND_INITIALIZED;
  current_buf = 0;
  end_win_print();
  return(OUTPUT_LINE);
}

static MMRESULT fill_buffer(int dbi, char *inbuf, int instart, int bytes)
{
  int i, j;
  win_out_err = 0;
  if (sound_state == SOUND_UNREADY) return(0);
  for (i = instart, j = 0; j < bytes; j++, i++)
    wh[dbi].lpData[j] = inbuf[i];
  wh[dbi].dwBufferLength = bytes;
  db_state[dbi] = BUFFER_FILLED;
  if ((sound_state == SOUND_INITIALIZED) && 
      (dbi == 1))
    {
      sound_state = SOUND_RUNNING;
      win_out_err = waveOutRestart(fd);
    }
  return(win_out_err);
}

static void wait_for_empty_buffer(int buf)
{
  while (db_state[buf] != BUFFER_EMPTY)
    {
      Sleep(1);      /* in millisecs, so even this may be too much if buf = 256 bytes */
    }
}

int mus_audio_write(int line, char *buf, int bytes) 
{
  int leftover, start;
  start_win_print();
  if (line != OUTPUT_LINE) 
    return_error_exit(MUS_AUDIO_CANT_WRITE,
		      mus_format("write error: line %d != %d?",
				 line, OUTPUT_LINE));
  win_out_err = 0;
  leftover = bytes;
  start = 0;
  if (sound_state == SOUND_UNREADY) 
    {
      end_win_print(); 
      return(MUS_NO_ERROR);
    }
  while (leftover > 0)
    {
      int lim;
      lim = leftover;
      if (lim > buffer_size) lim = buffer_size;
      leftover -= lim;
      wait_for_empty_buffer(current_buf);
      win_out_err = fill_buffer(current_buf, buf, start, lim);
      if (win_out_err) 
	return_error_exit(MUS_AUDIO_CANT_WRITE,
			  mus_format("write error on %d",
				     line));
      win_out_err = waveOutWrite(fd, &wh[current_buf], sizeof(WAVEHDR));
      if (win_out_err) 
	return_error_exit(MUS_AUDIO_CANT_WRITE,
			  mus_format("write error on %d",
				     line));
      start += lim;
      current_buf++;
      if (current_buf > 1) current_buf = 0;
    }
  return(MUS_NO_ERROR);
}

static float unlog(unsigned short val)
{
  /* 1.0 linear is 0xffff, rest is said to be "logarithmic", whatever that really means here */
  if (val == 0) return(0.0);
  return((float)val / 65536.0);
  /* return(pow(2.0, amp) - 1.0); */ /* doc seems to be bogus */
}

static char *mixer_status_name(int status)
{
  switch (status)
    {
    case MIXERLINE_LINEF_ACTIVE: return(", (active)"); break;
    case MIXERLINE_LINEF_DISCONNECTED: return(", (disconnected)"); break;
    case MIXERLINE_LINEF_SOURCE: return(", (source)"); break;
    default: return(""); break;
    }
}

static char *mixer_target_name(int type)
{
  switch (type)
    {
    case MIXERLINE_TARGETTYPE_UNDEFINED: return("undefined"); break;
    case MIXERLINE_TARGETTYPE_WAVEOUT: return("output"); break;
    case MIXERLINE_TARGETTYPE_WAVEIN: return("input"); break;
    case MIXERLINE_TARGETTYPE_MIDIOUT: return("midi output"); break;
    case MIXERLINE_TARGETTYPE_MIDIIN: return("midi input"); break;
    case MIXERLINE_TARGETTYPE_AUX: return("aux"); break;
    default: return(""); break;
    }
}

static char *mixer_component_name(int type)
{
  switch (type)
    {
    case MIXERLINE_COMPONENTTYPE_DST_UNDEFINED: return("undefined"); break;
    case MIXERLINE_COMPONENTTYPE_DST_DIGITAL: return("digital"); break;
    case MIXERLINE_COMPONENTTYPE_DST_LINE: return("line"); break;
    case MIXERLINE_COMPONENTTYPE_DST_MONITOR: return("monitor"); break;
    case MIXERLINE_COMPONENTTYPE_DST_SPEAKERS: return("speakers"); break;
    case MIXERLINE_COMPONENTTYPE_DST_HEADPHONES: return("headphones"); break;
    case MIXERLINE_COMPONENTTYPE_DST_TELEPHONE: return("telephone"); break;
    case MIXERLINE_COMPONENTTYPE_DST_WAVEIN: return("wave in"); break;
    case MIXERLINE_COMPONENTTYPE_DST_VOICEIN: return("voice in"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED: return("undefined"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_DIGITAL: return("digital"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_LINE: return("line"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE: return("mic"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER: return("synth"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC: return("CD"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE: return("telephone"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER: return("speaker"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT: return("wave out"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY: return("aux"); break;
    case MIXERLINE_COMPONENTTYPE_SRC_ANALOG: return("analog"); break;
    default: return(""); break;
    }
}

char *mus_audio_moniker(void) {return("MS audio");} /* version number of some sort? */

int mus_audio_initialize(void) 
{
  return(MUS_NO_ERROR);
}

int mus_audio_close(int line) 
{
  win_out_err = 0; 
  win_in_err = 0;
  if (line == OUTPUT_LINE)
    {
      /* fill with a few zeros, wait for empty flag */
      if (sound_state != SOUND_UNREADY)
        {
	  int i;
          wait_for_empty_buffer(current_buf);
          for (i = 0; i < 128; i++) wh[current_buf].lpData[i] = 0;
          wait_for_empty_buffer(current_buf);
          win_out_err = waveOutClose(fd);
	  i = 0;
          while (win_out_err == WAVERR_STILLPLAYING)
            {
	      Sleep(1);
              win_out_err = waveOutClose(fd);
	      i++;
	      if (i > 1024) break;
            }
          db_state[0] = BUFFER_EMPTY;
          db_state[1] = BUFFER_EMPTY;
          sound_state = SOUND_UNREADY;
          waveOutUnprepareHeader(fd, &(wh[0]), sizeof(WAVEHDR));
          waveOutUnprepareHeader(fd, &(wh[1]), sizeof(WAVEHDR));
          free(wh[0].lpData);
          free(wh[1].lpData);
          if (win_out_err) 
	    return_error_exit(MUS_AUDIO_CANT_CLOSE,
			      mus_format("close failed on %d",
					 line));
        }
    }
  else 
    {
      if (line == INPUT_LINE)
        {
          if (rec_state != SOUND_UNREADY)
            {
              waveInReset(record_fd);
              waveInClose(record_fd);
              waveInUnprepareHeader(record_fd, &rec_wh, sizeof(WAVEHDR));
              if (rec_wh.lpData) 
		{
		  free(rec_wh.lpData);
		  rec_wh.lpData = NULL;
		}
              rec_state = SOUND_UNREADY;
            }
        }
      else 
	return_error_exit(MUS_AUDIO_CANT_CLOSE,
			  mus_format("can't close unrecognized line %d",
				     line));
    }
  return(MUS_NO_ERROR);
}

  /*
   * waveInAddBuffer sends buffer to get data
   * MM_WIM_DATA lParam->WAVEHDR dwBytesRecorded =>how much data actually in buffer
   */

static int current_record_chans = 0, current_record_datum_size = 0;

DWORD CALLBACK next_input_buffer(HWAVEIN w, UINT msg, DWORD user_data, DWORD p1, DWORD p2)
{
  if (msg == WIM_DATA)
    {
      /* grab data */
      /* p1->dwBytesRecorded */
    }
  return(0);
}

int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  WAVEFORMATEX wf;
  int dev;
  win_in_err = 0;
  dev = MUS_AUDIO_DEVICE(ur_dev);
  wf.nChannels = chans;
  current_record_chans = chans;

  wf.wFormatTag = WAVE_FORMAT_PCM;
  wf.cbSize = 0;
  if (samp_type == MUS_UBYTE) 
    {
      wf.wBitsPerSample = 8;
      current_record_datum_size = 1;
    }
  else 
    {
      wf.wBitsPerSample = 16;
      current_record_datum_size = 2;
    }
  wf.nSamplesPerSec = srate;
  wf.nBlockAlign = chans * current_datum_size;
  wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;

  rec_wh.dwBufferLength = size * current_record_datum_size;
  rec_wh.dwFlags = 0;
  rec_wh.dwLoops = 0;
  rec_wh.lpData = (char *)calloc(rec_wh.dwBufferLength, sizeof(char));
  if ((rec_wh.lpData) == 0) 
    return_error_exit(MUS_AUDIO_SIZE_NOT_AVAILABLE,
		      mus_format("can't allocated %d bytes for input buffer of %d", size, dev));
#if _MSC_VER
  win_in_err = waveInOpen(&record_fd, WAVE_MAPPER, &wf, (DWORD (*)(HWAVEIN,UINT,DWORD,DWORD,DWORD))next_input_buffer, 0, CALLBACK_FUNCTION);
  /* why isn't the simple cast (DWORD) correct here as below? -- the docs say the 4th arg's type is DWORD */
#else
  win_in_err = waveInOpen(&record_fd, WAVE_MAPPER, &wf, (DWORD)next_input_buffer, 0, CALLBACK_FUNCTION);
#endif
  if (win_in_err) 
    {
      free(rec_wh.lpData);
      return_error_exit(MUS_AUDIO_DEVICE_NOT_AVAILABLE,
			mus_format("can't open input device %d", dev));
    }
  win_in_err = waveInPrepareHeader(record_fd, &(rec_wh), sizeof(WAVEHDR));
  if (win_in_err) 
    {
      free(rec_wh.lpData);
      waveInClose(record_fd);
      return_error_exit(MUS_AUDIO_CONFIGURATION_NOT_AVAILABLE,
			mus_format("can't prepare input 'header' for %d", dev));
    }
  return(MUS_NO_ERROR);
}

int mus_audio_read(int line, char *buf, int bytes) 
{
  win_in_err = 0;
  return(MUS_ERROR);
}

#endif



/* ------------------------------- Mac OSX ----------------------------------------- */

/* this code based primarily on the CoreAudio headers and portaudio pa_mac_core.c,
 *   and to a much lesser extent, coreaudio.pdf and the HAL/Daisy examples.
 */

#ifdef __APPLE__
#define AUDIO_OK 1

#include <AvailabilityMacros.h>

/*
#include <CoreServices/CoreServices.h>
#include <CoreAudio/CoreAudio.h>
*/
/* ./System/Library/Frameworks/CoreAudio.framework/Headers/CoreAudio.h */

static const char* osx_error(OSStatus err) 
{
  if (err == noErr) return("no error");
  switch (err) 
    {
    case kAudioHardwareNoError:               return("no error");                         
    case kAudioHardwareUnspecifiedError:      return("unspecified audio hardware error"); 
    case kAudioHardwareNotRunningError:       return("audio hardware not running");       
    case kAudioHardwareUnknownPropertyError:  return("unknown property");                 
    case kAudioHardwareBadPropertySizeError:  return("bad property");                     
    case kAudioHardwareBadDeviceError:        return("bad device");                       
    case kAudioHardwareBadStreamError:        return("bad stream");                       
    case kAudioHardwareIllegalOperationError: return("illegal operation");                
    case kAudioDeviceUnsupportedFormatError:  return("unsupported sample type");          
    case kAudioDevicePermissionsError:        return("device permissions error");         
    }
  return("unknown error");
}

#define MAX_BUFS 4
static char **bufs = NULL;
static uint32_t in_buf = 0, out_buf = 0;

static OSStatus writer(AudioDeviceID inDevice, 
		       const AudioTimeStamp *inNow, 
		       const AudioBufferList *InputData, const AudioTimeStamp *InputTime, 
		       AudioBufferList *OutputData, const AudioTimeStamp *OutputTime, 
		       void *appGlobals)
{
  AudioBuffer abuf;
  char *aplbuf, *sndbuf;
  abuf = OutputData->mBuffers[0];
  aplbuf = (char *)(abuf.mData);
  sndbuf = bufs[out_buf];
  memmove((void *)aplbuf, (void *)sndbuf, abuf.mDataByteSize);
  out_buf++;
  if (out_buf >= MAX_BUFS) out_buf = 0;
  return(noErr);
}

static OSStatus reader(AudioDeviceID inDevice, 
		       const AudioTimeStamp *inNow, 
		       const AudioBufferList *InputData, const AudioTimeStamp *InputTime, 
		       AudioBufferList *OutputData, const AudioTimeStamp *OutputTime, 
		       void *appGlobals)
{
  AudioBuffer abuf;
  char *aplbuf, *sndbuf;
  abuf = InputData->mBuffers[0];
  aplbuf = (char *)(abuf.mData);
  sndbuf = bufs[out_buf];
  memmove((void *)sndbuf, (void *)aplbuf, abuf.mDataByteSize);
  out_buf++;
  if (out_buf >= MAX_BUFS) out_buf = 0;
  return(noErr);
}


static AudioDeviceID device = kAudioDeviceUnknown;
static bool writing = false, open_for_input = false;

#ifdef MAC_OS_X_VERSION_10_5
  #define HAVE_OSX_10_5 1
#else
  #define HAVE_OSX_10_5 0
#endif

#if HAVE_OSX_10_5
  static AudioDeviceIOProcID read_procId, write_procId;
#endif 

int mus_audio_close(int line) 
{
  OSStatus err = noErr;
  UInt32 sizeof_running;
  UInt32 running;
  if (open_for_input)
    {
      in_buf = 0;
      err = AudioDeviceStop(device, (AudioDeviceIOProc)reader);
      if (err == noErr) 
#if HAVE_OSX_10_5
	err = AudioDeviceDestroyIOProcID(device, read_procId);
#else
        err = AudioDeviceRemoveIOProc(device, (AudioDeviceIOProc)reader);
#endif
    }
  else
    {
      if ((in_buf > 0) && (!writing))
	{
	  /* short enough sound that we never got started? */
#if HAVE_OSX_10_5
	  err = AudioDeviceCreateIOProcID(device, (AudioDeviceIOProc)writer, NULL, &write_procId);
#else
	  err = AudioDeviceAddIOProc(device, (AudioDeviceIOProc)writer, NULL);
#endif
	  if (err == noErr)
	    err = AudioDeviceStart(device, (AudioDeviceIOProc)writer); /* writer will be called right away */
	  if (err == noErr)
	    writing = true;
	}
      if (writing)
	{
	  /* send out waiting buffers */
	  sizeof_running = sizeof(UInt32);
	  while (in_buf == out_buf)
	    {
	      /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
	      {
		AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
							      kAudioDevicePropertyScopeOutput,
							      kAudioObjectPropertyElementMaster };
		err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
	      }	      
	    }
	  while (in_buf != out_buf)
	    {
	      /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
	      {
		AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
							      kAudioDevicePropertyScopeOutput,
							      kAudioObjectPropertyElementMaster };
		err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
	      }
	    }
	  in_buf = 0;
	  err = AudioDeviceStop(device, (AudioDeviceIOProc)writer);
	  if (err == noErr) 
#if HAVE_OSX_10_5
	    err = AudioDeviceDestroyIOProcID(device, write_procId);
#else
	    err = AudioDeviceRemoveIOProc(device, (AudioDeviceIOProc)writer);
#endif
	  writing = false;
	}
    }
  device = kAudioDeviceUnknown;
  if (err == noErr)
    return(MUS_NO_ERROR);
  return(MUS_ERROR);
}

typedef enum {CONVERT_NOT, CONVERT_COPY, CONVERT_SKIP, CONVERT_COPY_AND_SKIP, CONVERT_SKIP_N, CONVERT_COPY_AND_SKIP_N} audio_convert_t;
static audio_convert_t conversion_choice = CONVERT_NOT;
static float conversion_multiplier = 1.0;
static int dac_out_chans, dac_out_srate;
static int incoming_out_chans = 1, incoming_out_srate = 44100;
static uint32_t fill_point = 0;
static uint32_t bufsize = 0, current_bufsize = 0;
static bool match_dac_to_sound = true;


bool mus_audio_output_properties_mutable(bool mut)
{
  match_dac_to_sound = mut;
  return(mut);
}


/* I'm getting bogus buffer sizes from the audio conversion stuff from Apple,
 *   and I think AudioConvert doesn't handle cases like 4->6 chans correctly
 *   so, I'll just do the conversions myself -- there is little need here
 *   for non-integer srate conversion anyway, and the rest is trivial.
 */

int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  OSStatus err = noErr;
  UInt32 sizeof_device, sizeof_format, sizeof_bufsize;
  AudioStreamBasicDescription device_desc;

  device = 0;
  sizeof_device = sizeof(AudioDeviceID);
  sizeof_bufsize = sizeof(uint32_t);

  /* err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &sizeof_device, (void *)(&device)); */
  {
    AudioObjectPropertyAddress device_address = { kAudioHardwarePropertyDefaultOutputDevice,
						  kAudioObjectPropertyScopeGlobal,
						  kAudioObjectPropertyElementMaster };
    err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &device_address, 0, NULL, &sizeof_device, &device);
  }

  bufsize = 4096;
  if (err == noErr) 
    {
      /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyBufferSize, &sizeof_bufsize, &bufsize); */
      {
	AudioObjectPropertyAddress device_address = { kAudioDevicePropertyBufferSize,
						      kAudioDevicePropertyScopeOutput,
						      kAudioObjectPropertyElementMaster };
	err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_bufsize, &bufsize);
      }
    }
  if (err != noErr) 
    {
      fprintf(stderr, "open audio output err: %d %s\n", (int)err, osx_error(err));
      return(MUS_ERROR);
    }

  sizeof_format = sizeof(AudioStreamBasicDescription);
  /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &sizeof_format, &device_desc); */
  {
    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
						  kAudioDevicePropertyScopeOutput,
						  kAudioObjectPropertyElementMaster };
    err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
  }

  if (err != noErr)
    {
      fprintf(stderr, "open audio output (get device format) err: %d %s\n", (int)err, osx_error(err));
      return(MUS_ERROR);
    }

  if (match_dac_to_sound)
    {
      /* now check for srate/chan mismatches and so on */
      
      /* current DAC state: device_desc.mChannelsPerFrame, (int)(device_desc.mSampleRate) */
      /* apparently get stream format can return noErr but chans == 0?? */

      if (((int)device_desc.mChannelsPerFrame != chans) || 
	  ((int)(device_desc.mSampleRate) != srate))
	{
	  /* try to match DAC settings to current sound */
	  device_desc.mChannelsPerFrame = chans;
	  device_desc.mSampleRate = srate;
	  device_desc.mBytesPerPacket = chans * 4; /* assume 1 frame/packet and float32 data */
	  device_desc.mBytesPerFrame = chans * 4;
	  sizeof_format = sizeof(AudioStreamBasicDescription);
	  /* err = AudioDeviceSetProperty(device, 0, 0, false, kAudioDevicePropertyStreamFormat, sizeof_format, &device_desc); */
	  {
	    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
							  kAudioDevicePropertyScopeOutput,
							  kAudioObjectPropertyElementMaster };
	    err = AudioObjectSetPropertyData(device, &device_address, 0, NULL, sizeof_format, &device_desc);
	  }
	  
	  /* this error is bogus in some cases -- other audio systems just ignore it,
	   *   but in my case (a standard MacIntel with no special audio hardware), if I leave
	   *   this block out, the sound is played back at the wrong rate, and the volume
	   *   of outa is set to 0.0?? 
	   */
	  
	  if (err != noErr)
	    {
	      /* it must have failed for some reason -- look for closest match available */
	      /* if srate = 22050 try 44100, if chans = 1 try 2 */
	      /* the "get closest match" business appears to be completely bogus... */

	      device_desc.mChannelsPerFrame = (chans == 1) ? 2 : chans;
	      device_desc.mSampleRate = (srate == 22050) ? 44100 : srate;
	      device_desc.mBytesPerPacket = device_desc.mChannelsPerFrame * 4; /* assume 1 frame/packet and float32 data */
	      device_desc.mBytesPerFrame = device_desc.mChannelsPerFrame * 4;
	      sizeof_format = sizeof(AudioStreamBasicDescription);
	      /* err = AudioDeviceSetProperty(device, 0, 0, false, kAudioDevicePropertyStreamFormat, sizeof_format, &device_desc); */
	      {
		AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
							      kAudioDevicePropertyScopeOutput,
							      kAudioObjectPropertyElementMaster };
		err = AudioObjectSetPropertyData(device, &device_address, 0, NULL, sizeof_format, &device_desc);
	      }
	      if (err != noErr)
		{
		  sizeof_format = sizeof(AudioStreamBasicDescription);
		  /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormatMatch, &sizeof_format, &device_desc); */
		  {
		    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormatMatch,
								  kAudioDevicePropertyScopeOutput,
								  kAudioObjectPropertyElementMaster };
		    err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
		  }

		  if (err == noErr)
		    {
		      /* match suggests: device_desc.mChannelsPerFrame, (int)(device_desc.mSampleRate) */
		      /* try to set DAC to reflect that match */
		      /* a bug here in emagic 2|6 -- we can get 6 channel match, but then can't set it?? */

		      sizeof_format = sizeof(AudioStreamBasicDescription);
		      /* err = AudioDeviceSetProperty(device, 0, 0, false, kAudioDevicePropertyStreamFormat, sizeof_format, &device_desc); */
		      {
			AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
								      kAudioDevicePropertyScopeOutput,
								      kAudioObjectPropertyElementMaster };
			err = AudioObjectSetPropertyData(device, &device_address, 0, NULL, sizeof_format, &device_desc);
		      }
		      if (err != noErr) 
			{
			  /* no luck -- get current DAC settings at least */
			  sizeof_format = sizeof(AudioStreamBasicDescription);
			  /* AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &sizeof_format, &device_desc); */
			  {
			    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
									  kAudioDevicePropertyScopeOutput,
									  kAudioObjectPropertyElementMaster };
			    err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
			  }
			}
		    }
		}
	      else 
		{
		  /* nothing matches? -- get current DAC settings */
		  sizeof_format = sizeof(AudioStreamBasicDescription);
		  /* AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyStreamFormat, &sizeof_format, &device_desc); */
		  {
		    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyStreamFormat,
								  kAudioDevicePropertyScopeOutput,
								  kAudioObjectPropertyElementMaster };
		    err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_format, &device_desc);
		  }
		}
	    }
	}
    } /* end mismatch check */

  /* now DAC claims it is ready for device_desc.mChannelsPerFrame, (int)(device_desc.mSampleRate) */
  dac_out_chans = device_desc.mChannelsPerFrame; /* use better variable names */
  dac_out_srate = (int)(device_desc.mSampleRate);

  open_for_input = false;
  if ((!bufs) || (bufsize > current_bufsize))
    {
      int i;
      if (bufs)
	{
	  for (i = 0; i < MAX_BUFS; i++) free(bufs[i]);
	  free(bufs);
	}
      bufs = (char **)calloc(MAX_BUFS, sizeof(char *));
      for (i = 0; i < MAX_BUFS; i++)
	bufs[i] = (char *)calloc(bufsize, sizeof(char));
      current_bufsize = bufsize;
    }

  in_buf = 0;
  out_buf = 0;
  fill_point = 0;

  if (!match_dac_to_sound)
    {
      incoming_out_srate = dac_out_srate;
      incoming_out_chans = dac_out_chans;
      conversion_choice = CONVERT_NOT;
      conversion_multiplier = 1.0;
      return(MUS_NO_ERROR);
    }

  incoming_out_srate = srate;
  incoming_out_chans = chans;

  if (incoming_out_chans == dac_out_chans)
    {
      if (incoming_out_srate == dac_out_srate)
	{
	  conversion_choice = CONVERT_NOT;
	  conversion_multiplier = 1.0;
	}
      else 
	{
	  /* here we don't get very fancy -- assume dac/2=in */
	  conversion_choice = CONVERT_COPY;
	  conversion_multiplier = 2.0;
	}
    }
  else
    {
      if (incoming_out_srate == dac_out_srate)
	{
	  if ((dac_out_chans == 2) && (incoming_out_chans == 1)) /* the usual case */
	    {
	      conversion_choice = CONVERT_SKIP;
	      conversion_multiplier = 2.0;
	    }
	  else
	    {
	      conversion_choice = CONVERT_SKIP_N;
	      conversion_multiplier = ((float)dac_out_chans / (float)incoming_out_chans);
	    }
	}
      else 
	{
	  if ((dac_out_chans == 2) && (incoming_out_chans == 1)) /* the usual case */
	    {
	      conversion_choice = CONVERT_COPY_AND_SKIP;
	      conversion_multiplier = 4.0;
	    }
	  else
	    {
	      conversion_choice = CONVERT_COPY_AND_SKIP_N;
	      conversion_multiplier = ((float)dac_out_chans / (float)incoming_out_chans) * 2;
	    }
	}
    }
  return(MUS_NO_ERROR);
}


static void convert_incoming(char *to_buf, int fill_point, int lim, char *buf)
{
  int i, j, k, jc, kc, ic;
  switch (conversion_choice)
    {
    case CONVERT_NOT:
      /* no conversion needed */
      for (i = 0; i < lim; i++)
	to_buf[i + fill_point] = buf[i];
      break;

    case CONVERT_COPY:
      /* copy sample to mimic lower srate */
      for (i = 0, j = fill_point; i < lim; i += 8, j += 16)
	for (k = 0; k < 8; k++)
	  {
	    to_buf[j + k] = buf[i + k];
	    to_buf[j + k + 8] = buf[i + k];
	  }
      break;

    case CONVERT_SKIP:
      /* skip sample for empty chan */
      for (i = 0, j = fill_point; i < lim; i += 4, j += 8)
	for (k = 0; k < 4; k++)
	  {
	    to_buf[j + k] = buf[i + k];
	    to_buf[j + k + 4] = 0;
	  }
      break;

    case CONVERT_SKIP_N:
      /* copy incoming_out_chans then skip up to dac_out_chans */
      jc = dac_out_chans * 4;
      ic = incoming_out_chans * 4;
      for (i = 0, j = fill_point; i < lim; i += ic, j += jc)
	{
	  for (k = 0; k < ic; k++) to_buf[j + k] = buf[i + k];
	  for (k = ic; k < jc; k++) to_buf[j + k] = 0;
	}
      break;

    case CONVERT_COPY_AND_SKIP:
      for (i = 0, j = fill_point; i < lim; i += 4, j += 16)
	for (k = 0; k < 4; k++)
	  {
	    to_buf[j + k] = buf[i + k];
	    to_buf[j + k + 4] = 0;
	    to_buf[j + k + 8] = buf[i + k];
	    to_buf[j + k + 12] = 0;
	  }
      break;

    case CONVERT_COPY_AND_SKIP_N:
      /* copy for each active chan, skip rest */
      jc = dac_out_chans * 8;
      ic = incoming_out_chans * 4;
      kc = dac_out_chans * 4;
      for (i = 0, j = fill_point; i < lim; i += ic, j += jc)
	{
	  for (k = 0; k < ic; k++) 
	    {
	      to_buf[j + k] = buf[i + k];
	      to_buf[j + k + kc] = buf[i + k];	      
	    }
	  for (k = ic; k < kc; k++) 
	    {
	      to_buf[j + k] = 0;
	      to_buf[j + k + kc] = 0;
	    }
	}
      break;
    }
}


int mus_audio_write(int line, char *buf, int bytes) 
{
  OSStatus err = noErr;
  uint32_t lim, out_bytes;
  UInt32 sizeof_running;
  UInt32 running;
  char *to_buf;

  to_buf = bufs[in_buf];
  out_bytes = (uint32_t)(bytes * conversion_multiplier);
  if ((fill_point + out_bytes) > bufsize)
    out_bytes = bufsize - fill_point;
  lim = (uint32_t)(out_bytes / conversion_multiplier);

  if (!writing)
    {
      convert_incoming(to_buf, fill_point, lim, buf);
      fill_point += out_bytes;
      if (fill_point >= bufsize)
	{
	  in_buf++;
	  fill_point = 0;
	  if (in_buf == MAX_BUFS)
	    {
	      in_buf = 0;
#if HAVE_OSX_10_5
	      err = AudioDeviceCreateIOProcID(device, (AudioDeviceIOProc)writer, NULL, &write_procId);
#else
	      err = AudioDeviceAddIOProc(device, (AudioDeviceIOProc)writer, NULL);
#endif
	      if (err == noErr)
		err = AudioDeviceStart(device, (AudioDeviceIOProc)writer); /* writer will be called right away */
	      if (err == noErr)
		{
		  writing = true;
		  return(MUS_NO_ERROR);
		}
	      else return(MUS_ERROR);
	    }
	}
      return(MUS_NO_ERROR);
    }
  if ((fill_point == 0) && (in_buf == out_buf))
    {
      uint32_t bp;
      bp = out_buf;
      sizeof_running = sizeof(UInt32);
      while (bp == out_buf)
	{
	  /* i.e. just kill time without hanging */
	  /* err = AudioDeviceGetProperty(device, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
	  {
	    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
							  kAudioDevicePropertyScopeOutput,
							  kAudioObjectPropertyElementMaster };
	    err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
	  }
	  /* usleep(10); */
	}
    }
  to_buf = bufs[in_buf];
  if (fill_point == 0) memset((void *)to_buf, 0, bufsize);
  convert_incoming(to_buf, fill_point, lim, buf);
  fill_point += out_bytes;
  if (fill_point >= bufsize)
    {
      in_buf++;
      fill_point = 0;
      if (in_buf >= MAX_BUFS) in_buf = 0;
    }
  return(MUS_NO_ERROR);
}

int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  OSStatus err = noErr;
  UInt32 sizeof_device;
  UInt32 sizeof_bufsize;

  sizeof_device = sizeof(AudioDeviceID);
  sizeof_bufsize = sizeof(uint32_t);

  device = 0;
  /* err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &sizeof_device, (void *)(&device)); */
  {
    AudioObjectPropertyAddress device_address = { kAudioHardwarePropertyDefaultInputDevice,
						  kAudioObjectPropertyScopeGlobal,
						  kAudioObjectPropertyElementMaster };
    err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &device_address, 0, NULL, &sizeof_device, &device);
  }

  bufsize = 4096;
  if (err == noErr) 
    {
      /* err = AudioDeviceGetProperty(device, 0, true, kAudioDevicePropertyBufferSize, &sizeof_bufsize, &bufsize); */
      {
	AudioObjectPropertyAddress device_address = { kAudioDevicePropertyBufferSize,
						      kAudioDevicePropertyScopeInput,
						      kAudioObjectPropertyElementMaster };
	err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_bufsize, &bufsize);
      }
    }
  if (err != noErr) 
    {
      fprintf(stderr, "open audio input err: %d %s\n", (int)err, osx_error(err));
      return(MUS_ERROR);
    }
  open_for_input = true;
  /* assume for now that recorder (higher level) will enforce match */
  if ((!bufs) || (bufsize > current_bufsize))
    {
      int i;
      if (bufs)
	{
	  for (i = 0; i < MAX_BUFS; i++) free(bufs[i]);
	  free(bufs);
	}
      bufs = (char **)calloc(MAX_BUFS, sizeof(char *));
      for (i = 0; i < MAX_BUFS; i++)
	bufs[i] = (char *)calloc(bufsize, sizeof(char));
      current_bufsize = bufsize;
    }
  in_buf = 0;
  out_buf = 0;
  fill_point = 0;
  incoming_out_srate = srate;
  incoming_out_chans = chans;

#if HAVE_OSX_10_5
  err = AudioDeviceCreateIOProcID(device, (AudioDeviceIOProc)reader, NULL, &read_procId);
#else
  err = AudioDeviceAddIOProc(device, (AudioDeviceIOProc)reader, NULL);
#endif

  if (err == noErr)
    err = AudioDeviceStart(device, (AudioDeviceIOProc)reader);
  if (err != noErr) 
    {
      fprintf(stderr, "add open audio input err: %d %s\n", (int)err, osx_error(err));
      return(MUS_ERROR);
    }
  return(MUS_NO_ERROR);
}

int mus_audio_read(int line, char *buf, int bytes) 
{
  OSStatus err = noErr;
  UInt32 sizeof_running;
  UInt32 running;
  char *to_buf;

  if (in_buf == out_buf)
    {
      uint32_t bp;
      bp = out_buf;
      sizeof_running = sizeof(UInt32);
      while (bp == out_buf)
	{
	  /* err = AudioDeviceGetProperty(device, 0, true, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running); */
	  {
	    AudioObjectPropertyAddress device_address = { kAudioDevicePropertyDeviceIsRunning,
							  kAudioDevicePropertyScopeInput,
							  kAudioObjectPropertyElementMaster };
	    err = AudioObjectGetPropertyData(device, &device_address, 0, NULL, &sizeof_running, &running);
	  }
	  if (err != noErr) 
	    fprintf(stderr, "wait err: %s ", osx_error(err));
	}
    }
  to_buf = bufs[in_buf];
  if (bytes <= (int)bufsize)
    memmove((void *)buf, (void *)to_buf, bytes);
  else memmove((void *)buf, (void *)to_buf, bufsize);
  in_buf++;
  if (in_buf >= MAX_BUFS) in_buf = 0;
  return(MUS_ERROR);
}

int mus_audio_initialize(void) {return(MUS_NO_ERROR);}

char *mus_audio_moniker(void) {return((char *)"Mac OSX audio");}
#endif




/* ------------------------------- JACK ----------------------------------------- */

/* Kjetil S. Matheussen. k.s.matheussen@notam02.no */
/* Based on code from ceres. */

#if MUS_JACK
#define AUDIO_OK 1
#include <pthread.h>
#include <jack/jack.h>
#include <samplerate.h>
#include <sys/mman.h>
#include <signal.h>

#if MUS_LITTLE_ENDIAN
#  define MUS_COMP_SHORT MUS_LSHORT
#  define MUS_COMP_FLOAT MUS_LFLOAT
#else
#  define MUS_COMP_SHORT MUS_BSHORT
#  define MUS_COMP_FLOAT MUS_BFLOAT
#endif

#define SRC_QUALITY SRC_SINC_BEST_QUALITY

#if defined(__i386__) || defined(__x86_64)

static inline void __attribute__ ((__unused__)) atomic_add(volatile int* __mem, int __val)
{
  __asm__ __volatile__ ("lock; addl %1,%0"
			: "=m" (*__mem) : "ir" (__val), "m" (*__mem));
}

#elif defined(__powerpc__) || defined(__ppc__)

#ifdef __PPC405__ 
#define _STWCX "sync \n\tstwcx. " 
#else 
#define _STWCX "stwcx. " 
#endif 

static inline void __attribute__ ((__unused__)) atomic_add(volatile int* __mem, int __val)
{
  int __tmp;
  __asm__ __volatile__ (
	"/* Inline atomic add */\n"
	"0:\t"
	"lwarx    %0,0,%2 \n\t"
	"add%I3   %0,%0,%3 \n\t"
	_STWCX "  %0,0,%2 \n\t"
	"bne-     0b \n\t"
	"/* End atomic add */"
	: "=&b"(__tmp), "=m" (*__mem)
	: "r" (__mem), "Ir"(__val), "m" (*__mem)
	: "cr0");
}
#else
#error "Seems like an unsupported hardware for jack. Please contact k.s.matheussen@notam02.no"
#endif
 
 
/*************/
/* Jack Part */
/*************/

#define SNDJACK_BUFFERSIZE 32768

typedef jack_default_audio_sample_t sample_t;
typedef jack_nframes_t nframes_t;

struct SndjackChannel{
  jack_port_t *port;
  sample_t *buffer;
};

static jack_client_t *sndjack_client = NULL;


/*************************/
/* Variables for reading */
/*************************/
static int sndjack_num_read_channels_allocated=0;
static int sndjack_num_read_channels_inuse=0;
static struct SndjackChannel *sndjack_read_channels=NULL;
static pthread_cond_t sndjack_read_cond= PTHREAD_COND_INITIALIZER;
static pthread_mutex_t sndjack_read_mutex= PTHREAD_MUTEX_INITIALIZER;
static int sj_r_buffersize=0;
static int sj_r_writeplace=0;
static int sj_r_readplace=0;
static int sj_r_unread=0;
static int sj_r_xrun=0;
static int sj_r_totalxrun=0;

/*************************/
/* Variables for writing */
/*************************/
static pthread_cond_t sndjack_cond= PTHREAD_COND_INITIALIZER;
static pthread_mutex_t sndjack_mutex=  PTHREAD_MUTEX_INITIALIZER;

enum{SJ_STOPPED,SJ_RUNNING,SJ_ABOUTTOSTOP};

// Variables for the ringbuffer:
static  int sj_writeplace=0;
static  int sj_readplace=0;
static  int sj_unread=0;
static  int sj_buffersize;
static int sj_jackbuffersize; // number of frames sent to sndjack_process.
static int sj_totalxrun=0;
static int sj_xrun=0;
static int sj_status=SJ_STOPPED;

static int sndjack_num_channels_allocated=0;
static int sndjack_num_channels_inuse=0;
static struct SndjackChannel *sndjack_channels=NULL;
static int sndjack_read_format;

static SRC_STATE **sndjack_srcstates;
static double sndjack_srcratio=1.0;

static int jack_mus_watchdog_counter=0;


#define SJ_MAX(a,b) (((a)>(b))?(a):(b))

static void sndjack_read_process(jack_nframes_t nframes){
  int i,ch;
  sample_t *out[sndjack_num_channels_allocated];

  if (sndjack_num_read_channels_inuse==0) return;

  for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
    out[ch]=(sample_t*)jack_port_get_buffer(sndjack_read_channels[ch].port,nframes);
  }

  for (i=0;i<(int)nframes;i++){
    if (sj_r_unread==sj_buffersize){
      sj_r_xrun+=nframes-i;
      goto exit;
    }
    for (ch=0;ch<sndjack_num_read_channels_inuse;ch++)
      sndjack_read_channels[ch].buffer[sj_r_writeplace]=out[ch][i];
    atomic_add(&sj_r_unread,1);
    sj_r_writeplace++;
    if (sj_r_writeplace==sj_r_buffersize)
      sj_r_writeplace=0;
  }
 exit:
  pthread_cond_broadcast(&sndjack_read_cond);
}


static void sndjack_write_process(jack_nframes_t nframes){
  int ch,i;
  sample_t *out[sndjack_num_channels_allocated];

  for (ch=0;ch<sndjack_num_channels_allocated;ch++){
    out[ch]=(sample_t*)jack_port_get_buffer(sndjack_channels[ch].port,nframes);
  }

  if (sj_status==SJ_STOPPED){
    for (ch=0;ch<sndjack_num_channels_allocated;ch++){
      memset(out[ch],0,nframes*sizeof(sample_t));
    }
  }else{

    // First null out unused channels, if any.
    if (sndjack_num_channels_inuse==1 && sndjack_num_channels_allocated>=2){
      for (ch=2;ch<sndjack_num_channels_allocated;ch++){
	memset(out[ch],0,nframes*sizeof(sample_t));
      }
    }else{
      for (ch=sndjack_num_channels_inuse;ch<sndjack_num_channels_allocated;ch++){
	memset(out[ch],0,nframes*sizeof(sample_t));
      }
    }

    for (i=0;i<(int)nframes;i++){
      if (sj_unread==0){	
	if (sj_status==SJ_RUNNING)
	  sj_xrun+=nframes-i;
	for (;i<(int)nframes;i++){
	  for (ch=0;ch<sndjack_num_channels_inuse;ch++){
	    out[ch][i]=0.0f;
	  }
	}
	break;
      }

      if (sndjack_num_channels_inuse==1 && sndjack_num_channels_allocated>=2){
	for (ch=0;ch<2;ch++){
	  out[ch][i]=sndjack_channels[0].buffer[sj_readplace];
	}
      }else{
	for (ch=0;ch<sndjack_num_channels_inuse;ch++){
	  out[ch][i]=sndjack_channels[ch].buffer[sj_readplace];
	}
      }
      atomic_add(&sj_unread,-1);
      sj_readplace++;
      if (sj_readplace==sj_buffersize)
	sj_readplace=0;
    }
    
    pthread_cond_broadcast(&sndjack_cond);

    if (sj_status==SJ_ABOUTTOSTOP && sj_unread==0)
      sj_status=SJ_STOPPED;
  }

}
 


static int sndjack_process(jack_nframes_t nframes, void *arg){
  sndjack_read_process(nframes);
  sndjack_write_process(nframes);
  return 0;
}


static int sndjack_read(void *buf,int bytes,int chs){
  int i,ch;
  int nframes=bytes /
    sndjack_read_format==MUS_COMP_FLOAT ? sizeof(float) :
    sndjack_read_format==MUS_COMP_SHORT ? sizeof(short) :
    1;
  float *buf_f=(float *)buf;
  short *buf_s=(short *)buf;
  char *buf_c=(char *)buf;

  for (i=0;i<nframes;i++){
    while(sj_r_unread==0){
      pthread_cond_wait(&sndjack_read_cond,&sndjack_read_mutex);
      jack_mus_watchdog_counter++;
    }

    if (sj_r_xrun>0){
      sj_r_totalxrun+=sj_r_xrun;
      sj_r_xrun=0;
      return -1;
    }
    for (ch=0;ch<chs;ch++){
      switch (sndjack_read_format){
      case MUS_BYTE:
	buf_c[i*chs+ch]=sndjack_read_channels[ch].buffer[sj_r_readplace] * 127.9f;
	break;
      case MUS_COMP_SHORT:
	buf_s[i*chs+ch]=sndjack_read_channels[ch].buffer[sj_r_readplace] * 32767.9f;
	break;
      case MUS_COMP_FLOAT:
	buf_f[i*chs+ch]=sndjack_read_channels[ch].buffer[sj_r_readplace];
	break;
      }}
    atomic_add(&sj_r_unread,-1);
    sj_r_readplace++;
    if (sj_r_readplace==sj_r_buffersize)
      sj_r_readplace=0;
  }
  return 0;
}

static void sndjack_write(sample_t **buf,int nframes,int latencyframes,int chs){
  int ch;
  int i;

  if (sj_xrun>0){
    if (sj_status==SJ_RUNNING){
      printf("Warning. %d frames delayed.\n",sj_xrun);
      sj_totalxrun+=sj_xrun;
    }
    sj_xrun=0;
  }

  for (i=0;i<nframes;i++){
    while(
	  sj_status==SJ_RUNNING
	  && (sj_unread==sj_buffersize
	      || sj_unread >= SJ_MAX(sj_jackbuffersize*2, latencyframes))
	  )
      {
	jack_mus_watchdog_counter++;
	pthread_cond_wait(&sndjack_cond,&sndjack_mutex);
      }

    for (ch=0;ch<chs;ch++)
      sndjack_channels[ch].buffer[sj_writeplace]=buf[ch][i];

    atomic_add(&sj_unread,1);
    sj_writeplace++;
    if (sj_writeplace==sj_buffersize)
      sj_writeplace=0;
  }

  if (sj_status==SJ_STOPPED)
    if (sj_unread>=sj_jackbuffersize)
      sj_status=SJ_RUNNING;
}
 
static int sndjack_buffersizecallback(jack_nframes_t nframes, void *arg){
  sj_jackbuffersize=nframes;
  return 0;
}

static int sndjack_getnumoutchannels(void){
  char *a=getenv("SNDLIB_NUM_JACK_CHANNELS");
  if (a!=NULL){
    int num_ch=atoi(a);
    return
      (num_ch<=0 || num_ch > 100000)
      ? 2
      : num_ch;
  }else{
    int lokke=0;
    const char **ports=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsInput);
    while(ports!=NULL && ports[lokke]!=NULL){
      lokke++;
    }
    
    if (lokke<2) return 2;
    return lokke;
  }
}

static int sndjack_getnuminchannels(void){
  char *a=getenv("SNDLIB_NUM_JACK_CHANNELS");
  if (a!=NULL){
    int num_ch=atoi(a);
    return
      (num_ch<=0 || num_ch > 100000)
      ? 2
      : num_ch;
  }else{
    int lokke=0;
    const char **ports=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsOutput);
    while(ports!=NULL && ports[lokke]!=NULL){
      lokke++;
    }
    if (lokke<2) return 2;
    return lokke;
  }
}


static int sndjack_init(void){
  int ch;
  int numch;

  {
    jack_status_t status;
    sndjack_client=jack_client_open("sndlib",JackNoStartServer,&status,NULL);
    if (!sndjack_client) {
#if 0
      fprintf (stderr, "jack_client_open() failed, "
	       "status = 0x%2.0x\n", status);
      if (status & JackServerFailed) {
	fprintf (stderr, "Unable to connect to JACK server\n");
      }
#endif
      return -1;
    }
  }

  pthread_mutex_init(&sndjack_mutex,NULL);
  pthread_cond_init(&sndjack_cond,NULL);
  pthread_mutex_init(&sndjack_read_mutex,NULL);
  pthread_cond_init(&sndjack_read_cond,NULL);

  jack_set_process_callback(sndjack_client,sndjack_process,NULL);

  sndjack_num_channels_allocated = numch = sndjack_getnumoutchannels();
  sndjack_num_read_channels_allocated    = sndjack_getnuminchannels();
     
  sndjack_channels=(struct SndjackChannel *)calloc(sizeof(struct SndjackChannel),numch);
  sndjack_read_channels=(struct SndjackChannel *)calloc(sizeof(struct SndjackChannel),sndjack_num_read_channels_allocated);

  for (ch=0;ch<numch;ch++){
    sndjack_channels[ch].buffer=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  }
  for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
    sndjack_read_channels[ch].buffer=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  }
  sj_buffersize=SNDJACK_BUFFERSIZE;

  for (ch=0;ch<numch;ch++){
    char temp[500];
    snprintf(temp, 500, "out_%d",ch+1);
    if ((sndjack_channels[ch].port=jack_port_register(
						     sndjack_client,
						     mus_strdup(temp),
						     JACK_DEFAULT_AUDIO_TYPE,
						     JackPortIsOutput,
						     0
						     ))==NULL)
      {
	fprintf(stderr, "Error. Could not register jack port.\n");
	goto failed_register;
      }
  }

  for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
    char temp[500];
    snprintf(temp, 500, "in_%d",ch+1);
    if ((sndjack_read_channels[ch].port=jack_port_register(
							  sndjack_client,
							  mus_strdup(temp),
							  JACK_DEFAULT_AUDIO_TYPE,
							  JackPortIsInput,
							  0
							  ))==NULL)
      {
	fprintf(stderr, "Error. Could not register jack port.\n");
	goto failed_register;
      }
  }




  sj_jackbuffersize=jack_get_buffer_size(sndjack_client);
  jack_set_buffer_size_callback(sndjack_client,sndjack_buffersizecallback,NULL);

  if (jack_activate (sndjack_client)) {
    fprintf (stderr, "Error. Cannot activate jack client.\n");
    goto failed_activate;
  }

  if (getenv("SNDLIB_JACK_DONT_AUTOCONNECT")==NULL){

    const char **outportnames=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsInput);
    for (ch=0;outportnames && outportnames[ch]!=NULL && ch<numch;ch++){
      if (
	  jack_connect(
		       sndjack_client,
		       jack_port_name(sndjack_channels[ch].port),
		       outportnames[ch]
		       )
	  )
	{
	  printf ("Warning. Cannot connect jack output port %d: \"%s\".\n",ch,outportnames[ch]);
	}
    }

    const char **inportnames=jack_get_ports(sndjack_client,NULL,NULL,JackPortIsPhysical|JackPortIsOutput);
    for (ch=0;inportnames && inportnames[ch]!=NULL && ch<numch;ch++){
    if (
	jack_connect(
		     sndjack_client,
		     inportnames[ch],
		     jack_port_name(sndjack_read_channels[ch].port)
		     )
	)
      {
	printf ("Warning. Cannot connect jack input port %d: \"%s\".\n",ch,inportnames[ch]);
      }
    }
  }

  return 0;
  
  // failed_connect:
 failed_activate:
  jack_deactivate(sndjack_client);
  
 failed_register:
  jack_client_close(sndjack_client);
  sndjack_client=NULL;

  return -1;
}
static void sndjack_cleanup(void){
  int ch;
  for (ch=0;ch<sndjack_num_channels_allocated;ch++){
    src_delete(sndjack_srcstates[ch]);
  }
  jack_deactivate(sndjack_client);
  jack_client_close(sndjack_client);

}


/***************/
/* Sndlib Part */
/***************/

static int sndjack_format;
static sample_t **sndjack_buffer;
static sample_t *sndjack_srcbuffer;

static int sndjack_dev;
static int sndjack_read_dev;

/* prototypes for the jack sndlib functions */
static int   jack_mus_audio_initialize(void);
static void  jack_mus_oss_set_buffers(int num, int size);
static char* jack_mus_audio_moniker(void);
static int   jack_mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size);
static int   jack_mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size);
static int   jack_mus_audio_write(int id, char *buf, int bytes);
static int   jack_mus_audio_read(int id, char *buf, int bytes);
static int   jack_mus_audio_close(int id);

#if (!HAVE_JACK_IN_LINUX) // Ie. Not using Linux.
int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  return(jack_mus_audio_open_output(ur_dev, srate, chans, samp_type, size));
}

int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int requested_size) 
{
  return(jack_mus_audio_open_input(ur_dev, srate, chans, samp_type, requested_size));
}

int mus_audio_write(int id, char *buf, int bytes) 
{
  return(jack_mus_audio_write(id, buf, bytes));
}

int mus_audio_read(int id, char *buf, int bytes) 
{
  return(jack_mus_audio_read(id, buf, bytes));
}

int mus_audio_close(int id) 
{
  return(jack_mus_audio_close(id));
}

int mus_audio_initialize(void){
  return jack_mus_audio_initialize();
}

char* mus_audio_moniker(void) 
{
  return(jack_mus_audio_moniker());
}
#endif


static int jack_mus_audio_initialize(void) {
  int ch;

  if (audio_initialized){
    return MUS_NO_ERROR;
  }

  if (sndjack_init()!=0)
    return MUS_ERROR;

  sndjack_buffer=(sample_t **)calloc(sizeof(sample_t*),sndjack_num_channels_allocated);
  for (ch=0;ch<sndjack_num_channels_allocated;ch++)
    sndjack_buffer[ch]=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);
  sndjack_srcbuffer=(sample_t *)calloc(sizeof(sample_t),SNDJACK_BUFFERSIZE);

  sndjack_srcstates=(SRC_STATE **)calloc(sizeof(SRC_STATE*),sndjack_num_channels_allocated);
  for (ch=0;ch<sndjack_num_channels_allocated;ch++){
    sndjack_srcstates[ch]=src_new(SRC_QUALITY,1,NULL);
  }

  atexit(sndjack_cleanup);

  api = MUS_JACK_API;
  vect_mus_audio_initialize = jack_mus_audio_initialize;
  vect_mus_oss_set_buffers = jack_mus_oss_set_buffers;
  vect_mus_audio_moniker = jack_mus_audio_moniker;
  vect_mus_audio_open_output = jack_mus_audio_open_output;
  vect_mus_audio_open_input = jack_mus_audio_open_input;
  vect_mus_audio_write = jack_mus_audio_write;
  vect_mus_audio_read = jack_mus_audio_read;
  vect_mus_audio_close = jack_mus_audio_close;

  audio_initialized = true;

#if 0  

  /* Locking all future memory shouldn't be that necessary, and might even freeze the machine in certain situations. */
  /* So remove MCL_FUTURE from the mlockall call. (No. We can't do that. It can screw up code using the realtime extension. -Kjetil.*/
  munlockall();
  //mlockall(MCL_CURRENT);
  
  // Instead we just do this: (which is not enough, but maybe better than nothing)
  {
    mlock(sndjack_channels,sizeof(struct SndjackChannel)*sndjack_num_channels_allocated);
    mlock(sndjack_read_channels,sizeof(struct SndjackChannel)*sndjack_num_read_channels_allocated);

    for (ch=0;ch<numch;ch++){
      mlock(sndjack_channels[ch].buffer,sizeof(sample_t)*SNDJACK_BUFFERSIZE);
    }
    for (ch=0;ch<sndjack_num_read_channels_allocated;ch++){
      mlock(sndjack_read_channels[ch].buffer,sizeof(sample_t)*SNDJACK_BUFFERSIZE);
    }
  }
#endif

  return MUS_NO_ERROR;
}

// ??
static void  jack_mus_oss_set_buffers(int num, int size){
}

static int jack_mus_isrunning=0;
static pid_t jack_mus_player_pid;  
static pthread_t jack_mus_watchdog_thread;

static void *jack_mus_audio_watchdog(void *arg){
#if MUS_JACK
  struct sched_param par;

  par.sched_priority = sched_get_priority_max(SCHED_RR);
  if (sched_setscheduler(0,SCHED_RR,&par)==-1){
    fprintf(stderr, "SNDLIB: Unable to set SCHED_RR realtime priority for the watchdog thread. No watchdog.\n");
    goto exit;
  }

  for (;;){
    int last=jack_mus_watchdog_counter;
    sleep(1);

    if (jack_mus_isrunning && jack_mus_watchdog_counter<last+10){
      struct sched_param par;
      fprintf(stderr, "SNDLIB: Setting player to non-realtime for 2 seconds.\n");

      par.sched_priority = 0;
      if (sched_setscheduler(jack_mus_player_pid,SCHED_OTHER,&par)==-1){
	fprintf(stderr, "SNDLIB: Unable to set non-realtime priority. Must kill player thread. Sorry!\n");
	while(1){
	  kill(jack_mus_player_pid,SIGKILL);
	  sleep(2);
	}
      }

      sleep(2);

      if (jack_mus_isrunning){
	par.sched_priority = sched_get_priority_min(SCHED_RR)+1;
	if (sched_setscheduler(jack_mus_player_pid,SCHED_RR,&par)==-1){
	  fprintf(stderr, "SNDLIB: Could not set back to realtime priority...\n");
	}else
	  fprintf(stderr, "SNDLIB: Play thread set back to realtime priority.\n");
      }

    }
  }
 exit:
  fprintf(stderr, "SNDLIB: Watchdog exiting\n");
#endif
  return NULL;
}


static void jack_mus_audio_set_realtime(void){
#if HAVE_JACK_IN_LINUX
  struct sched_param par;
  static int watchdog_started=0;

  jack_mus_player_pid=getpid();

  if (watchdog_started==0){
    if (pthread_create(&jack_mus_watchdog_thread,NULL,jack_mus_audio_watchdog,NULL)!=0){
      fprintf(stderr, "Could not create watchdog. Not running realtime\n");
      return;
    }
    watchdog_started=1;
  }

  jack_mus_isrunning=1;

  par.sched_priority = sched_get_priority_min(SCHED_RR)+1;
  if (sched_setscheduler(0,SCHED_RR,&par)==-1){
    fprintf(stderr, "SNDLIB: Unable to set SCHED_RR realtime priority for the player thread.\n");
  }{
    //fprintf(stderr, "Set realtime priority\n");
  }
#endif
}

static void jack_mus_audio_set_non_realtime(void){
#if HAVE_JACK_IN_LINUX
  struct sched_param par;
  par.sched_priority = 0;
  sched_setscheduler(0,SCHED_OTHER,&par);
  //fprintf(stderr, "Set non-realtime priority\n");
  jack_mus_isrunning=0;
#endif
}

#ifndef JACK_AUTO_SRC
  #define JACK_AUTO_SRC 1
#endif

int jack_mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size){
  if (sndjack_client==NULL){
    if (jack_mus_audio_initialize()==MUS_ERROR)
      return MUS_ERROR;
  }
  
  if (sndjack_num_channels_allocated<chans){
    printf("Error. Can not play back %d channels. (Only %d)\n",chans,sndjack_num_channels_allocated);
    return MUS_ERROR;
  }

  if (samp_type!=MUS_BYTE && samp_type!=MUS_COMP_SHORT && samp_type!=MUS_COMP_FLOAT){
    printf("Error, unable to handle sample type %s.\n",mus_sample_type_to_string(samp_type));
    return MUS_ERROR;
  }

  while(sj_status!=SJ_STOPPED) usleep(5);

  sj_unread=0;
  sj_writeplace=0;
  sj_readplace=0;

#if JACK_AUTO_SRC
  if (srate!=(int)jack_get_sample_rate(sndjack_client)){
    int lokke;
    //printf("Warning, sample-rate differs between snd and jack. Sound will not be played correctly! %d/%d\n",srate,jack_get_sample_rate(sndjack_client));
    sndjack_srcratio=(double)jack_get_sample_rate(sndjack_client)/(double)srate;
    for (lokke=0;lokke<chans;lokke++){
      src_reset(sndjack_srcstates[lokke]);
    }
  }else{
    sndjack_srcratio=1.0;
  }
#else
  sndjack_srcratio=1.0;
#endif

  sndjack_format=samp_type;
  sndjack_num_channels_inuse=chans;
  sndjack_dev=dev;

  jack_mus_audio_set_realtime();

  return(MUS_NO_ERROR);
}
 

#define MUS_BYTE_TO_SAMPLE(n) (((mus_float_t)(n) / (mus_float_t)(1 << 7)))

static int sndjack_from_byte(int ch,int chs,char *buf,float *out,int bytes){
  int i;
  int len=bytes/chs;
  if (len>SNDJACK_BUFFERSIZE) return -1;

  for (i=0;i<len;i++){
    out[i]=MUS_BYTE_TO_SAMPLE(buf[i*chs+ch]);
  }
  return len;
}

static int sndjack_from_short(int ch,int chs,short *buf,float *out,int bytes){
  int i;
  int len=bytes/(sizeof(short)*chs);
  if (len>SNDJACK_BUFFERSIZE) return -1;

  for (i=0;i<len;i++){
    out[i]=(float)buf[i*chs+ch]/32768.1f;
  }
  return len;
}

static int sndjack_from_float(int ch,int chs,float *buf,float *out,int bytes){
  int i;
  int len=bytes/(sizeof(float)*chs);
  if (len>SNDJACK_BUFFERSIZE) return -1;

  for (i=0;i<len;i++){
    out[i]=buf[i*chs+ch];
  }
  return len;
}


int jack_mus_audio_write(int line, char *buf, int bytes){
  int ch;
  int outlen=0;

  for (ch=0;ch<sndjack_num_channels_inuse;ch++){
    int len = 0;
    float *buf2=sndjack_srcratio==1.0?sndjack_buffer[ch]:sndjack_srcbuffer;

    switch (sndjack_format){
    case MUS_BYTE:
      len=sndjack_from_byte(ch,sndjack_num_channels_inuse,buf,buf2,bytes);
      break;
    case MUS_COMP_SHORT:
      len=sndjack_from_short(ch,sndjack_num_channels_inuse,(short *)buf,buf2,bytes);
      break;
    case MUS_COMP_FLOAT:
      len=sndjack_from_float(ch,sndjack_num_channels_inuse,(float *)buf,buf2,bytes);
      break;
    }
    if (len<0){
      printf("Errur. Input buffer to large for mus_audio_write.\n");
      return MUS_ERROR;
    }

    if (sndjack_srcratio!=1.0){
      SRC_DATA src_data={
	buf2,sndjack_buffer[ch],
	len,SNDJACK_BUFFERSIZE,
	0,0,
	0,
	sndjack_srcratio
      };
      int res=src_process(sndjack_srcstates[ch],&src_data);
      if (res!=0){
	printf("Error while resampling. (%s)\n",src_strerror(res));
	return MUS_ERROR;
      }
      if (src_data.input_frames!=len){
	printf("Unsuccessfull resampling: Should have used %d bytes, used %ld.",len,(long int)(src_data.input_frames));
	return MUS_ERROR;
      }
      if (ch>0 && src_data.output_frames_gen!=outlen){
	printf("Error, src_process did not output the same number of frames as previous resampled channel (%ld/%d).\n"
	       "Please report this problem to k.s.matheussen@notam02.no. Thanks!\n",(long int)(src_data.output_frames_gen),outlen);
	return MUS_ERROR;
      }
      outlen=src_data.output_frames_gen;
    }else{
      outlen=len;
    }
  }


  sndjack_write(sndjack_buffer,outlen,outlen*2,sndjack_num_channels_inuse);

  return MUS_NO_ERROR;
}
 
int jack_mus_audio_close(int line) 
{
  jack_mus_audio_set_non_realtime();
  if (line==sndjack_dev){
    sj_status=SJ_ABOUTTOSTOP;
    sndjack_num_channels_inuse=0;
  }
  return MUS_NO_ERROR;
 }

int jack_mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size){
  if (sndjack_client==NULL){
    if (jack_mus_audio_initialize()==MUS_ERROR)
      return MUS_ERROR;
  }
  
  if (sndjack_num_read_channels_allocated<chans){
    printf("Error. Can not record %d channels. (Only %d)\n",chans,sndjack_num_read_channels_allocated);
    return MUS_ERROR;
  }

  printf("dev: %d\n" ,dev);
  if (samp_type!=MUS_BYTE && samp_type!=MUS_COMP_SHORT && samp_type!=MUS_COMP_FLOAT){
    printf("Error, unable to handle format %s.\n",mus_sample_type_to_string(samp_type));
    return MUS_ERROR;
  }

  if (srate!=(int)jack_get_sample_rate(sndjack_client)){
    printf("Warning, jacks samplerate is %d (and not %d), and the recording will use this samplerate too.\n",jack_get_sample_rate(sndjack_client),srate);
  }

  sndjack_read_format=samp_type;
  sndjack_num_read_channels_inuse=chans;
  sndjack_read_dev=dev;

  return(MUS_NO_ERROR);
}


int jack_mus_audio_read(int line, char *buf, int bytes){
  if (sndjack_read(buf,bytes,sndjack_num_read_channels_inuse)==-1)
    return(MUS_ERROR);
  return MUS_NO_ERROR;
}


char *jack_mus_audio_moniker(void) 
{
  return((char *)"Jack");
}
#endif
 


/* ------------------------------- HPUX ----------------------------------------- */

/* if this is basically the same as the Sun case with different macro names,
 * then it could perhaps be updated to match the new Sun version above --
 * Sun version changed 28-Jan-99
 */

#if defined(__hpux) && (!(defined(AUDIO_OK)))
#define AUDIO_OK 1
#include <sys/audio.h>


#define return_error_exit(Error_Type, Audio_Line, Ur_Error_Message) \
  do { char *Error_Message; Error_Message = Ur_Error_Message; \
    if (Audio_Line != -1) close(Audio_Line); \
    if (Error_Message) \
      {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
    else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
    return(MUS_ERROR); \
  } while (false)


char *mus_audio_moniker(void) 
{
  return("HPUX audio");
}


int mus_audio_open_output(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size)
{
  int fd, i, dev;
  struct audio_describe desc;

  dev = MUS_AUDIO_DEVICE(ur_dev);
  fd = open("/dev/audio", O_RDWR);
  if (fd == -1) 
    return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
		      mus_format("can't open /dev/audio for output: %s",
				 strerror(errno)));

  ioctl(fd, AUDIO_SET_CHANNELS, chans);
  if (dev == MUS_AUDIO_SPEAKERS)
    ioctl(fd, AUDIO_SET_OUTPUT, AUDIO_OUT_SPEAKER);
  else
    if (dev == MUS_AUDIO_LINE_OUT)
      ioctl(fd, AUDIO_SET_OUTPUT, AUDIO_OUT_LINE);
    else ioctl(fd, AUDIO_SET_OUTPUT, AUDIO_OUT_HEADPHONE);

  if (samp_type == MUS_BSHORT)
    ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_LINEAR16BIT);
  else
    {
      if (samp_type == MUS_MULAW)
	ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ULAW);
      else 
	{
	  if (samp_type == MUS_ALAW)
	    ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ALAW);
	  else 
	    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, fd,
			      mus_format("can't set output sample type to %d (%s) for %d",
					 samp_type, mus_sample_type_to_string(samp_type),
					 dev));
	}
    }

  ioctl(fd, AUDIO_DESCRIBE, &desc);
  for (i = 0; i < desc.nrates; i++) 
    if (srate == desc.sample_rate[i]) 
      break;

  if (i == desc.nrates) 
    return_error_exit(SRATE_NOT_AVAILABLE, fd,
		      mus_format("can't set srate to %d on %d",
				 srate, dev));

  ioctl(fd, AUDIO_SET_SAMPLE_RATE, srate);
  return(fd);
}


int mus_audio_write(int line, char *buf, int bytes)
{
  write(line, buf, bytes);
  return(MUS_NO_ERROR);
}


int mus_audio_close(int line) 
{
  close(line);
  return(MUS_NO_ERROR);
}


int mus_audio_initialize(void) 
{
  return(MUS_NO_ERROR);
}


/* struct audio_status status_b;
 * ioctl(devAudio, AUDIO_GET_STATUS, &status_b)
 * not_busy = (status_b.transmit_status == AUDIO_DONE);
*/

int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  int fd, i, dev;
  struct audio_describe desc;

  dev = MUS_AUDIO_DEVICE(ur_dev);
  fd = open("/dev/audio", O_RDWR);
  if (fd == -1)
    return_error_exit(MUS_AUDIO_CANT_OPEN, NULL,
		      mus_format("can't open /dev/audio for input: %s",
				 strerror(errno)));

  ioctl(fd, AUDIO_SET_CHANNELS, chans);
  if (dev == MUS_AUDIO_MICROPHONE)
    ioctl(fd, AUDIO_SET_INPUT, AUDIO_IN_MIKE);
  else ioctl(fd, AUDIO_SET_INPUT, AUDIO_IN_LINE);

  if (samp_type == MUS_BSHORT)
    ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_LINEAR16BIT);
  else
    {
      if (samp_type == MUS_MULAW)
	ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ULAW);
      else 
	{
	  if (samp_type == MUS_ALAW)
	    ioctl(fd, AUDIO_SET_SAMPLE_TYPE, AUDIO_FORMAT_ALAW);
	  else 
	    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, fd,
			      mus_format("can't set input sample type to %d (%s) on %d",
					 samp_type, mus_sample_type_to_string(samp_type),
					 dev));
	}
    }

  ioctl(fd, AUDIO_DESCRIBE, &desc);
  for (i = 0; i < desc.nrates; i++) 
    if (srate == desc.sample_rate[i]) 
      break;

  if (i == desc.nrates) 
    return_error_exit(MUS_AUDIO_SRATE_NOT_AVAILABLE, fd,
		      mus_format("can't set srate to %d on %d",
				 srate, dev));

  ioctl(fd, AUDIO_SET_SAMPLE_RATE, srate);
  return(fd);
}


int mus_audio_read(int line, char *buf, int bytes) 
{
  read(line, buf, bytes);
  return(MUS_NO_ERROR);
}

#endif

/* ------------------------------- OpenBSD ----------------------------------------- */
#if (__OpenBSD__) && (!(defined(AUDIO_OK)))
#define AUDIO_OK 1
#include <sndio.h>
/* this code thanks to Koen De Turck May-18 */

static struct sio_hdl *in_hdl = NULL;
static struct sio_hdl *out_hdl = NULL;

#define SNDIO_OUT 0
#define SNDIO_IN 1

int mus_audio_initialize(void) 
{
  return(MUS_NO_ERROR);
}

char *mus_audio_moniker(void) 
{
  return((char *)"OpenBSD audio (sndio)");
}

static int mus_sndio_open(int mode, int srate, int chans, mus_sample_t samp_type, int size) 
{
  struct sio_hdl *hdl;
  struct sio_par par, par2;
  hdl = sio_open(SIO_DEVANY, mode, 0 /*non-blocking io=0 -> we choose blocking*/);
  sio_initpar(&par);
  switch (samp_type)
    {
    case MUS_BYTE:    par.bits=8;par.bps=1;par.sig=1;break;
    case MUS_UBYTE:   par.bits=8;par.bps=1;par.sig=0;break; 
    case MUS_LSHORT:  par.bits=16;par.bps=2;par.sig=1;par.le=1;break; 
    case MUS_BSHORT:  par.bits=16;par.bps=2;par.sig=1;par.le=0;break; 
    case MUS_ULSHORT: par.bits=16;par.bps=2;par.sig=0;par.le=1;break; 
    case MUS_UBSHORT: par.bits=16;par.bps=2;par.sig=0;par.le=0;break; 
    /* actually, all linear integer formats are accepted by sndio */
    default: 
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
    }
  if(mode==SIO_PLAY)
    par.pchan=chans;
  else
    par.rchan=chans;
  par.rate=srate;
  par.appbufsz=size;
  /* set params */
  if (!sio_setpar(hdl, &par))  
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
  /* then see what sndio thinks of it */
  if (!sio_getpar(hdl, &par2)) 
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));

  if (par2.bits!=par.bits || par2.bps!=par.bps || 
      par2.sig!=par.sig   || par2.le!=par.le ||
      par2.rate!=par.rate ||par2.bufsz<size)
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
  if (mode==SIO_PLAY && par2.pchan != par.pchan)
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
  if (mode==SIO_REC && par2.rchan != par.rchan)
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));

  sio_start(hdl);

  if (mode==SIO_PLAY) out_hdl=hdl;
  if (mode==SIO_REC) in_hdl=hdl;
  return(MUS_NO_ERROR);
}

int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  if (out_hdl!=NULL) return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
  mus_sndio_open(SIO_PLAY, srate, chans, samp_type, size);
  return(SNDIO_OUT);
}

int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  if (in_hdl!=NULL) return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
  mus_sndio_open(SIO_REC, srate, chans, samp_type, size);
  return(SNDIO_IN);
}

int mus_audio_read(int line, char *buf, int bytes) 
{
  if(bytes==sio_read(in_hdl, buf, bytes))
	  return(MUS_NO_ERROR);
  else return MUS_ERROR;
}


int mus_audio_write(int line, char *buf, int bytes) 
{
  if(bytes==sio_write(out_hdl, buf, bytes))
	  return(MUS_NO_ERROR);
  else return MUS_ERROR;
}

int mus_audio_close(int line) 
{
  if (line==SNDIO_IN && in_hdl!=NULL) {
    sio_stop(in_hdl);
    sio_close(in_hdl);
    in_hdl=NULL;  
  }
  if (line==SNDIO_OUT && out_hdl!=NULL) {
    sio_stop(out_hdl);
    sio_close(out_hdl);
    out_hdl=NULL;  
  }
  return(MUS_NO_ERROR);
}

#endif

/* ------------------------------- NETBSD ----------------------------------------- */

#if (__NetBSD__) && (!(defined(AUDIO_OK)))
#define AUDIO_OK 1

/* started from Xanim a long time ago..., bugfixes from Thomas Klausner 30-Jul-05, worked into better shape Aug-05 */
#include <fcntl.h>
#include <sys/audioio.h>
#include <sys/ioctl.h>
#include <sys/param.h>

#define return_error_exit(Error_Type, Audio_Line, Ur_Error_Message) \
  do { char *Error_Message; Error_Message = Ur_Error_Message; \
    if (Audio_Line != -1) close(Audio_Line); \
    if (Error_Message) \
      {mus_standard_error(Error_Type, Error_Message); free(Error_Message);} \
    else mus_standard_error(Error_Type, mus_error_type_to_string(Error_Type)); \
    return(MUS_ERROR); \
  } while (false)


static mus_sample_t bsd_format_to_sndlib(int encoding)
{
  switch (encoding)
    {
    case AUDIO_ENCODING_ULAW:       return(MUS_MULAW);   
    case AUDIO_ENCODING_ALAW:       return(MUS_ALAW);    
    case AUDIO_ENCODING_LINEAR:     return(MUS_BSHORT);  /* "sun compatible" so probably big-endian? */
    case AUDIO_ENCODING_SLINEAR:
    case AUDIO_ENCODING_LINEAR8:    return(MUS_BYTE);    
    case AUDIO_ENCODING_SLINEAR_LE: return(MUS_LSHORT);  
    case AUDIO_ENCODING_SLINEAR_BE: return(MUS_BSHORT);  
    case AUDIO_ENCODING_ULINEAR_LE: return(MUS_ULSHORT); 
    case AUDIO_ENCODING_ULINEAR_BE: return(MUS_UBSHORT); 
    case AUDIO_ENCODING_ULINEAR:    return(MUS_UBYTE);   
    case AUDIO_ENCODING_NONE:
    case AUDIO_ENCODING_ADPCM: 
    default:                        return(MUS_UNKNOWN_SAMPLE); 
    }
  return(MUS_UNKNOWN_SAMPLE);
}


static int sndlib_format_to_bsd(mus_sample_t encoding)
{
  switch (encoding)
    {
    case MUS_MULAW:   return(AUDIO_ENCODING_ULAW);       
    case MUS_ALAW:    return(AUDIO_ENCODING_ALAW);       
    case MUS_BYTE:    return(AUDIO_ENCODING_SLINEAR);    
    case MUS_LSHORT:  return(AUDIO_ENCODING_SLINEAR_LE); 
    case MUS_BSHORT:  return(AUDIO_ENCODING_SLINEAR_BE); 
    case MUS_ULSHORT: return(AUDIO_ENCODING_ULINEAR_LE); 
    case MUS_UBSHORT: return(AUDIO_ENCODING_ULINEAR_BE); 
    case MUS_UBYTE:   return(AUDIO_ENCODING_ULINEAR);    
    default: break;
    }
  return(AUDIO_ENCODING_NONE);
}


int mus_audio_initialize(void) 
{
  return(MUS_NO_ERROR);
}


char *mus_audio_moniker(void) 
{
#if __NetBSD__
  return((char *)"NetBSD audio");
#else
  return((char *)"OpenBSD audio");
#endif
}


static int cur_chans = 1, cur_srate = 22050;

int mus_audio_write(int line, char *buf, int bytes) 
{
#if defined(__NetBSD__) && (__NetBSD_Version__ >= 700000000)
  if (write(line, buf, bytes) != bytes)
    return_error_exit(MUS_AUDIO_WRITE_ERROR, line,
		      mus_format("write error: %s", strerror(errno)));
#else
  /* trouble... AUDIO_WSEEK always returns 0, no way to tell that I'm about to
   *   hit "hiwat", but when I do, it hangs.  Can't use AUDIO_DRAIN --
   *   it introduces interruptions.  Not sure what to do...
   */
  int b = 0;

  b = write(line, buf, bytes);
  usleep(10000);

  if ((b != bytes) && (b > 0)) /* b <= 0 presumably some sort of error, and we want to avoid infinite recursion below */
    {
      /* hangs at close if we don't handle this somehow */
      if ((cur_chans == 1) || (cur_srate == 22050))
	sleep(1);
      else usleep(10000);
      mus_audio_write(line, (char *)(buf + b), bytes - b);
    }
#endif
  return(MUS_NO_ERROR);
}

/* from Mike Scholz, 11-Feb-16 (edited):
 *   On Netbsd sound output with Snd and Sndplay stops before the sound is really at the end.  
 *   [In audioplay] after the read-write loop they call ioctl(fd, AUDIO_DRAIN, NULL).  
 *   Before closing sound output they call ioctl(fd, AUDIO_FLUSH, NULL) (like in audio.c),
 *   and in addition ioctl(fd, AUDIO_SETINFO, &info).  The latter requires that 
 *   audio_info_t a_info be a global variable.  The AUDIO_DRAIN call has been in their 
 *   sources since version 1.1 of /usr/src/usr.bin/audio/play/play.c from March 1999.
 */

static audio_info_t a_info;

int mus_audio_close(int line) 
{
  ioctl(line, AUDIO_DRAIN, NULL);
  ioctl(line, AUDIO_FLUSH, NULL);
  ioctl(line, AUDIO_SETINFO, &a_info);
  close(line);
  return(MUS_NO_ERROR);
}


static int netbsd_default_outputs = (AUDIO_HEADPHONE | AUDIO_LINE_OUT | AUDIO_SPEAKER); 

int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  int line, encode;

  line = open("/dev/sound", O_WRONLY); /* /dev/audio assumes mono 8-bit mulaw */
  if (line == -1)
    {
      if (errno == EBUSY) 
	return(mus_error(MUS_AUDIO_CANT_OPEN, NULL));
      else return(mus_error(MUS_AUDIO_DEVICE_NOT_AVAILABLE, NULL));
    }
  AUDIO_INITINFO(&a_info);

  /* a_info.blocksize = size; */
  encode = sndlib_format_to_bsd(samp_type);
  if (encode == AUDIO_ENCODING_NONE)
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %d (%s) not available",
				 samp_type, 
				 mus_sample_type_name(samp_type)));

  a_info.play.encoding = encode;
  a_info.mode = AUMODE_PLAY | AUMODE_PLAY_ALL;
  a_info.play.precision = mus_bytes_per_sample(samp_type) * 8;
  a_info.play.sample_rate = srate;

  if (dev == MUS_AUDIO_LINE_OUT)
    a_info.play.port = AUDIO_LINE_OUT;
  else
    {
      if (dev == MUS_AUDIO_SPEAKERS)
	a_info.play.port = AUDIO_SPEAKER | (netbsd_default_outputs & AUDIO_HEADPHONE);
      else a_info.play.port = netbsd_default_outputs;
    }

  a_info.play.channels = chans;
  ioctl(line, AUDIO_SETINFO, &a_info);
  /* actually doesn't set the "ports" field -- always 0 */

  ioctl(line, AUDIO_GETINFO, &a_info);

  if ((int)(a_info.play.sample_rate) != srate)
    mus_print("srate: %d -> %d\n", srate, a_info.play.sample_rate);
  if ((int)(a_info.play.encoding) != sndlib_format_to_bsd(samp_type))
    mus_print("encoding: %d -> %d\n", sndlib_format_to_bsd(samp_type), a_info.play.encoding);
  if ((int)(a_info.play.channels) != chans)
    mus_print("chans: %d -> %d\n", chans, a_info.play.channels);

  cur_chans = chans;
  cur_srate = srate;

  return(line);
}


int mus_audio_read(int line, char *buf, int bytes) 
{
  read(line, buf, bytes);
  return(MUS_NO_ERROR);
}


static int netbsd_sample_types(int ur_dev, mus_sample_t *val)
{
  int i, audio_fd, err, dev;
  audio_info_t info;
  audio_encoding_t e_info;

  dev = MUS_AUDIO_DEVICE(ur_dev);
  AUDIO_INITINFO(&info);

  audio_fd = open("/dev/sound", O_RDONLY | O_NONBLOCK, 0);
  if (audio_fd == -1) 
    return_error_exit(MUS_AUDIO_CANT_READ, -1, mus_format("can't open /dev/sound: %s", strerror(errno)));
  err = ioctl(audio_fd, AUDIO_GETINFO, &info); 
  if (err == -1) 
    {
      close(audio_fd);
      return_error_exit(MUS_AUDIO_CANT_READ, audio_fd, mus_format("can't get dac info"));
    }

  for (i = 0; ; i++)
    {
      e_info.index = i;
      err = ioctl(audio_fd, AUDIO_GETENC, &e_info);
      if (err != 0) break;
      val[i + 1] = bsd_format_to_sndlib(e_info.encoding);
    }
  val[0] = (mus_sample_t)i;
  close(audio_fd);
  return(MUS_NO_ERROR);
}



int mus_audio_open_input(int ur_dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  audio_info_t info;
  int encode, bits, dev, audio_fd, err;

  dev = MUS_AUDIO_DEVICE(ur_dev);
  encode = sndlib_format_to_bsd(samp_type);
  bits = 8 * mus_bytes_per_sample(samp_type);
  if (encode == AUDIO_ENCODING_NONE) 
    return_error_exit(MUS_AUDIO_SAMPLE_TYPE_NOT_AVAILABLE, -1,
		      mus_format("sample type %s not available for recording",
				 mus_sample_type_name(samp_type)));

  if (dev != MUS_AUDIO_DUPLEX_DEFAULT)
    audio_fd = open("/dev/sound", O_RDONLY, 0);
  else audio_fd = open("/dev/sound", O_RDWR, 0);
  if (audio_fd == -1) 
    return_error_exit(MUS_AUDIO_CANT_OPEN, -1,
		      mus_format("can't open /dev/sound: %s",
				 strerror(errno)));

  AUDIO_INITINFO(&info);
  info.record.sample_rate = srate;
  info.record.channels = chans;
  info.record.precision = bits;
  info.record.encoding = encode;
  info.record.port = AUDIO_MICROPHONE;
  err = ioctl(audio_fd, AUDIO_SETINFO, &info); 
  if (err == -1) 
    return_error_exit(MUS_AUDIO_CANT_WRITE, audio_fd,
		      mus_format("can't set up for recording"));
  return(audio_fd);
}

#endif



/* -------------------------------- PULSEAUDIO -------------------------------- */

#if defined(MUS_PULSEAUDIO) && (!(defined(AUDIO_OK)))
#define AUDIO_OK 1


/* this code compiles/loads, but I don't know if it works -- paplay itself
 *   doesn't work on my machine due to either a libtool/dlopen mismatch
 *   or some problem with "pulse-rt".
 */


#include <pulse/simple.h>
#include <pulse/error.h>
#include <pulse/gccmacro.h>


static int sndlib_to_pa_format(mus_sample_t samp_type)
{
  switch (samp_type)
    {
    case MUS_BYTE:   return(PA_SAMPLE_U8);
    case MUS_LSHORT: return(PA_SAMPLE_S16LE);
    case MUS_BSHORT: return(PA_SAMPLE_S16BE);
    case MUS_LINT:   return(PA_SAMPLE_S32LE);
    case MUS_BINT:   return(PA_SAMPLE_S32BE);
    case MUS_LFLOAT: return(PA_SAMPLE_FLOAT32LE);
    case MUS_BFLOAT: return(PA_SAMPLE_FLOAT32BE);
    case MUS_ALAW:   return(PA_SAMPLE_ALAW);
    case MUS_MULAW:  return(PA_SAMPLE_ULAW);

    default: 
      fprintf(stderr, "unsupported sample type: %d\n", samp_type);
      return(0);
      break;
    }
} 


static pa_simple *pa_out = NULL, *pa_in = NULL;

int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  pa_sample_spec spec = {0};
  int error;

  spec.format = sndlib_to_pa_format(samp_type);
  spec.rate = srate;
  spec.channels = chans;

  pa_out = pa_simple_new(NULL, "snd", PA_STREAM_PLAYBACK, NULL, "playback", &spec, NULL, NULL, &error);
  if (!pa_out)
    {
      fprintf(stderr, "can't play: %s\n", pa_strerror(error));
      return(MUS_ERROR);
    }
  return(0);
}


int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  return(MUS_ERROR);
}


int mus_audio_write(int line, char *buf, int bytes) 
{
  int error;
  pa_simple_write(pa_out, (unsigned char *)buf, (size_t)bytes, &error);
  return(error);
}


int mus_audio_close(int line) 
{
  int error;
  pa_simple_drain(pa_out, &error);
  pa_simple_free(pa_out);
  pa_out = NULL;
  return(error);
}


int mus_audio_read(int line, char *buf, int bytes) 
{
  return(MUS_ERROR);
}


int mus_audio_initialize(void) 
{
  return(MUS_ERROR);
}


char *mus_audio_moniker(void) 
{
  return(mus_format("pulseaudio %s", pa_get_library_version()));
}


#endif



/* -------------------------------- PORTAUDIO -------------------------------- */

#if defined(MUS_PORTAUDIO) && (!(defined(AUDIO_OK)))
#define AUDIO_OK 1

#include <portaudio.h>

#define PA_OUT_STREAM 0
#define PA_IN_STREAM 1

static unsigned long sndlib_to_portaudio_format(mus_sample_t samp_type)
{
  switch (samp_type)
    {
    case MUS_BYTE:   return(paInt8);
    case MUS_LSHORT: return(paInt16);
    case MUS_BSHORT: return(paInt16);
    case MUS_LINT:   return(paInt32);
    case MUS_BINT:   return(paInt32);
    case MUS_LFLOAT: return(paFloat32);
    case MUS_BFLOAT: return(paFloat32);
    default: break;
    }
  return(paInt16);
}

static PaStream *out_stream = NULL;

int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  PaStreamParameters output_pars;
  PaError err;

  output_pars.device = Pa_GetDefaultOutputDevice();
  output_pars.channelCount = chans;
  output_pars.sampleFormat = sndlib_to_portaudio_format(samp_type);
  output_pars.suggestedLatency = Pa_GetDeviceInfo(output_pars.device)->defaultHighOutputLatency;
  output_pars.hostApiSpecificStreamInfo = NULL;

  err = Pa_OpenStream(&out_stream, NULL, &output_pars, srate, 1024, paClipOff, NULL, NULL); /* 1024 = frames [dac_size] but can we use "size"? */
  if (err == paNoError)
    err = Pa_StartStream(out_stream);

  if (err != paNoError)
    {
      fprintf(stderr, "portaudio open output: %s\n", Pa_GetErrorText(err));
      return(MUS_ERROR);
    }
  return(PA_OUT_STREAM);
}


static PaStream *in_stream = NULL;

int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) 
{
  PaStreamParameters input_pars;
  PaError err;

  input_pars.device = Pa_GetDefaultInputDevice();
  input_pars.channelCount = chans;
  input_pars.sampleFormat = sndlib_to_portaudio_format(samp_type);
  input_pars.suggestedLatency = Pa_GetDeviceInfo(input_pars.device)->defaultHighInputLatency;
  input_pars.hostApiSpecificStreamInfo = NULL;

  err = Pa_OpenStream(&in_stream, &input_pars, NULL, srate, 1024, paClipOff, NULL, NULL);
  if (err == paNoError)
    err = Pa_StartStream(in_stream);

  if (err != paNoError)
    {
      fprintf(stderr, "portaudio open input: %s\n", Pa_GetErrorText(err));
      return(MUS_ERROR);
    }
  return(MUS_NO_ERROR);

}


int mus_audio_write(int line, char *buf, int bytes) 
{
  PaError err;
  err = Pa_WriteStream(out_stream, buf, 1024);

  if (err != paNoError)
    {
      fprintf(stderr, "portaudio write: %s\n", Pa_GetErrorText(err));
      return(MUS_ERROR);
    }
  return(MUS_NO_ERROR);
}


int mus_audio_close(int line) 
{
  PaError err;
  if (line == PA_IN_STREAM)
    err = Pa_CloseStream(in_stream);
  else err = Pa_CloseStream(out_stream);

  if (err != paNoError)
    {
      fprintf(stderr, "portaudio close: %s\n", Pa_GetErrorText(err));
      return(MUS_ERROR);
    }
  return(MUS_NO_ERROR);
}


int mus_audio_read(int line, char *buf, int bytes) 
{
  PaError err;
  err = Pa_ReadStream(in_stream, buf, 1024);

  if (err != paNoError)
    {
      fprintf(stderr, "portaudio read: %s\n", Pa_GetErrorText(err));
      return(MUS_ERROR);
    }
  return(MUS_NO_ERROR);
}


static bool portaudio_initialized = false;

int mus_audio_initialize(void) 
{
  PaError err;

  if (portaudio_initialized) return(MUS_NO_ERROR);
  portaudio_initialized = true;

  err = Pa_Initialize();
  if (err == paNoError)
    return(MUS_NO_ERROR);

  fprintf(stderr, "portaudio initialize: %s\n", Pa_GetErrorText(err));
  return(MUS_ERROR);
}


char *mus_audio_moniker(void) 
{
  return((char *)Pa_GetVersionText());
}
#endif




/* ------------------------------- STUBS ----------------------------------------- */

#ifndef AUDIO_OK
int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(MUS_ERROR);}
int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(MUS_ERROR);}
int mus_audio_write(int line, char *buf, int bytes) {return(MUS_ERROR);}
int mus_audio_close(int line) {return(MUS_ERROR);}
int mus_audio_read(int line, char *buf, int bytes) {return(MUS_ERROR);}
int mus_audio_initialize(void) {return(MUS_ERROR);}
char *mus_audio_moniker(void) {return((char *)"no audio support");}
#endif



/* for CLM */
void mus_reset_audio_c(void)
{
  audio_initialized = false;
  version_name = NULL;
}


#if HAVE_ALSA || HAVE_OSS

void mus_audio_alsa_channel_info(int dev, int *info);
void mus_audio_alsa_channel_info(int dev, int *info)
{
#if MUS_JACK
  if (api == MUS_JACK_API) 
    {
      info[0] = sndjack_num_channels_allocated;
      return;
    }
#endif

#if HAVE_ALSA
  if (api == MUS_ALSA_API) 
    {
      alsa_chans(dev, info);
      return;
    }
#endif

#if HAVE_OSS
  info[0] = 2;
#endif

}


int mus_audio_alsa_samples_per_channel(int dev);
int mus_audio_alsa_samples_per_channel(int dev)
{
#if HAVE_ALSA
  return(alsa_samples_per_channel);
#else
  return(1024);
#endif
}


void mus_audio_alsa_device_list(int ur_dev, int chan, int *val);
void mus_audio_alsa_device_list(int ur_dev, int chan, int *val)
{
#if HAVE_ALSA
  int i = 1;
  
  if (!audio_initialized) mus_audio_initialize();
  
  if (alsa_hw_params[SND_PCM_STREAM_PLAYBACK]) 
    val[i++] = to_sndlib_device(0, SND_PCM_STREAM_PLAYBACK);

  if (alsa_hw_params[SND_PCM_STREAM_CAPTURE]) 
    val[i++] = to_sndlib_device(0, SND_PCM_STREAM_CAPTURE);

  val[0] = (i - 1);
#endif
}

#define MUS_AUDIO_DIRECTION_PLAYBACK 0
#define MUS_AUDIO_DIRECTION_RECORD 1

int mus_audio_alsa_device_direction(int dev);
int mus_audio_alsa_device_direction(int dev)
{
#if HAVE_OSS
  switch (MUS_AUDIO_DEVICE(dev))
    {
    case MUS_AUDIO_DIGITAL_OUT: case MUS_AUDIO_LINE_OUT: case MUS_AUDIO_DEFAULT:
    case MUS_AUDIO_SPEAKERS: case MUS_AUDIO_MIXER:
    case MUS_AUDIO_AUX_OUTPUT: case MUS_AUDIO_DAC_OUT: 
      return(MUS_AUDIO_DIRECTION_PLAYBACK);

    default:  
      return(MUS_AUDIO_DIRECTION_RECORD);
    }
#else
  {
    int card, device, alsa_device = 0;
    snd_pcm_stream_t alsa_stream = SND_PCM_STREAM_PLAYBACK;
  
    if ((!audio_initialized) && 
	(mus_audio_initialize() != MUS_NO_ERROR))
      return(MUS_ERROR);
  
    card = MUS_AUDIO_SYSTEM(dev);
    device = MUS_AUDIO_DEVICE(dev);
    to_alsa_device(device, &alsa_device, &alsa_stream);

    if (card > 0 || alsa_device > 0) 
      return(alsa_mus_error(MUS_AUDIO_CANT_READ, NULL));
    return(alsa_stream);
  }
#endif
}
#endif


int mus_audio_device_channels(int dev)
{
#if MUS_JACK
  if (api == MUS_JACK_API) 
    {
      return(sndjack_num_channels_allocated);
    }
#endif
 
#if HAVE_ALSA
  if (api == MUS_ALSA_API) 
    {
      return(alsa_chans(dev, NULL));
    }
#endif

  return(2); /* netbsd hpux sun mac and oss with quibbles */
}


mus_sample_t mus_audio_compatible_sample_type(int dev) /* snd-dac and sndplay */
{
#if HAVE_ALSA
  if (api == MUS_ALSA_API) 
    {
      int err;
      mus_sample_t ival[32];
      err = alsa_sample_types(dev, 32, ival);
      if (err != MUS_ERROR)
	{
	  int i;
	  for (i = 1; i <= (int)(ival[0]); i++)
	    if (ival[i] == MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE) 
	      return(MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);

	  for (i = 1; i <= (int)(ival[0]); i++) 
	    if ((ival[i] == MUS_BINT) || (ival[i] == MUS_LINT) ||
	        (ival[i] == MUS_BFLOAT) || (ival[i] == MUS_LFLOAT) ||
		(ival[i] == MUS_BSHORT) || (ival[i] == MUS_LSHORT))
	      return(ival[i]);

	  for (i = 1; i <= (int)(ival[0]); i++) 
	    if ((ival[i] == MUS_MULAW) || (ival[i] == MUS_ALAW) ||
	        (ival[i] == MUS_UBYTE) || (ival[i] == MUS_BYTE))
	      return(ival[i]);

	  return(ival[1]);
	}
    }
#endif

#if MUS_JACK
  if (api == MUS_JACK_API) 
    return(MUS_COMP_FLOAT);
#endif
  return(MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
}


static mus_sample_t look_for_sample_type (mus_sample_t *mixer_vals, mus_sample_t samp_type)
{
  int i, lim;
  lim = mixer_vals[0];
  for (i = 1; i <= lim; i++)
    if (mixer_vals[i] == samp_type)
      return(samp_type);
  return(MUS_UNKNOWN_SAMPLE);
}


mus_sample_t mus_audio_device_sample_type(int dev) /* snd-dac */
{
  mus_sample_t mixer_vals[16];
  mus_sample_t samp_type;
  int i;
  /* we return the new sample type, so mixer_vals is just a local collector of possible sample types */
  for (i = 0; i < 16; i++) mixer_vals[i] = MUS_UNKNOWN_SAMPLE;

#if (!WITH_AUDIO)
  return(MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
#endif

#if HAVE_OSS
  if (api == MUS_OSS_API) 
    oss_sample_types(dev, mixer_vals);
#endif

#if HAVE_ALSA
  if (api == MUS_ALSA_API) 
    alsa_sample_types(dev, 16, mixer_vals);
#endif

#if MUS_JACK
  if (api == MUS_JACK_API) 
    {
      mixer_vals[0] = (mus_sample_t)1;
      mixer_vals[1] = MUS_COMP_FLOAT;
    }
#endif

#if HAVE_SUN
  mixer_vals[0] = (mus_sample_t)2;
  mixer_vals[1] = MUS_LSHORT;
  mixer_vals[2] = MUS_MULAW;
#endif

#if __APPLE__
  mixer_vals[0] = (mus_sample_t)1;
#if MUS_LITTLE_ENDIAN
  mixer_vals[1] = MUS_LFLOAT;
#else
  mixer_vals[1] = MUS_BFLOAT;
#endif
#endif

#if __NetBSD__
  netbsd_sample_types(dev, mixer_vals);
#endif

#if __OpenBSD__
  mixer_vals[0] = (mus_sample_t)1;
#if MUS_LITTLE_ENDIAN
  mixer_vals[1] = MUS_LSHORT;
#else
  mixer_vals[1] = MUS_BSHORT;
#endif
#endif

  samp_type = look_for_sample_type(mixer_vals, MUS_AUDIO_COMPATIBLE_SAMPLE_TYPE);
  if (samp_type != MUS_UNKNOWN_SAMPLE)
    return(samp_type);

#if MUS_LITTLE_ENDIAN
  samp_type = look_for_sample_type(mixer_vals, MUS_LFLOAT);
  if (samp_type == MUS_UNKNOWN_SAMPLE)
    {
      samp_type = look_for_sample_type(mixer_vals, MUS_LSHORT);
      if (samp_type == MUS_UNKNOWN_SAMPLE)
	samp_type = mixer_vals[1];
    }
#else
  samp_type = look_for_sample_type(mixer_vals, MUS_BFLOAT);
  if (samp_type == MUS_UNKNOWN_SAMPLE)
    {
      samp_type = look_for_sample_type(mixer_vals, MUS_BSHORT);
      if (samp_type == MUS_UNKNOWN_SAMPLE)
	samp_type = mixer_vals[1];
    }
#endif
  return(samp_type);
}


#else
/* not WITH_AUDIO */

int mus_audio_open_output(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(-1);}
int mus_audio_open_input(int dev, int srate, int chans, mus_sample_t samp_type, int size) {return(-1);}
int mus_audio_write(int line, char *buf, int bytes) {return(-1);}
int mus_audio_close(int line) {return(-1);}
int mus_audio_read(int line, char *buf, int bytes) {return(-1);}
int mus_audio_initialize(void) {return(-1);}
char *mus_audio_moniker(void) {return((char *)"no audio support");}

void mus_reset_audio_c(void) {}

int mus_audio_device_channels(int dev) {return(0);}
mus_sample_t mus_audio_compatible_sample_type(int dev) {return(MUS_UNKNOWN_SAMPLE);}
mus_sample_t mus_audio_device_sample_type(int dev) {return(MUS_UNKNOWN_SAMPLE);}

#if __APPLE__
bool mus_audio_output_properties_mutable(bool mut) {return(false);}
#endif
#endif