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 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527
|
/************************************************************************/
/*! \class RtAudio
\brief Realtime audio i/o C++ classes.
RtAudio provides a common API (Application Programming Interface)
for realtime audio input/output across Linux (native ALSA, Jack,
and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
(DirectSound, ASIO and WASAPI) operating systems.
RtAudio GitHub site: https://github.com/thestk/rtaudio
RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
RtAudio: realtime audio i/o C++ classes
Copyright (c) 2001-2023 Gary P. Scavone
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Any person wishing to distribute modifications to the Software is
asked to send the modifications to the original developer so that
they can be incorporated into the canonical version. This is,
however, not a binding provision of this license.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/************************************************************************/
// RtAudio: Version 6.0.1
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cmath>
#include <algorithm>
#include <codecvt>
#include <locale>
#if defined(_WIN32)
#include <windows.h>
#endif
// Static variable definitions.
const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
const unsigned int RtApi::SAMPLE_RATES[] = {
4000, 5512, 8000, 9600, 11025, 16000, 22050,
32000, 44100, 48000, 88200, 96000, 176400, 192000
};
template<typename T> inline
std::string convertCharPointerToStdString(const T *text);
template<> inline
std::string convertCharPointerToStdString(const char *text)
{
return text;
}
template<> inline
std::string convertCharPointerToStdString(const wchar_t *text)
{
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>{}.to_bytes(text);
}
#if defined(_MSC_VER)
#define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
#define MUTEX_DESTROY(A) DeleteCriticalSection(A)
#define MUTEX_LOCK(A) EnterCriticalSection(A)
#define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
#else
#define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
#define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
#define MUTEX_LOCK(A) pthread_mutex_lock(A)
#define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
#endif
// *************************************************** //
//
// RtApi subclass prototypes.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
#include <CoreAudio/AudioHardware.h>
class RtApiCore: public RtApi
{
public:
RtApiCore();
~RtApiCore();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::MACOSX_CORE; }
unsigned int getDefaultOutputDevice( void ) override;
unsigned int getDefaultInputDevice( void ) override;
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by an internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
bool callbackEvent( AudioDeviceID deviceId,
const AudioBufferList *inBufferList,
const AudioBufferList *outBufferList );
private:
void probeDevices( void ) override;
bool probeDeviceInfo( AudioDeviceID id, RtAudio::DeviceInfo &info );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
static const char* getErrorCode( OSStatus code );
std::vector< AudioDeviceID > deviceIds_;
};
#endif
#if defined(__UNIX_JACK__)
#include <jack/jack.h>
class RtApiJack: public RtApi
{
public:
RtApiJack();
~RtApiJack();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::UNIX_JACK; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
bool callbackEvent( unsigned long nframes );
private:
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, jack_client_t *client );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
bool shouldAutoconnect_;
};
#endif
#if defined(__WINDOWS_ASIO__)
class RtApiAsio: public RtApi
{
public:
RtApiAsio();
~RtApiAsio();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::WINDOWS_ASIO; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
bool callbackEvent( long bufferIndex );
private:
bool coInitialized_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info );
bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__WINDOWS_DS__)
class RtApiDs: public RtApi
{
public:
RtApiDs();
~RtApiDs();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::WINDOWS_DS; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
private:
bool coInitialized_;
bool buffersRolling;
long duplexPrerollBytes;
std::vector<struct DsDevice> dsDevices_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, DsDevice &dsDevice );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__WINDOWS_WASAPI__)
struct IMMDeviceEnumerator;
class RtApiWasapi : public RtApi
{
public:
RtApiWasapi();
virtual ~RtApiWasapi();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::WINDOWS_WASAPI; }
unsigned int getDefaultOutputDevice( void ) override;
unsigned int getDefaultInputDevice( void ) override;
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
private:
bool coInitialized_;
IMMDeviceEnumerator* deviceEnumerator_;
std::vector< std::pair< std::string, bool> > deviceIds_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, LPWSTR deviceId, bool isCaptureDevice );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int* bufferSize,
RtAudio::StreamOptions* options ) override;
static DWORD WINAPI runWasapiThread( void* wasapiPtr );
static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
void wasapiThread();
};
#endif
#if defined(__LINUX_ALSA__)
class RtApiAlsa: public RtApi
{
public:
RtApiAlsa();
~RtApiAlsa();
RtAudio::Api getCurrentApi() override { return RtAudio::LINUX_ALSA; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
private:
std::vector<std::pair<std::string, unsigned int>> deviceIdPairs_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, std::string name );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__LINUX_PULSE__)
#include <pulse/pulseaudio.h>
class RtApiPulse: public RtApi
{
public:
~RtApiPulse();
RtAudio::Api getCurrentApi() override { return RtAudio::LINUX_PULSE; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
struct PaDeviceInfo {
std::string sinkName;
std::string sourceName;
};
private:
std::vector< PaDeviceInfo > paDeviceList_;
void probeDevices( void ) override;
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__LINUX_OSS__)
#include <sys/soundcard.h>
class RtApiOss: public RtApi
{
public:
RtApiOss();
~RtApiOss();
RtAudio::Api getCurrentApi() override { return RtAudio::LINUX_OSS; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
private:
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, oss_audioinfo &ainfo );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__RTAUDIO_DUMMY__)
class RtApiDummy: public RtApi
{
public:
RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RTAUDIO_WARNING ); }
RtAudio::Api getCurrentApi( void ) override { return RtAudio::RTAUDIO_DUMMY; }
void closeStream( void ) override {}
RtAudioErrorType startStream( void ) override { return RTAUDIO_NO_ERROR; }
RtAudioErrorType stopStream( void ) override { return RTAUDIO_NO_ERROR; }
RtAudioErrorType abortStream( void ) override { return RTAUDIO_NO_ERROR; }
private:
bool probeDeviceOpen( unsigned int /*deviceId*/, StreamMode /*mode*/, unsigned int /*channels*/,
unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
RtAudio::StreamOptions * /*options*/ ) override { return false; }
};
#endif
// *************************************************** //
//
// RtAudio definitions.
//
// *************************************************** //
std::string RtAudio :: getVersion( void )
{
return RTAUDIO_VERSION;
}
// Define API names and display names.
// Must be in same order as API enum.
extern "C" {
const char* rtaudio_api_names[][2] = {
{ "unspecified" , "Unknown" },
{ "core" , "CoreAudio" },
{ "alsa" , "ALSA" },
{ "jack" , "Jack" },
{ "pulse" , "Pulse" },
{ "oss" , "OpenSoundSystem" },
{ "asio" , "ASIO" },
{ "wasapi" , "WASAPI" },
{ "ds" , "DirectSound" },
{ "dummy" , "Dummy" },
};
const unsigned int rtaudio_num_api_names =
sizeof(rtaudio_api_names)/sizeof(rtaudio_api_names[0]);
// The order here will control the order of RtAudio's API search in
// the constructor.
extern "C" const RtAudio::Api rtaudio_compiled_apis[] = {
#if defined(__MACOSX_CORE__)
RtAudio::MACOSX_CORE,
#endif
#if defined(__LINUX_ALSA__)
RtAudio::LINUX_ALSA,
#endif
#if defined(__UNIX_JACK__)
RtAudio::UNIX_JACK,
#endif
#if defined(__LINUX_PULSE__)
RtAudio::LINUX_PULSE,
#endif
#if defined(__LINUX_OSS__)
RtAudio::LINUX_OSS,
#endif
#if defined(__WINDOWS_ASIO__)
RtAudio::WINDOWS_ASIO,
#endif
#if defined(__WINDOWS_WASAPI__)
RtAudio::WINDOWS_WASAPI,
#endif
#if defined(__WINDOWS_DS__)
RtAudio::WINDOWS_DS,
#endif
#if defined(__RTAUDIO_DUMMY__)
RtAudio::RTAUDIO_DUMMY,
#endif
RtAudio::UNSPECIFIED,
};
extern "C" const unsigned int rtaudio_num_compiled_apis =
sizeof(rtaudio_compiled_apis)/sizeof(rtaudio_compiled_apis[0])-1;
}
// This is a compile-time check that rtaudio_num_api_names == RtAudio::NUM_APIS.
// If the build breaks here, check that they match.
template<bool b> class StaticAssert { private: StaticAssert() {} };
template<> class StaticAssert<true>{ public: StaticAssert() {} };
class StaticAssertions { StaticAssertions() {
StaticAssert<rtaudio_num_api_names == RtAudio::NUM_APIS>();
}};
void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis )
{
apis = std::vector<RtAudio::Api>(rtaudio_compiled_apis,
rtaudio_compiled_apis + rtaudio_num_compiled_apis);
}
std::string RtAudio :: getApiName( RtAudio::Api api )
{
if (api < 0 || api >= RtAudio::NUM_APIS)
return "";
return rtaudio_api_names[api][0];
}
std::string RtAudio :: getApiDisplayName( RtAudio::Api api )
{
if (api < 0 || api >= RtAudio::NUM_APIS)
return "Unknown";
return rtaudio_api_names[api][1];
}
RtAudio::Api RtAudio :: getCompiledApiByName( const std::string &name )
{
unsigned int i=0;
for (i = 0; i < rtaudio_num_compiled_apis; ++i)
if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][0])
return rtaudio_compiled_apis[i];
return RtAudio::UNSPECIFIED;
}
RtAudio::Api RtAudio :: getCompiledApiByDisplayName( const std::string &name )
{
unsigned int i=0;
for (i = 0; i < rtaudio_num_compiled_apis; ++i)
if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][1])
return rtaudio_compiled_apis[i];
return RtAudio::UNSPECIFIED;
}
void RtAudio :: openRtApi( RtAudio::Api api )
{
if ( rtapi_ )
delete rtapi_;
rtapi_ = 0;
#if defined(__UNIX_JACK__)
if ( api == UNIX_JACK )
rtapi_ = new RtApiJack();
#endif
#if defined(__LINUX_ALSA__)
if ( api == LINUX_ALSA )
rtapi_ = new RtApiAlsa();
#endif
#if defined(__LINUX_PULSE__)
if ( api == LINUX_PULSE )
rtapi_ = new RtApiPulse();
#endif
#if defined(__LINUX_OSS__)
if ( api == LINUX_OSS )
rtapi_ = new RtApiOss();
#endif
#if defined(__WINDOWS_ASIO__)
if ( api == WINDOWS_ASIO )
rtapi_ = new RtApiAsio();
#endif
#if defined(__WINDOWS_WASAPI__)
if ( api == WINDOWS_WASAPI )
rtapi_ = new RtApiWasapi();
#endif
#if defined(__WINDOWS_DS__)
if ( api == WINDOWS_DS )
rtapi_ = new RtApiDs();
#endif
#if defined(__MACOSX_CORE__)
if ( api == MACOSX_CORE )
rtapi_ = new RtApiCore();
#endif
#if defined(__RTAUDIO_DUMMY__)
if ( api == RTAUDIO_DUMMY )
rtapi_ = new RtApiDummy();
#endif
}
RtAudio :: RtAudio( RtAudio::Api api, RtAudioErrorCallback&& errorCallback )
{
rtapi_ = 0;
std::string errorMessage;
if ( api != UNSPECIFIED ) {
// Attempt to open the specified API.
openRtApi( api );
if ( rtapi_ ) {
if ( errorCallback ) rtapi_->setErrorCallback( errorCallback );
return;
}
// No compiled support for specified API value. Issue a warning
// and continue as if no API was specified.
errorMessage = "RtAudio: no compiled support for specified API argument!";
if ( errorCallback )
errorCallback( RTAUDIO_INVALID_USE, errorMessage );
else
std::cerr << '\n' << errorMessage << '\n' << std::endl;
}
// Iterate through the compiled APIs and return as soon as we find
// one with at least one device or we reach the end of the list.
std::vector< RtAudio::Api > apis;
getCompiledApi( apis );
for ( unsigned int i=0; i<apis.size(); i++ ) {
openRtApi( apis[i] );
if ( rtapi_ && (rtapi_->getDeviceNames()).size() > 0 )
break;
}
if ( rtapi_ ) {
if ( errorCallback ) rtapi_->setErrorCallback( errorCallback );
return;
}
// It should not be possible to get here because the preprocessor
// definition __RTAUDIO_DUMMY__ is automatically defined in RtAudio.h
// if no API-specific definitions are passed to the compiler. But just
// in case something weird happens, issue an error message and abort.
errorMessage = "RtAudio: no compiled API support found ... critical error!";
if ( errorCallback )
errorCallback( RTAUDIO_INVALID_USE, errorMessage );
else
std::cerr << '\n' << errorMessage << '\n' << std::endl;
abort();
}
RtAudio :: ~RtAudio()
{
if ( rtapi_ )
delete rtapi_;
}
RtAudioErrorType RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
RtAudio::StreamParameters *inputParameters,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options )
{
return rtapi_->openStream( outputParameters, inputParameters, format,
sampleRate, bufferFrames, callback,
userData, options );
}
// *************************************************** //
//
// Public RtApi definitions (see end of file for
// private or protected utility functions).
//
// *************************************************** //
RtApi :: RtApi()
{
clearStreamInfo();
MUTEX_INITIALIZE( &stream_.mutex );
errorCallback_ = 0;
showWarnings_ = true;
currentDeviceId_ = 129;
}
RtApi :: ~RtApi()
{
MUTEX_DESTROY( &stream_.mutex );
}
RtAudioErrorType RtApi :: openStream( RtAudio::StreamParameters *oParams,
RtAudio::StreamParameters *iParams,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options )
{
if ( stream_.state != STREAM_CLOSED ) {
errorText_ = "RtApi::openStream: a stream is already open!";
return error( RTAUDIO_INVALID_USE );
}
// Clear stream information potentially left from a previously open stream.
clearStreamInfo();
if ( oParams && oParams->nChannels < 1 ) {
errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
return error( RTAUDIO_INVALID_PARAMETER );
}
if ( iParams && iParams->nChannels < 1 ) {
errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
return error( RTAUDIO_INVALID_PARAMETER );
}
if ( oParams == NULL && iParams == NULL ) {
errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
return error( RTAUDIO_INVALID_PARAMETER );
}
if ( formatBytes(format) == 0 ) {
errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
return error( RTAUDIO_INVALID_PARAMETER );
}
// Scan devices if none currently listed.
if ( deviceList_.size() == 0 ) probeDevices();
unsigned int m, oChannels = 0;
if ( oParams ) {
oChannels = oParams->nChannels;
// Verify that the oParams->deviceId is found in our list
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == oParams->deviceId ) break;
}
if ( m == deviceList_.size() ) {
errorText_ = "RtApi::openStream: output device ID is invalid.";
return error( RTAUDIO_INVALID_PARAMETER );
}
}
unsigned int iChannels = 0;
if ( iParams ) {
iChannels = iParams->nChannels;
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == iParams->deviceId ) break;
}
if ( m == deviceList_.size() ) {
errorText_ = "RtApi::openStream: input device ID is invalid.";
return error( RTAUDIO_INVALID_PARAMETER );
}
}
bool result;
if ( oChannels > 0 ) {
result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
sampleRate, format, bufferFrames, options );
if ( result == false )
return error( RTAUDIO_SYSTEM_ERROR );
}
if ( iChannels > 0 ) {
result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
sampleRate, format, bufferFrames, options );
if ( result == false )
return error( RTAUDIO_SYSTEM_ERROR );
}
stream_.callbackInfo.callback = (void *) callback;
stream_.callbackInfo.userData = userData;
if ( options ) options->numberOfBuffers = stream_.nBuffers;
stream_.state = STREAM_STOPPED;
return RTAUDIO_NO_ERROR;
}
void RtApi :: probeDevices( void )
{
// This function MUST be implemented in all subclasses! Within each
// API, this function will be used to:
// - enumerate the devices and fill or update our
// std::vector< RtAudio::DeviceInfo> deviceList_ class variable
// - store corresponding (usually API-specific) identifiers that
// are needed to open each device
// - make sure that the default devices are properly identified
// within the deviceList_ (unless API-specific functions are
// available for this purpose).
//
// The function should not reprobe devices that have already been
// found. The function must properly handle devices that are removed
// or added.
//
// Ideally, we would also configure callback functions to be invoked
// when devices are added or removed (which could be used to inform
// clients about changes). However, none of the APIs currently
// support notification of _new_ devices and I don't see the
// usefulness of having this work only for device removal.
return;
}
unsigned int RtApi :: getDeviceCount( void )
{
probeDevices();
return (unsigned int)deviceList_.size();
}
std::vector<unsigned int> RtApi :: getDeviceIds( void )
{
probeDevices();
// Copy device IDs into output vector.
std::vector<unsigned int> deviceIds;
for ( unsigned int m=0; m<deviceList_.size(); m++ )
deviceIds.push_back( deviceList_[m].ID );
return deviceIds;
}
std::vector<std::string> RtApi :: getDeviceNames( void )
{
probeDevices();
// Copy device names into output vector.
std::vector<std::string> deviceNames;
for ( unsigned int m=0; m<deviceList_.size(); m++ )
deviceNames.push_back( deviceList_[m].name );
return deviceNames;
}
unsigned int RtApi :: getDefaultInputDevice( void )
{
// Should be reimplemented in subclasses if necessary.
if ( deviceList_.size() == 0 ) probeDevices();
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].isDefaultInput )
return deviceList_[i].ID;
}
// If not found, find the first device with input channels, set it
// as the default, and return the ID.
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].inputChannels > 0 ) {
deviceList_[i].isDefaultInput = true;
return deviceList_[i].ID;
}
}
return 0;
}
unsigned int RtApi :: getDefaultOutputDevice( void )
{
// Should be reimplemented in subclasses if necessary.
if ( deviceList_.size() == 0 ) probeDevices();
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].isDefaultOutput )
return deviceList_[i].ID;
}
// If not found, find the first device with output channels, set it
// as the default, and return the ID.
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].outputChannels > 0 ) {
deviceList_[i].isDefaultOutput = true;
return deviceList_[i].ID;
}
}
return 0;
}
RtAudio::DeviceInfo RtApi :: getDeviceInfo( unsigned int deviceId )
{
if ( deviceList_.size() == 0 ) probeDevices();
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId )
return deviceList_[m];
}
errorText_ = "RtApi::getDeviceInfo: deviceId argument not found.";
error( RTAUDIO_INVALID_PARAMETER );
return RtAudio::DeviceInfo();
}
void RtApi :: closeStream( void )
{
// MUST be implemented in subclasses!
return;
}
bool RtApi :: probeDeviceOpen( unsigned int /*deviceId*/, StreamMode /*mode*/, unsigned int /*channels*/,
unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
RtAudio::StreamOptions * /*options*/ )
{
// MUST be implemented in subclasses!
return FAILURE;
}
void RtApi :: tickStreamTime( void )
{
// Subclasses that do not provide their own implementation of
// getStreamTime should call this function once per buffer I/O to
// provide basic stream time support.
stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
}
long RtApi :: getStreamLatency( void )
{
long totalLatency = 0;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
totalLatency = stream_.latency[0];
if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
totalLatency += stream_.latency[1];
return totalLatency;
}
/*
double RtApi :: getStreamTime( void )
{
#if defined( HAVE_GETTIMEOFDAY )
// Return a very accurate estimate of the stream time by
// adding in the elapsed time since the last tick.
struct timeval then;
struct timeval now;
if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
return stream_.streamTime;
gettimeofday( &now, NULL );
then = stream_.lastTickTimestamp;
return stream_.streamTime +
((now.tv_sec + 0.000001 * now.tv_usec) -
(then.tv_sec + 0.000001 * then.tv_usec));
#else
return stream_.streamTime;
#endif
}
*/
void RtApi :: setStreamTime( double time )
{
if ( time >= 0.0 )
stream_.streamTime = time;
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
}
unsigned int RtApi :: getStreamSampleRate( void )
{
if ( isStreamOpen() ) return stream_.sampleRate;
else return 0;
}
// *************************************************** //
//
// OS/API-specific methods.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
#include <unistd.h>
// The OS X CoreAudio API is designed to use a separate callback
// procedure for each of its audio devices. A single RtAudio duplex
// stream using two different devices is supported here, though it
// cannot be guaranteed to always behave correctly because we cannot
// synchronize these two callbacks.
//
// A property listener is installed for over/underrun information.
// However, no functionality is currently provided to allow property
// listeners to trigger user handlers because it is unclear what could
// be done if a critical stream parameter (buffer size, sample rate,
// device disconnect) notification arrived. The listeners entail
// quite a bit of extra code and most likely, a user program wouldn't
// be prepared for the result anyway. However, we do provide a flag
// to the client callback function to inform of an over/underrun.
// A structure to hold various information related to the CoreAudio API
// implementation.
struct CoreHandle {
AudioDeviceID id[2]; // device ids
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
AudioDeviceIOProcID procId[2];
#endif
UInt32 iStream[2]; // device stream index (or first if using multiple)
UInt32 nStreams[2]; // number of streams to use
bool xrun[2];
char *deviceBuffer;
pthread_cond_t condition;
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
bool xrunListenerAdded[2];
bool disconnectListenerAdded[2];
CoreHandle()
:deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; procId[0] = 0; procId[1] = 0; xrun[0] = false; xrun[1] = false; xrunListenerAdded[0] = false; xrunListenerAdded[1] = false; disconnectListenerAdded[0] = false; disconnectListenerAdded[1] = false; }
};
#if defined( MAC_OS_VERSION_12_0 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_VERSION_12_0 )
#define KAUDIOOBJECTPROPERTYELEMENT kAudioObjectPropertyElementMain
#else
#define KAUDIOOBJECTPROPERTYELEMENT kAudioObjectPropertyElementMaster // deprecated with macOS 12
#endif
RtApiCore:: RtApiCore()
{
#if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
// This is a largely undocumented but absolutely necessary
// requirement starting with OS-X 10.6. If not called, queries and
// updates to various audio device properties are not handled
// correctly.
CFRunLoopRef theRunLoop = NULL;
AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
kAudioObjectPropertyScopeGlobal,
KAUDIOOBJECTPROPERTYELEMENT };
OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
if ( result != noErr ) {
errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
error( RTAUDIO_SYSTEM_ERROR );
}
#endif
}
RtApiCore :: ~RtApiCore()
{
// The subclass destructor gets called before the base class
// destructor, so close an existing stream before deallocating
// apiDeviceId memory.
if ( stream_.state != STREAM_CLOSED ) closeStream();
}
unsigned int RtApiCore :: getDefaultOutputDevice( void )
{
AudioDeviceID id;
UInt32 dataSize = sizeof( AudioDeviceID );
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, KAUDIOOBJECTPROPERTYELEMENT };
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
error( RTAUDIO_SYSTEM_ERROR );
return 0;
}
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m] == id ) {
if ( deviceList_[m].isDefaultOutput == false ) {
deviceList_[m].isDefaultOutput = true;
for ( unsigned int j=m+1; j<deviceIds_.size(); j++ ) {
// make sure any remaining devices are not listed as the default
deviceList_[j].isDefaultOutput = false;
}
}
return deviceList_[m].ID;
}
deviceList_[m].isDefaultOutput = false;
}
// If not found above, then do system probe of devices and try again.
probeDevices();
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m] == id ) return deviceList_[m].ID;
}
return 0;
}
unsigned int RtApiCore :: getDefaultInputDevice( void )
{
AudioDeviceID id;
UInt32 dataSize = sizeof( AudioDeviceID );
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, KAUDIOOBJECTPROPERTYELEMENT };
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
error( RTAUDIO_SYSTEM_ERROR );
return 0;
}
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m] == id ) {
if ( deviceList_[m].isDefaultInput == false ) {
deviceList_[m].isDefaultInput = true;
for ( unsigned int j=m+1; j<deviceIds_.size(); j++ ) {
// make sure any remaining devices are not listed as the default
deviceList_[j].isDefaultInput = false;
}
}
return deviceList_[m].ID;
}
deviceList_[m].isDefaultInput = false;
}
// If not found above, then do system probe of devices and try again.
probeDevices();
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m] == id ) return deviceList_[m].ID;
}
return 0;
}
// If a device used in an open stream is disconnected, close the stream.
static OSStatus streamDisconnectListener( AudioObjectID /*id*/,
UInt32 nAddresses,
const AudioObjectPropertyAddress properties[],
void* infoPointer )
{
for ( UInt32 i=0; i<nAddresses; i++ ) {
if ( properties[i].mSelector == kAudioDevicePropertyDeviceIsAlive ) {
CallbackInfo *info = (CallbackInfo *) infoPointer;
RtApiCore *object = (RtApiCore *) info->object;
info->deviceDisconnected = true;
object->closeStream();
return kAudioHardwareUnspecifiedError;
}
}
return kAudioHardwareNoError;
}
void RtApiCore :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
// Find out how many audio devices there are.
UInt32 dataSize;
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, KAUDIOOBJECTPROPERTYELEMENT };
OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &property, 0, NULL, &dataSize );
if ( result != noErr ) {
errorText_ = "RtApiCore::probeDevices: OS-X system error getting device info!";
error( RTAUDIO_SYSTEM_ERROR );
return;
}
unsigned int nDevices = dataSize / sizeof( AudioDeviceID );
if ( nDevices == 0 ) {
deviceList_.clear();
deviceIds_.clear();
return;
}
AudioDeviceID ids[ nDevices ];
property.mSelector = kAudioHardwarePropertyDevices;
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &ids );
if ( result != noErr ) {
errorText_ = "RtApiCore::probeDevices: OS-X system error getting device IDs.";
error( RTAUDIO_SYSTEM_ERROR );
return;
}
// Fill or update the deviceList_ and also save a corresponding list of Ids.
for ( unsigned int n=0; n<nDevices; n++ ) {
if ( std::find( deviceIds_.begin(), deviceIds_.end(), ids[n] ) != deviceIds_.end() ) {
continue; // We already have this device.
}
else { // There is a new device to probe.
RtAudio::DeviceInfo info;
if ( probeDeviceInfo( ids[n], info ) == false ) continue; // ignore if probe fails
deviceIds_.push_back( ids[n] );
info.ID = currentDeviceId_++; // arbitrary internal device ID
deviceList_.push_back( info );
// We could set a property listener here for each device to know
// if it is removed. However, we cannot detect (AFAIK) when a new
// device is plugged in. If we cannot detect BOTH cases, I'm not
// going to bother with only the one.
}
}
// Remove any devices left in the list that are no longer available.
unsigned int m;
for ( std::vector<AudioDeviceID>::iterator it=deviceIds_.begin(); it!=deviceIds_.end(); ) {
for ( m=0; m<nDevices; m++ ) {
if ( ids[m] == *it ) {
++it;
break;
}
}
if ( m == nDevices ) { // not found so remove it from our two lists
it = deviceIds_.erase(it);
deviceList_.erase( deviceList_.begin() + distance(deviceIds_.begin(), it ) );
}
}
// Get default devices and set flags in deviceList_.
AudioDeviceID defaultOutputId, defaultInputId;
dataSize = sizeof( AudioDeviceID );
property.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &defaultOutputId );
if ( result != noErr ) {
errorText_ = "RtApiCore::probeDeviceInfo: OS-X system error getting default output device.";
error( RTAUDIO_WARNING );
defaultOutputId = 0;
}
property.mSelector = kAudioHardwarePropertyDefaultInputDevice;
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &defaultInputId );
if ( result != noErr ) {
errorText_ = "RtApiCore::probeDeviceInfo: OS-X system error getting default input device.";
error( RTAUDIO_WARNING );
defaultInputId = 0;
}
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceIds_[m] == defaultOutputId )
deviceList_[m].isDefaultOutput = true;
else
deviceList_[m].isDefaultOutput = false;
if ( deviceIds_[m] == defaultInputId )
deviceList_[m].isDefaultInput = true;
else
deviceList_[m].isDefaultInput = false;
}
}
bool RtApiCore :: probeDeviceInfo( AudioDeviceID id, RtAudio::DeviceInfo& info )
{
// Get the device name.
info.name.erase();
CFStringRef cfname;
UInt32 dataSize = sizeof( CFStringRef );
AudioObjectPropertyAddress property = { kAudioObjectPropertyManufacturer,
kAudioObjectPropertyScopeGlobal,
KAUDIOOBJECTPROPERTYELEMENT };
OSStatus result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
long length = CFStringGetLength(cfname);
char *mname = (char *)malloc(length * 3 + 1);
#if defined( UNICODE ) || defined( _UNICODE )
CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
#else
CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
#endif
info.name.append( (const char *)mname, strlen(mname) );
info.name.append( ": " );
CFRelease( cfname );
free(mname);
property.mSelector = kAudioObjectPropertyName;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
length = CFStringGetLength(cfname);
char *name = (char *)malloc(length * 3 + 1);
#if defined( UNICODE ) || defined( _UNICODE )
CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
#else
CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
#endif
info.name.append( (const char *)name, strlen(name) );
CFRelease( cfname );
free(name);
// Get the output stream "configuration".
AudioBufferList *bufferList = nil;
property.mSelector = kAudioDevicePropertyStreamConfiguration;
property.mScope = kAudioDevicePropertyScopeOutput;
dataSize = 0;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != noErr || dataSize == 0 ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *) malloc( dataSize );
if ( bufferList == NULL ) {
errorText_ = "RtApiCore::probeDeviceInfo: memory error allocating output AudioBufferList.";
error( RTAUDIO_WARNING );
return false;
}
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
if ( result != noErr || dataSize == 0 ) {
free( bufferList );
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Get output channel information.
unsigned int i, nStreams = bufferList->mNumberBuffers;
for ( i=0; i<nStreams; i++ )
info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
free( bufferList );
// Get the input stream "configuration".
property.mScope = kAudioDevicePropertyScopeInput;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != noErr || dataSize == 0 ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *) malloc( dataSize );
if ( bufferList == NULL ) {
errorText_ = "RtApiCore::probeDeviceInfo: memory error allocating input AudioBufferList.";
error( RTAUDIO_WARNING );
return false;
}
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
if (result != noErr || dataSize == 0) {
free( bufferList );
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Get input channel information.
nStreams = bufferList->mNumberBuffers;
for ( i=0; i<nStreams; i++ )
info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
free( bufferList );
// If device opens for both playback and capture, we determine the channels.
if ( info.outputChannels > 0 && info.inputChannels > 0 )
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Probe the device sample rates.
bool isInput = false;
if ( info.outputChannels == 0 ) isInput = true;
// Determine the supported sample rates.
property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != kAudioHardwareNoError || dataSize == 0 ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
UInt32 nRanges = dataSize / sizeof( AudioValueRange );
AudioValueRange rangeList[ nRanges ];
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
if ( result != kAudioHardwareNoError ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// The sample rate reporting mechanism is a bit of a mystery. It
// seems that it can either return individual rates or a range of
// rates. I assume that if the min / max range values are the same,
// then that represents a single supported rate and if the min / max
// range values are different, the device supports an arbitrary
// range of values (though there might be multiple ranges, so we'll
// use the most conservative range).
Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
bool haveValueRange = false;
info.sampleRates.clear();
for ( UInt32 i=0; i<nRanges; i++ ) {
if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {
unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;
info.sampleRates.push_back( tmpSr );
if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )
info.preferredSampleRate = tmpSr;
} else {
haveValueRange = true;
if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
}
}
if ( haveValueRange ) {
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {
info.sampleRates.push_back( SAMPLE_RATES[k] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
}
// Sort and remove any redundant values
std::sort( info.sampleRates.begin(), info.sampleRates.end() );
info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
if ( info.sampleRates.size() == 0 ) {
errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Probe the currently configured sample rate
Float64 nominalRate;
dataSize = sizeof( Float64 );
property.mSelector = kAudioDevicePropertyNominalSampleRate;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
if ( result == noErr ) info.currentSampleRate = (unsigned int) nominalRate;
// CoreAudio always uses 32-bit floating point data for PCM streams.
// Thus, any other "physical" formats supported by the device are of
// no interest to the client.
info.nativeFormats = RTAUDIO_FLOAT32;
return true;
}
static OSStatus callbackHandler( AudioDeviceID inDevice,
const AudioTimeStamp* /*inNow*/,
const AudioBufferList* inInputData,
const AudioTimeStamp* /*inInputTime*/,
AudioBufferList* outOutputData,
const AudioTimeStamp* /*inOutputTime*/,
void* infoPointer )
{
CallbackInfo *info = (CallbackInfo *) infoPointer;
if(info == NULL || info->object == NULL)
return kAudioHardwareUnspecifiedError;
RtApiCore *object = (RtApiCore *) info->object;
if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
return kAudioHardwareUnspecifiedError;
else
return kAudioHardwareNoError;
}
static OSStatus xrunListener( AudioObjectID /*inDevice*/,
UInt32 nAddresses,
const AudioObjectPropertyAddress properties[],
void* handlePointer )
{
CoreHandle *handle = (CoreHandle *) handlePointer;
for ( UInt32 i=0; i<nAddresses; i++ ) {
if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
handle->xrun[1] = true;
else
handle->xrun[0] = true;
}
}
return kAudioHardwareNoError;
}
bool RtApiCore :: probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
AudioDeviceID id = 0;
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId ) {
id = deviceIds_[m];
break;
}
}
if ( id == 0 ) {
errorText_ = "RtApiCore::probeDeviceOpen: the device ID was not found!";
return FAILURE;
}
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
kAudioDevicePropertyScopeOutput,
KAUDIOOBJECTPROPERTYELEMENT };
// Setup for stream mode.
if ( mode == INPUT ) {
property.mScope = kAudioDevicePropertyScopeInput;
}
// Get the stream "configuration".
AudioBufferList *bufferList = nil;
UInt32 dataSize = 0;
property.mSelector = kAudioDevicePropertyStreamConfiguration;
OSStatus result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != noErr || dataSize == 0 ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *) malloc( dataSize );
if ( bufferList == NULL ) {
errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
return FAILURE;
}
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
if (result != noErr || dataSize == 0) {
free( bufferList );
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Search for one or more streams that contain the desired number of
// channels. CoreAudio devices can have an arbitrary number of
// streams and each stream can have an arbitrary number of channels.
// For each stream, a single buffer of interleaved samples is
// provided. RtAudio prefers the use of one stream of interleaved
// data or multiple consecutive single-channel streams. However, we
// now support multiple consecutive multi-channel streams of
// interleaved data as well.
UInt32 iStream, offsetCounter = firstChannel;
UInt32 nStreams = bufferList->mNumberBuffers;
bool monoMode = false;
bool foundStream = false;
// First check that the device supports the requested number of
// channels.
UInt32 deviceChannels = 0;
for ( iStream=0; iStream<nStreams; iStream++ )
deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
if ( deviceChannels < ( channels + firstChannel ) ) {
free( bufferList );
errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << deviceId << ") does not support the requested channel count.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Look for a single stream meeting our needs.
UInt32 firstStream = 0, streamCount = 1, streamChannels = 0, channelOffset = 0;
for ( iStream=0; iStream<nStreams; iStream++ ) {
streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
if ( streamChannels >= channels + offsetCounter ) {
firstStream = iStream;
channelOffset = offsetCounter;
foundStream = true;
break;
}
if ( streamChannels > offsetCounter ) break;
offsetCounter -= streamChannels;
}
// If we didn't find a single stream above, then we should be able
// to meet the channel specification with multiple streams.
if ( foundStream == false ) {
monoMode = true;
offsetCounter = firstChannel;
for ( iStream=0; iStream<nStreams; iStream++ ) {
streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
if ( streamChannels > offsetCounter ) break;
offsetCounter -= streamChannels;
}
firstStream = iStream;
channelOffset = offsetCounter;
Int32 channelCounter = channels + offsetCounter - streamChannels;
if ( streamChannels > 1 ) monoMode = false;
while ( channelCounter > 0 ) {
streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
if ( streamChannels > 1 ) monoMode = false;
channelCounter -= streamChannels;
streamCount++;
}
}
free( bufferList );
// Determine the buffer size.
AudioValueRange bufferRange;
dataSize = sizeof( AudioValueRange );
property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned int) bufferRange.mMinimum;
else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned int) bufferRange.mMaximum;
if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned int) bufferRange.mMinimum;
// Set the buffer size. For multiple streams, I'm assuming we only
// need to make this setting for the master channel.
UInt32 theSize = (UInt32) *bufferSize;
dataSize = sizeof( UInt32 );
property.mSelector = kAudioDevicePropertyBufferFrameSize;
result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// If attempting to setup a duplex stream, the bufferSize parameter
// MUST be the same in both directions!
*bufferSize = theSize;
if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.bufferSize = *bufferSize;
stream_.nBuffers = 1;
// Try to set "hog" mode ... it's not clear to me this is working.
if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {
pid_t hog_pid;
dataSize = sizeof( hog_pid );
property.mSelector = kAudioDevicePropertyHogMode;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";
errorText_ = errorStream_.str();
return FAILURE;
}
if ( hog_pid != getpid() ) {
hog_pid = getpid();
result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
}
// Check and if necessary, change the sample rate for the device.
Float64 nominalRate;
dataSize = sizeof( Float64 );
property.mSelector = kAudioDevicePropertyNominalSampleRate;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Only try to change the sample rate if off by more than 1 Hz.
if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {
nominalRate = (Float64) sampleRate;
result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Now wait until the reported nominal rate is what we just set.
UInt32 microCounter = 0;
Float64 reportedRate = 0.0;
while ( reportedRate != nominalRate ) {
microCounter += 5000;
if ( microCounter > 2000000 ) break;
usleep( 5000 );
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &reportedRate );
}
if ( microCounter > 2000000 ) {
errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Now set the stream format for all streams. Also, check the
// physical format of the device and change that if necessary.
AudioStreamBasicDescription description;
dataSize = sizeof( AudioStreamBasicDescription );
property.mSelector = kAudioStreamPropertyVirtualFormat;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the sample rate and data format id. However, only make the
// change if the sample rate is not within 1.0 of the desired
// rate and the format is not linear pcm.
bool updateFormat = false;
if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {
description.mSampleRate = (Float64) sampleRate;
updateFormat = true;
}
if ( description.mFormatID != kAudioFormatLinearPCM ) {
description.mFormatID = kAudioFormatLinearPCM;
updateFormat = true;
}
if ( updateFormat ) {
result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Now check the physical format.
property.mSelector = kAudioStreamPropertyPhysicalFormat;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
//std::cout << "Current physical stream format:" << std::endl;
//std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
//std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
//std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
//std::cout << " sample rate = " << description.mSampleRate << std::endl;
if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {
description.mFormatID = kAudioFormatLinearPCM;
//description.mSampleRate = (Float64) sampleRate;
AudioStreamBasicDescription testDescription = description;
UInt32 formatFlags;
// We'll try higher bit rates first and then work our way down.
std::vector< std::pair<UInt32, UInt32> > physicalFormats;
formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed
formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );
physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low
formatFlags |= kAudioFormatFlagIsAlignedHigh;
physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high
formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );
physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );
bool setPhysicalFormat = false;
for( unsigned int i=0; i<physicalFormats.size(); i++ ) {
testDescription = description;
testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;
testDescription.mFormatFlags = physicalFormats[i].second;
if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )
testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
else
testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;
testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );
if ( result == noErr ) {
setPhysicalFormat = true;
//std::cout << "Updated physical stream format:" << std::endl;
//std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
//std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
//std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
//std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
break;
}
}
if ( !setPhysicalFormat ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << deviceId << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
} // done setting virtual/physical formats.
// Get the stream / device latency.
UInt32 latency;
dataSize = sizeof( UInt32 );
property.mSelector = kAudioDevicePropertyLatency;
if ( AudioObjectHasProperty( id, &property ) == true ) {
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );
if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
else {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << deviceId << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
}
// Byte-swapping: According to AudioHardware.h, the stream data will
// always be presented in native-endian format, so we should never
// need to byte swap.
stream_.doByteSwap[mode] = false;
// From the CoreAudio documentation, PCM data must be supplied as
// 32-bit floats.
stream_.userFormat = format;
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
if ( streamCount == 1 )
stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
else // multiple streams
stream_.nDeviceChannels[mode] = channels;
stream_.nUserChannels[mode] = channels;
stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
else stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
stream_.doConvertBuffer[mode] = true;
if ( streamCount == 1 ) {
if ( stream_.nUserChannels[mode] > 1 &&
stream_.userInterleaved != stream_.deviceInterleaved[mode] )
stream_.doConvertBuffer[mode] = true;
}
else if ( monoMode && stream_.userInterleaved )
stream_.doConvertBuffer[mode] = true;
// Allocate our CoreHandle structure for the stream.
CoreHandle *handle = 0;
if ( stream_.apiHandle == 0 ) {
try {
handle = new CoreHandle;
}
catch ( std::bad_alloc& ) {
errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
goto error;
}
if ( pthread_cond_init( &handle->condition, NULL ) ) {
errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *) handle;
}
else
handle = (CoreHandle *) stream_.apiHandle;
handle->iStream[mode] = firstStream;
handle->nStreams[mode] = streamCount;
handle->id[mode] = id;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
// If possible, we will make use of the CoreAudio stream buffers as
// "device buffers". However, we can't do this if using multiple
// streams.
if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
if ( mode == INPUT ) {
if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
if ( bufferBytes <= bytesOut ) makeBuffer = false;
}
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.sampleRate = sampleRate;
stream_.deviceId[mode] = deviceId;
stream_.state = STREAM_STOPPED;
stream_.callbackInfo.object = (void *) this;
// Setup the buffer conversion information structure.
if ( stream_.doConvertBuffer[mode] ) {
if ( streamCount > 1 ) setConvertInfo( mode, 0 );
else setConvertInfo( mode, channelOffset );
}
if ( mode == INPUT && stream_.mode == OUTPUT && stream_.deviceId[0] == deviceId )
// Only one callback procedure and property listener per device.
stream_.mode = DUPLEX;
else {
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
#else
// deprecated in favor of AudioDeviceCreateIOProcID()
result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
#endif
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << deviceId << ").";
errorText_ = errorStream_.str();
goto error;
}
if ( stream_.mode == OUTPUT && mode == INPUT )
stream_.mode = DUPLEX;
else
stream_.mode = mode;
// Setup the device property listener for over/underload.
property.mSelector = kAudioDeviceProcessorOverload;
property.mScope = kAudioObjectPropertyScopeGlobal;
result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error setting xrun listener for device (" << deviceId << ").";
errorText_ = errorStream_.str();
goto error;
}
handle->xrunListenerAdded[mode] = true;
// Setup a listener to detect a possible device disconnect.
property.mSelector = kAudioDevicePropertyDeviceIsAlive;
result = AudioObjectAddPropertyListener( id , &property, streamDisconnectListener, (void *) &stream_.callbackInfo );
if ( result != noErr ) {
AudioObjectRemovePropertyListener( id, &property, xrunListener, (void *) handle );
errorStream_ << "RtApiCore::probeDeviceOpen: system error setting disconnect listener for device (" << deviceId << ").";
errorText_ = errorStream_.str();
goto error;
}
handle->disconnectListenerAdded[mode] = true;
}
return SUCCESS;
error:
closeStream(); // this should safely clear out procedures, listeners and memory, even for duplex stream
return FAILURE;
}
void RtApiCore :: closeStream( void )
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiCore::closeStream(): no open stream to close!";
error( RTAUDIO_WARNING );
return;
}
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( handle ) {
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
KAUDIOOBJECTPROPERTYELEMENT };
if ( handle->xrunListenerAdded[0] ) {
property.mSelector = kAudioDeviceProcessorOverload;
if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {
errorText_ = "RtApiCore::closeStream(): error removing xrun property listener!";
error( RTAUDIO_WARNING );
}
}
if ( handle->disconnectListenerAdded[0] ) {
property.mSelector = kAudioDevicePropertyDeviceIsAlive;
if (AudioObjectRemovePropertyListener( handle->id[0], &property, streamDisconnectListener, (void *) &stream_.callbackInfo ) != noErr) {
errorText_ = "RtApiCore::closeStream(): error removing disconnect property listener!";
error( RTAUDIO_WARNING );
}
}
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
if ( handle->procId[0] ) {
if ( stream_.state == STREAM_RUNNING )
AudioDeviceStop( handle->id[0], handle->procId[0] );
AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
}
#else // deprecated behaviour
if ( stream_.state == STREAM_RUNNING )
AudioDeviceStop( handle->id[0], callbackHandler );
AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
#endif
}
}
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.deviceId[0] != stream_.deviceId[1] ) ) {
if ( handle ) {
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
KAUDIOOBJECTPROPERTYELEMENT };
if ( handle->xrunListenerAdded[1] ) {
property.mSelector = kAudioDeviceProcessorOverload;
if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {
errorText_ = "RtApiCore::closeStream(): error removing xrun property listener!";
error( RTAUDIO_WARNING );
}
}
if ( handle->disconnectListenerAdded[0] ) {
property.mSelector = kAudioDevicePropertyDeviceIsAlive;
if (AudioObjectRemovePropertyListener( handle->id[1], &property, streamDisconnectListener, (void *) &stream_.callbackInfo ) != noErr) {
errorText_ = "RtApiCore::closeStream(): error removing disconnect property listener!";
error( RTAUDIO_WARNING );
}
}
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
if ( handle->procId[1] ) {
if ( stream_.state == STREAM_RUNNING )
AudioDeviceStop( handle->id[1], handle->procId[1] );
AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
}
#else // deprecated behaviour
if ( stream_.state == STREAM_RUNNING )
AudioDeviceStop( handle->id[1], callbackHandler );
AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
#endif
}
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
// Destroy pthread condition variable.
pthread_cond_signal( &handle->condition ); // signal condition variable in case stopStream is blocked
pthread_cond_destroy( &handle->condition );
delete handle;
stream_.apiHandle = 0;
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
if ( info->deviceDisconnected ) {
errorText_ = "RtApiCore: the stream device was disconnected (and closed)!";
error( RTAUDIO_DEVICE_DISCONNECT );
}
clearStreamInfo();
}
RtAudioErrorType RtApiCore :: startStream( void )
{
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiCore::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiCore::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
OSStatus result = noErr;
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
result = AudioDeviceStart( handle->id[0], handle->procId[0] );
#else // deprecated behaviour
result = AudioDeviceStart( handle->id[0], callbackHandler );
#endif
if ( result != noErr ) {
errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.deviceId[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ( stream_.mode == INPUT ||
( stream_.mode == DUPLEX && stream_.deviceId[0] != stream_.deviceId[1] ) ) {
// Clear user input buffer
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[1] * stream_.bufferSize * formatBytes( stream_.userFormat );
memset( stream_.userBuffer[1], 0, bufferBytes * sizeof(char) );
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
result = AudioDeviceStart( handle->id[1], handle->procId[1] );
#else // deprecated behaviour
result = AudioDeviceStart( handle->id[1], callbackHandler );
#endif
if ( result != noErr ) {
errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.deviceId[1] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
handle->drainCounter = 0;
handle->internalDrain = false;
stream_.state = STREAM_RUNNING;
unlock:
if ( result == noErr ) return RTAUDIO_NO_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
RtAudioErrorType RtApiCore :: stopStream( void )
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiCore::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
OSStatus result = noErr;
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( handle->drainCounter == 0 ) {
handle->drainCounter = 2;
pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
}
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
result = AudioDeviceStop( handle->id[0], handle->procId[0] );
#else // deprecated behaviour
result = AudioDeviceStop( handle->id[0], callbackHandler );
#endif
if ( result != noErr ) {
errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.deviceId[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.deviceId[0] != stream_.deviceId[1] ) ) {
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
result = AudioDeviceStop( handle->id[1], handle->procId[1] );
#else // deprecated behaviour
result = AudioDeviceStop( handle->id[1], callbackHandler );
#endif
if ( result != noErr ) {
errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.deviceId[1] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
stream_.state = STREAM_STOPPED;
unlock:
if ( result == noErr ) return RTAUDIO_NO_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
RtAudioErrorType RtApiCore :: abortStream( void )
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiCore::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
handle->drainCounter = 2;
stream_.state = STREAM_STOPPING;
return stopStream();
}
// This function will be called by a spawned thread when the user
// callback function signals that the stream should be stopped or
// aborted. It is better to handle it this way because the
// callbackEvent() function probably should return before the
// AudioDeviceStop() function is called.
static void *coreStopStream( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiCore *object = (RtApiCore *) info->object;
object->stopStream();
pthread_exit( NULL );
}
bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
const AudioBufferList *inBufferList,
const AudioBufferList *outBufferList )
{
if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
error( RTAUDIO_WARNING );
return FAILURE;
}
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
// Check if we were draining the stream and signal is finished.
if ( handle->drainCounter > 3 ) {
ThreadHandle threadId;
stream_.state = STREAM_STOPPING;
if ( handle->internalDrain == true )
pthread_create( &threadId, NULL, coreStopStream, info );
else // external call to stopStream()
pthread_cond_signal( &handle->condition );
return SUCCESS;
}
AudioDeviceID outputDevice = handle->id[0];
// Invoke user callback to get fresh output data UNLESS we are
// draining stream or duplex mode AND the input/output devices are
// different AND this function is called for the input device.
if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
RtAudioCallback callback = (RtAudioCallback) info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData );
if ( cbReturnValue == 2 ) {
abortStream();
return SUCCESS;
}
else if ( cbReturnValue == 1 ) {
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
if ( handle->drainCounter > 1 ) { // write zeros to the output stream
if ( handle->nStreams[0] == 1 ) {
memset( outBufferList->mBuffers[handle->iStream[0]].mData,
0,
outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
}
else { // fill multiple streams with zeros
for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
0,
outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
}
}
}
else if ( handle->nStreams[0] == 1 ) {
if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
stream_.userBuffer[0], stream_.convertInfo[0] );
}
else { // copy from user buffer
memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
stream_.userBuffer[0],
outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
}
}
else { // fill multiple streams
Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
if ( stream_.doConvertBuffer[0] ) {
convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
inBuffer = (Float32 *) stream_.deviceBuffer;
}
if ( stream_.deviceInterleaved[0] == false ) { // mono mode
UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
(void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
}
}
else { // fill multiple multi-channel streams with interleaved data
UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
Float32 *out, *in;
bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
UInt32 inChannels = stream_.nUserChannels[0];
if ( stream_.doConvertBuffer[0] ) {
inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
inChannels = stream_.nDeviceChannels[0];
}
if ( inInterleaved ) inOffset = 1;
else inOffset = stream_.bufferSize;
channelsLeft = inChannels;
for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
in = inBuffer;
out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
outJump = 0;
// Account for possible channel offset in first stream
if ( i == 0 && stream_.channelOffset[0] > 0 ) {
streamChannels -= stream_.channelOffset[0];
outJump = stream_.channelOffset[0];
out += outJump;
}
// Account for possible unfilled channels at end of the last stream
if ( streamChannels > channelsLeft ) {
outJump = streamChannels - channelsLeft;
streamChannels = channelsLeft;
}
// Determine input buffer offsets and skips
if ( inInterleaved ) {
inJump = inChannels;
in += inChannels - channelsLeft;
}
else {
inJump = 1;
in += (inChannels - channelsLeft) * inOffset;
}
for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
for ( unsigned int j=0; j<streamChannels; j++ ) {
*out++ = in[j*inOffset];
}
out += outJump;
in += inJump;
}
channelsLeft -= streamChannels;
}
}
}
}
// Don't bother draining input
if ( handle->drainCounter ) {
handle->drainCounter++;
goto unlock;
}
AudioDeviceID inputDevice;
inputDevice = handle->id[1];
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
if ( handle->nStreams[1] == 1 ) {
if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
convertBuffer( stream_.userBuffer[1],
(char *) inBufferList->mBuffers[handle->iStream[1]].mData,
stream_.convertInfo[1] );
}
else { // copy to user buffer
memcpy( stream_.userBuffer[1],
inBufferList->mBuffers[handle->iStream[1]].mData,
inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
}
}
else { // read from multiple streams
Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
if ( stream_.deviceInterleaved[1] == false ) { // mono mode
UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
memcpy( (void *)&outBuffer[i*stream_.bufferSize],
inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
}
}
else { // read from multiple multi-channel streams
UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
Float32 *out, *in;
bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
UInt32 outChannels = stream_.nUserChannels[1];
if ( stream_.doConvertBuffer[1] ) {
outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
outChannels = stream_.nDeviceChannels[1];
}
if ( outInterleaved ) outOffset = 1;
else outOffset = stream_.bufferSize;
channelsLeft = outChannels;
for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
out = outBuffer;
in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
inJump = 0;
// Account for possible channel offset in first stream
if ( i == 0 && stream_.channelOffset[1] > 0 ) {
streamChannels -= stream_.channelOffset[1];
inJump = stream_.channelOffset[1];
in += inJump;
}
// Account for possible unread channels at end of the last stream
if ( streamChannels > channelsLeft ) {
inJump = streamChannels - channelsLeft;
streamChannels = channelsLeft;
}
// Determine output buffer offsets and skips
if ( outInterleaved ) {
outJump = outChannels;
out += outChannels - channelsLeft;
}
else {
outJump = 1;
out += (outChannels - channelsLeft) * outOffset;
}
for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
for ( unsigned int j=0; j<streamChannels; j++ ) {
out[j*outOffset] = *in++;
}
out += outJump;
in += inJump;
}
channelsLeft -= streamChannels;
}
}
if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
convertBuffer( stream_.userBuffer[1],
stream_.deviceBuffer,
stream_.convertInfo[1] );
}
}
}
unlock:
// Make sure to only tick duplex stream time once if using two devices
if ( stream_.mode == DUPLEX ) {
if ( handle->id[0] == handle->id[1] ) // same device, only one callback
RtApi::tickStreamTime();
else if ( deviceId == handle->id[0] )
RtApi::tickStreamTime(); // two devices, only tick on the output callback
} else
RtApi::tickStreamTime(); // input or output stream only
return SUCCESS;
}
const char* RtApiCore :: getErrorCode( OSStatus code )
{
switch( code ) {
case kAudioHardwareNotRunningError:
return "kAudioHardwareNotRunningError";
case kAudioHardwareUnspecifiedError:
return "kAudioHardwareUnspecifiedError";
case kAudioHardwareUnknownPropertyError:
return "kAudioHardwareUnknownPropertyError";
case kAudioHardwareBadPropertySizeError:
return "kAudioHardwareBadPropertySizeError";
case kAudioHardwareIllegalOperationError:
return "kAudioHardwareIllegalOperationError";
case kAudioHardwareBadObjectError:
return "kAudioHardwareBadObjectError";
case kAudioHardwareBadDeviceError:
return "kAudioHardwareBadDeviceError";
case kAudioHardwareBadStreamError:
return "kAudioHardwareBadStreamError";
case kAudioHardwareUnsupportedOperationError:
return "kAudioHardwareUnsupportedOperationError";
case kAudioDeviceUnsupportedFormatError:
return "kAudioDeviceUnsupportedFormatError";
case kAudioDevicePermissionsError:
return "kAudioDevicePermissionsError";
default:
return "CoreAudio unknown error";
}
}
//******************** End of __MACOSX_CORE__ *********************//
#endif
#if defined(__UNIX_JACK__)
// JACK is a low-latency audio server, originally written for the
// GNU/Linux operating system and now also ported to OS-X and
// Windows. It can connect a number of different applications to an
// audio device, as well as allowing them to share audio between
// themselves.
//
// When using JACK with RtAudio, "devices" refer to JACK clients that
// have ports connected to the server, while ports correspond to device
// channels. The JACK server is typically started in a terminal as
// follows:
//
// .jackd -d alsa -d hw:0
//
// or through an interface program such as qjackctl. Many of the
// parameters normally set for a stream are fixed by the JACK server
// and can be specified when the JACK server is started. In
// particular,
//
// .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
//
// specifies a sample rate of 44100 Hz, a buffer size of 512 sample
// frames, and number of buffers = 4. Once the server is running, it
// is not possible to override these values. If the values are not
// specified in the command-line, the JACK server uses default values.
//
// The JACK server does not have to be running when an instance of
// RtApiJack is created, though the function getDeviceCount() will
// report 0 devices found until JACK has been started. When no
// devices are available (i.e., the JACK server is not running), a
// stream cannot be opened.
#include <unistd.h>
#include <cstdio>
// A structure to hold various information related to the Jack API
// implementation.
struct JackHandle {
jack_client_t *client;
jack_port_t **ports[2];
std::string deviceName[2];
bool xrun[2];
pthread_cond_t condition;
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
JackHandle()
:client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
};
std::string escapeJackPortRegex(std::string &str)
{
const std::string need_escaping = "()[]{}*+?$^.|\\";
std::string escaped_string;
for (auto c : str)
{
if (need_escaping.find(c) != std::string::npos)
escaped_string.push_back('\\');
escaped_string.push_back(c);
}
return escaped_string;
}
#if !defined(__RTAUDIO_DEBUG__)
static void jackSilentError( const char * ) {};
#endif
RtApiJack :: RtApiJack()
:shouldAutoconnect_(true) {
// Nothing to do here.
#if !defined(__RTAUDIO_DEBUG__)
// Turn off Jack's internal error reporting.
jack_set_error_function( &jackSilentError );
#endif
}
RtApiJack :: ~RtApiJack()
{
if ( stream_.state != STREAM_CLOSED ) closeStream();
}
void RtApiJack :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
// See if we can become a jack client.
jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
jack_status_t *status = NULL;
jack_client_t *client = jack_client_open( "RtApiJackProbe", options, status );
if ( client == 0 ) {
deviceList_.clear(); // in case the server is shutdown after a previous successful probe
errorText_ = "RtApiJack::probeDevices: Jack server not found or connection error!";
//error( RTAUDIO_SYSTEM_ERROR );
error( RTAUDIO_WARNING );
return;
}
const char **ports;
std::string port, previousPort;
unsigned int nChannels = 0, nDevices = 0;
std::vector<std::string> portNames;
ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
if ( ports ) {
// Parse the port names up to the first colon (:).
size_t iColon = 0;
do {
port = (char *) ports[ nChannels ];
iColon = port.find(":");
if ( iColon != std::string::npos ) {
port = port.substr( 0, iColon );
if ( port != previousPort ) {
portNames.push_back( port );
nDevices++;
previousPort = port;
}
}
} while ( ports[++nChannels] );
free( ports );
}
// Fill or update the deviceList_.
unsigned int m, n;
for ( n=0; n<nDevices; n++ ) {
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].name == portNames[n] )
break; // We already have this device.
}
if ( m == deviceList_.size() ) { // new device
RtAudio::DeviceInfo info;
info.name = portNames[n];
if ( probeDeviceInfo( info, client ) == false ) continue; // ignore if probe fails
info.ID = currentDeviceId_++; // arbitrary internal device ID
deviceList_.push_back( info );
// A callback can be registered in Jack to be notified about client
// (dis)connections. However, this can only be done with an open client,
// so unless we want to keep a special client open all the time, this
// would only report (dis)connections when a stream is open. I'm not
// going to bother for the moment.
}
}
// Remove any devices left in the list that are no longer available.
for ( std::vector<RtAudio::DeviceInfo>::iterator it=deviceList_.begin(); it!=deviceList_.end(); ) {
for ( m=0; m<portNames.size(); m++ ) {
if ( (*it).name == portNames[m] ) {
++it;
break;
}
}
if ( m == portNames.size() ) // not found so remove it from our list
it = deviceList_.erase( it );
}
jack_client_close( client );
if ( nDevices == 0 ) {
deviceList_.clear();
return;
}
// Jack doesn't provide default devices so call the getDefault
// functions, which will set the first available input and output
// devices as the defaults.
getDefaultInputDevice();
getDefaultOutputDevice();
}
bool RtApiJack :: probeDeviceInfo( RtAudio::DeviceInfo& info, jack_client_t *client )
{
// Get the current jack server sample rate.
info.sampleRates.clear();
info.preferredSampleRate = jack_get_sample_rate( client );
info.sampleRates.push_back( info.preferredSampleRate );
// Count the available ports containing the client name as device
// channels. Jack "input ports" equal RtAudio output channels.
unsigned int nChannels = 0;
const char **ports = jack_get_ports( client, escapeJackPortRegex(info.name).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput );
if ( ports ) {
while ( ports[ nChannels ] ) nChannels++;
free( ports );
info.outputChannels = nChannels;
}
// Jack "output ports" equal RtAudio input channels.
nChannels = 0;
ports = jack_get_ports( client, escapeJackPortRegex(info.name).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
if ( ports ) {
while ( ports[ nChannels ] ) nChannels++;
free( ports );
info.inputChannels = nChannels;
}
if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
jack_client_close(client);
errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
error( RTAUDIO_WARNING );
return false;
}
// If device opens for both playback and capture, we determine the channels.
if ( info.outputChannels > 0 && info.inputChannels > 0 )
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Jack always uses 32-bit floats.
info.nativeFormats = RTAUDIO_FLOAT32;
return true;
}
static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
{
CallbackInfo *info = (CallbackInfo *) infoPointer;
RtApiJack *object = (RtApiJack *) info->object;
if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
return 0;
}
// This function will be called by a spawned thread when the Jack
// server signals that it is shutting down. It is necessary to handle
// it this way because the jackShutdown() function must return before
// the jack_deactivate() function (in closeStream()) will return.
static void *jackCloseStream( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiJack *object = (RtApiJack *) info->object;
info->deviceDisconnected = true;
object->closeStream();
pthread_exit( NULL );
}
/*
// Could be used to catch client connections but requires open client.
static void jackClientChange( const char *name, int registered, void *infoPointer )
{
std::cout << "in jackClientChange, name = " << name << ", registered = " << registered << std::endl;
}
*/
static void jackShutdown( void *infoPointer )
{
CallbackInfo *info = (CallbackInfo *) infoPointer;
RtApiJack *object = (RtApiJack *) info->object;
// Check current stream state. If stopped, then we'll assume this
// was called as a result of a call to RtApiJack::stopStream (the
// deactivation of a client handle causes this function to be called).
// If not, we'll assume the Jack server is shutting down or some
// other problem occurred and we should close the stream.
if ( object->isStreamRunning() == false ) return;
ThreadHandle threadId;
pthread_create( &threadId, NULL, jackCloseStream, info );
}
static int jackXrun( void *infoPointer )
{
JackHandle *handle = *((JackHandle **) infoPointer);
if ( handle->ports[0] ) handle->xrun[0] = true;
if ( handle->ports[1] ) handle->xrun[1] = true;
return 0;
}
bool RtApiJack :: probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
JackHandle *handle = (JackHandle *) stream_.apiHandle;
// Look for jack server and try to become a client (only do once per stream).
jack_client_t *client = 0;
if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
jack_status_t *status = NULL;
if ( options && !options->streamName.empty() )
client = jack_client_open( options->streamName.c_str(), jackoptions, status );
else
client = jack_client_open( "RtApiJack", jackoptions, status );
if ( client == 0 ) {
errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
error( RTAUDIO_WARNING );
return FAILURE;
}
}
else {
// The handle must have been created on an earlier pass.
client = handle->client;
}
std::string deviceName;
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId ) {
deviceName = deviceList_[m].name;
break;
}
}
if ( deviceName.empty() ) {
errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
unsigned long flag = JackPortIsInput;
if ( mode == INPUT ) flag = JackPortIsOutput;
const char **ports;
if ( ! (options && (options->flags & RTAUDIO_JACK_DONT_CONNECT)) ) {
// Count the available ports containing the client name as device
// channels. Jack "input ports" equal RtAudio output channels.
unsigned int nChannels = 0;
ports = jack_get_ports( client, escapeJackPortRegex(deviceName).c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
if ( ports ) {
while ( ports[ nChannels ] ) nChannels++;
free( ports );
}
// Compare the jack ports for specified client to the requested number of channels.
if ( nChannels < (channels + firstChannel) ) {
errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << deviceName << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Check the jack server sample rate.
unsigned int jackRate = jack_get_sample_rate( client );
if ( sampleRate != jackRate ) {
jack_client_close( client );
errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.sampleRate = jackRate;
// Get the latency of the JACK port.
ports = jack_get_ports( client, escapeJackPortRegex(deviceName).c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
if ( ports[ firstChannel ] ) {
// Added by Ge Wang
jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
// the range (usually the min and max are equal)
jack_latency_range_t latrange; latrange.min = latrange.max = 0;
// get the latency range
jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
// be optimistic, use the min!
stream_.latency[mode] = latrange.min;
//stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
}
free( ports );
// The jack server always uses 32-bit floating-point data.
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
stream_.userFormat = format;
if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
else stream_.userInterleaved = true;
// Jack always uses non-interleaved buffers.
stream_.deviceInterleaved[mode] = false;
// Jack always provides host byte-ordered data.
stream_.doByteSwap[mode] = false;
// Get the buffer size. The buffer size and number of buffers
// (periods) is set when the jack server is started.
stream_.bufferSize = (int) jack_get_buffer_size( client );
*bufferSize = stream_.bufferSize;
stream_.nDeviceChannels[mode] = channels;
stream_.nUserChannels[mode] = channels;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1 )
stream_.doConvertBuffer[mode] = true;
// Allocate our JackHandle structure for the stream.
if ( handle == 0 ) {
try {
handle = new JackHandle;
}
catch ( std::bad_alloc& ) {
errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
goto error;
}
if ( pthread_cond_init(&handle->condition, NULL) ) {
errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *) handle;
handle->client = client;
}
handle->deviceName[mode] = deviceName;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if ( stream_.doConvertBuffer[mode] ) {
bool makeBuffer = true;
if ( mode == OUTPUT )
bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
else { // mode == INPUT
bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if ( bufferBytes < bytesOut ) makeBuffer = false;
}
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
// Allocate memory for the Jack ports (channels) identifiers.
handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
if ( handle->ports[mode] == NULL ) {
errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
goto error;
}
stream_.channelOffset[mode] = firstChannel;
stream_.state = STREAM_STOPPED;
stream_.callbackInfo.object = (void *) this;
if ( stream_.mode == OUTPUT && mode == INPUT )
// We had already set up the stream for output.
stream_.mode = DUPLEX;
else {
stream_.mode = mode;
jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
jack_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle );
jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
//jack_set_client_registration_callback( handle->client, jackClientChange, (void *) &stream_.callbackInfo );
}
// Register our ports.
char label[64];
if ( mode == OUTPUT ) {
for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
snprintf( label, 64, "outport %d", i );
handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
}
}
else {
for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
snprintf( label, 64, "inport %d", i );
handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
}
}
// Setup the buffer conversion information structure. We don't use
// buffers to do channel offsets, so we override that parameter
// here.
if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false;
return SUCCESS;
error:
if ( handle ) {
pthread_cond_destroy( &handle->condition );
jack_client_close( handle->client );
if ( handle->ports[0] ) free( handle->ports[0] );
if ( handle->ports[1] ) free( handle->ports[1] );
delete handle;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
return FAILURE;
}
void RtApiJack :: closeStream( void )
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiJack::closeStream(): no open stream to close!";
error( RTAUDIO_WARNING );
return;
}
JackHandle *handle = (JackHandle *) stream_.apiHandle;
if ( handle ) {
if ( stream_.state == STREAM_RUNNING )
jack_deactivate( handle->client );
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ )
jack_port_unregister( handle->client, handle->ports[0][i] );
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ )
jack_port_unregister( handle->client, handle->ports[1][i] );
}
jack_client_close( handle->client );
if ( handle->ports[0] ) free( handle->ports[0] );
if ( handle->ports[1] ) free( handle->ports[1] );
pthread_cond_destroy( &handle->condition );
delete handle;
stream_.apiHandle = 0;
}
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
if ( info->deviceDisconnected ) {
errorText_ = "RtApiJack: the Jack server is shutting down this client ... stream stopped and closed!";
error( RTAUDIO_DEVICE_DISCONNECT );
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
clearStreamInfo();
}
RtAudioErrorType RtApiJack :: startStream( void )
{
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiJack::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiJack::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
JackHandle *handle = (JackHandle *) stream_.apiHandle;
int result = jack_activate( handle->client );
if ( result ) {
errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
goto unlock;
}
const char **ports;
// Get the list of available ports.
if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) {
ports = jack_get_ports( handle->client, escapeJackPortRegex(handle->deviceName[0]).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput);
if ( ports == NULL) {
errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
goto unlock;
}
// Now make the port connections. Since RtAudio wasn't designed to
// allow the user to select particular channels of a device, we'll
// just open the first "nChannels" ports with offset.
for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
result = 1;
if ( ports[ stream_.channelOffset[0] + i ] )
result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
if ( result ) {
free( ports );
errorText_ = "RtApiJack::startStream(): error connecting output ports!";
goto unlock;
}
}
free(ports);
}
if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) {
ports = jack_get_ports( handle->client, escapeJackPortRegex(handle->deviceName[1]).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
if ( ports == NULL) {
errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
goto unlock;
}
// Now make the port connections. See note above.
for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
result = 1;
if ( ports[ stream_.channelOffset[1] + i ] )
result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
if ( result ) {
free( ports );
errorText_ = "RtApiJack::startStream(): error connecting input ports!";
goto unlock;
}
}
free(ports);
}
handle->drainCounter = 0;
handle->internalDrain = false;
stream_.state = STREAM_RUNNING;
unlock:
if ( result == 0 ) return RTAUDIO_NO_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
RtAudioErrorType RtApiJack :: stopStream( void )
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiJack::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
JackHandle *handle = (JackHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( handle->drainCounter == 0 ) {
handle->drainCounter = 2;
pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
}
}
jack_deactivate( handle->client );
stream_.state = STREAM_STOPPED;
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiJack :: abortStream( void )
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiJack::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
JackHandle *handle = (JackHandle *) stream_.apiHandle;
handle->drainCounter = 2;
return stopStream();
}
// This function will be called by a spawned thread when the user
// callback function signals that the stream should be stopped or
// aborted. It is necessary to handle it this way because the
// callbackEvent() function must return before the jack_deactivate()
// function will return.
static void *jackStopStream( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiJack *object = (RtApiJack *) info->object;
object->stopStream();
pthread_exit( NULL );
}
bool RtApiJack :: callbackEvent( unsigned long nframes )
{
if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiJack::callbackEvent(): the stream is closed ... this shouldn't happen!";
error( RTAUDIO_WARNING );
return FAILURE;
}
if ( stream_.bufferSize != nframes ) {
errorText_ = "RtApiJack::callbackEvent(): the JACK buffer size has changed ... cannot process!";
error( RTAUDIO_WARNING );
return FAILURE;
}
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
JackHandle *handle = (JackHandle *) stream_.apiHandle;
// Check if we were draining the stream and signal is finished.
if ( handle->drainCounter > 3 ) {
ThreadHandle threadId;
stream_.state = STREAM_STOPPING;
if ( handle->internalDrain == true )
pthread_create( &threadId, NULL, jackStopStream, info );
else // external call to stopStream()
pthread_cond_signal( &handle->condition );
return SUCCESS;
}
// Invoke user callback first, to get fresh output data.
if ( handle->drainCounter == 0 ) {
RtAudioCallback callback = (RtAudioCallback) info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData );
if ( cbReturnValue == 2 ) {
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
ThreadHandle id;
pthread_create( &id, NULL, jackStopStream, info );
return SUCCESS;
}
else if ( cbReturnValue == 1 ) {
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
jack_default_audio_sample_t *jackbuffer;
unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( handle->drainCounter > 1 ) { // write zeros to the output stream
for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
memset( jackbuffer, 0, bufferBytes );
}
}
else if ( stream_.doConvertBuffer[0] ) {
convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
}
}
else { // no buffer conversion
for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
}
}
}
// Don't bother draining input
if ( handle->drainCounter ) {
handle->drainCounter++;
goto unlock;
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
if ( stream_.doConvertBuffer[1] ) {
for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
}
convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
}
else { // no buffer conversion
for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
}
}
}
unlock:
RtApi::tickStreamTime();
return SUCCESS;
}
//******************** End of __UNIX_JACK__ *********************//
#endif
#if defined(__WINDOWS_ASIO__) // ASIO API on Windows
// The ASIO API is designed around a callback scheme, so this
// implementation is similar to that used for OS-X CoreAudio and unix
// Jack. The primary constraint with ASIO is that it only allows
// access to a single driver at a time. Thus, it is not possible to
// have more than one simultaneous RtAudio stream.
//
// This implementation also requires a number of external ASIO files
// and a few global variables. The ASIO callback scheme does not
// allow for the passing of user data, so we must create a global
// pointer to our callbackInfo structure.
//
// On unix systems, we make use of a pthread condition variable.
// Since there is no equivalent in Windows, I hacked something based
// on information found in
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
#include "asiosys.h"
#include "asio.h"
#include "iasiothiscallresolver.h"
#include "asiodrivers.h"
#include <cmath>
static AsioDrivers drivers;
static ASIOCallbacks asioCallbacks;
static ASIODriverInfo driverInfo;
static CallbackInfo *asioCallbackInfo;
static bool asioXRun;
static bool streamOpen = false; // Tracks whether any instance of RtAudio has a stream open
struct AsioHandle {
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
ASIOBufferInfo *bufferInfos;
HANDLE condition;
AsioHandle()
:drainCounter(0), internalDrain(false), bufferInfos(0) {}
};
// Function declarations (definitions at end of section)
static const char* getAsioErrorString( ASIOError result );
static void sampleRateChanged( ASIOSampleRate sRate );
static long asioMessages( long selector, long value, void* message, double* opt );
RtApiAsio :: RtApiAsio()
{
// ASIO cannot run on a multi-threaded apartment. You can call
// CoInitialize beforehand, but it must be for apartment threading
// (in which case, CoInitilialize will return S_FALSE here).
coInitialized_ = false;
HRESULT hr = CoInitialize( NULL );
if ( FAILED(hr) ) {
errorText_ = "RtApiAsio::ASIO requires a single-threaded apartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
error( RTAUDIO_WARNING );
}
coInitialized_ = true;
// Check whether another RtAudio instance has an ASIO stream open.
if ( streamOpen ) {
errorText_ = "RtApiAsio(): Another RtAudio ASIO stream is open, functionality may be limited.";
error( RTAUDIO_WARNING );
}
else
drivers.removeCurrentDriver();
driverInfo.asioVersion = 2;
// See note in DirectSound implementation about GetDesktopWindow().
driverInfo.sysRef = GetForegroundWindow();
}
RtApiAsio :: ~RtApiAsio()
{
if ( stream_.state != STREAM_CLOSED ) closeStream();
if ( coInitialized_ ) CoUninitialize();
}
void RtApiAsio :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
if ( streamOpen ) {
errorText_ = "RtApiAsio::probeDevices: Another RtAudio ASIO stream is open, cannot probe devices.";
error( RTAUDIO_WARNING );
return;
}
unsigned int nDevices = drivers.asioGetNumDev();
if ( nDevices == 0 ) {
deviceList_.clear();
return;
}
char tmp[32];
std::vector< std::string > driverNames;
unsigned int n, m;
for ( n=0; n<nDevices; n++ ) {
ASIOError result = drivers.asioGetDriverName( (int) n, tmp, 32 );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDevices: unable to get driver name (" << getAsioErrorString( result ) << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
continue;
}
driverNames.push_back( tmp );
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].name == driverNames.back() )
break; // We already have this device.
}
if ( m == deviceList_.size() ) { // new device
RtAudio::DeviceInfo info;
info.name = driverNames.back();
if ( probeDeviceInfo( info ) == false ) continue; // ignore if probe fails
info.ID = currentDeviceId_++; // arbitrary internal device ID
deviceList_.push_back( info );
}
}
// Remove any devices left in the list that are no longer available.
for ( std::vector<RtAudio::DeviceInfo>::iterator it=deviceList_.begin(); it!=deviceList_.end(); ) {
for ( m=0; m<driverNames.size(); m++ ) {
if ( (*it).name == driverNames[m] ) {
++it;
break;
}
}
if ( m == driverNames.size() ) // not found so remove it from our list
it = deviceList_.erase( it );
}
// Asio doesn't provide default devices so call the getDefault
// functions, which will set the first available input and output
// devices as the defaults. Don't call getDefaultXXXDevice if
// deviceList is empty.
if(deviceList_.size() > 0)
{
getDefaultInputDevice();
getDefaultOutputDevice();
}
}
bool RtApiAsio :: probeDeviceInfo( RtAudio::DeviceInfo &info )
{
if ( !drivers.loadDriver( const_cast<char *>(info.name.c_str()) ) ) {
errorStream_ << "RtApiAsio::probeDeviceInfo: unable to load driver (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
ASIOError result = ASIOInit( &driverInfo );
if ( result != ASE_OK ) {
drivers.removeCurrentDriver();
errorStream_ << "RtApiAsio::probeDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Determine the device channel information.
long inputChannels, outputChannels;
result = ASIOGetChannels( &inputChannels, &outputChannels );
if ( result != ASE_OK ) {
ASIOExit();
drivers.removeCurrentDriver();
errorStream_ << "RtApiAsio::probeDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
info.outputChannels = outputChannels;
info.inputChannels = inputChannels;
if ( info.outputChannels > 0 && info.inputChannels > 0 )
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Determine the supported sample rates.
info.sampleRates.clear();
for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
if ( result == ASE_OK ) {
info.sampleRates.push_back( SAMPLE_RATES[i] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[i];
}
}
// Determine supported data types ... just check first channel and assume rest are the same.
ASIOChannelInfo channelInfo;
channelInfo.channel = 0;
channelInfo.isInput = true;
if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
result = ASIOGetChannelInfo( &channelInfo );
if ( result != ASE_OK ) {
ASIOExit();
drivers.removeCurrentDriver();
errorStream_ << "RtApiAsio::probeDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << info.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
info.nativeFormats = 0;
if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
info.nativeFormats |= RTAUDIO_SINT16;
else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
info.nativeFormats |= RTAUDIO_SINT32;
else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
info.nativeFormats |= RTAUDIO_FLOAT32;
else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
info.nativeFormats |= RTAUDIO_FLOAT64;
else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
info.nativeFormats |= RTAUDIO_SINT24;
ASIOExit();
drivers.removeCurrentDriver();
return true;
}
static void bufferSwitch( long index, ASIOBool /*processNow*/ )
{
RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
object->callbackEvent( index );
}
bool RtApiAsio :: probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
// For ASIO, a duplex stream MUST use the same driver.
if ( isDuplexInput && stream_.deviceId[0] != deviceId ) {
errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
return FAILURE;
}
std::string driverName;
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId ) {
driverName = deviceList_[m].name;
break;
}
}
if ( driverName.empty() ) {
errorText_ = "RtApiAsio::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
// Only load the driver once for duplex stream.
ASIOError result;
if ( !isDuplexInput ) {
if ( streamOpen ) {
errorText_ = "RtApiAsio::probeDeviceOpen: Another RtAudio ASIO stream is open, cannot open more than one at a time.";
return FAILURE;
}
if ( !drivers.loadDriver( const_cast<char *>(driverName.c_str()) ) ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
result = ASIOInit( &driverInfo );
if ( result != ASE_OK ) {
drivers.removeCurrentDriver();
errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
bool buffersAllocated = false;
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
unsigned int nChannels;
// Check the device channel count.
long inputChannels, outputChannels;
result = ASIOGetChannels( &inputChannels, &outputChannels );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
errorText_ = errorStream_.str();
goto error;
}
if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
errorText_ = errorStream_.str();
goto error;
}
stream_.nDeviceChannels[mode] = channels;
stream_.nUserChannels[mode] = channels;
stream_.channelOffset[mode] = firstChannel;
// Verify the sample rate is supported.
result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
errorText_ = errorStream_.str();
goto error;
}
// Get the current sample rate
ASIOSampleRate currentRate;
result = ASIOGetSampleRate( ¤tRate );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
errorText_ = errorStream_.str();
goto error;
}
// Set the sample rate only if necessary
if ( currentRate != sampleRate ) {
result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
errorText_ = errorStream_.str();
goto error;
}
}
// Determine the driver data type.
ASIOChannelInfo channelInfo;
channelInfo.channel = 0;
if ( mode == OUTPUT ) channelInfo.isInput = false;
else channelInfo.isInput = true;
result = ASIOGetChannelInfo( &channelInfo );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
errorText_ = errorStream_.str();
goto error;
}
// Assuming WINDOWS host is always little-endian.
stream_.doByteSwap[mode] = false;
stream_.userFormat = format;
stream_.deviceFormat[mode] = 0;
if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
}
else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
}
else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
}
else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
}
else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
}
if ( stream_.deviceFormat[mode] == 0 ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
goto error;
}
// Set the buffer size. For a duplex stream, this will end up
// setting the buffer size based on the input constraints, which
// should be ok.
long minSize, maxSize, preferSize, granularity;
result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
errorText_ = errorStream_.str();
goto error;
}
if ( isDuplexInput ) {
// When this is the duplex input (output was opened before), then we have to use the same
// buffersize as the output, because it might use the preferred buffer size, which most
// likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
// So instead of throwing an error, make them equal. The caller uses the reference
// to the "bufferSize" param as usual to set up processing buffers.
*bufferSize = stream_.bufferSize;
} else {
if ( *bufferSize == 0 ) *bufferSize = preferSize;
else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
else if ( granularity == -1 ) {
// Make sure bufferSize is a power of two.
int log2_of_min_size = 0;
int log2_of_max_size = 0;
for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
}
long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
int min_delta_num = log2_of_min_size;
for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
if (current_delta < min_delta) {
min_delta = current_delta;
min_delta_num = i;
}
}
*bufferSize = ( (unsigned int)1 << min_delta_num );
if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
}
else if ( granularity != 0 ) {
// Set to an even multiple of granularity, rounding up.
*bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
}
}
/*
// we don't use it anymore, see above!
// Just left it here for the case...
if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
goto error;
}
*/
stream_.bufferSize = *bufferSize;
stream_.nBuffers = 2;
if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
else stream_.userInterleaved = true;
// ASIO always uses non-interleaved buffers.
stream_.deviceInterleaved[mode] = false;
// Allocate, if necessary, our AsioHandle structure for the stream.
if ( handle == 0 ) {
try {
handle = new AsioHandle;
}
catch ( std::bad_alloc& ) {
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
goto error;
}
handle->bufferInfos = 0;
// Create a manual-reset event.
handle->condition = CreateEvent( NULL, // no security
TRUE, // manual-reset
FALSE, // non-signaled initially
NULL ); // unnamed
stream_.apiHandle = (void *) handle;
}
// Create the ASIO internal buffers. Since RtAudio sets up input
// and output separately, we'll have to dispose of previously
// created output buffers for a duplex stream.
if ( mode == INPUT && stream_.mode == OUTPUT ) {
ASIODisposeBuffers();
if ( handle->bufferInfos ) free( handle->bufferInfos );
}
// Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
unsigned int i;
nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
if ( handle->bufferInfos == NULL ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
errorText_ = errorStream_.str();
goto error;
}
ASIOBufferInfo *infos;
infos = handle->bufferInfos;
for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
infos->isInput = ASIOFalse;
infos->channelNum = i + stream_.channelOffset[0];
infos->buffers[0] = infos->buffers[1] = 0;
}
for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
infos->isInput = ASIOTrue;
infos->channelNum = i + stream_.channelOffset[1];
infos->buffers[0] = infos->buffers[1] = 0;
}
// prepare for callbacks
stream_.sampleRate = sampleRate;
stream_.deviceId[mode] = deviceId;
stream_.mode = isDuplexInput ? DUPLEX : mode;
// store this class instance before registering callbacks, that are going to use it
asioCallbackInfo = &stream_.callbackInfo;
stream_.callbackInfo.object = (void *) this;
// Set up the ASIO callback structure and create the ASIO data buffers.
asioCallbacks.bufferSwitch = &bufferSwitch;
asioCallbacks.sampleRateDidChange = &sampleRateChanged;
asioCallbacks.asioMessage = &asioMessages;
asioCallbacks.bufferSwitchTimeInfo = NULL;
result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
if ( result != ASE_OK ) {
// Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
// but only accept the preferred buffer size as parameter for ASIOCreateBuffers (e.g. Creative's ASIO driver).
// In that case, let's be naïve and try that instead.
*bufferSize = preferSize;
stream_.bufferSize = *bufferSize;
result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
}
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
errorText_ = errorStream_.str();
goto error;
}
buffersAllocated = true;
stream_.state = STREAM_STOPPED;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1 )
stream_.doConvertBuffer[mode] = true;
// Allocate necessary internal buffers
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if ( stream_.doConvertBuffer[mode] ) {
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
if ( isDuplexInput && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
if ( bufferBytes <= bytesOut ) makeBuffer = false;
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
// Determine device latencies
long inputLatency, outputLatency;
result = ASIOGetLatencies( &inputLatency, &outputLatency );
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING); // warn but don't fail
}
else {
stream_.latency[0] = outputLatency;
stream_.latency[1] = inputLatency;
}
// Setup the buffer conversion information structure. We don't use
// buffers to do channel offsets, so we override that parameter
// here.
if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
streamOpen = true;
return SUCCESS;
error:
if ( !isDuplexInput ) {
// the cleanup for error in the duplex input, is done by RtApi::openStream
// So we clean up for single channel only
if ( buffersAllocated )
ASIODisposeBuffers();
ASIOExit();
drivers.removeCurrentDriver();
if ( handle ) {
CloseHandle( handle->condition );
if ( handle->bufferInfos )
free( handle->bufferInfos );
delete handle;
stream_.apiHandle = 0;
}
if ( stream_.userBuffer[mode] ) {
free( stream_.userBuffer[mode] );
stream_.userBuffer[mode] = 0;
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
}
return FAILURE;
}
void RtApiAsio :: closeStream()
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
error( RTAUDIO_WARNING );
return;
}
if ( stream_.state == STREAM_RUNNING ) {
stream_.state = STREAM_STOPPED;
ASIOStop();
}
stream_.state = STREAM_CLOSED;
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
if ( info->deviceDisconnected ) {
// This could be either a disconnect or a sample rate change.
errorText_ = "RtApiAsio: the streaming device was disconnected or the sample rate changed, closing stream!";
error( RTAUDIO_DEVICE_DISCONNECT );
}
ASIODisposeBuffers();
ASIOExit();
drivers.removeCurrentDriver();
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
if ( handle ) {
CloseHandle( handle->condition );
if ( handle->bufferInfos )
free( handle->bufferInfos );
delete handle;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
clearStreamInfo();
streamOpen = false;
//stream_.mode = UNINITIALIZED;
//stream_.state = STREAM_CLOSED;
}
RtAudioErrorType RtApiAsio :: startStream()
{
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiAsio::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiAsio::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
ASIOError result = ASIOStart();
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
errorText_ = errorStream_.str();
goto unlock;
}
handle->drainCounter = 0;
handle->internalDrain = false;
ResetEvent( handle->condition );
stream_.state = STREAM_RUNNING;
asioXRun = false;
unlock:
if ( result == ASE_OK ) return RTAUDIO_NO_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
RtAudioErrorType RtApiAsio :: stopStream()
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiAsio::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( handle->drainCounter == 0 ) {
handle->drainCounter = 2;
WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
}
}
stream_.state = STREAM_STOPPED;
ASIOError result = ASIOStop();
if ( result != ASE_OK ) {
errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
errorText_ = errorStream_.str();
}
if ( result == ASE_OK ) return RTAUDIO_NO_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
RtAudioErrorType RtApiAsio :: abortStream()
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiAsio::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
// The following lines were commented-out because some behavior was
// noted where the device buffers need to be zeroed to avoid
// continuing sound, even when the device buffers are completely
// disposed. So now, calling abort is the same as calling stop.
// AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
// handle->drainCounter = 2;
stopStream();
return RTAUDIO_NO_ERROR;
}
// This function will be called by a spawned thread when: 1. The user
// callback function signals that the stream should be stopped or
// aborted; or 2. When a signal is received indicating that the device
// sample rate has changed or it has been disconnected. It is
// necessary to handle it this way because the callbackEvent() or
// signaling function must return before the ASIOStop() function will
// return (or the driver can be removed).
static unsigned __stdcall asioStopStream( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiAsio *object = (RtApiAsio *) info->object;
if ( info->deviceDisconnected == false )
object->stopStream(); // drain the stream
else
object->closeStream(); // disconnect or sample rate change ... close the stream
_endthreadex( 0 );
return 0;
}
bool RtApiAsio :: callbackEvent( long bufferIndex )
{
if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
error( RTAUDIO_WARNING );
return FAILURE;
}
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
// Check if we were draining the stream and signal if finished.
if ( handle->drainCounter > 3 ) {
stream_.state = STREAM_STOPPING;
if ( handle->internalDrain == false )
SetEvent( handle->condition );
else { // spawn a thread to stop the stream
unsigned threadId;
stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
&stream_.callbackInfo, 0, &threadId );
}
return SUCCESS;
}
// Invoke user callback to get fresh output data UNLESS we are
// draining stream.
if ( handle->drainCounter == 0 ) {
RtAudioCallback callback = (RtAudioCallback) info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if ( stream_.mode != INPUT && asioXRun == true ) {
status |= RTAUDIO_OUTPUT_UNDERFLOW;
asioXRun = false;
}
if ( stream_.mode != OUTPUT && asioXRun == true ) {
status |= RTAUDIO_INPUT_OVERFLOW;
asioXRun = false;
}
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData );
if ( cbReturnValue == 2 ) {
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
unsigned threadId;
stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
&stream_.callbackInfo, 0, &threadId );
return SUCCESS;
}
else if ( cbReturnValue == 1 ) {
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
unsigned int nChannels, bufferBytes, i, j;
nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
if ( handle->drainCounter > 1 ) { // write zeros to the output stream
for ( i=0, j=0; i<nChannels; i++ ) {
if ( handle->bufferInfos[i].isInput != ASIOTrue )
memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
}
}
else if ( stream_.doConvertBuffer[0] ) {
convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
if ( stream_.doByteSwap[0] )
byteSwapBuffer( stream_.deviceBuffer,
stream_.bufferSize * stream_.nDeviceChannels[0],
stream_.deviceFormat[0] );
for ( i=0, j=0; i<nChannels; i++ ) {
if ( handle->bufferInfos[i].isInput != ASIOTrue )
memcpy( handle->bufferInfos[i].buffers[bufferIndex],
&stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
}
}
else {
if ( stream_.doByteSwap[0] )
byteSwapBuffer( stream_.userBuffer[0],
stream_.bufferSize * stream_.nUserChannels[0],
stream_.userFormat );
for ( i=0, j=0; i<nChannels; i++ ) {
if ( handle->bufferInfos[i].isInput != ASIOTrue )
memcpy( handle->bufferInfos[i].buffers[bufferIndex],
&stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
}
}
}
// Don't bother draining input
if ( handle->drainCounter ) {
handle->drainCounter++;
goto unlock;
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
if (stream_.doConvertBuffer[1]) {
// Always interleave ASIO input data.
for ( i=0, j=0; i<nChannels; i++ ) {
if ( handle->bufferInfos[i].isInput == ASIOTrue )
memcpy( &stream_.deviceBuffer[j++*bufferBytes],
handle->bufferInfos[i].buffers[bufferIndex],
bufferBytes );
}
if ( stream_.doByteSwap[1] )
byteSwapBuffer( stream_.deviceBuffer,
stream_.bufferSize * stream_.nDeviceChannels[1],
stream_.deviceFormat[1] );
convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
}
else {
for ( i=0, j=0; i<nChannels; i++ ) {
if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
memcpy( &stream_.userBuffer[1][bufferBytes*j++],
handle->bufferInfos[i].buffers[bufferIndex],
bufferBytes );
}
}
if ( stream_.doByteSwap[1] )
byteSwapBuffer( stream_.userBuffer[1],
stream_.bufferSize * stream_.nUserChannels[1],
stream_.userFormat );
}
}
unlock:
// The following call was suggested by Malte Clasen. While the API
// documentation indicates it should not be required, some device
// drivers apparently do not function correctly without it.
ASIOOutputReady();
RtApi::tickStreamTime();
return SUCCESS;
}
static void sampleRateChanged( ASIOSampleRate sRate )
{
// The ASIO documentation says that this usually only happens during
// external sync. Audio processing is not stopped by the driver,
// actual sample rate might not have even changed, maybe only the
// sample rate status of an AES/EBU or S/PDIF digital input at the
// audio device.
RtApi *object = (RtApi *) asioCallbackInfo->object;
if ( object->getStreamSampleRate() != sRate ) {
asioCallbackInfo->deviceDisconnected = true; // flag for either rate change or disconnect
unsigned threadId;
asioCallbackInfo->thread = _beginthreadex( NULL, 0, &asioStopStream,
asioCallbackInfo, 0, &threadId );
}
}
static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
{
long ret = 0;
switch( selector ) {
case kAsioSelectorSupported:
if ( value == kAsioResetRequest
|| value == kAsioEngineVersion
|| value == kAsioResyncRequest
|| value == kAsioLatenciesChanged
// The following three were added for ASIO 2.0, you don't
// necessarily have to support them.
|| value == kAsioSupportsTimeInfo
|| value == kAsioSupportsTimeCode
|| value == kAsioSupportsInputMonitor)
ret = 1L;
break;
case kAsioResetRequest:
// This message is received when a device is disconnected (and
// perhaps when the sample rate changes). It indicates that the
// driver should be reset, which is accomplished by calling
// ASIOStop(), ASIODisposeBuffers() and removing the driver. But
// since this message comes from the driver, we need to let this
// function return before attempting to close the stream and
// remove the driver. Thus, we invoke a thread to initiate the
// stream closing.
asioCallbackInfo->deviceDisconnected = true; // flag for either rate change or disconnect
unsigned threadId;
asioCallbackInfo->thread = _beginthreadex( NULL, 0, &asioStopStream,
asioCallbackInfo, 0, &threadId );
//std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
ret = 1L;
break;
case kAsioResyncRequest:
// This informs the application that the driver encountered some
// non-fatal data loss. It is used for synchronization purposes
// of different media. Added mainly to work around the Win16Mutex
// problems in Windows 95/98 with the Windows Multimedia system,
// which could lose data because the Mutex was held too long by
// another thread. However a driver can issue it in other
// situations, too.
// std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
asioXRun = true;
ret = 1L;
break;
case kAsioLatenciesChanged:
// This will inform the host application that the drivers were
// latencies changed. Beware, it this does not mean that the
// buffer sizes have changed! You might need to update internal
// delay data.
std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
ret = 1L;
break;
case kAsioEngineVersion:
// Return the supported ASIO version of the host application. If
// a host application does not implement this selector, ASIO 1.0
// is assumed by the driver.
ret = 2L;
break;
case kAsioSupportsTimeInfo:
// Informs the driver whether the
// asioCallbacks.bufferSwitchTimeInfo() callback is supported.
// For compatibility with ASIO 1.0 drivers the host application
// should always support the "old" bufferSwitch method, too.
ret = 0;
break;
case kAsioSupportsTimeCode:
// Informs the driver whether application is interested in time
// code info. If an application does not need to know about time
// code, the driver has less work to do.
ret = 0;
break;
}
return ret;
}
static const char* getAsioErrorString( ASIOError result )
{
struct Messages
{
ASIOError value;
const char*message;
};
static const Messages m[] =
{
{ ASE_NotPresent, "Hardware input or output is not present or available." },
{ ASE_HWMalfunction, "Hardware is malfunctioning." },
{ ASE_InvalidParameter, "Invalid input parameter." },
{ ASE_InvalidMode, "Invalid mode." },
{ ASE_SPNotAdvancing, "Sample position not advancing." },
{ ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
{ ASE_NoMemory, "Not enough memory to complete the request." }
};
for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
if ( m[i].value == result ) return m[i].message;
return "Unknown error.";
}
//******************** End of __WINDOWS_ASIO__ *********************//
#endif
#if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
// Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
// Updates for new device selection scheme by Gary Scavone, January 2022
// - Introduces support for the Windows WASAPI API
// - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
// - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
// - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
#ifndef INITGUID
#define INITGUID
#endif
#include <mfapi.h>
#include <mferror.h>
#include <mfplay.h>
#include <mftransform.h>
#include <wmcodecdsp.h>
#include <audioclient.h>
#include <avrt.h>
#include <mmdeviceapi.h>
#include <functiondiscoverykeys_devpkey.h>
#ifndef MF_E_TRANSFORM_NEED_MORE_INPUT
#define MF_E_TRANSFORM_NEED_MORE_INPUT _HRESULT_TYPEDEF_(0xc00d6d72)
#endif
#ifndef MFSTARTUP_NOSOCKET
#define MFSTARTUP_NOSOCKET 0x1
#endif
#ifdef _MSC_VER
#pragma comment( lib, "ksuser" )
#pragma comment( lib, "mfplat.lib" )
#pragma comment( lib, "mfuuid.lib" )
#pragma comment( lib, "wmcodecdspuuid" )
#endif
//=============================================================================
#define SAFE_RELEASE( objectPtr )\
if ( objectPtr )\
{\
objectPtr->Release();\
objectPtr = NULL;\
}
typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
#ifndef __IAudioClient3_INTERFACE_DEFINED__
MIDL_INTERFACE( "00000000-0000-0000-0000-000000000000" ) IAudioClient3
{
virtual HRESULT GetSharedModeEnginePeriod( WAVEFORMATEX*, UINT32*, UINT32*, UINT32*, UINT32* ) = 0;
virtual HRESULT InitializeSharedAudioStream( DWORD, UINT32, WAVEFORMATEX*, LPCGUID ) = 0;
virtual HRESULT Release() = 0;
};
#ifdef __CRT_UUID_DECL
__CRT_UUID_DECL( IAudioClient3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 )
#endif
#endif
//-----------------------------------------------------------------------------
// WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
// Therefore we must perform all necessary conversions to user buffers in order to satisfy these
// requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
// provide intermediate storage for read / write synchronization.
class WasapiBuffer
{
public:
WasapiBuffer()
: buffer_( NULL ),
bufferSize_( 0 ),
inIndex_( 0 ),
outIndex_( 0 ) {}
~WasapiBuffer() {
free( buffer_ );
}
// sets the length of the internal ring buffer
void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
free( buffer_ );
buffer_ = ( char* ) calloc( bufferSize, formatBytes );
bufferSize_ = bufferSize;
inIndex_ = 0;
outIndex_ = 0;
}
// attempt to push a buffer into the ring buffer at the current "in" index
bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
{
if ( !buffer || // incoming buffer is NULL
bufferSize == 0 || // incoming buffer has no data
bufferSize > bufferSize_ ) // incoming buffer too large
{
return false;
}
unsigned int relOutIndex = outIndex_;
unsigned int inIndexEnd = inIndex_ + bufferSize;
if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
relOutIndex += bufferSize_;
}
// the "IN" index CAN BEGIN at the "OUT" index
// the "IN" index CANNOT END at the "OUT" index
if ( inIndex_ < relOutIndex && inIndexEnd >= relOutIndex ) {
return false; // not enough space between "in" index and "out" index
}
// copy buffer from external to internal
int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
int fromInSize = bufferSize - fromZeroSize;
switch( format )
{
case RTAUDIO_SINT8:
memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
break;
case RTAUDIO_SINT16:
memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
break;
case RTAUDIO_SINT24:
memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
break;
case RTAUDIO_SINT32:
memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
break;
case RTAUDIO_FLOAT32:
memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
break;
case RTAUDIO_FLOAT64:
memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
break;
}
// update "in" index
inIndex_ += bufferSize;
inIndex_ %= bufferSize_;
return true;
}
// attempt to pull a buffer from the ring buffer from the current "out" index
bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
{
if ( !buffer || // incoming buffer is NULL
bufferSize == 0 || // incoming buffer has no data
bufferSize > bufferSize_ ) // incoming buffer too large
{
return false;
}
unsigned int relInIndex = inIndex_;
unsigned int outIndexEnd = outIndex_ + bufferSize;
if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
relInIndex += bufferSize_;
}
// the "OUT" index CANNOT BEGIN at the "IN" index
// the "OUT" index CAN END at the "IN" index
if ( outIndex_ <= relInIndex && outIndexEnd > relInIndex ) {
return false; // not enough space between "out" index and "in" index
}
// copy buffer from internal to external
int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
int fromOutSize = bufferSize - fromZeroSize;
switch( format )
{
case RTAUDIO_SINT8:
memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
break;
case RTAUDIO_SINT16:
memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
break;
case RTAUDIO_SINT24:
memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
break;
case RTAUDIO_SINT32:
memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
break;
case RTAUDIO_FLOAT32:
memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
break;
case RTAUDIO_FLOAT64:
memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
break;
}
// update "out" index
outIndex_ += bufferSize;
outIndex_ %= bufferSize_;
return true;
}
private:
char* buffer_;
unsigned int bufferSize_;
unsigned int inIndex_;
unsigned int outIndex_;
};
//-----------------------------------------------------------------------------
// In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate
// between HW and the user. The WasapiResampler class is used to perform this conversion between
// HwIn->UserIn and UserOut->HwOut during the stream callback loop.
class WasapiResampler
{
public:
WasapiResampler( bool isFloat, unsigned int bitsPerSample, unsigned int channelCount,
unsigned int inSampleRate, unsigned int outSampleRate )
: _bytesPerSample( bitsPerSample / 8 )
, _channelCount( channelCount )
, _sampleRatio( ( float ) outSampleRate / inSampleRate )
, _transformUnk( NULL )
, _transform( NULL )
, _mediaType( NULL )
, _inputMediaType( NULL )
, _outputMediaType( NULL )
#ifdef __IWMResamplerProps_FWD_DEFINED__
, _resamplerProps( NULL )
#endif
{
// 1. Initialization
MFStartup( MF_VERSION, MFSTARTUP_NOSOCKET );
// 2. Create Resampler Transform Object
CoCreateInstance( CLSID_CResamplerMediaObject, NULL, CLSCTX_INPROC_SERVER,
IID_IUnknown, ( void** ) &_transformUnk );
_transformUnk->QueryInterface( IID_PPV_ARGS( &_transform ) );
#ifdef __IWMResamplerProps_FWD_DEFINED__
_transformUnk->QueryInterface( IID_PPV_ARGS( &_resamplerProps ) );
_resamplerProps->SetHalfFilterLength( 60 ); // best conversion quality
#endif
// 3. Specify input / output format
MFCreateMediaType( &_mediaType );
_mediaType->SetGUID( MF_MT_MAJOR_TYPE, MFMediaType_Audio );
_mediaType->SetGUID( MF_MT_SUBTYPE, isFloat ? MFAudioFormat_Float : MFAudioFormat_PCM );
_mediaType->SetUINT32( MF_MT_AUDIO_NUM_CHANNELS, channelCount );
_mediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, inSampleRate );
_mediaType->SetUINT32( MF_MT_AUDIO_BLOCK_ALIGNMENT, _bytesPerSample * channelCount );
_mediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * inSampleRate );
_mediaType->SetUINT32( MF_MT_AUDIO_BITS_PER_SAMPLE, bitsPerSample );
_mediaType->SetUINT32( MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE );
MFCreateMediaType( &_inputMediaType );
_mediaType->CopyAllItems( _inputMediaType );
_transform->SetInputType( 0, _inputMediaType, 0 );
MFCreateMediaType( &_outputMediaType );
_mediaType->CopyAllItems( _outputMediaType );
_outputMediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, outSampleRate );
_outputMediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * outSampleRate );
_transform->SetOutputType( 0, _outputMediaType, 0 );
// 4. Send stream start messages to Resampler
_transform->ProcessMessage( MFT_MESSAGE_COMMAND_FLUSH, 0 );
_transform->ProcessMessage( MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0 );
_transform->ProcessMessage( MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0 );
}
~WasapiResampler()
{
// 8. Send stream stop messages to Resampler
_transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0 );
_transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_STREAMING, 0 );
// 9. Cleanup
MFShutdown();
SAFE_RELEASE( _transformUnk );
SAFE_RELEASE( _transform );
SAFE_RELEASE( _mediaType );
SAFE_RELEASE( _inputMediaType );
SAFE_RELEASE( _outputMediaType );
#ifdef __IWMResamplerProps_FWD_DEFINED__
SAFE_RELEASE( _resamplerProps );
#endif
}
void Convert( char* outBuffer, const char* inBuffer, unsigned int inSampleCount, unsigned int& outSampleCount, int maxOutSampleCount = -1 )
{
unsigned int inputBufferSize = _bytesPerSample * _channelCount * inSampleCount;
if ( _sampleRatio == 1 )
{
// no sample rate conversion required
memcpy( outBuffer, inBuffer, inputBufferSize );
outSampleCount = inSampleCount;
return;
}
unsigned int outputBufferSize = 0;
if ( maxOutSampleCount != -1 )
{
outputBufferSize = _bytesPerSample * _channelCount * maxOutSampleCount;
}
else
{
outputBufferSize = ( unsigned int ) ceilf( inputBufferSize * _sampleRatio ) + ( _bytesPerSample * _channelCount );
}
IMFMediaBuffer* rInBuffer;
IMFSample* rInSample;
BYTE* rInByteBuffer = NULL;
// 5. Create Sample object from input data
MFCreateMemoryBuffer( inputBufferSize, &rInBuffer );
rInBuffer->Lock( &rInByteBuffer, NULL, NULL );
memcpy( rInByteBuffer, inBuffer, inputBufferSize );
rInBuffer->Unlock();
rInByteBuffer = NULL;
rInBuffer->SetCurrentLength( inputBufferSize );
MFCreateSample( &rInSample );
rInSample->AddBuffer( rInBuffer );
// 6. Pass input data to Resampler
_transform->ProcessInput( 0, rInSample, 0 );
SAFE_RELEASE( rInBuffer );
SAFE_RELEASE( rInSample );
// 7. Perform sample rate conversion
IMFMediaBuffer* rOutBuffer = NULL;
BYTE* rOutByteBuffer = NULL;
MFT_OUTPUT_DATA_BUFFER rOutDataBuffer;
DWORD rStatus;
DWORD rBytes = outputBufferSize; // maximum bytes accepted per ProcessOutput
// 7.1 Create Sample object for output data
memset( &rOutDataBuffer, 0, sizeof rOutDataBuffer );
MFCreateSample( &( rOutDataBuffer.pSample ) );
MFCreateMemoryBuffer( rBytes, &rOutBuffer );
rOutDataBuffer.pSample->AddBuffer( rOutBuffer );
rOutDataBuffer.dwStreamID = 0;
rOutDataBuffer.dwStatus = 0;
rOutDataBuffer.pEvents = NULL;
// 7.2 Get output data from Resampler
if ( _transform->ProcessOutput( 0, 1, &rOutDataBuffer, &rStatus ) == MF_E_TRANSFORM_NEED_MORE_INPUT )
{
outSampleCount = 0;
SAFE_RELEASE( rOutBuffer );
SAFE_RELEASE( rOutDataBuffer.pSample );
return;
}
// 7.3 Write output data to outBuffer
SAFE_RELEASE( rOutBuffer );
rOutDataBuffer.pSample->ConvertToContiguousBuffer( &rOutBuffer );
rOutBuffer->GetCurrentLength( &rBytes );
rOutBuffer->Lock( &rOutByteBuffer, NULL, NULL );
memcpy( outBuffer, rOutByteBuffer, rBytes );
rOutBuffer->Unlock();
rOutByteBuffer = NULL;
outSampleCount = rBytes / _bytesPerSample / _channelCount;
SAFE_RELEASE( rOutBuffer );
SAFE_RELEASE( rOutDataBuffer.pSample );
}
private:
unsigned int _bytesPerSample;
unsigned int _channelCount;
float _sampleRatio;
IUnknown* _transformUnk;
IMFTransform* _transform;
IMFMediaType* _mediaType;
IMFMediaType* _inputMediaType;
IMFMediaType* _outputMediaType;
#ifdef __IWMResamplerProps_FWD_DEFINED__
IWMResamplerProps* _resamplerProps;
#endif
};
//-----------------------------------------------------------------------------
// A structure to hold various information related to the WASAPI implementation.
struct WasapiHandle
{
IAudioClient* captureAudioClient;
IAudioClient* renderAudioClient;
IAudioCaptureClient* captureClient;
IAudioRenderClient* renderClient;
HANDLE captureEvent;
HANDLE renderEvent;
WasapiHandle()
: captureAudioClient( NULL ),
renderAudioClient( NULL ),
captureClient( NULL ),
renderClient( NULL ),
captureEvent( NULL ),
renderEvent( NULL ) {}
};
//-----------------------------------------------------------------------------
RtApiWasapi::RtApiWasapi()
: coInitialized_( false ), deviceEnumerator_( NULL )
{
// WASAPI can run either apartment or multi-threaded
HRESULT hr = CoInitialize( NULL );
if ( !FAILED( hr ) )
coInitialized_ = true;
// Instantiate device enumerator
hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
( void** ) &deviceEnumerator_ );
// If this runs on an old Windows, it will fail. Ignore and proceed.
if ( FAILED( hr ) )
deviceEnumerator_ = NULL;
}
//-----------------------------------------------------------------------------
RtApiWasapi::~RtApiWasapi()
{
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state != STREAM_CLOSED )
{
MUTEX_UNLOCK( &stream_.mutex );
closeStream();
MUTEX_LOCK( &stream_.mutex );
}
SAFE_RELEASE( deviceEnumerator_ );
// If this object previously called CoInitialize()
if ( coInitialized_ )
CoUninitialize();
MUTEX_UNLOCK( &stream_.mutex );
}
//-----------------------------------------------------------------------------
unsigned int RtApiWasapi::getDefaultInputDevice( void )
{
IMMDevice* devicePtr = NULL;
LPWSTR defaultId = NULL;
std::string id;
if ( !deviceEnumerator_ ) return 0; // invalid ID
errorText_.clear();
// Get the default capture device Id.
HRESULT hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &devicePtr );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::getDefaultInputDevice: Unable to retrieve default capture device handle.";
goto Release;
}
hr = devicePtr->GetId( &defaultId );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::getDefaultInputDevice: Unable to get default capture device Id.";
goto Release;
}
id = convertCharPointerToStdString( defaultId );
Release:
SAFE_RELEASE( devicePtr );
CoTaskMemFree( defaultId );
if ( !errorText_.empty() ) {
error( RTAUDIO_DRIVER_ERROR );
return 0;
}
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m].first == id ) {
if ( deviceList_[m].isDefaultInput == false ) {
deviceList_[m].isDefaultInput = true;
for ( unsigned int j=m+1; j<deviceIds_.size(); j++ ) {
// make sure any remaining devices are not listed as the default
deviceList_[j].isDefaultInput = false;
}
}
return deviceList_[m].ID;
}
deviceList_[m].isDefaultInput = false;
}
// If not found above, then do system probe of devices and try again.
probeDevices();
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m].first == id ) return deviceList_[m].ID;
}
return 0;
}
//-----------------------------------------------------------------------------
unsigned int RtApiWasapi::getDefaultOutputDevice( void )
{
IMMDevice* devicePtr = NULL;
LPWSTR defaultId = NULL;
std::string id;
if ( !deviceEnumerator_ ) return 0; // invalid ID
errorText_.clear();
// Get the default render device Id.
HRESULT hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &devicePtr );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::getDefaultOutputDevice: Unable to retrieve default render device handle.";
goto Release;
}
hr = devicePtr->GetId( &defaultId );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::getDefaultOutputDevice: Unable to get default render device Id.";
goto Release;
}
id = convertCharPointerToStdString( defaultId );
Release:
SAFE_RELEASE( devicePtr );
CoTaskMemFree( defaultId );
if ( !errorText_.empty() ) {
error( RTAUDIO_DRIVER_ERROR );
return 0;
}
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m].first == id ) {
if ( deviceList_[m].isDefaultOutput == false ) {
deviceList_[m].isDefaultOutput = true;
for ( unsigned int j=m+1; j<deviceIds_.size(); j++ ) {
// make sure any remaining devices are not listed as the default
deviceList_[j].isDefaultOutput = false;
}
}
return deviceList_[m].ID;
}
deviceList_[m].isDefaultOutput = false;
}
// If not found above, then do system probe of devices and try again.
probeDevices();
for ( unsigned int m=0; m<deviceIds_.size(); m++ ) {
if ( deviceIds_[m].first == id ) return deviceList_[m].ID;
}
return 0;
}
//-----------------------------------------------------------------------------
void RtApiWasapi::probeDevices( void )
{
unsigned int captureDeviceCount = 0;
unsigned int renderDeviceCount = 0;
IMMDeviceCollection* captureDevices = NULL;
IMMDeviceCollection* renderDevices = NULL;
IMMDevice* devicePtr = NULL;
LPWSTR defaultCaptureId = NULL;
LPWSTR defaultRenderId = NULL;
std::string defaultCaptureString;
std::string defaultRenderString;
unsigned int nDevices;
bool isCaptureDevice = false;
std::vector< std::pair< std::string, bool> > ids;
LPWSTR deviceId = NULL;
if ( !deviceEnumerator_ ) return;
errorText_.clear();
// Count capture devices
HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to retrieve capture device collection.";
goto Exit;
}
hr = captureDevices->GetCount( &captureDeviceCount );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to retrieve capture device count.";
goto Exit;
}
// Count render devices
hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to retrieve render device collection.";
goto Exit;
}
hr = renderDevices->GetCount( &renderDeviceCount );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to retrieve render device count.";
goto Exit;
}
nDevices = captureDeviceCount + renderDeviceCount;
if ( nDevices == 0 ) {
errorText_ = "RtApiWasapi::probeDevices: No devices found.";
goto Exit;
}
// Get the default capture device Id.
hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &devicePtr );
if ( SUCCEEDED( hr) ) {
hr = devicePtr->GetId( &defaultCaptureId );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to get default capture device Id.";
goto Exit;
}
defaultCaptureString = convertCharPointerToStdString( defaultCaptureId );
}
// Get the default render device Id.
SAFE_RELEASE( devicePtr );
hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &devicePtr );
if ( SUCCEEDED( hr) ) {
hr = devicePtr->GetId( &defaultRenderId );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to get default render device Id.";
goto Exit;
}
defaultRenderString = convertCharPointerToStdString( defaultRenderId );
}
// Collect device IDs with mode.
for ( unsigned int n=0; n<nDevices; n++ ) {
SAFE_RELEASE( devicePtr );
if ( n < renderDeviceCount ) {
hr = renderDevices->Item( n, &devicePtr );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to retrieve render device handle.";
error( RTAUDIO_WARNING );
continue;
}
}
else {
hr = captureDevices->Item( n - renderDeviceCount, &devicePtr );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to retrieve capture device handle.";
error( RTAUDIO_WARNING );
continue;
}
isCaptureDevice = true;
}
hr = devicePtr->GetId( &deviceId );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDevices: Unable to get device Id.";
error( RTAUDIO_WARNING );
continue;
}
ids.push_back( std::pair< std::string, bool>(convertCharPointerToStdString(deviceId), isCaptureDevice) );
CoTaskMemFree( deviceId );
}
// Fill or update the deviceList_ and also save a corresponding list of Ids.
for ( unsigned int n=0; n<ids.size(); n++ ) {
if ( std::find( deviceIds_.begin(), deviceIds_.end(), ids[n] ) != deviceIds_.end() ) {
continue; // We already have this device.
}
else { // There is a new device to probe.
RtAudio::DeviceInfo info;
std::wstring temp = std::wstring(ids[n].first.begin(), ids[n].first.end());
if ( probeDeviceInfo( info, (LPWSTR) temp.c_str(), ids[n].second ) == false ) continue; // ignore if probe fails
deviceIds_.push_back( ids[n] );
info.ID = currentDeviceId_++; // arbitrary internal device ID
deviceList_.push_back( info );
}
}
// Remove any devices left in the list that are no longer available.
unsigned int m;
for ( std::vector< std::pair< std::string, bool> >::iterator it=deviceIds_.begin(); it!=deviceIds_.end(); ) {
for ( m=0; m<ids.size(); m++ ) {
if ( ids[m] == *it ) {
++it;
break;
}
}
if ( m == ids.size() ) { // not found so remove it from our two lists
it = deviceIds_.erase(it);
deviceList_.erase( deviceList_.begin() + distance(deviceIds_.begin(), it ) );
}
}
// Set the default device flags in deviceList_.
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceIds_[m].first == defaultRenderString )
deviceList_[m].isDefaultOutput = true;
else
deviceList_[m].isDefaultOutput = false;
if ( deviceIds_[m].first == defaultCaptureString )
deviceList_[m].isDefaultInput = true;
else
deviceList_[m].isDefaultInput = false;
}
Exit:
// Release all references
SAFE_RELEASE( captureDevices );
SAFE_RELEASE( renderDevices );
SAFE_RELEASE( devicePtr );
CoTaskMemFree( defaultCaptureId );
CoTaskMemFree( defaultRenderId );
if ( !errorText_.empty() ) {
deviceList_.clear();
deviceIds_.clear();
error( RTAUDIO_DRIVER_ERROR );
}
return;
}
//-----------------------------------------------------------------------------
bool RtApiWasapi::probeDeviceInfo( RtAudio::DeviceInfo &info, LPWSTR deviceId, bool isCaptureDevice )
{
PROPVARIANT deviceNameProp;
IMMDevice* devicePtr = NULL;
IAudioClient* audioClient = NULL;
IPropertyStore* devicePropStore = NULL;
WAVEFORMATEX* deviceFormat = NULL;
WAVEFORMATEX* closestMatchFormat = NULL;
errorText_.clear();
RtAudioErrorType errorType = RTAUDIO_DRIVER_ERROR;
// Get the device pointer from the device Id
HRESULT hr = deviceEnumerator_->GetDevice( deviceId, &devicePtr );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceInfo: Unable to retrieve device handle.";
goto Exit;
}
// Get device name
hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceInfo: Unable to open device property store.";
goto Exit;
}
PropVariantInit( &deviceNameProp );
hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
if ( FAILED( hr ) || deviceNameProp.pwszVal == nullptr ) {
errorText_ = "RtApiWasapi::probeDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
goto Exit;
}
info.name = convertCharPointerToStdString( deviceNameProp.pwszVal );
// Get audio client
hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceInfo: Unable to retrieve device audio client.";
goto Exit;
}
hr = audioClient->GetMixFormat( &deviceFormat );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceInfo: Unable to retrieve device mix format.";
goto Exit;
}
// Set channel count
if ( isCaptureDevice ) {
info.inputChannels = deviceFormat->nChannels;
info.outputChannels = 0;
info.duplexChannels = 0;
}
else {
info.inputChannels = 0;
info.outputChannels = deviceFormat->nChannels;
info.duplexChannels = 0;
}
// Set sample rates
info.sampleRates.clear();
// Allow support for all sample rates as we have a built-in sample rate converter.
for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {
info.sampleRates.push_back( SAMPLE_RATES[i] );
}
info.preferredSampleRate = deviceFormat->nSamplesPerSec;
// Set native formats
info.nativeFormats = 0;
if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
{
if ( deviceFormat->wBitsPerSample == 32 ) {
info.nativeFormats |= RTAUDIO_FLOAT32;
}
else if ( deviceFormat->wBitsPerSample == 64 ) {
info.nativeFormats |= RTAUDIO_FLOAT64;
}
}
else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
{
if ( deviceFormat->wBitsPerSample == 8 ) {
info.nativeFormats |= RTAUDIO_SINT8;
}
else if ( deviceFormat->wBitsPerSample == 16 ) {
info.nativeFormats |= RTAUDIO_SINT16;
}
else if ( deviceFormat->wBitsPerSample == 24 ) {
info.nativeFormats |= RTAUDIO_SINT24;
}
else if ( deviceFormat->wBitsPerSample == 32 ) {
info.nativeFormats |= RTAUDIO_SINT32;
}
}
Exit:
// Release all references
PropVariantClear( &deviceNameProp );
SAFE_RELEASE( devicePtr );
SAFE_RELEASE( audioClient );
SAFE_RELEASE( devicePropStore );
CoTaskMemFree( deviceFormat );
CoTaskMemFree( closestMatchFormat );
if ( !errorText_.empty() ) {
error( errorType );
return false;
}
return true;
}
void RtApiWasapi::closeStream( void )
{
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
error( RTAUDIO_WARNING );
MUTEX_UNLOCK( &stream_.mutex );
return;
}
if ( stream_.state != STREAM_STOPPED )
{
MUTEX_UNLOCK( &stream_.mutex );
stopStream();
MUTEX_LOCK( &stream_.mutex );
}
// clean up stream memory
SAFE_RELEASE(((WasapiHandle*)stream_.apiHandle)->captureClient)
SAFE_RELEASE(((WasapiHandle*)stream_.apiHandle)->renderClient)
SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
delete ( WasapiHandle* ) stream_.apiHandle;
stream_.apiHandle = NULL;
for ( int i = 0; i < 2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
clearStreamInfo();
MUTEX_UNLOCK( &stream_.mutex );
}
//-----------------------------------------------------------------------------
RtAudioErrorType RtApiWasapi::startStream( void )
{
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiWasapi::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiWasapi::startStream(): the stream is stopping or closed!";
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_WARNING );
}
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
// update stream state
stream_.state = STREAM_RUNNING;
// create WASAPI stream thread
stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
if ( !stream_.callbackInfo.thread ) {
errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_THREAD_ERROR );
}
else {
SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
ResumeThread( ( void* ) stream_.callbackInfo.thread );
}
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
//-----------------------------------------------------------------------------
RtAudioErrorType RtApiWasapi::stopStream( void )
{
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiWasapi::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiWasapi::stopStream(): the stream is closed!";
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_WARNING );
}
// inform stream thread by setting stream state to STREAM_STOPPING
stream_.state = STREAM_STOPPING;
WaitForSingleObject( ( void* ) stream_.callbackInfo.thread, INFINITE );
// close thread handle
if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_THREAD_ERROR );
}
stream_.callbackInfo.thread = (ThreadHandle) NULL;
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
//-----------------------------------------------------------------------------
RtAudioErrorType RtApiWasapi::abortStream( void )
{
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiWasapi::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiWasapi::abortStream(): the stream is stopping or closed!";
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_WARNING );
}
// inform stream thread by setting stream state to STREAM_STOPPING
stream_.state = STREAM_STOPPING;
WaitForSingleObject( ( void* ) stream_.callbackInfo.thread, INFINITE );
// close thread handle
if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_THREAD_ERROR );
}
stream_.callbackInfo.thread = (ThreadHandle) NULL;
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
//-----------------------------------------------------------------------------
bool RtApiWasapi::probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int* bufferSize,
RtAudio::StreamOptions* options )
{
MUTEX_LOCK( &stream_.mutex );
bool methodResult = FAILURE;
IMMDevice* devicePtr = NULL;
WAVEFORMATEX* deviceFormat = NULL;
unsigned int bufferBytes;
stream_.state = STREAM_STOPPED;
bool isInput = false;
std::string id;
unsigned int deviceIdx;
for ( deviceIdx=0; deviceIdx<deviceList_.size(); deviceIdx++ ) {
if ( deviceList_[deviceIdx].ID == deviceId ) {
id = deviceIds_[deviceIdx].first;
if ( deviceIds_[deviceIdx].second ) isInput = true;
break;
}
}
errorText_.clear();
RtAudioErrorType errorType = RTAUDIO_INVALID_USE;
if ( id.empty() ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: the device ID was not found!";
MUTEX_UNLOCK( &stream_.mutex );
return FAILURE;
}
if ( isInput && mode != INPUT ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: deviceId specified does not support output mode.";
MUTEX_UNLOCK( &stream_.mutex );
return FAILURE;
}
// Get the device pointer from the device Id
errorType = RTAUDIO_DRIVER_ERROR;
std::wstring temp = std::wstring(id.begin(), id.end());
HRESULT hr = deviceEnumerator_->GetDevice( (LPWSTR)temp.c_str(), &devicePtr );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device handle.";
MUTEX_UNLOCK( &stream_.mutex );
return FAILURE;
}
// Create API handle if not already created.
if ( !stream_.apiHandle )
stream_.apiHandle = ( void* ) new WasapiHandle();
if ( isInput ) {
IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
NULL, ( void** ) &captureAudioClient );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device audio client.";
goto Exit;
}
hr = captureAudioClient->GetMixFormat( &deviceFormat );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device mix format.";
goto Exit;
}
stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
}
// If an output device and is configured for loopback (input mode)
if ( isInput == false && mode == INPUT ) {
// If renderAudioClient is not initialised, initialise it now
IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
if ( !renderAudioClient ) {
MUTEX_UNLOCK( &stream_.mutex );
probeDeviceOpen( deviceId, OUTPUT, channels, firstChannel, sampleRate, format, bufferSize, options );
MUTEX_LOCK( &stream_.mutex );
}
// Retrieve captureAudioClient from our stream handle.
IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
NULL, ( void** ) &captureAudioClient );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
goto Exit;
}
hr = captureAudioClient->GetMixFormat( &deviceFormat );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
goto Exit;
}
stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
}
// If output device and is configured for output.
if ( isInput == false && mode == OUTPUT ) {
// If renderAudioClient is already initialised, don't initialise it again
IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
if ( renderAudioClient ) {
methodResult = SUCCESS;
goto Exit;
}
hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
NULL, ( void** ) &renderAudioClient );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
goto Exit;
}
hr = renderAudioClient->GetMixFormat( &deviceFormat );
if ( FAILED( hr ) ) {
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
goto Exit;
}
stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
}
// Fill stream data
if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
( stream_.mode == INPUT && mode == OUTPUT ) ) {
stream_.mode = DUPLEX;
}
else {
stream_.mode = mode;
}
stream_.deviceId[mode] = deviceId;
stream_.doByteSwap[mode] = false;
stream_.sampleRate = sampleRate;
stream_.bufferSize = *bufferSize;
stream_.nBuffers = 1;
stream_.nUserChannels[mode] = channels;
stream_.channelOffset[mode] = firstChannel;
stream_.userFormat = format;
stream_.deviceFormat[mode] = deviceList_[deviceIdx].nativeFormats;
if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] ||
stream_.nUserChannels[0] != stream_.nDeviceChannels[0] ||
stream_.nUserChannels[1] != stream_.nDeviceChannels[1] )
stream_.doConvertBuffer[mode] = true;
else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1 )
stream_.doConvertBuffer[mode] = true;
if ( stream_.doConvertBuffer[mode] )
setConvertInfo( mode, firstChannel );
// Allocate necessary internal buffers
bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
if ( !stream_.userBuffer[mode] ) {
errorType = RTAUDIO_MEMORY_ERROR;
errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
goto Exit;
}
if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
stream_.callbackInfo.priority = 15;
else
stream_.callbackInfo.priority = 0;
///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
methodResult = SUCCESS;
Exit:
//clean up
SAFE_RELEASE( devicePtr );
CoTaskMemFree( deviceFormat );
// if method failed, close the stream
if ( methodResult == FAILURE )
{
MUTEX_UNLOCK( &stream_.mutex );
closeStream();
MUTEX_LOCK( &stream_.mutex );
}
if ( !errorText_.empty() )
error( errorType );
MUTEX_UNLOCK( &stream_.mutex );
return methodResult;
}
//=============================================================================
DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
{
if ( wasapiPtr )
( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
return 0;
}
DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
{
if ( wasapiPtr )
( ( RtApiWasapi* ) wasapiPtr )->stopStream();
return 0;
}
DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
{
if ( wasapiPtr )
( ( RtApiWasapi* ) wasapiPtr )->abortStream();
return 0;
}
//-----------------------------------------------------------------------------
void RtApiWasapi::wasapiThread()
{
// as this is a new thread, we must CoInitialize it
CoInitialize( NULL );
HRESULT hr;
IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
WAVEFORMATEX* captureFormat = NULL;
WAVEFORMATEX* renderFormat = NULL;
float captureSrRatio = 0.0f;
float renderSrRatio = 0.0f;
WasapiBuffer captureBuffer;
WasapiBuffer renderBuffer;
WasapiResampler* captureResampler = NULL;
WasapiResampler* renderResampler = NULL;
// declare local stream variables
RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
BYTE* streamBuffer = NULL;
DWORD captureFlags = 0;
unsigned int bufferFrameCount = 0;
unsigned int numFramesPadding = 0;
unsigned int convBufferSize = 0;
bool loopbackEnabled = stream_.deviceId[INPUT] == stream_.deviceId[OUTPUT];
bool callbackPushed = true;
bool callbackPulled = false;
bool callbackStopped = false;
int callbackResult = 0;
// convBuffer is used to store converted buffers between WASAPI and the user
char* convBuffer = NULL;
unsigned int convBuffSize = 0;
unsigned int deviceBuffSize = 0;
std::string errorText;
RtAudioErrorType errorType = RTAUDIO_DRIVER_ERROR;
// Attempt to assign "Pro Audio" characteristic to thread
HMODULE AvrtDll = LoadLibraryW( L"AVRT.dll" );
if ( AvrtDll ) {
DWORD taskIndex = 0;
TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr =
( TAvSetMmThreadCharacteristicsPtr ) (void(*)()) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
FreeLibrary( AvrtDll );
}
// start capture stream if applicable
if ( captureAudioClient ) {
hr = captureAudioClient->GetMixFormat( &captureFormat );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
goto Exit;
}
// init captureResampler
captureResampler = new WasapiResampler( stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT64,
formatBytes( stream_.deviceFormat[INPUT] ) * 8, stream_.nDeviceChannels[INPUT],
captureFormat->nSamplesPerSec, stream_.sampleRate );
captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );
if ( !captureClient ) {
IAudioClient3* captureAudioClient3 = nullptr;
captureAudioClient->QueryInterface( __uuidof( IAudioClient3 ), ( void** ) &captureAudioClient3 );
if ( captureAudioClient3 && !loopbackEnabled )
{
UINT32 Ignore;
UINT32 MinPeriodInFrames;
hr = captureAudioClient3->GetSharedModeEnginePeriod( captureFormat,
&Ignore,
&Ignore,
&MinPeriodInFrames,
&Ignore );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
goto Exit;
}
hr = captureAudioClient3->InitializeSharedAudioStream( AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
MinPeriodInFrames,
captureFormat,
NULL );
SAFE_RELEASE(captureAudioClient3);
}
else
{
hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
loopbackEnabled ? AUDCLNT_STREAMFLAGS_LOOPBACK : AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
0,
0,
captureFormat,
NULL );
}
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
goto Exit;
}
hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
( void** ) &captureClient );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
goto Exit;
}
// don't configure captureEvent if in loopback mode
if ( !loopbackEnabled )
{
// configure captureEvent to trigger on every available capture buffer
captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
if ( !captureEvent ) {
errorType = RTAUDIO_SYSTEM_ERROR;
errorText = "RtApiWasapi::wasapiThread: Unable to create capture event.";
goto Exit;
}
hr = captureAudioClient->SetEventHandle( captureEvent );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
goto Exit;
}
( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
}
( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
// reset the capture stream
hr = captureAudioClient->Reset();
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
goto Exit;
}
// start the capture stream
hr = captureAudioClient->Start();
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
goto Exit;
}
}
unsigned int inBufferSize = 0;
hr = captureAudioClient->GetBufferSize( &inBufferSize );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
goto Exit;
}
// scale outBufferSize according to stream->user sample rate ratio
unsigned int outBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];
inBufferSize *= stream_.nDeviceChannels[INPUT];
// set captureBuffer size
captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
}
// start render stream if applicable
if ( renderAudioClient ) {
hr = renderAudioClient->GetMixFormat( &renderFormat );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
goto Exit;
}
// init renderResampler
renderResampler = new WasapiResampler( stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT64,
formatBytes( stream_.deviceFormat[OUTPUT] ) * 8, stream_.nDeviceChannels[OUTPUT],
stream_.sampleRate, renderFormat->nSamplesPerSec );
renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );
if ( !renderClient ) {
IAudioClient3* renderAudioClient3 = nullptr;
renderAudioClient->QueryInterface( __uuidof( IAudioClient3 ), ( void** ) &renderAudioClient3 );
if ( renderAudioClient3 )
{
UINT32 Ignore;
UINT32 MinPeriodInFrames;
hr = renderAudioClient3->GetSharedModeEnginePeriod( renderFormat,
&Ignore,
&Ignore,
&MinPeriodInFrames,
&Ignore );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
goto Exit;
}
hr = renderAudioClient3->InitializeSharedAudioStream( AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
MinPeriodInFrames,
renderFormat,
NULL );
SAFE_RELEASE(renderAudioClient3);
}
else
{
hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
0,
0,
renderFormat,
NULL );
}
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
goto Exit;
}
hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
( void** ) &renderClient );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
goto Exit;
}
// configure renderEvent to trigger on every available render buffer
renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
if ( !renderEvent ) {
errorType = RTAUDIO_SYSTEM_ERROR;
errorText = "RtApiWasapi::wasapiThread: Unable to create render event.";
goto Exit;
}
hr = renderAudioClient->SetEventHandle( renderEvent );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
goto Exit;
}
( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
// reset the render stream
hr = renderAudioClient->Reset();
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
goto Exit;
}
// start the render stream
hr = renderAudioClient->Start();
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to start render stream.";
goto Exit;
}
}
unsigned int outBufferSize = 0;
hr = renderAudioClient->GetBufferSize( &outBufferSize );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
goto Exit;
}
// scale inBufferSize according to user->stream sample rate ratio
unsigned int inBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];
outBufferSize *= stream_.nDeviceChannels[OUTPUT];
// set renderBuffer size
renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
}
// malloc buffer memory
if ( stream_.mode == INPUT )
{
using namespace std; // for ceilf
convBuffSize = ( unsigned int ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
}
else if ( stream_.mode == OUTPUT )
{
convBuffSize = ( unsigned int ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
}
else if ( stream_.mode == DUPLEX )
{
convBuffSize = std::max( ( unsigned int ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
( unsigned int ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
}
convBuffSize *= 2; // allow overflow for *SrRatio remainders
convBuffer = ( char* ) calloc( convBuffSize, 1 );
stream_.deviceBuffer = ( char* ) calloc( deviceBuffSize, 1 );
if ( !convBuffer || !stream_.deviceBuffer ) {
errorType = RTAUDIO_MEMORY_ERROR;
errorText = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
goto Exit;
}
// stream process loop
while ( stream_.state != STREAM_STOPPING ) {
if ( !callbackPulled ) {
// Callback Input
// ==============
// 1. Pull callback buffer from inputBuffer
// 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
// Convert callback buffer to user format
if ( captureAudioClient )
{
int samplesToPull = ( unsigned int ) floorf( stream_.bufferSize * captureSrRatio );
convBufferSize = 0;
while ( convBufferSize < stream_.bufferSize )
{
// Pull callback buffer from inputBuffer
callbackPulled = captureBuffer.pullBuffer( convBuffer,
samplesToPull * stream_.nDeviceChannels[INPUT],
stream_.deviceFormat[INPUT] );
if ( !callbackPulled )
{
break;
}
// Convert callback buffer to user sample rate
unsigned int deviceBufferOffset = convBufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
unsigned int convSamples = 0;
captureResampler->Convert( stream_.deviceBuffer + deviceBufferOffset,
convBuffer,
samplesToPull,
convSamples,
convBufferSize == 0 ? -1 : stream_.bufferSize - convBufferSize );
convBufferSize += convSamples;
samplesToPull = 1; // now pull one sample at a time until we have stream_.bufferSize samples
}
if ( callbackPulled )
{
if ( stream_.doConvertBuffer[INPUT] ) {
// Convert callback buffer to user format
convertBuffer( stream_.userBuffer[INPUT],
stream_.deviceBuffer,
stream_.convertInfo[INPUT] );
}
else {
// no further conversion, simple copy deviceBuffer to userBuffer
memcpy( stream_.userBuffer[INPUT],
stream_.deviceBuffer,
stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
}
}
}
else {
// if there is no capture stream, set callbackPulled flag
callbackPulled = true;
}
// Execute Callback
// ================
// 1. Execute user callback method
// 2. Handle return value from callback
// if callback has not requested the stream to stop
if ( callbackPulled && !callbackStopped ) {
// Execute user callback method
callbackResult = callback( stream_.userBuffer[OUTPUT],
stream_.userBuffer[INPUT],
stream_.bufferSize,
getStreamTime(),
captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
stream_.callbackInfo.userData );
// tick stream time
RtApi::tickStreamTime();
// Handle return value from callback
if ( callbackResult == 1 ) {
// instantiate a thread to stop this thread
HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
if ( !threadHandle ) {
errorType = RTAUDIO_THREAD_ERROR;
errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
goto Exit;
}
else if ( !CloseHandle( threadHandle ) ) {
errorType = RTAUDIO_THREAD_ERROR;
errorText = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
goto Exit;
}
callbackStopped = true;
}
else if ( callbackResult == 2 ) {
// instantiate a thread to stop this thread
HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
if ( !threadHandle ) {
errorType = RTAUDIO_THREAD_ERROR;
errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
goto Exit;
}
else if ( !CloseHandle( threadHandle ) ) {
errorType = RTAUDIO_THREAD_ERROR;
errorText = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
goto Exit;
}
callbackStopped = true;
}
}
}
// Callback Output
// ===============
// 1. Convert callback buffer to stream format
// 2. Convert callback buffer to stream sample rate and channel count
// 3. Push callback buffer into outputBuffer
if ( renderAudioClient && callbackPulled )
{
// if the last call to renderBuffer.PushBuffer() was successful
if ( callbackPushed || convBufferSize == 0 )
{
if ( stream_.doConvertBuffer[OUTPUT] )
{
// Convert callback buffer to stream format
convertBuffer( stream_.deviceBuffer,
stream_.userBuffer[OUTPUT],
stream_.convertInfo[OUTPUT] );
}
else {
// no further conversion, simple copy userBuffer to deviceBuffer
memcpy( stream_.deviceBuffer,
stream_.userBuffer[OUTPUT],
stream_.bufferSize * stream_.nUserChannels[OUTPUT] * formatBytes( stream_.userFormat ) );
}
// Convert callback buffer to stream sample rate
renderResampler->Convert( convBuffer,
stream_.deviceBuffer,
stream_.bufferSize,
convBufferSize );
}
// Push callback buffer into outputBuffer
callbackPushed = renderBuffer.pushBuffer( convBuffer,
convBufferSize * stream_.nDeviceChannels[OUTPUT],
stream_.deviceFormat[OUTPUT] );
}
else {
// if there is no render stream, set callbackPushed flag
callbackPushed = true;
}
// Stream Capture
// ==============
// 1. Get capture buffer from stream
// 2. Push capture buffer into inputBuffer
// 3. If 2. was successful: Release capture buffer
if ( captureAudioClient ) {
// if the callback input buffer was not pulled from captureBuffer, wait for next capture event
if ( !callbackPulled ) {
WaitForSingleObject( loopbackEnabled ? renderEvent : captureEvent, INFINITE );
}
// Get capture buffer from stream
hr = captureClient->GetBuffer( &streamBuffer,
&bufferFrameCount,
&captureFlags, NULL, NULL );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
goto Exit;
}
if ( bufferFrameCount != 0 ) {
// Push capture buffer into inputBuffer
if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
bufferFrameCount * stream_.nDeviceChannels[INPUT],
stream_.deviceFormat[INPUT] ) )
{
// Release capture buffer
hr = captureClient->ReleaseBuffer( bufferFrameCount );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
goto Exit;
}
}
else
{
// Inform WASAPI that capture was unsuccessful
hr = captureClient->ReleaseBuffer( 0 );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
goto Exit;
}
}
}
else
{
// Inform WASAPI that capture was unsuccessful
hr = captureClient->ReleaseBuffer( 0 );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
goto Exit;
}
}
}
// Stream Render
// =============
// 1. Get render buffer from stream
// 2. Pull next buffer from outputBuffer
// 3. If 2. was successful: Fill render buffer with next buffer
// Release render buffer
if ( renderAudioClient ) {
// if the callback output buffer was not pushed to renderBuffer, wait for next render event
if ( callbackPulled && !callbackPushed ) {
WaitForSingleObject( renderEvent, INFINITE );
}
// Get render buffer from stream
hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
goto Exit;
}
hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
goto Exit;
}
bufferFrameCount -= numFramesPadding;
if ( bufferFrameCount != 0 ) {
hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
goto Exit;
}
// Pull next buffer from outputBuffer
// Fill render buffer with next buffer
if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
stream_.deviceFormat[OUTPUT] ) )
{
// Release render buffer
hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
goto Exit;
}
}
else
{
// Inform WASAPI that render was unsuccessful
hr = renderClient->ReleaseBuffer( 0, 0 );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
goto Exit;
}
}
}
else
{
// Inform WASAPI that render was unsuccessful
hr = renderClient->ReleaseBuffer( 0, 0 );
if ( FAILED( hr ) ) {
errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
goto Exit;
}
}
}
// if the callback buffer was pushed renderBuffer reset callbackPulled flag
if ( callbackPushed ) {
// unsetting the callbackPulled flag lets the stream know that
// the audio device is ready for another callback output buffer.
callbackPulled = false;
}
}
Exit:
// clean up
CoTaskMemFree( captureFormat );
CoTaskMemFree( renderFormat );
free ( convBuffer );
delete renderResampler;
delete captureResampler;
CoUninitialize();
if ( !errorText.empty() )
{
errorText_ = errorText;
error( errorType );
}
// update stream state
stream_.state = STREAM_STOPPED;
}
//******************** End of __WINDOWS_WASAPI__ *********************//
#endif
#if defined(__WINDOWS_DS__) // Windows DirectSound API
// Modified by Robin Davies, October 2005
// - Improvements to DirectX pointer chasing.
// - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
// - Auto-call CoInitialize for DSOUND and ASIO platforms.
// Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
// Changed device query structure for RtAudio 4.0.7, January 2010
#include <windows.h>
#include <process.h>
#include <mmsystem.h>
#include <mmreg.h>
#include <dsound.h>
#include <assert.h>
#include <algorithm>
#if defined(__MINGW32__)
// missing from latest mingw winapi
#define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
#define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
#define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
#define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
#endif
#define MINIMUM_DEVICE_BUFFER_SIZE 32768
#ifdef _MSC_VER // if Microsoft Visual C++
#pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
#endif
static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
{
if ( pointer > bufferSize ) pointer -= bufferSize;
if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
if ( pointer < earlierPointer ) pointer += bufferSize;
return pointer >= earlierPointer && pointer < laterPointer;
}
// A structure to hold various information related to the DirectSound
// API implementation.
struct DsHandle {
unsigned int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
void *id[2];
void *buffer[2];
bool xrun[2];
UINT bufferPointer[2];
DWORD dsBufferSize[2];
DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
HANDLE condition;
DsHandle()
:drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }
};
// Declarations for utility functions, callbacks, and structures
// specific to the DirectSound implementation.
static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
LPCTSTR description,
LPCTSTR module,
LPVOID lpContext );
static const char* getErrorString( int code );
static unsigned __stdcall callbackHandler( void *ptr );
struct DsDevice {
LPGUID id;
bool isInput;
std::string name;
std::string epID; // endpoint ID
DsDevice()
: isInput(false) {}
};
struct DsProbeData {
bool isInput;
std::vector<struct DsDevice>* dsDevices;
};
RtApiDs :: RtApiDs()
{
// Dsound will run both-threaded. If CoInitialize fails, then just
// accept whatever the mainline chose for a threading model.
coInitialized_ = false;
HRESULT hr = CoInitialize( NULL );
if ( !FAILED( hr ) ) coInitialized_ = true;
}
RtApiDs :: ~RtApiDs()
{
if ( stream_.state != STREAM_CLOSED ) closeStream();
if ( coInitialized_ ) CoUninitialize(); // balanced call.
}
void RtApiDs :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
// Query DirectSound devices.
struct DsProbeData probeInfo;
probeInfo.isInput = false;
std::vector< struct DsDevice > devices;
probeInfo.dsDevices = &devices;
HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::probeDevices: error (" << getErrorString( result ) << ") enumerating output devices!";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
// Query DirectSoundCapture devices.
probeInfo.isInput = true;
result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::probeDevices: error (" << getErrorString( result ) << ") enumerating input devices!";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
// Now fill or update our deviceList_ vector.
unsigned int m, n;
for ( n=0; n<devices.size(); n++ ) {
for ( m=0; m<dsDevices_.size(); m++ ) {
if ( ( dsDevices_[m].epID == devices[n].epID ) && ( devices[n].isInput == dsDevices_[m].isInput ) ) {
dsDevices_[m].id = devices[n].id; // Update the ID, since it seems to change when devices are added/removed
break; // We already have this device.
}
}
if ( m == dsDevices_.size() ) { // new device
RtAudio::DeviceInfo info;
if ( probeDeviceInfo( info, devices[n] ) == false ) continue; // ignore if probe fails
info.ID = currentDeviceId_++; // arbitrary internal device ID
deviceList_.push_back( info );
dsDevices_.push_back( devices[n] );
}
}
// Remove any devices left in the list that are no longer available.
for ( std::vector< struct DsDevice >::iterator it=dsDevices_.begin(); it!=dsDevices_.end(); ) {
for ( n=0; n<devices.size(); n++ ) {
if ( (*it).epID == devices[n].epID ) {
++it;
break;
}
}
if ( n == devices.size() ) { // not found so remove it from our list
it = dsDevices_.erase( it );
deviceList_.erase( deviceList_.begin() + distance(dsDevices_.begin(), it ) );
}
}
// Determine the default devices
for ( n=0; n<dsDevices_.size(); n++ ) {
if ( dsDevices_[n].id == NULL ) { // default device
if ( dsDevices_[n].isInput )
deviceList_[n].isDefaultInput = true;
else
deviceList_[n].isDefaultOutput = true;
}
else if ( dsDevices_[n].isInput )
deviceList_[n].isDefaultInput = false;
else
deviceList_[n].isDefaultOutput = false;
}
}
bool RtApiDs :: probeDeviceInfo( RtAudio::DeviceInfo &info, DsDevice &dsDevice )
{
// Devices will either be input or output devices but not both.
HRESULT result;
if ( dsDevice.isInput ) goto probeInput;
LPDIRECTSOUND output;
DSCAPS outCaps;
result = DirectSoundCreate( dsDevice.id, &output, NULL );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::probeDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevice.name << ")!";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto probeInput;
}
outCaps.dwSize = sizeof( outCaps );
result = output->GetCaps( &outCaps );
if ( FAILED( result ) ) {
output->Release();
errorStream_ << "RtApiDs::probeDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto probeInput;
}
// Get output channel information.
info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
// Get sample rate information.
info.sampleRates.clear();
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
info.sampleRates.push_back( SAMPLE_RATES[k] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
// Get format information.
if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
output->Release();
info.name = dsDevice.name;
return true;
probeInput:
LPDIRECTSOUNDCAPTURE input;
result = DirectSoundCaptureCreate( dsDevice.id, &input, NULL );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::probeDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevice.name << ")!";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
DSCCAPS inCaps;
inCaps.dwSize = sizeof( inCaps );
result = input->GetCaps( &inCaps );
if ( FAILED( result ) ) {
input->Release();
errorStream_ << "RtApiDs::probeDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevice.name << ")!";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Get input channel information.
info.inputChannels = inCaps.dwChannels;
// Get sample rate and format information.
std::vector<unsigned int> rates;
if ( inCaps.dwChannels >= 2 ) {
if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( info.nativeFormats & RTAUDIO_SINT16 ) {
if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
}
else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
}
}
else if ( inCaps.dwChannels == 1 ) {
if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
if ( info.nativeFormats & RTAUDIO_SINT16 ) {
if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
}
else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
}
}
else info.inputChannels = 0; // technically, this would be an error
input->Release();
if ( info.inputChannels == 0 ) return false;
// Copy the supported rates to the info structure but avoid duplication.
bool found;
for ( unsigned int i=0; i<rates.size(); i++ ) {
found = false;
for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
if ( rates[i] == info.sampleRates[j] ) {
found = true;
break;
}
}
if ( found == false ) info.sampleRates.push_back( rates[i] );
}
std::sort( info.sampleRates.begin(), info.sampleRates.end() );
for ( unsigned int i=0; i<info.sampleRates.size(); i++ ) {
if ( !info.preferredSampleRate || ( info.sampleRates[i] <= 48000 && info.sampleRates[i] > info.preferredSampleRate ) )
info.preferredSampleRate = info.sampleRates[i];
}
// Copy name and return.
info.name = dsDevice.name;
return true;
}
bool RtApiDs :: probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
if ( channels + firstChannel > 2 ) {
errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
return FAILURE;
}
size_t nDevices = dsDevices_.size();
if ( nDevices == 0 ) {
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
return FAILURE;
}
int deviceIdx = -1;
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId ) {
deviceIdx = m;
break;
}
}
if ( deviceIdx < 0 ) {
errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
if ( mode == OUTPUT ) {
if ( dsDevices_[ deviceIdx ].isInput ) {
errorStream_ << "RtApiDs::probeDeviceOpen: device (" << deviceIdx << ") does not support output!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
else { // mode == INPUT
if ( dsDevices_[ deviceIdx ].isInput == false ) {
errorStream_ << "RtApiDs::probeDeviceOpen: device (" << deviceIdx << ") does not support input!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// According to a note in PortAudio, using GetDesktopWindow()
// instead of GetForegroundWindow() is supposed to avoid problems
// that occur when the application's window is not the foreground
// window. Also, if the application window closes before the
// DirectSound buffer, DirectSound can crash. In the past, I had
// problems when using GetDesktopWindow() but it seems fine now
// (January 2010). I'll leave it commented here.
// HWND hWnd = GetForegroundWindow();
HWND hWnd = GetDesktopWindow();
// Check the numberOfBuffers parameter and limit the lowest value to
// two. This is a judgement call and a value of two is probably too
// low for capture, but it should work for playback.
int nBuffers = 0;
if ( options ) nBuffers = options->numberOfBuffers;
if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
if ( nBuffers < 2 ) nBuffers = 3;
// Check the lower range of the user-specified buffer size and set
// (arbitrarily) to a lower bound of 32.
if ( *bufferSize < 32 ) *bufferSize = 32;
// Create the wave format structure. The data format setting will
// be determined later.
WAVEFORMATEX waveFormat;
ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = channels + firstChannel;
waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
// Determine the device buffer size. By default, we'll use the value
// defined above (32K), but we will grow it to make allowances for
// very large software buffer sizes.
DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
DWORD dsPointerLeadTime = 0;
void *ohandle = 0, *bhandle = 0;
HRESULT result;
if ( mode == OUTPUT ) {
LPDIRECTSOUND output;
result = DirectSoundCreate( dsDevices_[ deviceIdx ].id, &output, NULL );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
DSCAPS outCaps;
outCaps.dwSize = sizeof( outCaps );
result = output->GetCaps( &outCaps );
if ( FAILED( result ) ) {
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check channel information.
if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
errorStream_ << "RtApiDs::probeDeviceInfo: the output device (" << dsDevices_[ deviceIdx ].name << ") does not support stereo playback.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check format information. Use 16-bit format unless not
// supported or user requests 8-bit.
if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
!( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
waveFormat.wBitsPerSample = 16;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
else {
waveFormat.wBitsPerSample = 8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
stream_.userFormat = format;
// Update wave format structure and buffer information.
waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
// If the user wants an even bigger buffer, increase the device buffer size accordingly.
while ( dsPointerLeadTime * 2U > dsBufferSize )
dsBufferSize *= 2;
// Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
// result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
// Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
if ( FAILED( result ) ) {
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Even though we will write to the secondary buffer, we need to
// access the primary buffer to set the correct output format
// (since the default is 8-bit, 22 kHz!). Setup the DS primary
// buffer description.
DSBUFFERDESC bufferDescription;
ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
bufferDescription.dwSize = sizeof( DSBUFFERDESC );
bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
// Obtain the primary buffer
LPDIRECTSOUNDBUFFER buffer;
result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
if ( FAILED( result ) ) {
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the primary DS buffer sound format.
result = buffer->SetFormat( &waveFormat );
if ( FAILED( result ) ) {
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Setup the secondary DS buffer description.
ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
bufferDescription.dwSize = sizeof( DSBUFFERDESC );
bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
DSBCAPS_GLOBALFOCUS |
DSBCAPS_GETCURRENTPOSITION2 |
DSBCAPS_LOCHARDWARE ); // Force hardware mixing
bufferDescription.dwBufferBytes = dsBufferSize;
bufferDescription.lpwfxFormat = &waveFormat;
// Try to create the secondary DS buffer. If that doesn't work,
// try to use software mixing. Otherwise, there's a problem.
result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
if ( FAILED( result ) ) {
bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
DSBCAPS_GLOBALFOCUS |
DSBCAPS_GETCURRENTPOSITION2 |
DSBCAPS_LOCSOFTWARE ); // Force software mixing
result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
if ( FAILED( result ) ) {
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Get the buffer size ... might be different from what we specified.
DSBCAPS dsbcaps;
dsbcaps.dwSize = sizeof( DSBCAPS );
result = buffer->GetCaps( &dsbcaps );
if ( FAILED( result ) ) {
output->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
dsBufferSize = dsbcaps.dwBufferBytes;
// Lock the DS buffer
LPVOID audioPtr;
DWORD dataLen;
result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
if ( FAILED( result ) ) {
output->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Zero the DS buffer
ZeroMemory( audioPtr, dataLen );
// Unlock the DS buffer
result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
if ( FAILED( result ) ) {
output->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
ohandle = (void *) output;
bhandle = (void *) buffer;
}
if ( mode == INPUT ) {
LPDIRECTSOUNDCAPTURE input;
result = DirectSoundCaptureCreate( dsDevices_[ deviceIdx ].id, &input, NULL );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
DSCCAPS inCaps;
inCaps.dwSize = sizeof( inCaps );
result = input->GetCaps( &inCaps );
if ( FAILED( result ) ) {
input->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check channel information.
if ( inCaps.dwChannels < channels + firstChannel ) {
errorText_ = "RtApiDs::probeDeviceInfo: the input device does not support requested input channels.";
return FAILURE;
}
// Check format information. Use 16-bit format unless user
// requests 8-bit.
DWORD deviceFormats;
if ( channels + firstChannel == 2 ) {
deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
waveFormat.wBitsPerSample = 8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
else { // assume 16-bit is supported
waveFormat.wBitsPerSample = 16;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
}
else { // channel == 1
deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
waveFormat.wBitsPerSample = 8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
else { // assume 16-bit is supported
waveFormat.wBitsPerSample = 16;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
}
stream_.userFormat = format;
// Update wave format structure and buffer information.
waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
// If the user wants an even bigger buffer, increase the device buffer size accordingly.
while ( dsPointerLeadTime * 2U > dsBufferSize )
dsBufferSize *= 2;
// Setup the secondary DS buffer description.
DSCBUFFERDESC bufferDescription;
ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
bufferDescription.dwFlags = 0;
bufferDescription.dwReserved = 0;
bufferDescription.dwBufferBytes = dsBufferSize;
bufferDescription.lpwfxFormat = &waveFormat;
// Create the capture buffer.
LPDIRECTSOUNDCAPTUREBUFFER buffer;
result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
if ( FAILED( result ) ) {
input->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Get the buffer size ... might be different from what we specified.
DSCBCAPS dscbcaps;
dscbcaps.dwSize = sizeof( DSCBCAPS );
result = buffer->GetCaps( &dscbcaps );
if ( FAILED( result ) ) {
input->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
dsBufferSize = dscbcaps.dwBufferBytes;
// NOTE: We could have a problem here if this is a duplex stream
// and the play and capture hardware buffer sizes are different
// (I'm actually not sure if that is a problem or not).
// Currently, we are not verifying that.
// Lock the capture buffer
LPVOID audioPtr;
DWORD dataLen;
result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
if ( FAILED( result ) ) {
input->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Zero the buffer
ZeroMemory( audioPtr, dataLen );
// Unlock the buffer
result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
if ( FAILED( result ) ) {
input->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices_[ deviceIdx ].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
ohandle = (void *) input;
bhandle = (void *) buffer;
}
// Set various stream parameters
DsHandle *handle = 0;
stream_.nDeviceChannels[mode] = channels + firstChannel;
stream_.nUserChannels[mode] = channels;
stream_.bufferSize = *bufferSize;
stream_.channelOffset[mode] = firstChannel;
stream_.deviceInterleaved[mode] = true;
if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
else stream_.userInterleaved = true;
// Set flag for buffer conversion
stream_.doConvertBuffer[mode] = false;
if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1 )
stream_.doConvertBuffer[mode] = true;
// Allocate necessary internal buffers
long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if ( stream_.doConvertBuffer[mode] ) {
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
if ( mode == INPUT ) {
if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
}
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
// Allocate our DsHandle structures for the stream.
if ( stream_.apiHandle == 0 ) {
try {
handle = new DsHandle;
}
catch ( std::bad_alloc& ) {
errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
goto error;
}
// Create a manual-reset event.
handle->condition = CreateEvent( NULL, // no security
TRUE, // manual-reset
FALSE, // non-signaled initially
NULL ); // unnamed
stream_.apiHandle = (void *) handle;
}
else
handle = (DsHandle *) stream_.apiHandle;
handle->id[mode] = ohandle;
handle->buffer[mode] = bhandle;
handle->dsBufferSize[mode] = dsBufferSize;
handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
stream_.deviceId[mode] = deviceIdx;
stream_.state = STREAM_STOPPED;
if ( stream_.mode == OUTPUT && mode == INPUT )
// We had already set up an output stream.
stream_.mode = DUPLEX;
else
stream_.mode = mode;
stream_.nBuffers = nBuffers;
stream_.sampleRate = sampleRate;
// Setup the buffer conversion information structure.
if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
// Setup the callback thread.
if ( stream_.callbackInfo.isRunning == false ) {
unsigned threadId;
stream_.callbackInfo.isRunning = true;
stream_.callbackInfo.object = (void *) this;
stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
&stream_.callbackInfo, 0, &threadId );
if ( stream_.callbackInfo.thread == 0 ) {
errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
goto error;
}
// Boost DS thread priority
SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
}
return SUCCESS;
error:
if ( handle ) {
if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
if ( buffer ) buffer->Release();
object->Release();
}
if ( handle->buffer[1] ) {
LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
if ( buffer ) buffer->Release();
object->Release();
}
CloseHandle( handle->condition );
delete handle;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiDs :: closeStream()
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiDs::closeStream(): no open stream to close!";
error( RTAUDIO_WARNING );
return;
}
// Stop the callback thread.
stream_.callbackInfo.isRunning = false;
WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
CloseHandle( (HANDLE) stream_.callbackInfo.thread );
DsHandle *handle = (DsHandle *) stream_.apiHandle;
if ( handle ) {
if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
if ( buffer ) {
buffer->Stop();
buffer->Release();
}
object->Release();
}
if ( handle->buffer[1] ) {
LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
if ( buffer ) {
buffer->Stop();
buffer->Release();
}
object->Release();
}
CloseHandle( handle->condition );
delete handle;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
clearStreamInfo();
//stream_.mode = UNINITIALIZED;
//stream_.state = STREAM_CLOSED;
}
RtAudioErrorType RtApiDs :: startStream()
{
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiDs::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiDs::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
DsHandle *handle = (DsHandle *) stream_.apiHandle;
// Increase scheduler frequency on lesser windows (a side-effect of
// increasing timer accuracy). On greater windows (Win2K or later),
// this is already in effect.
timeBeginPeriod( 1 );
buffersRolling = false;
duplexPrerollBytes = 0;
if ( stream_.mode == DUPLEX ) {
// 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
}
HRESULT result = 0;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
result = buffer->Start( DSCBSTART_LOOPING );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
}
handle->drainCounter = 0;
handle->internalDrain = false;
ResetEvent( handle->condition );
stream_.state = STREAM_RUNNING;
unlock:
if ( FAILED( result ) ) error( RTAUDIO_SYSTEM_ERROR );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiDs :: stopStream()
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiDs::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
HRESULT result = 0;
LPVOID audioPtr;
DWORD dataLen;
DsHandle *handle = (DsHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( handle->drainCounter == 0 ) {
handle->drainCounter = 2;
WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK( &stream_.mutex );
// Stop the buffer and clear memory
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
result = buffer->Stop();
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Lock the buffer and clear it so that if we start to play again,
// we won't have old data playing.
result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Zero the DS buffer
ZeroMemory( audioPtr, dataLen );
// Unlock the DS buffer
result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// If we start playing again, we must begin at beginning of buffer.
handle->bufferPointer[0] = 0;
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
audioPtr = NULL;
dataLen = 0;
stream_.state = STREAM_STOPPED;
if ( stream_.mode != DUPLEX )
MUTEX_LOCK( &stream_.mutex );
result = buffer->Stop();
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Lock the buffer and clear it so that if we start to play again,
// we won't have old data playing.
result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Zero the DS buffer
ZeroMemory( audioPtr, dataLen );
// Unlock the DS buffer
result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// If we start recording again, we must begin at beginning of buffer.
handle->bufferPointer[1] = 0;
}
unlock:
timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
MUTEX_UNLOCK( &stream_.mutex );
if ( FAILED( result ) ) error( RTAUDIO_SYSTEM_ERROR );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiDs :: abortStream()
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiDs::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
DsHandle *handle = (DsHandle *) stream_.apiHandle;
handle->drainCounter = 2;
return stopStream();
}
void RtApiDs :: callbackEvent()
{
if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
Sleep( 50 ); // sleep 50 milliseconds
return;
}
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
error( RTAUDIO_WARNING );
return;
}
CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
DsHandle *handle = (DsHandle *) stream_.apiHandle;
// Check if we were draining the stream and signal is finished.
if ( handle->drainCounter > stream_.nBuffers + 2 ) {
stream_.state = STREAM_STOPPING;
if ( handle->internalDrain == false )
SetEvent( handle->condition );
else
stopStream();
return;
}
// Invoke user callback to get fresh output data UNLESS we are
// draining stream.
if ( handle->drainCounter == 0 ) {
RtAudioCallback callback = (RtAudioCallback) info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData );
if ( cbReturnValue == 2 ) {
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
abortStream();
return;
}
else if ( cbReturnValue == 1 ) {
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
HRESULT result;
DWORD currentWritePointer, safeWritePointer;
DWORD currentReadPointer, safeReadPointer;
UINT nextWritePointer;
LPVOID buffer1 = NULL;
LPVOID buffer2 = NULL;
DWORD bufferSize1 = 0;
DWORD bufferSize2 = 0;
char *buffer;
long bufferBytes;
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state == STREAM_STOPPED ) {
MUTEX_UNLOCK( &stream_.mutex );
return;
}
if ( buffersRolling == false ) {
if ( stream_.mode == DUPLEX ) {
//assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
// It takes a while for the devices to get rolling. As a result,
// there's no guarantee that the capture and write device pointers
// will move in lockstep. Wait here for both devices to start
// rolling, and then set our buffer pointers accordingly.
// e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
// bytes later than the write buffer.
// Stub: a serious risk of having a pre-emptive scheduling round
// take place between the two GetCurrentPosition calls... but I'm
// really not sure how to solve the problem. Temporarily boost to
// Realtime priority, maybe; but I'm not sure what priority the
// DirectSound service threads run at. We *should* be roughly
// within a ms or so of correct.
LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
DWORD startSafeWritePointer, startSafeReadPointer;
result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
while ( true ) {
result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
Sleep( 1 );
}
//assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
handle->bufferPointer[1] = safeReadPointer;
}
else if ( stream_.mode == OUTPUT ) {
// Set the proper nextWritePosition after initial startup.
LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
result = dsWriteBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
}
buffersRolling = true;
}
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
if ( handle->drainCounter > 1 ) { // write zeros to the output stream
bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
bufferBytes *= formatBytes( stream_.userFormat );
memset( stream_.userBuffer[0], 0, bufferBytes );
}
// Setup parameters and do buffer conversion if necessary.
if ( stream_.doConvertBuffer[0] ) {
buffer = stream_.deviceBuffer;
convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
bufferBytes *= formatBytes( stream_.deviceFormat[0] );
}
else {
buffer = stream_.userBuffer[0];
bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
bufferBytes *= formatBytes( stream_.userFormat );
}
// No byte swapping necessary in DirectSound implementation.
// Ahhh ... windoze. 16-bit data is signed but 8-bit data is
// unsigned. So, we need to convert our signed 8-bit data here to
// unsigned.
if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
DWORD dsBufferSize = handle->dsBufferSize[0];
nextWritePointer = handle->bufferPointer[0];
DWORD endWrite, leadPointer;
while ( true ) {
// Find out where the read and "safe write" pointers are.
result = dsBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
// We will copy our output buffer into the region between
// safeWritePointer and leadPointer. If leadPointer is not
// beyond the next endWrite position, wait until it is.
leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
//std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
endWrite = nextWritePointer + bufferBytes;
// Check whether the entire write region is behind the play pointer.
if ( leadPointer >= endWrite ) break;
// If we are here, then we must wait until the leadPointer advances
// beyond the end of our next write region. We use the
// Sleep() function to suspend operation until that happens.
double millis = ( endWrite - leadPointer ) * 1000.0;
millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
if ( millis < 1.0 ) millis = 1.0;
Sleep( (DWORD) millis );
}
if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
|| dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
// We've strayed into the forbidden zone ... resync the read pointer.
handle->xrun[0] = true;
nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
handle->bufferPointer[0] = nextWritePointer;
endWrite = nextWritePointer + bufferBytes;
}
// Lock free space in the buffer
result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
&bufferSize1, &buffer2, &bufferSize2, 0 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
// Copy our buffer into the DS buffer
CopyMemory( buffer1, buffer, bufferSize1 );
if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
// Update our buffer offset and unlock sound buffer
dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
handle->bufferPointer[0] = nextWritePointer;
}
// Don't bother draining input
if ( handle->drainCounter ) {
handle->drainCounter++;
goto unlock;
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
// Setup parameters.
if ( stream_.doConvertBuffer[1] ) {
buffer = stream_.deviceBuffer;
bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
bufferBytes *= formatBytes( stream_.deviceFormat[1] );
}
else {
buffer = stream_.userBuffer[1];
bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
bufferBytes *= formatBytes( stream_.userFormat );
}
LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
long nextReadPointer = handle->bufferPointer[1];
DWORD dsBufferSize = handle->dsBufferSize[1];
// Find out where the write and "safe read" pointers are.
result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
DWORD endRead = nextReadPointer + bufferBytes;
// Handling depends on whether we are INPUT or DUPLEX.
// If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
// then a wait here will drag the write pointers into the forbidden zone.
//
// In DUPLEX mode, rather than wait, we will back off the read pointer until
// it's in a safe position. This causes dropouts, but it seems to be the only
// practical way to sync up the read and write pointers reliably, given the
// the very complex relationship between phase and increment of the read and write
// pointers.
//
// In order to minimize audible dropouts in DUPLEX mode, we will
// provide a pre-roll period of 0.5 seconds in which we return
// zeros from the read buffer while the pointers sync up.
if ( stream_.mode == DUPLEX ) {
if ( safeReadPointer < endRead ) {
if ( duplexPrerollBytes <= 0 ) {
// Pre-roll time over. Be more aggressive.
int adjustment = endRead-safeReadPointer;
handle->xrun[1] = true;
// Two cases:
// - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
// and perform fine adjustments later.
// - small adjustments: back off by twice as much.
if ( adjustment >= 2*bufferBytes )
nextReadPointer = safeReadPointer-2*bufferBytes;
else
nextReadPointer = safeReadPointer-bufferBytes-adjustment;
if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
}
else {
// In pre=roll time. Just do it.
nextReadPointer = safeReadPointer - bufferBytes;
while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
}
endRead = nextReadPointer + bufferBytes;
}
}
else { // mode == INPUT
while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
// See comments for playback.
double millis = (endRead - safeReadPointer) * 1000.0;
millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
if ( millis < 1.0 ) millis = 1.0;
Sleep( (DWORD) millis );
// Wake up and find out where we are now.
result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
}
}
// Lock free space in the buffer
result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
&bufferSize1, &buffer2, &bufferSize2, 0 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
if ( duplexPrerollBytes <= 0 ) {
// Copy our buffer into the DS buffer
CopyMemory( buffer, buffer1, bufferSize1 );
if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
}
else {
memset( buffer, 0, bufferSize1 );
if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
duplexPrerollBytes -= bufferSize1 + bufferSize2;
}
// Update our buffer offset and unlock sound buffer
nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
if ( FAILED( result ) ) {
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
error( RTAUDIO_SYSTEM_ERROR );
return;
}
handle->bufferPointer[1] = nextReadPointer;
// No byte swapping necessary in DirectSound implementation.
// If necessary, convert 8-bit data from unsigned to signed.
if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
// Do buffer conversion if necessary.
if ( stream_.doConvertBuffer[1] )
convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
}
unlock:
MUTEX_UNLOCK( &stream_.mutex );
RtApi::tickStreamTime();
}
// Definitions for utility functions and callbacks
// specific to the DirectSound implementation.
static unsigned __stdcall callbackHandler( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiDs *object = (RtApiDs *) info->object;
bool* isRunning = &info->isRunning;
while ( *isRunning == true ) {
object->callbackEvent();
}
_endthreadex( 0 );
return 0;
}
static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
LPCTSTR description,
LPCTSTR lpctstr,
LPVOID lpContext )
{
struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
HRESULT hr;
bool validDevice = false;
if ( probeInfo.isInput == true ) {
DSCCAPS caps;
LPDIRECTSOUNDCAPTURE object;
hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
if ( hr != DS_OK ) return TRUE;
caps.dwSize = sizeof(caps);
hr = object->GetCaps( &caps );
if ( hr == DS_OK ) {
if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
validDevice = true;
}
object->Release();
}
else {
DSCAPS caps;
LPDIRECTSOUND object;
hr = DirectSoundCreate( lpguid, &object, NULL );
if ( hr != DS_OK ) return TRUE;
caps.dwSize = sizeof(caps);
hr = object->GetCaps( &caps );
if ( hr == DS_OK ) {
if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
validDevice = true;
}
object->Release();
}
if ( validDevice ) {
// If good device, then save its name and guid.
DsDevice device;
device.name = convertCharPointerToStdString( description );
device.epID = convertCharPointerToStdString(lpctstr);
device.id = lpguid;
device.isInput = probeInfo.isInput;
dsDevices.push_back( device );
}
return TRUE;
}
static const char* getErrorString( int code )
{
switch ( code ) {
case DSERR_ALLOCATED:
return "Already allocated";
case DSERR_CONTROLUNAVAIL:
return "Control unavailable";
case DSERR_INVALIDPARAM:
return "Invalid parameter";
case DSERR_INVALIDCALL:
return "Invalid call";
case DSERR_GENERIC:
return "Generic error";
case DSERR_PRIOLEVELNEEDED:
return "Priority level needed";
case DSERR_OUTOFMEMORY:
return "Out of memory";
case DSERR_BADFORMAT:
return "The sample rate or the channel format is not supported";
case DSERR_UNSUPPORTED:
return "Not supported";
case DSERR_NODRIVER:
return "No driver";
case DSERR_ALREADYINITIALIZED:
return "Already initialized";
case DSERR_NOAGGREGATION:
return "No aggregation";
case DSERR_BUFFERLOST:
return "Buffer lost";
case DSERR_OTHERAPPHASPRIO:
return "Another application already has priority";
case DSERR_UNINITIALIZED:
return "Uninitialized";
default:
return "DirectSound unknown error";
}
}
//******************** End of __WINDOWS_DS__ *********************//
#endif
#if defined(__LINUX_ALSA__)
#include <alsa/asoundlib.h>
#include <unistd.h>
// A structure to hold various information related to the ALSA API
// implementation.
struct AlsaHandle {
snd_pcm_t *handles[2];
bool synchronized;
bool xrun[2];
pthread_cond_t runnable_cv;
bool runnable;
AlsaHandle()
#if _cplusplus >= 201103L
:handles{nullptr, nullptr}, synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
#else
: synchronized(false), runnable(false) { handles[0] = NULL; handles[1] = NULL; xrun[0] = false; xrun[1] = false; }
#endif
};
static void *alsaCallbackHandler( void * ptr );
RtApiAlsa :: RtApiAlsa()
{
// Nothing to do here.
}
RtApiAlsa :: ~RtApiAlsa()
{
if ( stream_.state != STREAM_CLOSED ) closeStream();
}
void RtApiAlsa :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
int result, device, card;
char name[128];
snd_ctl_t *handle = 0;
snd_ctl_card_info_t *ctlinfo;
snd_pcm_info_t *pcminfo;
snd_ctl_card_info_alloca(&ctlinfo);
snd_pcm_info_alloca(&pcminfo);
// First element isthe device hw ID, second is the device "pretty name"
std::vector<std::pair<std::string, std::string>> deviceID_prettyName;
snd_pcm_stream_t stream;
std::string defaultDeviceName;
// Add the default interface if available.
result = snd_ctl_open( &handle, "default", 0 );
if (result == 0) {
deviceID_prettyName.push_back({"default", "Default ALSA Device"});
defaultDeviceName = deviceID_prettyName[0].second;
snd_ctl_close( handle );
}
// Add the Pulse interface if available.
result = snd_ctl_open( &handle, "pulse", 0 );
if (result == 0) {
deviceID_prettyName.push_back({"pulse", "PulseAudio Sound Server"});
snd_ctl_close( handle );
}
// Count cards and devices and get ascii identifiers.
card = -1;
snd_card_next( &card );
while ( card >= 0 ) {
sprintf( name, "hw:%d", card );
result = snd_ctl_open( &handle, name, 0 );
if ( result < 0 ) {
handle = 0;
errorStream_ << "RtApiAlsa::probeDevices: control open, card = " << card << ", " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto nextcard;
}
result = snd_ctl_card_info( handle, ctlinfo );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::probeDevices: control info, card = " << card << ", " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto nextcard;
}
device = -1;
while( 1 ) {
result = snd_ctl_pcm_next_device( handle, &device );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::probeDevices: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
break;
}
if ( device < 0 )
break;
snd_pcm_info_set_device( pcminfo, device );
snd_pcm_info_set_subdevice( pcminfo, 0 );
stream = SND_PCM_STREAM_PLAYBACK;
snd_pcm_info_set_stream( pcminfo, stream );
result = snd_ctl_pcm_info( handle, pcminfo );
if ( result < 0 ) {
if ( result == -ENOENT ) { // try as input stream
stream = SND_PCM_STREAM_CAPTURE;
snd_pcm_info_set_stream( pcminfo, stream );
result = snd_ctl_pcm_info( handle, pcminfo );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::probeDevices: control pcm info, card = " << card << ", device = " << device << ", " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
continue;
}
}
else continue;
}
sprintf( name, "hw:%s,%d", snd_ctl_card_info_get_id(ctlinfo), device );
std::string id(name);
sprintf( name, "%s (%s)", snd_ctl_card_info_get_name(ctlinfo), snd_pcm_info_get_id(pcminfo) );
std::string prettyName(name);
deviceID_prettyName.push_back( {id, prettyName} );
if ( card == 0 && device == 0 && defaultDeviceName.empty() )
defaultDeviceName = name;
}
nextcard:
if ( handle )
snd_ctl_close( handle );
snd_card_next( &card );
}
if ( deviceID_prettyName.size() == 0 ) {
deviceList_.clear();
deviceIdPairs_.clear();
return;
}
// Clean removed devices
for ( auto it = deviceIdPairs_.begin(); it != deviceIdPairs_.end(); ) {
bool found = false;
for ( auto& d: deviceID_prettyName ) {
if ( d.first == (*it).first ) {
found = true;
break;
}
}
if ( found )
++it;
else
it = deviceIdPairs_.erase(it);
}
// Fill or update the deviceList_ and also save a corresponding list of Ids.
for ( auto& d : deviceID_prettyName ) {
bool found = false;
for ( auto& dID : deviceIdPairs_ ) {
if ( d.first == dID.first ) {
found = true;
break; // We already have this device.
}
}
if ( found )
continue;
// new device
RtAudio::DeviceInfo info;
info.name = d.second;
if ( probeDeviceInfo( info, d.first ) == false ) continue; // ignore if probe fails
info.ID = currentDeviceId_++; // arbitrary internal device ID
if ( info.name == defaultDeviceName ) {
if ( info.outputChannels > 0 ) info.isDefaultOutput = true;
if ( info.inputChannels > 0 ) info.isDefaultInput = true;
}
deviceList_.push_back( info );
deviceIdPairs_.push_back({d.first, info.ID});
// I don't see that ALSA provides property listeners to know if
// devices are removed or added.
}
// Remove any devices left in the list that are no longer available.
for ( std::vector<RtAudio::DeviceInfo>::iterator it=deviceList_.begin(); it!=deviceList_.end(); )
{
auto itID = deviceIdPairs_.begin();
while ( itID != deviceIdPairs_.end() ) {
if ( (*it).ID == (*itID).second ) {
break;
}
++itID;
}
if ( itID == deviceIdPairs_.end() ) {
// not found so remove it from our list
it = deviceList_.erase( it );
}
else
++it;
}
}
bool RtApiAlsa :: probeDeviceInfo( RtAudio::DeviceInfo& info, std::string name )
{
int result, openMode = SND_PCM_ASYNC;
snd_pcm_stream_t stream;
snd_pcm_t *phandle;
snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca( ¶ms );
// First try for playback
stream = SND_PCM_STREAM_PLAYBACK;
result = snd_pcm_open( &phandle, name.c_str(), stream, openMode | SND_PCM_NONBLOCK );
if ( result < 0 ) {
if ( result == -16 ) return false; // device busy ... can't probe or use
if ( result != -2 ) { // device doesn't support playback
errorStream_ << "RtApiAlsa::probeDeviceInfo: snd_pcm_open (playback) error for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
goto captureProbe;
}
// The device is open ... fill the parameter structure.
result = snd_pcm_hw_params_any( phandle, params );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto captureProbe;
}
// Get output channel information.
unsigned int value;
result = snd_pcm_hw_params_get_channels_max( params, &value );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto captureProbe;
}
info.outputChannels = value;
snd_pcm_close( phandle );
captureProbe:
stream = SND_PCM_STREAM_CAPTURE;
result = snd_pcm_open( &phandle, name.c_str(), stream, openMode | SND_PCM_NONBLOCK);
if ( result < 0 && result ) {
if ( result != -2 && result != -16 ) { // device busy or doesn't support capture
errorStream_ << "RtApiAlsa::probeDeviceInfo: snd_pcm_open (capture) error for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
if ( info.outputChannels == 0 ) return false;
goto probeParameters;
}
// The device is open ... fill the parameter structure.
result = snd_pcm_hw_params_any( phandle, params );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
if ( info.outputChannels == 0 ) return false;
goto probeParameters;
}
result = snd_pcm_hw_params_get_channels_max( params, &value );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
if ( info.outputChannels == 0 ) return false;
goto probeParameters;
}
info.inputChannels = value;
snd_pcm_close( phandle );
// If device opens for both playback and capture, we determine the channels.
if ( info.outputChannels > 0 && info.inputChannels > 0 )
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
probeParameters:
// At this point, we just need to figure out the supported data
// formats and sample rates. We'll proceed by opening the device in
// the direction with the maximum number of channels, or playback if
// they are equal. This might limit our sample rate options, but so
// be it.
if ( info.outputChannels >= info.inputChannels )
stream = SND_PCM_STREAM_PLAYBACK;
else
stream = SND_PCM_STREAM_CAPTURE;
result = snd_pcm_open( &phandle, name.c_str(), stream, openMode | SND_PCM_NONBLOCK);
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::probeDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// The device is open ... fill the parameter structure.
result = snd_pcm_hw_params_any( phandle, params );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Test our discrete set of sample rate values.
info.sampleRates.clear();
for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {
info.sampleRates.push_back( SAMPLE_RATES[i] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[i];
}
}
if ( info.sampleRates.size() == 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: no supported sample rates found for device (" << name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Probe the supported data formats ... we don't care about endian-ness just yet
snd_pcm_format_t format;
info.nativeFormats = 0;
format = SND_PCM_FORMAT_S8;
if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
info.nativeFormats |= RTAUDIO_SINT8;
format = SND_PCM_FORMAT_S16;
if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
info.nativeFormats |= RTAUDIO_SINT16;
format = SND_PCM_FORMAT_S24;
if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
info.nativeFormats |= RTAUDIO_SINT24;
format = SND_PCM_FORMAT_S32;
if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
info.nativeFormats |= RTAUDIO_SINT32;
format = SND_PCM_FORMAT_FLOAT;
if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
info.nativeFormats |= RTAUDIO_FLOAT32;
format = SND_PCM_FORMAT_FLOAT64;
if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
info.nativeFormats |= RTAUDIO_FLOAT64;
// Check that we have at least one supported format
if ( info.nativeFormats == 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Close the device and return
snd_pcm_close( phandle );
return true;
}
bool RtApiAlsa :: probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
#if defined(__RTAUDIO_DEBUG__)
struct SndOutputTdealloc {
SndOutputTdealloc() : _out(NULL) { snd_output_stdio_attach(&_out, stderr, 0); }
~SndOutputTdealloc() { snd_output_close(_out); }
operator snd_output_t*() { return _out; }
snd_output_t *_out;
} out;
#endif
std::string name;
for ( auto& id : deviceIdPairs_) {
if ( id.second == deviceId ) {
name = id.first;
break;
}
}
snd_pcm_stream_t stream;
if ( mode == OUTPUT )
stream = SND_PCM_STREAM_PLAYBACK;
else
stream = SND_PCM_STREAM_CAPTURE;
snd_pcm_t *phandle;
int openMode = SND_PCM_ASYNC;
int result = snd_pcm_open( &phandle, name.c_str(), stream, openMode );
if ( result < 0 ) {
if ( mode == OUTPUT )
errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
else
errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Fill the parameter structure.
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca( &hw_params );
result = snd_pcm_hw_params_any( phandle, hw_params );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
#if defined(__RTAUDIO_DEBUG__)
fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
snd_pcm_hw_params_dump( hw_params, out );
#endif
// Set access ... check user preference.
if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
stream_.userInterleaved = false;
result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
if ( result < 0 ) {
result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
stream_.deviceInterleaved[mode] = true;
}
else
stream_.deviceInterleaved[mode] = false;
}
else {
stream_.userInterleaved = true;
result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
if ( result < 0 ) {
result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
stream_.deviceInterleaved[mode] = false;
}
else
stream_.deviceInterleaved[mode] = true;
}
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine how to set the device format.
stream_.userFormat = format;
snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
if ( format == RTAUDIO_SINT8 )
deviceFormat = SND_PCM_FORMAT_S8;
else if ( format == RTAUDIO_SINT16 )
deviceFormat = SND_PCM_FORMAT_S16;
else if ( format == RTAUDIO_SINT24 )
deviceFormat = SND_PCM_FORMAT_S24;
else if ( format == RTAUDIO_SINT32 )
deviceFormat = SND_PCM_FORMAT_S32;
else if ( format == RTAUDIO_FLOAT32 )
deviceFormat = SND_PCM_FORMAT_FLOAT;
else if ( format == RTAUDIO_FLOAT64 )
deviceFormat = SND_PCM_FORMAT_FLOAT64;
if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
stream_.deviceFormat[mode] = format;
goto setFormat;
}
// The user requested format is not natively supported by the device.
deviceFormat = SND_PCM_FORMAT_FLOAT64;
if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_FLOAT;
if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S32;
if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S24;
if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S16;
if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S8;
if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
goto setFormat;
}
// If we get here, no supported format was found.
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
return FAILURE;
setFormat:
result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine whether byte-swaping is necessary.
stream_.doByteSwap[mode] = false;
if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
result = snd_pcm_format_cpu_endian( deviceFormat );
if ( result == 0 )
stream_.doByteSwap[mode] = true;
else if (result < 0) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Set the sample rate.
result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine the number of channels for this device. We support a possible
// minimum device channel number > than the value requested by the user.
stream_.nUserChannels[mode] = channels;
unsigned int value;
result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
unsigned int deviceChannels = value;
if ( result < 0 || deviceChannels < channels + firstChannel ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
deviceChannels = value;
if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
stream_.nDeviceChannels[mode] = deviceChannels;
// Set the device channels.
result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the buffer (or period) size.
int dir = 0;
snd_pcm_uframes_t periodSize = *bufferSize;
result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
*bufferSize = periodSize;
// Set the buffer number, which in ALSA is referred to as the "period".
unsigned int periods = 0;
if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;
if ( periods < 2 ) periods = 4; // a fairly safe default value
result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// If attempting to setup a duplex stream, the bufferSize parameter
// MUST be the same in both directions!
if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.bufferSize = *bufferSize;
// Install the hardware configuration
result = snd_pcm_hw_params( phandle, hw_params );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
#if defined(__RTAUDIO_DEBUG__)
fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
snd_pcm_hw_params_dump( hw_params, out );
#endif
// Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
snd_pcm_sw_params_t *sw_params = NULL;
snd_pcm_sw_params_alloca( &sw_params );
snd_pcm_sw_params_current( phandle, sw_params );
snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
// The following two settings were suggested by Theo Veenker
//snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
//snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
// here are two options for a fix
//snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
snd_pcm_uframes_t val;
snd_pcm_sw_params_get_boundary( sw_params, &val );
snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
result = snd_pcm_sw_params( phandle, sw_params );
if ( result < 0 ) {
snd_pcm_close( phandle );
errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
#if defined(__RTAUDIO_DEBUG__)
fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
snd_pcm_sw_params_dump( sw_params, out );
#endif
// Set flags for buffer conversion
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1 )
stream_.doConvertBuffer[mode] = true;
// Allocate the ApiHandle if necessary and then save.
AlsaHandle *apiInfo = 0;
if ( stream_.apiHandle == 0 ) {
try {
apiInfo = (AlsaHandle *) new AlsaHandle;
}
catch ( std::bad_alloc& ) {
errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
goto error;
}
if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {
errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *) apiInfo;
apiInfo->handles[0] = 0;
apiInfo->handles[1] = 0;
}
else {
apiInfo = (AlsaHandle *) stream_.apiHandle;
}
apiInfo->handles[mode] = phandle;
phandle = 0;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if ( stream_.doConvertBuffer[mode] ) {
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
if ( mode == INPUT ) {
if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
if ( bufferBytes <= bytesOut ) makeBuffer = false;
}
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.sampleRate = sampleRate;
stream_.nBuffers = periods;
stream_.deviceId[mode] = deviceId;
stream_.state = STREAM_STOPPED;
// Setup the buffer conversion information structure.
if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
// Setup thread if necessary.
if ( stream_.mode == OUTPUT && mode == INPUT ) {
// We had already set up an output stream.
stream_.mode = DUPLEX;
// Link the streams if possible.
apiInfo->synchronized = false;
if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
apiInfo->synchronized = true;
else {
errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
error( RTAUDIO_WARNING );
}
}
else {
stream_.mode = mode;
// Setup callback thread.
stream_.callbackInfo.object = (void *) this;
// Set the thread attributes for joinable and realtime scheduling
// priority (optional). The higher priority will only take affect
// if the program is run as root or suid. Note, under Linux
// processes with CAP_SYS_NICE privilege, a user can change
// scheduling policy and priority (thus need not be root). See
// POSIX "capabilities".
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
#ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
stream_.callbackInfo.doRealtime = true;
struct sched_param param;
int priority = options->priority;
int min = sched_get_priority_min( SCHED_RR );
int max = sched_get_priority_max( SCHED_RR );
if ( priority < min ) priority = min;
else if ( priority > max ) priority = max;
param.sched_priority = priority;
// Set the policy BEFORE the priority. Otherwise it fails.
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
// This is definitely required. Otherwise it fails.
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedparam(&attr, ¶m);
}
else
pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
#else
pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
#endif
stream_.callbackInfo.isRunning = true;
result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
pthread_attr_destroy( &attr );
if ( result ) {
// Failed. Try instead with default attributes.
result = pthread_create( &stream_.callbackInfo.thread, NULL, alsaCallbackHandler, &stream_.callbackInfo );
if ( result ) {
stream_.callbackInfo.isRunning = false;
errorText_ = "RtApiAlsa::error creating callback thread!";
goto error;
}
}
}
return SUCCESS;
error:
if ( apiInfo ) {
pthread_cond_destroy( &apiInfo->runnable_cv );
if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
delete apiInfo;
stream_.apiHandle = 0;
}
if ( phandle) snd_pcm_close( phandle );
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiAlsa :: closeStream()
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
error( RTAUDIO_WARNING );
return;
}
AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
stream_.callbackInfo.isRunning = false;
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state == STREAM_STOPPED ) {
apiInfo->runnable = true;
pthread_cond_signal( &apiInfo->runnable_cv );
}
MUTEX_UNLOCK( &stream_.mutex );
pthread_join( stream_.callbackInfo.thread, NULL );
if ( stream_.state == STREAM_RUNNING ) {
stream_.state = STREAM_STOPPED;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
snd_pcm_drop( apiInfo->handles[0] );
if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
snd_pcm_drop( apiInfo->handles[1] );
}
if ( apiInfo ) {
pthread_cond_destroy( &apiInfo->runnable_cv );
if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
delete apiInfo;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
clearStreamInfo();
}
RtAudioErrorType RtApiAlsa :: startStream()
{
// This method calls snd_pcm_prepare if the device isn't already in that state.
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiAlsa::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
MUTEX_LOCK( &stream_.mutex );
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
int result = 0;
snd_pcm_state_t state;
AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
state = snd_pcm_state( handle[0] );
if ( state != SND_PCM_STATE_PREPARED ) {
result = snd_pcm_prepare( handle[0] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
}
if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
state = snd_pcm_state( handle[1] );
if ( state != SND_PCM_STATE_PREPARED ) {
result = snd_pcm_prepare( handle[1] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
}
stream_.state = STREAM_RUNNING;
unlock:
apiInfo->runnable = true;
pthread_cond_signal( &apiInfo->runnable_cv );
MUTEX_UNLOCK( &stream_.mutex );
if ( result < 0 ) return error( RTAUDIO_SYSTEM_ERROR );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiAlsa :: stopStream()
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiAlsa::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK( &stream_.mutex );
int result = 0;
AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( apiInfo->synchronized )
result = snd_pcm_drop( handle[0] );
else
result = snd_pcm_drain( handle[0] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
result = snd_pcm_drop( handle[1] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
apiInfo->runnable = false; // fixes high CPU usage when stopped
MUTEX_UNLOCK( &stream_.mutex );
if ( result < 0 ) return error( RTAUDIO_SYSTEM_ERROR );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiAlsa :: abortStream()
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiAlsa::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK( &stream_.mutex );
int result = 0;
AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
result = snd_pcm_drop( handle[0] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
result = snd_pcm_drop( handle[1] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
apiInfo->runnable = false; // fixes high CPU usage when stopped
MUTEX_UNLOCK( &stream_.mutex );
if ( result < 0 ) return error( RTAUDIO_SYSTEM_ERROR );
return RTAUDIO_NO_ERROR;
}
void RtApiAlsa :: callbackEvent()
{
AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
if ( stream_.state == STREAM_STOPPED ) {
MUTEX_LOCK( &stream_.mutex );
while ( !apiInfo->runnable )
pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );
if ( stream_.state != STREAM_RUNNING ) {
MUTEX_UNLOCK( &stream_.mutex );
return;
}
MUTEX_UNLOCK( &stream_.mutex );
}
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
error( RTAUDIO_WARNING );
return;
}
int doStopStream = 0;
RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
status |= RTAUDIO_OUTPUT_UNDERFLOW;
apiInfo->xrun[0] = false;
}
if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
status |= RTAUDIO_INPUT_OVERFLOW;
apiInfo->xrun[1] = false;
}
doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
if ( doStopStream == 2 ) {
abortStream();
return;
}
MUTEX_LOCK( &stream_.mutex );
// The state might change while waiting on a mutex.
if ( stream_.state == STREAM_STOPPED ) goto unlock;
int result;
char *buffer;
int channels;
snd_pcm_t **handle;
snd_pcm_sframes_t frames;
RtAudioFormat format;
handle = (snd_pcm_t **) apiInfo->handles;
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
// Setup parameters.
if ( stream_.doConvertBuffer[1] ) {
buffer = stream_.deviceBuffer;
channels = stream_.nDeviceChannels[1];
format = stream_.deviceFormat[1];
}
else {
buffer = stream_.userBuffer[1];
channels = stream_.nUserChannels[1];
format = stream_.userFormat;
}
// Read samples from device in interleaved/non-interleaved format.
if ( stream_.deviceInterleaved[1] )
result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
else {
void *bufs[channels];
size_t offset = stream_.bufferSize * formatBytes( format );
for ( int i=0; i<channels; i++ )
bufs[i] = (void *) (buffer + (i * offset));
result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
}
if ( result < (int) stream_.bufferSize ) {
// Either an error or overrun occurred.
if ( result == -EPIPE ) {
snd_pcm_state_t state = snd_pcm_state( handle[1] );
if ( state == SND_PCM_STATE_XRUN ) {
apiInfo->xrun[1] = true;
result = snd_pcm_prepare( handle[1] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
}
}
else {
errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
}
}
else {
errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
}
error( RTAUDIO_WARNING );
goto tryOutput;
}
// Do byte swapping if necessary.
if ( stream_.doByteSwap[1] )
byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
// Do buffer conversion if necessary.
if ( stream_.doConvertBuffer[1] )
convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
// Check stream latency
result = snd_pcm_delay( handle[1], &frames );
if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
}
tryOutput:
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
// Setup parameters and do buffer conversion if necessary.
if ( stream_.doConvertBuffer[0] ) {
buffer = stream_.deviceBuffer;
convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
channels = stream_.nDeviceChannels[0];
format = stream_.deviceFormat[0];
}
else {
buffer = stream_.userBuffer[0];
channels = stream_.nUserChannels[0];
format = stream_.userFormat;
}
// Do byte swapping if necessary.
if ( stream_.doByteSwap[0] )
byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
// Write samples to device in interleaved/non-interleaved format.
if ( stream_.deviceInterleaved[0] )
result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
else {
void *bufs[channels];
size_t offset = stream_.bufferSize * formatBytes( format );
for ( int i=0; i<channels; i++ )
bufs[i] = (void *) (buffer + (i * offset));
result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
}
if ( result < (int) stream_.bufferSize ) {
// Either an error or underrun occurred.
if ( result == -EPIPE ) {
snd_pcm_state_t state = snd_pcm_state( handle[0] );
if ( state == SND_PCM_STATE_XRUN ) {
apiInfo->xrun[0] = true;
result = snd_pcm_prepare( handle[0] );
if ( result < 0 ) {
errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
}
else
errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";
}
else {
errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
}
}
else {
errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
errorText_ = errorStream_.str();
}
error( RTAUDIO_WARNING );
goto unlock;
}
// Check stream latency
result = snd_pcm_delay( handle[0], &frames );
if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
}
unlock:
MUTEX_UNLOCK( &stream_.mutex );
RtApi::tickStreamTime();
if ( doStopStream == 1 ) this->stopStream();
}
static void *alsaCallbackHandler( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiAlsa *object = (RtApiAlsa *) info->object;
bool *isRunning = &info->isRunning;
#ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
if ( info->doRealtime ) {
std::cerr << "RtAudio alsa: " <<
(sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
"running realtime scheduling" << std::endl;
}
#endif
while ( *isRunning == true ) {
pthread_testcancel();
object->callbackEvent();
}
pthread_exit( NULL );
}
//******************** End of __LINUX_ALSA__ *********************//
#endif
#if defined(__LINUX_PULSE__)
// Code written by Peter Meerwald, pmeerw@pmeerw.net and Tristan Matthews.
// Updated by Gary Scavone, 2021.
#include <pulse/error.h>
#include <pulse/simple.h>
#include <cstdio>
// A structure needed to pass variables for device probing.
struct PaDeviceProbeInfo {
pa_mainloop_api *paMainLoopApi;
std::string defaultSinkName;
std::string defaultSourceName;
int defaultRate;
unsigned int *currentDeviceId;
std::vector< std::string > deviceNames;
std::vector< RtApiPulse::PaDeviceInfo > *paDeviceList;
std::vector< RtAudio::DeviceInfo > *rtDeviceList;
};
static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,
44100, 48000, 96000, 192000, 0};
struct rtaudio_pa_format_mapping_t {
RtAudioFormat rtaudio_format;
pa_sample_format_t pa_format;
};
static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
{RTAUDIO_SINT16, PA_SAMPLE_S16LE},
{RTAUDIO_SINT24, PA_SAMPLE_S24LE},
{RTAUDIO_SINT32, PA_SAMPLE_S32LE},
{RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
{0, PA_SAMPLE_INVALID}};
struct PulseAudioHandle {
pa_simple *s_play;
pa_simple *s_rec;
pthread_t thread;
pthread_cond_t runnable_cv;
bool runnable;
PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }
};
// The following 3 functions are called by the device probing
// system. This first one gets overall system information.
static void rt_pa_set_server_info( pa_context *context, const pa_server_info *info, void *userdata )
{
(void)context;
pa_sample_spec ss;
PaDeviceProbeInfo *paProbeInfo = static_cast<PaDeviceProbeInfo *>( userdata );
if (!info) {
paProbeInfo->paMainLoopApi->quit( paProbeInfo->paMainLoopApi, 1 );
return;
}
ss = info->sample_spec;
paProbeInfo->defaultRate = ss.rate;
paProbeInfo->defaultSinkName = info->default_sink_name;
paProbeInfo->defaultSourceName = info->default_source_name;
}
// Used to get output device information.
static void rt_pa_set_sink_info( pa_context * /*c*/, const pa_sink_info *i,
int eol, void *userdata )
{
if ( eol ) return;
PaDeviceProbeInfo *paProbeInfo = static_cast<PaDeviceProbeInfo *>( userdata );
std::string name = pa_proplist_gets( i->proplist, "device.description" );
paProbeInfo->deviceNames.push_back( name );
for ( size_t n=0; n<paProbeInfo->rtDeviceList->size(); n++ )
if ( paProbeInfo->rtDeviceList->at(n).name == name ) return; // we've already probed this one
RtAudio::DeviceInfo info;
info.name = name;
info.outputChannels = i->sample_spec.channels;
info.preferredSampleRate = i->sample_spec.rate;
info.isDefaultOutput = ( paProbeInfo->defaultSinkName == i->name );
for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
info.sampleRates.push_back( *sr );
for ( const rtaudio_pa_format_mapping_t *fm = supported_sampleformats; fm->rtaudio_format; ++fm )
info.nativeFormats |= fm->rtaudio_format;
info.ID = *(paProbeInfo->currentDeviceId);
*(paProbeInfo->currentDeviceId) = info.ID + 1;
paProbeInfo->rtDeviceList->push_back( info );
RtApiPulse::PaDeviceInfo painfo;
painfo.sinkName = i->name;
paProbeInfo->paDeviceList->push_back( painfo );
}
// Used to get input device information.
static void rt_pa_set_source_info_and_quit( pa_context * /*c*/, const pa_source_info *i,
int eol, void *userdata )
{
PaDeviceProbeInfo *paProbeInfo = static_cast<PaDeviceProbeInfo *>( userdata );
if ( eol ) {
paProbeInfo->paMainLoopApi->quit( paProbeInfo->paMainLoopApi, 0 );
return;
}
std::string name = pa_proplist_gets( i->proplist, "device.description" );
paProbeInfo->deviceNames.push_back( name );
for ( size_t n=0; n<paProbeInfo->rtDeviceList->size(); n++ ) {
if ( paProbeInfo->rtDeviceList->at(n).name == name ) {
// Check if we've already probed this as an output.
if ( !paProbeInfo->paDeviceList->at(n).sinkName.empty() ) {
// This must be a duplex device. Update the device info.
paProbeInfo->paDeviceList->at(n).sourceName = i->name;
paProbeInfo->rtDeviceList->at(n).inputChannels = i->sample_spec.channels;
paProbeInfo->rtDeviceList->at(n).isDefaultInput = ( paProbeInfo->defaultSourceName == i->name );
paProbeInfo->rtDeviceList->at(n).duplexChannels =
(paProbeInfo->rtDeviceList->at(n).inputChannels < paProbeInfo->rtDeviceList->at(n).outputChannels)
? paProbeInfo->rtDeviceList->at(n).inputChannels : paProbeInfo->rtDeviceList->at(n).outputChannels;
}
return; // we already have this
}
}
RtAudio::DeviceInfo info;
info.name = name;
info.inputChannels = i->sample_spec.channels;
info.preferredSampleRate = i->sample_spec.rate;
info.isDefaultInput = ( paProbeInfo->defaultSourceName == i->name );
for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
info.sampleRates.push_back( *sr );
for ( const rtaudio_pa_format_mapping_t *fm = supported_sampleformats; fm->rtaudio_format; ++fm )
info.nativeFormats |= fm->rtaudio_format;
info.ID = *(paProbeInfo->currentDeviceId);
*(paProbeInfo->currentDeviceId) = info.ID + 1;
paProbeInfo->rtDeviceList->push_back( info );
RtApiPulse::PaDeviceInfo painfo;
painfo.sourceName = i->name;
paProbeInfo->paDeviceList->push_back( painfo );
}
// This is the initial function that is called when the callback is
// set. This one then calls the functions above.
static void rt_pa_context_state_callback( pa_context *context, void *userdata )
{
PaDeviceProbeInfo *paProbeInfo = static_cast<PaDeviceProbeInfo *>( userdata );
auto state = pa_context_get_state(context);
switch (state) {
case PA_CONTEXT_CONNECTING:
case PA_CONTEXT_AUTHORIZING:
case PA_CONTEXT_SETTING_NAME:
break;
case PA_CONTEXT_READY:
pa_context_get_server_info( context, rt_pa_set_server_info, userdata ); // server info
pa_context_get_sink_info_list( context, rt_pa_set_sink_info, userdata ); // output info ... needs to be before input
pa_context_get_source_info_list( context, rt_pa_set_source_info_and_quit, userdata ); // input info
break;
case PA_CONTEXT_TERMINATED:
paProbeInfo->paMainLoopApi->quit( paProbeInfo->paMainLoopApi, 0 );
break;
case PA_CONTEXT_FAILED:
default:
paProbeInfo->paMainLoopApi->quit( paProbeInfo->paMainLoopApi, 1 );
}
}
RtApiPulse::~RtApiPulse()
{
if ( stream_.state != STREAM_CLOSED )
closeStream();
}
void RtApiPulse :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
pa_mainloop *ml = NULL;
pa_context *context = NULL;
char *server = NULL;
int ret = 1;
PaDeviceProbeInfo paProbeInfo;
if (!(ml = pa_mainloop_new())) {
errorStream_ << "RtApiPulse::probeDevices: pa_mainloop_new() failed.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto quit;
}
paProbeInfo.paMainLoopApi = pa_mainloop_get_api( ml );
paProbeInfo.currentDeviceId = ¤tDeviceId_;
paProbeInfo.paDeviceList = &paDeviceList_;
paProbeInfo.rtDeviceList = &deviceList_;
if (!(context = pa_context_new_with_proplist( paProbeInfo.paMainLoopApi, NULL, NULL ))) {
errorStream_ << "RtApiPulse::probeDevices: pa_context_new() failed.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto quit;
}
pa_context_set_state_callback( context, rt_pa_context_state_callback, &paProbeInfo );
if (pa_context_connect( context, server, PA_CONTEXT_NOFLAGS, NULL ) < 0) {
errorStream_ << "RtApiPulse::probeDevices: pa_context_connect() failed: "
<< pa_strerror(pa_context_errno(context));
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto quit;
}
if (pa_mainloop_run( ml, &ret ) < 0) {
errorStream_ << "RtApiPulse::probeDevices: pa_mainloop_run() failed.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto quit;
}
if (ret != 0) {
errorStream_ << "RtApiPulse::probeDevices: could not get server info.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
goto quit;
}
// Check for devices that have been unplugged.
unsigned int m;
for ( std::vector<RtAudio::DeviceInfo>::iterator it=deviceList_.begin(); it!=deviceList_.end(); ) {
for ( m=0; m<paProbeInfo.deviceNames.size(); m++ ) {
if ( (*it).name == paProbeInfo.deviceNames[m] ) {
++it;
break;
}
}
if ( m == paProbeInfo.deviceNames.size() ) { // not found so remove it from our list
it = deviceList_.erase( it );
paDeviceList_.erase( paDeviceList_.begin() + distance(deviceList_.begin(), it ) );
}
}
quit:
if (context)
pa_context_unref(context);
if (ml)
pa_mainloop_free(ml);
pa_xfree(server);
}
static void *pulseaudio_callback( void * user )
{
CallbackInfo *cbi = static_cast<CallbackInfo *>( user );
RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );
volatile bool *isRunning = &cbi->isRunning;
#ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
if (cbi->doRealtime) {
std::cerr << "RtAudio pulse: " <<
(sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
"running realtime scheduling" << std::endl;
}
#endif
while ( *isRunning ) {
pthread_testcancel();
context->callbackEvent();
}
pthread_exit( NULL );
}
bool RtApiPulse::probeDeviceOpen( unsigned int deviceId, StreamMode mode,
unsigned int channels, unsigned int firstChannel,
unsigned int sampleRate, RtAudioFormat format,
unsigned int *bufferSize, RtAudio::StreamOptions *options )
{
PulseAudioHandle *pah = 0;
unsigned long bufferBytes = 0;
pa_sample_spec ss;
int deviceIdx = -1;
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId ) {
deviceIdx = m;
break;
}
}
if ( deviceIdx < 0 ) return false;
if ( firstChannel != 0 ) {
errorText_ = "PulseAudio does not support channel offset mapping.";
return false;
}
// These may be NULL for default devices but we already have the names.
const char *dev_input = NULL;
const char *dev_output = NULL;
if ( !paDeviceList_[deviceIdx].sourceName.empty() )
dev_input = paDeviceList_[deviceIdx].sourceName.c_str();
if ( !paDeviceList_[deviceIdx].sinkName.empty() )
dev_output = paDeviceList_[deviceIdx].sinkName.c_str();
if ( mode==INPUT && deviceList_[deviceIdx].inputChannels < channels ) {
errorText_ = "PulseAudio device does not support requested input channel count.";
return false;
}
if ( mode==OUTPUT && deviceList_[deviceIdx].outputChannels < channels ) {
errorText_ = "PulseAudio device does not support requested output channel count.";
return false;
}
ss.channels = channels;
bool sr_found = false;
for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {
if ( sampleRate == *sr ) {
sr_found = true;
stream_.sampleRate = sampleRate;
ss.rate = sampleRate;
break;
}
}
if ( !sr_found ) {
stream_.sampleRate = sampleRate;
ss.rate = sampleRate;
}
bool sf_found = 0;
for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {
if ( format == sf->rtaudio_format ) {
sf_found = true;
stream_.userFormat = sf->rtaudio_format;
stream_.deviceFormat[mode] = stream_.userFormat;
ss.format = sf->pa_format;
break;
}
}
if ( !sf_found ) { // Use internal data format conversion.
stream_.userFormat = format;
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
ss.format = PA_SAMPLE_FLOAT32LE;
}
// Set other stream parameters.
if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
else stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
stream_.nBuffers = options ? options->numberOfBuffers : 1;
stream_.doByteSwap[mode] = false;
stream_.nUserChannels[mode] = channels;
stream_.nDeviceChannels[mode] = channels + firstChannel;
stream_.channelOffset[mode] = 0;
std::string streamName = "RtAudio";
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] )
stream_.doConvertBuffer[mode] = true;
// Allocate necessary internal buffers.
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
stream_.bufferSize = *bufferSize;
if ( stream_.doConvertBuffer[mode] ) {
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
if ( mode == INPUT ) {
if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
if ( bufferBytes <= bytesOut ) makeBuffer = false;
}
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.deviceId[mode] = deviceIdx;
// Setup the buffer conversion information structure.
if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
if ( !stream_.apiHandle ) {
PulseAudioHandle *pah = new PulseAudioHandle;
if ( !pah ) {
errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
goto error;
}
stream_.apiHandle = pah;
if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {
errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
goto error;
}
}
pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
int error;
if ( options && !options->streamName.empty() ) streamName = options->streamName;
switch ( mode ) {
pa_buffer_attr buffer_attr;
case INPUT:
buffer_attr.fragsize = bufferBytes;
buffer_attr.maxlength = -1;
pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD,
dev_input, "Record", &ss, NULL, &buffer_attr, &error );
if ( !pah->s_rec ) {
errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
goto error;
}
break;
case OUTPUT: {
pa_buffer_attr * attr_ptr;
if ( options && options->numberOfBuffers > 0 ) {
// pa_buffer_attr::fragsize is recording-only.
// Hopefully PortAudio won't access uninitialized fields.
buffer_attr.maxlength = bufferBytes * options->numberOfBuffers;
buffer_attr.minreq = -1;
buffer_attr.prebuf = -1;
buffer_attr.tlength = -1;
attr_ptr = &buffer_attr;
} else {
attr_ptr = nullptr;
}
pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK,
dev_output, "Playback", &ss, NULL, attr_ptr, &error );
if ( !pah->s_play ) {
errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
goto error;
}
break;
}
case DUPLEX:
/* Note: We could add DUPLEX by synchronizing multiple streams,
but it would mean moving from Simple API to Asynchronous API:
https://freedesktop.org/software/pulseaudio/doxygen/streams.html#sync_streams */
errorText_ = "RtApiPulse::probeDeviceOpen: duplex not supported for PulseAudio.";
goto error;
default:
goto error;
}
if ( stream_.mode == UNINITIALIZED )
stream_.mode = mode;
else if ( stream_.mode == mode )
goto error;
else
stream_.mode = DUPLEX;
if ( !stream_.callbackInfo.isRunning ) {
stream_.callbackInfo.object = this;
stream_.state = STREAM_STOPPED;
// Set the thread attributes for joinable and realtime scheduling
// priority (optional). The higher priority will only take affect
// if the program is run as root or suid. Note, under Linux
// processes with CAP_SYS_NICE privilege, a user can change
// scheduling policy and priority (thus need not be root). See
// POSIX "capabilities".
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
#ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
stream_.callbackInfo.doRealtime = true;
struct sched_param param;
int priority = options->priority;
int min = sched_get_priority_min( SCHED_RR );
int max = sched_get_priority_max( SCHED_RR );
if ( priority < min ) priority = min;
else if ( priority > max ) priority = max;
param.sched_priority = priority;
// Set the policy BEFORE the priority. Otherwise it fails.
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
// This is definitely required. Otherwise it fails.
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedparam(&attr, ¶m);
}
else
pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
#else
pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
#endif
stream_.callbackInfo.isRunning = true;
int result = pthread_create( &pah->thread, &attr, pulseaudio_callback, (void *)&stream_.callbackInfo);
pthread_attr_destroy(&attr);
if(result != 0) {
// Failed. Try instead with default attributes.
result = pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo);
if(result != 0) {
stream_.callbackInfo.isRunning = false;
errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
goto error;
}
}
}
return SUCCESS;
error:
if ( pah && stream_.callbackInfo.isRunning ) {
pthread_cond_destroy( &pah->runnable_cv );
delete pah;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiPulse::closeStream( void )
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
stream_.callbackInfo.isRunning = false;
if ( pah ) {
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state == STREAM_STOPPED ) {
pah->runnable = true;
pthread_cond_signal( &pah->runnable_cv );
}
MUTEX_UNLOCK( &stream_.mutex );
pthread_join( pah->thread, 0 );
if ( pah->s_play ) {
pa_simple_flush( pah->s_play, NULL );
pa_simple_free( pah->s_play );
}
if ( pah->s_rec )
pa_simple_free( pah->s_rec );
pthread_cond_destroy( &pah->runnable_cv );
delete pah;
stream_.apiHandle = 0;
}
if ( stream_.userBuffer[0] ) {
free( stream_.userBuffer[0] );
stream_.userBuffer[0] = 0;
}
if ( stream_.userBuffer[1] ) {
free( stream_.userBuffer[1] );
stream_.userBuffer[1] = 0;
}
clearStreamInfo();
}
void RtApiPulse::callbackEvent( void )
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
if ( stream_.state == STREAM_STOPPED ) {
MUTEX_LOCK( &stream_.mutex );
while ( !pah->runnable )
pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );
if ( stream_.state != STREAM_RUNNING ) {
MUTEX_UNLOCK( &stream_.mutex );
return;
}
MUTEX_UNLOCK( &stream_.mutex );
}
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "
"this shouldn't happen!";
error( RTAUDIO_WARNING );
return;
}
RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
stream_.bufferSize, streamTime, status,
stream_.callbackInfo.userData );
if ( doStopStream == 2 ) {
abortStream();
return;
}
MUTEX_LOCK( &stream_.mutex );
void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
if ( stream_.state != STREAM_RUNNING )
goto unlock;
int pa_error;
size_t bytes;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
if ( stream_.doConvertBuffer[OUTPUT] ) {
convertBuffer( stream_.deviceBuffer,
stream_.userBuffer[OUTPUT],
stream_.convertInfo[OUTPUT] );
bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
formatBytes( stream_.deviceFormat[OUTPUT] );
} else
bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
formatBytes( stream_.userFormat );
if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {
errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<
pa_strerror( pa_error ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {
if ( stream_.doConvertBuffer[INPUT] )
bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
formatBytes( stream_.deviceFormat[INPUT] );
else
bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
formatBytes( stream_.userFormat );
if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {
errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<
pa_strerror( pa_error ) << ".";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
}
if ( stream_.doConvertBuffer[INPUT] ) {
convertBuffer( stream_.userBuffer[INPUT],
stream_.deviceBuffer,
stream_.convertInfo[INPUT] );
}
}
unlock:
MUTEX_UNLOCK( &stream_.mutex );
RtApi::tickStreamTime();
if ( doStopStream == 1 )
stopStream();
}
RtAudioErrorType RtApiPulse::startStream( void )
{
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiPulse::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiPulse::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
MUTEX_LOCK( &stream_.mutex );
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
stream_.state = STREAM_RUNNING;
pah->runnable = true;
pthread_cond_signal( &pah->runnable_cv );
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiPulse::stopStream( void )
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiPulse::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
stream_.state = STREAM_STOPPED;
MUTEX_LOCK( &stream_.mutex );
if ( pah ) {
pah->runnable = false;
if ( pah->s_play ) {
int pa_error;
if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {
errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<
pa_strerror( pa_error ) << ".";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_SYSTEM_ERROR );
}
}
}
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiPulse::abortStream( void )
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiPulse::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );
stream_.state = STREAM_STOPPED;
MUTEX_LOCK( &stream_.mutex );
if ( pah ) {
pah->runnable = false;
if ( pah->s_play ) {
int pa_error;
if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {
errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<
pa_strerror( pa_error ) << ".";
errorText_ = errorStream_.str();
MUTEX_UNLOCK( &stream_.mutex );
return error( RTAUDIO_SYSTEM_ERROR );
}
}
}
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
//******************** End of __LINUX_PULSE__ *********************//
#endif
#if defined(__LINUX_OSS__)
#include <unistd.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
static void *ossCallbackHandler(void * ptr);
// A structure to hold various information related to the OSS API
// implementation.
struct OssHandle {
int id[2]; // device ids
bool xrun[2];
bool triggered;
pthread_cond_t runnable;
OssHandle()
:triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
};
RtApiOss :: RtApiOss()
{
// Nothing to do here.
}
RtApiOss :: ~RtApiOss()
{
if ( stream_.state != STREAM_CLOSED ) closeStream();
}
void RtApiOss :: probeDevices( void )
{
// See list of required functionality in RtApi::probeDevices().
int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
if ( mixerfd == -1 ) {
errorText_ = "RtApiOss::probeDevices: error opening '/dev/mixer'.";
error( RTAUDIO_SYSTEM_ERROR );
return;
}
oss_sysinfo sysinfo;
if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
close( mixerfd );
errorText_ = "RtApiOss::probeDevices: error getting sysinfo, OSS version >= 4.0 is required.";
error( RTAUDIO_SYSTEM_ERROR );
return;
}
unsigned int nDevices = sysinfo.numaudios;
if ( nDevices == 0 ) {
close( mixerfd );
deviceList_.clear();
return;
}
oss_audioinfo ainfo;
unsigned int m, n;
std::vector<std::string> deviceNames;
for ( n=0; n<nDevices; n++ ) {
ainfo.dev = n;
if ( ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo ) == -1 ) continue;
deviceNames.push_back( ainfo.name );
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].name == deviceNames.back() )
break; // We already have this device.
}
if ( m == deviceList_.size() ) { // new device
RtAudio::DeviceInfo info;
if ( probeDeviceInfo( info, ainfo ) == false ) continue; // ignore if probe fails
info.ID = currentDeviceId_++; // arbitrary internal device ID
deviceList_.push_back( info );
}
}
close( mixerfd );
// Remove any devices left in the list that are no longer available.
for ( std::vector<RtAudio::DeviceInfo>::iterator it=deviceList_.begin(); it!=deviceList_.end(); ) {
for ( m=0; m<deviceNames.size(); m++ ) {
if ( (*it).name == deviceNames[m] ) {
++it;
break;
}
}
if ( m == deviceNames.size() ) // not found so remove it from our list
it = deviceList_.erase( it );
}
// I don't think the OSS API supports default devices. Our parent
// class versions of the getDefault functions will return the first
// one found.
}
bool RtApiOss :: probeDeviceInfo( RtAudio::DeviceInfo &info, oss_audioinfo &ainfo )
{
// Probe channels
if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
if ( ainfo.caps & PCM_CAP_DUPLEX ) {
if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
}
// Probe data formats ... do for input
unsigned long mask = ainfo.iformats;
if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
info.nativeFormats |= RTAUDIO_SINT16;
if ( mask & AFMT_S8 )
info.nativeFormats |= RTAUDIO_SINT8;
if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
info.nativeFormats |= RTAUDIO_SINT32;
#ifdef AFMT_FLOAT
if ( mask & AFMT_FLOAT )
info.nativeFormats |= RTAUDIO_FLOAT32;
#endif
if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
info.nativeFormats |= RTAUDIO_SINT24;
// Check that we have at least one supported format
if ( info.nativeFormats == 0 ) {
errorStream_ << "RtApiOss::probeDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
// Probe the supported sample rates.
info.sampleRates.clear();
if ( ainfo.nrates ) {
for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
info.sampleRates.push_back( SAMPLE_RATES[k] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[k];
break;
}
}
}
}
else {
// Check min and max rate values;
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {
info.sampleRates.push_back( SAMPLE_RATES[k] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
}
if ( info.sampleRates.size() == 0 ) {
errorStream_ << "RtApiOss::probeDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
error( RTAUDIO_WARNING );
return false;
}
return true;
}
bool RtApiOss :: probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
if ( mixerfd == -1 ) {
errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
return FAILURE;
}
oss_sysinfo sysinfo;
int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
if ( result == -1 ) {
close( mixerfd );
errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
return FAILURE;
}
unsigned int nDevices = sysinfo.numaudios;
if ( nDevices == 0 ) {
// This should not happen because a check is made before this function is called.
close( mixerfd );
errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
return FAILURE;
}
std::string deviceName;
unsigned int m, device;
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId ) {
deviceName = deviceList_[m].name;
break;
}
}
if ( deviceName.empty() ) {
errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
oss_audioinfo ainfo;
for ( device=0; device<nDevices; device++ ) {
ainfo.dev = device;
result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
if ( result == -1 ) continue;
if ( deviceName == std::string( ainfo.name ) ) break;
}
close( mixerfd );
if ( device == nDevices ) {
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") not found.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check if device supports input or output
if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
if ( mode == OUTPUT )
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
else
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
errorText_ = errorStream_.str();
return FAILURE;
}
int flags = 0;
OssHandle *handle = (OssHandle *) stream_.apiHandle;
if ( mode == OUTPUT )
flags |= O_WRONLY;
else { // mode == INPUT
if (stream_.mode == OUTPUT && stream_.deviceId[0] == device) {
// We just set the same device for playback ... close and reopen for duplex (OSS only).
close( handle->id[0] );
handle->id[0] = 0;
if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check that the number previously set channels is the same.
if ( stream_.nUserChannels[0] != channels ) {
errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
flags |= O_RDWR;
}
else
flags |= O_RDONLY;
}
// Set exclusive access if specified.
if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
// Try to open the device.
int fd;
fd = open( ainfo.devnode, flags, 0 );
if ( fd == -1 ) {
if ( errno == EBUSY )
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
else
errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// For duplex operation, specifically set this mode (this doesn't seem to work).
/*
if ( flags | O_RDWR ) {
result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
if ( result == -1) {
errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
*/
// Check the device channel support.
stream_.nUserChannels[mode] = channels;
if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the number of channels.
int deviceChannels = channels + firstChannel;
result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.nDeviceChannels[mode] = deviceChannels;
// Get the data format mask
int mask;
result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
if ( result == -1 ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine how to set the device format.
stream_.userFormat = format;
int deviceFormat = -1;
stream_.doByteSwap[mode] = false;
if ( format == RTAUDIO_SINT8 ) {
if ( mask & AFMT_S8 ) {
deviceFormat = AFMT_S8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
}
else if ( format == RTAUDIO_SINT16 ) {
if ( mask & AFMT_S16_NE ) {
deviceFormat = AFMT_S16_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
else if ( mask & AFMT_S16_OE ) {
deviceFormat = AFMT_S16_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
stream_.doByteSwap[mode] = true;
}
}
else if ( format == RTAUDIO_SINT24 ) {
if ( mask & AFMT_S24_NE ) {
deviceFormat = AFMT_S24_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
}
else if ( mask & AFMT_S24_OE ) {
deviceFormat = AFMT_S24_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
stream_.doByteSwap[mode] = true;
}
}
else if ( format == RTAUDIO_SINT32 ) {
if ( mask & AFMT_S32_NE ) {
deviceFormat = AFMT_S32_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
}
else if ( mask & AFMT_S32_OE ) {
deviceFormat = AFMT_S32_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
stream_.doByteSwap[mode] = true;
}
}
if ( deviceFormat == -1 ) {
// The user requested format is not natively supported by the device.
if ( mask & AFMT_S16_NE ) {
deviceFormat = AFMT_S16_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
else if ( mask & AFMT_S32_NE ) {
deviceFormat = AFMT_S32_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
}
else if ( mask & AFMT_S24_NE ) {
deviceFormat = AFMT_S24_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
}
else if ( mask & AFMT_S16_OE ) {
deviceFormat = AFMT_S16_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
stream_.doByteSwap[mode] = true;
}
else if ( mask & AFMT_S32_OE ) {
deviceFormat = AFMT_S32_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
stream_.doByteSwap[mode] = true;
}
else if ( mask & AFMT_S24_OE ) {
deviceFormat = AFMT_S24_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
stream_.doByteSwap[mode] = true;
}
else if ( mask & AFMT_S8) {
deviceFormat = AFMT_S8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
}
if ( stream_.deviceFormat[mode] == 0 ) {
// This really shouldn't happen ...
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the data format.
int temp = deviceFormat;
result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
if ( result == -1 || deviceFormat != temp ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Attempt to set the buffer size. According to OSS, the minimum
// number of buffers is two. The supposed minimum buffer size is 16
// bytes, so that will be our lower bound. The argument to this
// call is in the form 0xMMMMSSSS (hex), where the buffer size (in
// bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
// We'll check the actual value used near the end of the setup
// procedure.
int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
int buffers = 0;
if ( options ) buffers = options->numberOfBuffers;
if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
if ( buffers < 2 ) buffers = 3;
temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
if ( result == -1 ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.nBuffers = buffers;
// Save buffer size (in sample frames).
*bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
stream_.bufferSize = *bufferSize;
// Set the sample rate.
int srate = sampleRate;
result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
if ( result == -1 ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Verify the sample rate setup worked.
if ( abs( srate - (int)sampleRate ) > 100 ) {
close( fd );
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.sampleRate = sampleRate;
if ( mode == INPUT && stream_.mode == OUTPUT && stream_.deviceId[0] == device) {
// We're doing duplex setup here.
stream_.deviceFormat[0] = stream_.deviceFormat[1];
stream_.nDeviceChannels[0] = deviceChannels;
}
// Set interleaving parameters.
stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
stream_.userInterleaved = false;
// Set flags for buffer conversion
stream_.doConvertBuffer[mode] = false;
if ( stream_.userFormat != stream_.deviceFormat[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
stream_.doConvertBuffer[mode] = true;
if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1 )
stream_.doConvertBuffer[mode] = true;
// Allocate the stream handles if necessary and then save.
if ( stream_.apiHandle == 0 ) {
try {
handle = new OssHandle;
}
catch ( std::bad_alloc& ) {
errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
goto error;
}
if ( pthread_cond_init( &handle->runnable, NULL ) ) {
errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *) handle;
}
else {
handle = (OssHandle *) stream_.apiHandle;
}
handle->id[mode] = fd;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
if ( stream_.userBuffer[mode] == NULL ) {
errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if ( stream_.doConvertBuffer[mode] ) {
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
if ( mode == INPUT ) {
if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
if ( bufferBytes <= bytesOut ) makeBuffer = false;
}
}
if ( makeBuffer ) {
bufferBytes *= *bufferSize;
if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
if ( stream_.deviceBuffer == NULL ) {
errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.deviceId[mode] = device;
stream_.state = STREAM_STOPPED;
// Setup the buffer conversion information structure.
if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
// Setup thread if necessary.
if ( stream_.mode == OUTPUT && mode == INPUT ) {
// We had already set up an output stream.
stream_.mode = DUPLEX;
if ( stream_.deviceId[0] == device ) handle->id[0] = fd;
}
else {
stream_.mode = mode;
// Setup callback thread.
stream_.callbackInfo.object = (void *) this;
// Set the thread attributes for joinable and realtime scheduling
// priority. The higher priority will only take affect if the
// program is run as root or suid.
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
#ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
stream_.callbackInfo.doRealtime = true;
struct sched_param param;
int priority = options->priority;
int min = sched_get_priority_min( SCHED_RR );
int max = sched_get_priority_max( SCHED_RR );
if ( priority < min ) priority = min;
else if ( priority > max ) priority = max;
param.sched_priority = priority;
// Set the policy BEFORE the priority. Otherwise it fails.
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
// This is definitely required. Otherwise it fails.
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedparam(&attr, ¶m);
}
else
pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
#else
pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
#endif
stream_.callbackInfo.isRunning = true;
result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
pthread_attr_destroy( &attr );
if ( result ) {
// Failed. Try instead with default attributes.
result = pthread_create( &stream_.callbackInfo.thread, NULL, ossCallbackHandler, &stream_.callbackInfo );
if ( result ) {
stream_.callbackInfo.isRunning = false;
errorText_ = "RtApiOss::error creating callback thread!";
goto error;
}
}
}
return SUCCESS;
error:
if ( handle ) {
pthread_cond_destroy( &handle->runnable );
if ( handle->id[0] ) close( handle->id[0] );
if ( handle->id[1] ) close( handle->id[1] );
delete handle;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiOss :: closeStream()
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiOss::closeStream(): no open stream to close!";
error( RTAUDIO_WARNING );
return;
}
OssHandle *handle = (OssHandle *) stream_.apiHandle;
stream_.callbackInfo.isRunning = false;
MUTEX_LOCK( &stream_.mutex );
if ( stream_.state == STREAM_STOPPED )
pthread_cond_signal( &handle->runnable );
MUTEX_UNLOCK( &stream_.mutex );
pthread_join( stream_.callbackInfo.thread, NULL );
if ( stream_.state == STREAM_RUNNING ) {
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
else
ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
stream_.state = STREAM_STOPPED;
}
if ( handle ) {
pthread_cond_destroy( &handle->runnable );
if ( handle->id[0] ) close( handle->id[0] );
if ( handle->id[1] ) close( handle->id[1] );
delete handle;
stream_.apiHandle = 0;
}
for ( int i=0; i<2; i++ ) {
if ( stream_.userBuffer[i] ) {
free( stream_.userBuffer[i] );
stream_.userBuffer[i] = 0;
}
}
if ( stream_.deviceBuffer ) {
free( stream_.deviceBuffer );
stream_.deviceBuffer = 0;
}
clearStreamInfo();
//stream_.mode = UNINITIALIZED;
//stream_.state = STREAM_CLOSED;
}
RtAudioErrorType RtApiOss :: startStream()
{
if ( stream_.state != STREAM_STOPPED ) {
if ( stream_.state == STREAM_RUNNING )
errorText_ = "RtApiOss::startStream(): the stream is already running!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiOss::startStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
MUTEX_LOCK( &stream_.mutex );
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
stream_.state = STREAM_RUNNING;
// No need to do anything else here ... OSS automatically starts
// when fed samples.
MUTEX_UNLOCK( &stream_.mutex );
OssHandle *handle = (OssHandle *) stream_.apiHandle;
pthread_cond_signal( &handle->runnable );
return RTAUDIO_NO_ERROR;
}
RtAudioErrorType RtApiOss :: stopStream()
{
if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_CLOSED )
errorText_ = "RtApiOss::stopStream(): the stream is closed!";
return error( RTAUDIO_WARNING );
}
MUTEX_LOCK( &stream_.mutex );
// The state might change while waiting on a mutex.
if ( stream_.state == STREAM_STOPPED ) {
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
int result = 0;
OssHandle *handle = (OssHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
// Flush the output with zeros a few times.
char *buffer;
int samples;
RtAudioFormat format;
if ( stream_.doConvertBuffer[0] ) {
buffer = stream_.deviceBuffer;
samples = stream_.bufferSize * stream_.nDeviceChannels[0];
format = stream_.deviceFormat[0];
}
else {
buffer = stream_.userBuffer[0];
samples = stream_.bufferSize * stream_.nUserChannels[0];
format = stream_.userFormat;
}
memset( buffer, 0, samples * formatBytes(format) );
for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
result = write( handle->id[0], buffer, samples * formatBytes(format) );
if ( result == -1 ) {
errorText_ = "RtApiOss::stopStream: audio write error.";
error( RTAUDIO_WARNING );
}
}
result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
if ( result == -1 ) {
errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.deviceId[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
handle->triggered = false;
}
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
if ( result == -1 ) {
errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.deviceId[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK( &stream_.mutex );
if ( result != -1 ) return RTAUDIO_NO_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
RtAudioErrorType RtApiOss :: abortStream()
{
if ( stream_.state != STREAM_RUNNING ) {
if ( stream_.state == STREAM_STOPPED )
errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED )
errorText_ = "RtApiOss::abortStream(): the stream is stopping or closed!";
return error( RTAUDIO_WARNING );
}
MUTEX_LOCK( &stream_.mutex );
// The state might change while waiting on a mutex.
if ( stream_.state == STREAM_STOPPED ) {
MUTEX_UNLOCK( &stream_.mutex );
return RTAUDIO_NO_ERROR;
}
int result = 0;
OssHandle *handle = (OssHandle *) stream_.apiHandle;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
if ( result == -1 ) {
errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.deviceId[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
handle->triggered = false;
}
if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
if ( result == -1 ) {
errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.deviceId[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK( &stream_.mutex );
if ( result != -1 ) return RTAUDIO_SYSTEM_ERROR;
return error( RTAUDIO_SYSTEM_ERROR );
}
void RtApiOss :: callbackEvent()
{
OssHandle *handle = (OssHandle *) stream_.apiHandle;
if ( stream_.state == STREAM_STOPPED ) {
MUTEX_LOCK( &stream_.mutex );
pthread_cond_wait( &handle->runnable, &stream_.mutex );
if ( stream_.state != STREAM_RUNNING ) {
MUTEX_UNLOCK( &stream_.mutex );
return;
}
MUTEX_UNLOCK( &stream_.mutex );
}
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
error( RTAUDIO_WARNING );
return;
}
// Invoke user callback to get fresh output data.
int doStopStream = 0;
RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
if ( doStopStream == 2 ) {
this->abortStream();
return;
}
MUTEX_LOCK( &stream_.mutex );
// The state might change while waiting on a mutex.
if ( stream_.state == STREAM_STOPPED ) goto unlock;
int result;
char *buffer;
int samples;
RtAudioFormat format;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
// Setup parameters and do buffer conversion if necessary.
if ( stream_.doConvertBuffer[0] ) {
buffer = stream_.deviceBuffer;
convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
samples = stream_.bufferSize * stream_.nDeviceChannels[0];
format = stream_.deviceFormat[0];
}
else {
buffer = stream_.userBuffer[0];
samples = stream_.bufferSize * stream_.nUserChannels[0];
format = stream_.userFormat;
}
// Do byte swapping if necessary.
if ( stream_.doByteSwap[0] )
byteSwapBuffer( buffer, samples, format );
if ( stream_.mode == DUPLEX && handle->triggered == false ) {
int trig = 0;
ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
result = write( handle->id[0], buffer, samples * formatBytes(format) );
trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
handle->triggered = true;
}
else
// Write samples to device.
result = write( handle->id[0], buffer, samples * formatBytes(format) );
if ( result == -1 ) {
// We'll assume this is an underrun, though there isn't a
// specific means for determining that.
handle->xrun[0] = true;
errorText_ = "RtApiOss::callbackEvent: audio write error.";
error( RTAUDIO_WARNING );
// Continue on to input section.
}
}
if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
// Setup parameters.
if ( stream_.doConvertBuffer[1] ) {
buffer = stream_.deviceBuffer;
samples = stream_.bufferSize * stream_.nDeviceChannels[1];
format = stream_.deviceFormat[1];
}
else {
buffer = stream_.userBuffer[1];
samples = stream_.bufferSize * stream_.nUserChannels[1];
format = stream_.userFormat;
}
// Read samples from device.
result = read( handle->id[1], buffer, samples * formatBytes(format) );
if ( result == -1 ) {
// We'll assume this is an overrun, though there isn't a
// specific means for determining that.
handle->xrun[1] = true;
errorText_ = "RtApiOss::callbackEvent: audio read error.";
error( RTAUDIO_WARNING );
goto unlock;
}
// Do byte swapping if necessary.
if ( stream_.doByteSwap[1] )
byteSwapBuffer( buffer, samples, format );
// Do buffer conversion if necessary.
if ( stream_.doConvertBuffer[1] )
convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
}
unlock:
MUTEX_UNLOCK( &stream_.mutex );
RtApi::tickStreamTime();
if ( doStopStream == 1 ) this->stopStream();
}
static void *ossCallbackHandler( void *ptr )
{
CallbackInfo *info = (CallbackInfo *) ptr;
RtApiOss *object = (RtApiOss *) info->object;
bool *isRunning = &info->isRunning;
#ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
if (info->doRealtime) {
std::cerr << "RtAudio oss: " <<
(sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
"running realtime scheduling" << std::endl;
}
#endif
while ( *isRunning == true ) {
pthread_testcancel();
object->callbackEvent();
}
pthread_exit( NULL );
}
//******************** End of __LINUX_OSS__ *********************//
#endif
// *************************************************** //
//
// Protected common (OS-independent) RtAudio methods.
//
// *************************************************** //
// This method can be modified to control the behavior of error
// message printing.
RtAudioErrorType RtApi :: error( RtAudioErrorType type )
{
errorStream_.str(""); // clear the ostringstream to avoid repeated messages
// Don't output warnings if showWarnings_ is false
if ( type == RTAUDIO_WARNING && showWarnings_ == false ) return type;
if ( errorCallback_ ) {
//const std::string errorMessage = errorText_;
//errorCallback_( type, errorMessage );
errorCallback_( type, errorText_ );
}
else
std::cerr << '\n' << errorText_ << "\n\n";
return type;
}
/*
void RtApi :: verifyStream()
{
if ( stream_.state == STREAM_CLOSED ) {
errorText_ = "RtApi:: a stream is not open!";
error( RtAudioError::INVALID_USE );
}
}
*/
void RtApi :: clearStreamInfo()
{
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
stream_.sampleRate = 0;
stream_.bufferSize = 0;
stream_.nBuffers = 0;
stream_.userFormat = 0;
stream_.userInterleaved = true;
stream_.streamTime = 0.0;
stream_.apiHandle = 0;
stream_.deviceBuffer = 0;
stream_.callbackInfo.callback = 0;
stream_.callbackInfo.userData = 0;
stream_.callbackInfo.isRunning = false;
stream_.callbackInfo.deviceDisconnected = false;
for ( int i=0; i<2; i++ ) {
stream_.deviceId[i] = 11111;
stream_.doConvertBuffer[i] = false;
stream_.deviceInterleaved[i] = true;
stream_.doByteSwap[i] = false;
stream_.nUserChannels[i] = 0;
stream_.nDeviceChannels[i] = 0;
stream_.channelOffset[i] = 0;
stream_.deviceFormat[i] = 0;
stream_.latency[i] = 0;
stream_.userBuffer[i] = 0;
stream_.convertInfo[i].channels = 0;
stream_.convertInfo[i].inJump = 0;
stream_.convertInfo[i].outJump = 0;
stream_.convertInfo[i].inFormat = 0;
stream_.convertInfo[i].outFormat = 0;
stream_.convertInfo[i].inOffset.clear();
stream_.convertInfo[i].outOffset.clear();
}
}
unsigned int RtApi :: formatBytes( RtAudioFormat format )
{
if ( format == RTAUDIO_SINT16 )
return 2;
else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )
return 4;
else if ( format == RTAUDIO_FLOAT64 )
return 8;
else if ( format == RTAUDIO_SINT24 )
return 3;
else if ( format == RTAUDIO_SINT8 )
return 1;
errorText_ = "RtApi::formatBytes: undefined format.";
error( RTAUDIO_WARNING );
return 0;
}
void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
{
if ( mode == INPUT ) { // convert device to user buffer
stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
stream_.convertInfo[mode].outFormat = stream_.userFormat;
}
else { // convert user to device buffer
stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
stream_.convertInfo[mode].inFormat = stream_.userFormat;
stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
}
if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
else
stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
// Set up the interleave/deinterleave offsets.
if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
( mode == INPUT && stream_.userInterleaved ) ) {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
stream_.convertInfo[mode].outOffset.push_back( k );
stream_.convertInfo[mode].inJump = 1;
}
}
else {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
stream_.convertInfo[mode].inOffset.push_back( k );
stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
stream_.convertInfo[mode].outJump = 1;
}
}
}
else { // no (de)interleaving
if ( stream_.userInterleaved ) {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
stream_.convertInfo[mode].inOffset.push_back( k );
stream_.convertInfo[mode].outOffset.push_back( k );
}
}
else {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
stream_.convertInfo[mode].inJump = 1;
stream_.convertInfo[mode].outJump = 1;
}
}
}
// Add channel offset.
if ( firstChannel > 0 ) {
if ( stream_.deviceInterleaved[mode] ) {
if ( mode == OUTPUT ) {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
stream_.convertInfo[mode].outOffset[k] += firstChannel;
}
else {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
stream_.convertInfo[mode].inOffset[k] += firstChannel;
}
}
else {
if ( mode == OUTPUT ) {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
}
else {
for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
}
}
}
}
void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
{
// This function does format conversion, input/output channel compensation, and
// data interleaving/deinterleaving. 24-bit integers are assumed to occupy
// the lower three bytes of a 32-bit integer.
// Clear our duplex device output buffer if there are more device outputs than user outputs
if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX && info.outJump > info.inJump )
memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
int j;
if (info.outFormat == RTAUDIO_FLOAT64) {
Float64 *out = (Float64 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8) {
signed char *in = (signed char *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float64) in[info.inOffset[j]] / 128.0;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16) {
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float64) in[info.inOffset[j]] / 32768.0;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24) {
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float64) in[info.inOffset[j]].asInt() / 8388608.0;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32) {
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float64) in[info.inOffset[j]] / 2147483648.0;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32) {
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64) {
// Channel compensation and/or (de)interleaving only.
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_FLOAT32) {
Float32 *out = (Float32 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8) {
signed char *in = (signed char *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float32) in[info.inOffset[j]] / 128.f;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16) {
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float32) in[info.inOffset[j]] / 32768.f;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24) {
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float32) in[info.inOffset[j]].asInt() / 8388608.f;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32) {
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float32) in[info.inOffset[j]] / 2147483648.f;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32) {
// Channel compensation and/or (de)interleaving only.
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64) {
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT32) {
Int32 *out = (Int32 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8) {
signed char *in = (signed char *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
out[info.outOffset[j]] <<= 24;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16) {
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
out[info.outOffset[j]] <<= 16;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24) {
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();
out[info.outOffset[j]] <<= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32) {
// Channel compensation and/or (de)interleaving only.
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32) {
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
// Use llround() which returns `long long` which is guaranteed to be at least 64 bits.
out[info.outOffset[j]] = (Int32) std::max(std::min(std::llround(in[info.inOffset[j]] * 2147483648.f), 2147483647LL), -2147483648LL);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64) {
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) std::max(std::min(std::llround(in[info.inOffset[j]] * 2147483648.0), 2147483647LL), -2147483648LL);
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT24) {
Int24 *out = (Int24 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8) {
signed char *in = (signed char *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);
//out[info.outOffset[j]] <<= 16;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16) {
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);
//out[info.outOffset[j]] <<= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24) {
// Channel compensation and/or (de)interleaving only.
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32) {
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);
//out[info.outOffset[j]] >>= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32) {
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) std::max(std::min(std::llround(in[info.inOffset[j]] * 8388608.f), 8388607LL), -8388608LL);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64) {
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int32) std::max(std::min(std::llround(in[info.inOffset[j]] * 8388608.0), 8388607LL), -8388608LL);
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT16) {
Int16 *out = (Int16 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8) {
signed char *in = (signed char *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
out[info.outOffset[j]] <<= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16) {
// Channel compensation and/or (de)interleaving only.
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24) {
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32) {
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32) {
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int16) std::max(std::min(std::llround(in[info.inOffset[j]] * 32768.f), 32767LL), -32768LL);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64) {
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (Int16) std::max(std::min(std::llround(in[info.inOffset[j]] * 32768.0), 32767LL), -32768LL);
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT8) {
signed char *out = (signed char *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8) {
// Channel compensation and/or (de)interleaving only.
signed char *in = (signed char *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
if (info.inFormat == RTAUDIO_SINT16) {
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24) {
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32) {
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32) {
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (signed char) std::max(std::min(std::llround(in[info.inOffset[j]] * 128.f), 127LL), -128LL);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64) {
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i=0; i<stream_.bufferSize; i++) {
for (j=0; j<info.channels; j++) {
out[info.outOffset[j]] = (signed char) std::max(std::min(std::llround(in[info.inOffset[j]] * 128.0), 127LL), -128LL);
}
in += info.inJump;
out += info.outJump;
}
}
}
}
//static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
//static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
//static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
{
char val;
char *ptr;
ptr = buffer;
if ( format == RTAUDIO_SINT16 ) {
for ( unsigned int i=0; i<samples; i++ ) {
// Swap 1st and 2nd bytes.
val = *(ptr);
*(ptr) = *(ptr+1);
*(ptr+1) = val;
// Increment 2 bytes.
ptr += 2;
}
}
else if ( format == RTAUDIO_SINT32 ||
format == RTAUDIO_FLOAT32 ) {
for ( unsigned int i=0; i<samples; i++ ) {
// Swap 1st and 4th bytes.
val = *(ptr);
*(ptr) = *(ptr+3);
*(ptr+3) = val;
// Swap 2nd and 3rd bytes.
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr+1);
*(ptr+1) = val;
// Increment 3 more bytes.
ptr += 3;
}
}
else if ( format == RTAUDIO_SINT24 ) {
for ( unsigned int i=0; i<samples; i++ ) {
// Swap 1st and 3rd bytes.
val = *(ptr);
*(ptr) = *(ptr+2);
*(ptr+2) = val;
// Increment 2 more bytes.
ptr += 2;
}
}
else if ( format == RTAUDIO_FLOAT64 ) {
for ( unsigned int i=0; i<samples; i++ ) {
// Swap 1st and 8th bytes
val = *(ptr);
*(ptr) = *(ptr+7);
*(ptr+7) = val;
// Swap 2nd and 7th bytes
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr+5);
*(ptr+5) = val;
// Swap 3rd and 6th bytes
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr+3);
*(ptr+3) = val;
// Swap 4th and 5th bytes
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr+1);
*(ptr+1) = val;
// Increment 5 more bytes.
ptr += 5;
}
}
}
// Indentation settings for Vim and Emacs
//
// Local Variables:
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
//
// vim: et sts=2 sw=2
|