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
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
#if JUCE_COREAUDIO_LOGGING_ENABLED
#define JUCE_COREAUDIOLOG(a) { String camsg ("CoreAudio: "); camsg << a; Logger::writeToLog (camsg); }
#else
#define JUCE_COREAUDIOLOG(a)
#endif
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnonnull")
constexpr auto juceAudioObjectPropertyElementMain =
#if defined (MAC_OS_VERSION_12_0)
kAudioObjectPropertyElementMain;
#else
kAudioObjectPropertyElementMaster;
#endif
//==============================================================================
struct AsyncRestarter
{
virtual ~AsyncRestarter() = default;
virtual void restartAsync() = 0;
};
struct SystemVol
{
SystemVol (AudioObjectPropertySelector selector) noexcept
: outputDeviceID (kAudioObjectUnknown)
{
addr.mScope = kAudioObjectPropertyScopeGlobal;
addr.mElement = juceAudioObjectPropertyElementMain;
addr.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
if (AudioObjectHasProperty (kAudioObjectSystemObject, &addr))
{
UInt32 deviceIDSize = sizeof (outputDeviceID);
OSStatus status = AudioObjectGetPropertyData (kAudioObjectSystemObject, &addr, 0, nullptr, &deviceIDSize, &outputDeviceID);
if (status == noErr)
{
addr.mElement = juceAudioObjectPropertyElementMain;
addr.mSelector = selector;
addr.mScope = kAudioDevicePropertyScopeOutput;
if (! AudioObjectHasProperty (outputDeviceID, &addr))
outputDeviceID = kAudioObjectUnknown;
}
}
}
float getGain() const noexcept
{
Float32 gain = 0;
if (outputDeviceID != kAudioObjectUnknown)
{
UInt32 size = sizeof (gain);
AudioObjectGetPropertyData (outputDeviceID, &addr, 0, nullptr, &size, &gain);
}
return (float) gain;
}
bool setGain (float gain) const noexcept
{
if (outputDeviceID != kAudioObjectUnknown && canSetVolume())
{
Float32 newVolume = gain;
UInt32 size = sizeof (newVolume);
return AudioObjectSetPropertyData (outputDeviceID, &addr, 0, nullptr, size, &newVolume) == noErr;
}
return false;
}
bool isMuted() const noexcept
{
UInt32 muted = 0;
if (outputDeviceID != kAudioObjectUnknown)
{
UInt32 size = sizeof (muted);
AudioObjectGetPropertyData (outputDeviceID, &addr, 0, nullptr, &size, &muted);
}
return muted != 0;
}
bool setMuted (bool mute) const noexcept
{
if (outputDeviceID != kAudioObjectUnknown && canSetVolume())
{
UInt32 newMute = mute ? 1 : 0;
UInt32 size = sizeof (newMute);
return AudioObjectSetPropertyData (outputDeviceID, &addr, 0, nullptr, size, &newMute) == noErr;
}
return false;
}
private:
AudioDeviceID outputDeviceID;
AudioObjectPropertyAddress addr;
bool canSetVolume() const noexcept
{
Boolean isSettable = NO;
return AudioObjectIsPropertySettable (outputDeviceID, &addr, &isSettable) == noErr && isSettable;
}
};
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
constexpr auto juceAudioHardwareServiceDeviceProperty_VirtualMainVolume =
#if defined (MAC_OS_VERSION_12_0)
kAudioHardwareServiceDeviceProperty_VirtualMainVolume;
#else
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume;
#endif
#define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
float JUCE_CALLTYPE SystemAudioVolume::getGain() { return SystemVol (juceAudioHardwareServiceDeviceProperty_VirtualMainVolume).getGain(); }
bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return SystemVol (juceAudioHardwareServiceDeviceProperty_VirtualMainVolume).setGain (gain); }
bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return SystemVol (kAudioDevicePropertyMute).isMuted(); }
bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return SystemVol (kAudioDevicePropertyMute).setMuted (mute); }
//==============================================================================
struct CoreAudioClasses
{
class CoreAudioIODeviceType;
class CoreAudioIODevice;
//==============================================================================
class CoreAudioInternal : private Timer,
private AsyncUpdater
{
public:
CoreAudioInternal (CoreAudioIODevice& d, AudioDeviceID id, bool input, bool output)
: owner (d),
deviceID (id),
isInputDevice (input),
isOutputDevice (output)
{
jassert (deviceID != 0);
updateDetailsFromDevice();
JUCE_COREAUDIOLOG ("Creating CoreAudioInternal\n"
<< (isInputDevice ? (" inputDeviceId " + String (deviceID) + "\n") : "")
<< (isOutputDevice ? (" outputDeviceId " + String (deviceID) + "\n") : "")
<< getDeviceDetails().joinIntoString ("\n "));
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioObjectPropertySelectorWildcard;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
}
~CoreAudioInternal() override
{
stopTimer();
cancelPendingUpdate();
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioObjectPropertySelectorWildcard;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
stop (false);
}
void allocateTempBuffers()
{
auto tempBufSize = bufferSize + 4;
audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
tempInputBuffers.calloc (numInputChans + 2);
tempOutputBuffers.calloc (numOutputChans + 2);
int count = 0;
for (int i = 0; i < numInputChans; ++i) tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
for (int i = 0; i < numOutputChans; ++i) tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
}
struct CallbackDetailsForChannel
{
int streamNum;
int dataOffsetSamples;
int dataStrideSamples;
};
// returns the number of actual available channels
StringArray getChannelInfo (bool input, Array<CallbackDetailsForChannel>& newChannelInfo) const
{
StringArray newNames;
int chanNum = 0;
UInt32 size;
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyStreamConfiguration;
pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
pa.mElement = juceAudioObjectPropertyElementMain;
if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, nullptr, &size)))
{
HeapBlock<AudioBufferList> bufList;
bufList.calloc (size, 1);
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, bufList)))
{
const int numStreams = (int) bufList->mNumberBuffers;
for (int i = 0; i < numStreams; ++i)
{
auto& b = bufList->mBuffers[i];
for (unsigned int j = 0; j < b.mNumberChannels; ++j)
{
String name;
NSString* nameNSString = nil;
size = sizeof (nameNSString);
pa.mSelector = kAudioObjectPropertyElementName;
pa.mElement = (AudioObjectPropertyElement) chanNum + 1;
if (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &nameNSString) == noErr)
{
name = nsStringToJuce (nameNSString);
[nameNSString release];
}
if ((input ? activeInputChans : activeOutputChans) [chanNum])
{
CallbackDetailsForChannel info = { i, (int) j, (int) b.mNumberChannels };
newChannelInfo.add (info);
}
if (name.isEmpty())
name << (input ? "Input " : "Output ") << (chanNum + 1);
newNames.add (name);
++chanNum;
}
}
}
}
return newNames;
}
Array<double> getSampleRatesFromDevice() const
{
Array<double> newSampleRates;
AudioObjectPropertyAddress pa;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
UInt32 size = 0;
if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, nullptr, &size)))
{
HeapBlock<AudioValueRange> ranges;
ranges.calloc (size, 1);
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, ranges)))
{
for (auto r : { 8000, 11025, 16000, 22050, 32000,
44100, 48000, 88200, 96000, 176400,
192000, 352800, 384000, 705600, 768000 })
{
auto rate = (double) r;
for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
{
if (rate >= ranges[j].mMinimum - 2 && rate <= ranges[j].mMaximum + 2)
{
newSampleRates.add (rate);
break;
}
}
}
}
}
if (newSampleRates.isEmpty() && sampleRate > 0)
newSampleRates.add (sampleRate);
return newSampleRates;
}
Array<int> getBufferSizesFromDevice() const
{
Array<int> newBufferSizes;
AudioObjectPropertyAddress pa;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
UInt32 size = 0;
if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, nullptr, &size)))
{
HeapBlock<AudioValueRange> ranges;
ranges.calloc (size, 1);
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, ranges)))
{
newBufferSizes.add ((int) (ranges[0].mMinimum + 15) & ~15);
for (int i = 32; i <= 2048; i += 32)
{
for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
{
if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
{
newBufferSizes.addIfNotAlreadyThere (i);
break;
}
}
}
if (bufferSize > 0)
newBufferSizes.addIfNotAlreadyThere (bufferSize);
}
}
if (newBufferSizes.isEmpty() && bufferSize > 0)
newBufferSizes.add (bufferSize);
return newBufferSizes;
}
int getLatencyFromDevice (AudioObjectPropertyScope scope) const
{
UInt32 latency = 0;
UInt32 size = sizeof (latency);
AudioObjectPropertyAddress pa;
pa.mElement = juceAudioObjectPropertyElementMain;
pa.mSelector = kAudioDevicePropertyLatency;
pa.mScope = scope;
AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &latency);
UInt32 safetyOffset = 0;
size = sizeof (safetyOffset);
pa.mSelector = kAudioDevicePropertySafetyOffset;
AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &safetyOffset);
return (int) (latency + safetyOffset);
}
int getBitDepthFromDevice (AudioObjectPropertyScope scope) const
{
AudioObjectPropertyAddress pa;
pa.mElement = juceAudioObjectPropertyElementMain;
pa.mSelector = kAudioStreamPropertyPhysicalFormat;
pa.mScope = scope;
AudioStreamBasicDescription asbd;
UInt32 size = sizeof (asbd);
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &asbd)))
return (int) asbd.mBitsPerChannel;
return 0;
}
int getFrameSizeFromDevice() const
{
AudioObjectPropertyAddress pa;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
pa.mSelector = kAudioDevicePropertyBufferFrameSize;
UInt32 framesPerBuf = (UInt32) bufferSize;
UInt32 size = sizeof (framesPerBuf);
AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &framesPerBuf);
return (int) framesPerBuf;
}
bool isDeviceAlive() const
{
AudioObjectPropertyAddress pa;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
pa.mSelector = kAudioDevicePropertyDeviceIsAlive;
UInt32 isAlive = 0;
UInt32 size = sizeof (isAlive);
return deviceID != 0
&& OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &isAlive))
&& isAlive != 0;
}
bool updateDetailsFromDevice()
{
stopTimer();
if (! isDeviceAlive())
return false;
// this collects all the new details from the device without any locking, then
// locks + swaps them afterwards.
auto newSampleRate = getNominalSampleRate();
auto newBufferSize = getFrameSizeFromDevice();
auto newBufferSizes = getBufferSizesFromDevice();
auto newSampleRates = getSampleRatesFromDevice();
auto newInputLatency = getLatencyFromDevice (kAudioDevicePropertyScopeInput);
auto newOutputLatency = getLatencyFromDevice (kAudioDevicePropertyScopeOutput);
Array<CallbackDetailsForChannel> newInChans, newOutChans;
auto newInNames = isInputDevice ? getChannelInfo (true, newInChans) : StringArray();
auto newOutNames = isOutputDevice ? getChannelInfo (false, newOutChans) : StringArray();
auto inputBitDepth = isInputDevice ? getBitDepthFromDevice (kAudioDevicePropertyScopeInput) : 0;
auto outputBitDepth = isOutputDevice ? getBitDepthFromDevice (kAudioDevicePropertyScopeOutput) : 0;
auto newBitDepth = jmax (inputBitDepth, outputBitDepth);
{
const ScopedLock sl (callbackLock);
bitDepth = newBitDepth > 0 ? newBitDepth : 32;
if (newSampleRate > 0)
sampleRate = newSampleRate;
inputLatency = newInputLatency;
outputLatency = newOutputLatency;
bufferSize = newBufferSize;
sampleRates.swapWith (newSampleRates);
bufferSizes.swapWith (newBufferSizes);
inChanNames.swapWith (newInNames);
outChanNames.swapWith (newOutNames);
inputChannelInfo.swapWith (newInChans);
outputChannelInfo.swapWith (newOutChans);
numInputChans = inputChannelInfo.size();
numOutputChans = outputChannelInfo.size();
allocateTempBuffers();
}
return true;
}
StringArray getDeviceDetails()
{
StringArray result;
String availableSampleRates ("Available sample rates:");
for (auto& s : sampleRates)
availableSampleRates << " " << s;
result.add (availableSampleRates);
result.add ("Sample rate: " + String (sampleRate));
String availableBufferSizes ("Available buffer sizes:");
for (auto& b : bufferSizes)
availableBufferSizes << " " << b;
result.add (availableBufferSizes);
result.add ("Buffer size: " + String (bufferSize));
result.add ("Bit depth: " + String (bitDepth));
result.add ("Input latency: " + String (inputLatency));
result.add ("Output latency: " + String (outputLatency));
result.add ("Input channel names: " + inChanNames.joinIntoString (" "));
result.add ("Output channel names: " + outChanNames.joinIntoString (" "));
return result;
}
//==============================================================================
StringArray getSources (bool input)
{
StringArray s;
HeapBlock<OSType> types;
auto num = getAllDataSourcesForDevice (deviceID, types);
for (int i = 0; i < num; ++i)
{
AudioValueTranslation avt;
char buffer[256];
avt.mInputData = &(types[i]);
avt.mInputDataSize = sizeof (UInt32);
avt.mOutputData = buffer;
avt.mOutputDataSize = 256;
UInt32 transSize = sizeof (avt);
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
pa.mElement = juceAudioObjectPropertyElementMain;
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &transSize, &avt)))
s.add (buffer);
}
return s;
}
int getCurrentSourceIndex (bool input) const
{
OSType currentSourceID = 0;
UInt32 size = sizeof (currentSourceID);
int result = -1;
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyDataSource;
pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
pa.mElement = juceAudioObjectPropertyElementMain;
if (deviceID != 0)
{
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, ¤tSourceID)))
{
HeapBlock<OSType> types;
auto num = getAllDataSourcesForDevice (deviceID, types);
for (int i = 0; i < num; ++i)
{
if (types[num] == currentSourceID)
{
result = i;
break;
}
}
}
}
return result;
}
void setCurrentSourceIndex (int index, bool input)
{
if (deviceID != 0)
{
HeapBlock<OSType> types;
auto num = getAllDataSourcesForDevice (deviceID, types);
if (isPositiveAndBelow (index, num))
{
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyDataSource;
pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
pa.mElement = juceAudioObjectPropertyElementMain;
OSType typeId = types[index];
OK (AudioObjectSetPropertyData (deviceID, &pa, 0, nullptr, sizeof (typeId), &typeId));
}
}
}
double getNominalSampleRate() const
{
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyNominalSampleRate;
pa.mScope = kAudioObjectPropertyScopeGlobal;
pa.mElement = juceAudioObjectPropertyElementMain;
Float64 sr = 0;
UInt32 size = (UInt32) sizeof (sr);
return OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, &sr)) ? (double) sr : 0.0;
}
bool setNominalSampleRate (double newSampleRate) const
{
if (std::abs (getNominalSampleRate() - newSampleRate) < 1.0)
return true;
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyNominalSampleRate;
pa.mScope = kAudioObjectPropertyScopeGlobal;
pa.mElement = juceAudioObjectPropertyElementMain;
Float64 sr = newSampleRate;
return OK (AudioObjectSetPropertyData (deviceID, &pa, 0, nullptr, sizeof (sr), &sr));
}
//==============================================================================
String reopen (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double newSampleRate, int bufferSizeSamples)
{
String error;
callbacksAllowed = false;
stopTimer();
stop (false);
updateDetailsFromDevice();
activeInputChans = inputChannels;
activeInputChans.setRange (inChanNames.size(),
activeInputChans.getHighestBit() + 1 - inChanNames.size(),
false);
activeOutputChans = outputChannels;
activeOutputChans.setRange (outChanNames.size(),
activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
false);
numInputChans = activeInputChans.countNumberOfSetBits();
numOutputChans = activeOutputChans.countNumberOfSetBits();
if (! setNominalSampleRate (newSampleRate))
{
updateDetailsFromDevice();
error = "Couldn't change sample rate";
}
else
{
// change buffer size
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyBufferFrameSize;
pa.mScope = kAudioObjectPropertyScopeGlobal;
pa.mElement = juceAudioObjectPropertyElementMain;
UInt32 framesPerBuf = (UInt32) bufferSizeSamples;
if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, nullptr, sizeof (framesPerBuf), &framesPerBuf)))
{
updateDetailsFromDevice();
error = "Couldn't change buffer size";
}
else
{
// Annoyingly, after changing the rate and buffer size, some devices fail to
// correctly report their new settings until some random time in the future, so
// after calling updateDetailsFromDevice, we need to manually bodge these values
// to make sure we're using the correct numbers..
updateDetailsFromDevice();
sampleRate = newSampleRate;
bufferSize = bufferSizeSamples;
if (sampleRates.size() == 0)
error = "Device has no available sample-rates";
else if (bufferSizes.size() == 0)
error = "Device has no available buffer-sizes";
}
}
callbacksAllowed = true;
return error;
}
bool start (AudioIODeviceCallback* callbackToNotify)
{
const ScopedLock sl (callbackLock);
if (! started)
{
callback = nullptr;
if (deviceID != 0)
{
if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
{
if (OK (AudioDeviceStart (deviceID, audioProcID)))
{
started = true;
}
else
{
OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
audioProcID = {};
}
}
}
if (started)
{
callback = callbackToNotify;
if (callback != nullptr)
callback->audioDeviceAboutToStart (&owner);
}
}
playing = started && callback != nullptr;
return started;
}
AudioIODeviceCallback* stop (bool leaveInterruptRunning)
{
const ScopedLock sl (callbackLock);
auto result = std::exchange (callback, nullptr);
if (started && (deviceID != 0) && ! leaveInterruptRunning)
{
audioDeviceStopPending = true;
// wait until AudioDeviceStop() has been called on the IO thread
for (int i = 40; --i >= 0;)
{
if (audioDeviceStopPending == false)
break;
const ScopedUnlock ul (callbackLock);
Thread::sleep (50);
}
OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
audioProcID = {};
started = false;
playing = false;
}
return result;
}
double getSampleRate() const { return sampleRate; }
int getBufferSize() const { return bufferSize; }
void audioCallback (const AudioBufferList* inInputData,
AudioBufferList* outOutputData)
{
const ScopedLock sl (callbackLock);
if (audioDeviceStopPending)
{
if (OK (AudioDeviceStop (deviceID, audioProcID)))
audioDeviceStopPending = false;
return;
}
if (callback != nullptr)
{
for (int i = numInputChans; --i >= 0;)
{
auto& info = inputChannelInfo.getReference(i);
auto dest = tempInputBuffers[i];
auto src = ((const float*) inInputData->mBuffers[info.streamNum].mData) + info.dataOffsetSamples;
auto stride = info.dataStrideSamples;
if (stride != 0) // if this is zero, info is invalid
{
for (int j = bufferSize; --j >= 0;)
{
*dest++ = *src;
src += stride;
}
}
}
callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.get()),
numInputChans,
tempOutputBuffers,
numOutputChans,
bufferSize);
for (int i = numOutputChans; --i >= 0;)
{
auto& info = outputChannelInfo.getReference (i);
auto src = tempOutputBuffers[i];
auto dest = ((float*) outOutputData->mBuffers[info.streamNum].mData) + info.dataOffsetSamples;
auto stride = info.dataStrideSamples;
if (stride != 0) // if this is zero, info is invalid
{
for (int j = bufferSize; --j >= 0;)
{
*dest = *src++;
dest += stride;
}
}
}
}
else
{
for (UInt32 i = 0; i < outOutputData->mNumberBuffers; ++i)
zeromem (outOutputData->mBuffers[i].mData,
outOutputData->mBuffers[i].mDataByteSize);
}
}
// called by callbacks (possibly off the main thread)
void deviceDetailsChanged()
{
if (callbacksAllowed.get() == 1)
startTimer (100);
}
// called by callbacks (possibly off the main thread)
void deviceRequestedRestart()
{
owner.restart();
triggerAsyncUpdate();
}
bool isPlaying() const { return playing.load(); }
//==============================================================================
CoreAudioIODevice& owner;
int inputLatency = 0;
int outputLatency = 0;
int bitDepth = 32;
int xruns = 0;
BigInteger activeInputChans, activeOutputChans;
StringArray inChanNames, outChanNames;
Array<double> sampleRates;
Array<int> bufferSizes;
AudioDeviceIOProcID audioProcID = {};
private:
AudioIODeviceCallback* callback = nullptr;
CriticalSection callbackLock;
AudioDeviceID deviceID;
bool started = false, audioDeviceStopPending = false;
std::atomic<bool> playing { false };
double sampleRate = 0;
int bufferSize = 512;
HeapBlock<float> audioBuffer;
int numInputChans = 0;
int numOutputChans = 0;
Atomic<int> callbacksAllowed { 1 };
const bool isInputDevice, isOutputDevice;
Array<CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
HeapBlock<float*> tempInputBuffers, tempOutputBuffers;
//==============================================================================
void timerCallback() override
{
JUCE_COREAUDIOLOG ("Device changed");
stopTimer();
auto oldSampleRate = sampleRate;
auto oldBufferSize = bufferSize;
if (! updateDetailsFromDevice())
owner.stopInternal();
else if ((oldBufferSize != bufferSize || oldSampleRate != sampleRate) && owner.shouldRestartDevice())
owner.restart();
}
void handleAsyncUpdate() override
{
if (owner.deviceType != nullptr)
owner.deviceType->audioDeviceListChanged();
}
static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
const AudioTimeStamp* /*inNow*/,
const AudioBufferList* inInputData,
const AudioTimeStamp* /*inInputTime*/,
AudioBufferList* outOutputData,
const AudioTimeStamp* /*inOutputTime*/,
void* device)
{
static_cast<CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
return noErr;
}
static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/,
const AudioObjectPropertyAddress* pa, void* inClientData)
{
auto intern = static_cast<CoreAudioInternal*> (inClientData);
switch (pa->mSelector)
{
case kAudioDeviceProcessorOverload:
intern->xruns++;
break;
case kAudioDevicePropertyBufferSize:
case kAudioDevicePropertyBufferFrameSize:
case kAudioDevicePropertyNominalSampleRate:
case kAudioDevicePropertyStreamFormat:
case kAudioDevicePropertyDeviceIsAlive:
case kAudioStreamPropertyPhysicalFormat:
intern->deviceDetailsChanged();
break;
case kAudioDevicePropertyDeviceHasChanged:
case kAudioObjectPropertyOwnedObjects:
intern->deviceRequestedRestart();
break;
case kAudioDevicePropertyBufferSizeRange:
case kAudioDevicePropertyVolumeScalar:
case kAudioDevicePropertyMute:
case kAudioDevicePropertyPlayThru:
case kAudioDevicePropertyDataSource:
case kAudioDevicePropertyDeviceIsRunning:
break;
}
return noErr;
}
//==============================================================================
static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock<OSType>& types)
{
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyDataSources;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
UInt32 size = 0;
if (deviceID != 0
&& AudioObjectGetPropertyDataSize (deviceID, &pa, 0, nullptr, &size) == noErr)
{
types.calloc (size, 1);
if (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, types) == noErr)
return size / (int) sizeof (OSType);
}
return 0;
}
bool OK (const OSStatus errorCode) const
{
if (errorCode == noErr)
return true;
const String errorMessage ("CoreAudio error: " + String::toHexString ((int) errorCode));
JUCE_COREAUDIOLOG (errorMessage);
if (callback != nullptr)
callback->audioDeviceError (errorMessage);
return false;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal)
};
//==============================================================================
class CoreAudioIODevice : public AudioIODevice,
private Timer
{
public:
CoreAudioIODevice (CoreAudioIODeviceType* dt,
const String& deviceName,
AudioDeviceID inputDeviceId, int inputIndex_,
AudioDeviceID outputDeviceId, int outputIndex_)
: AudioIODevice (deviceName, "CoreAudio"),
deviceType (dt),
inputIndex (inputIndex_),
outputIndex (outputIndex_)
{
internal = [this, &inputDeviceId, &outputDeviceId]
{
if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
{
jassert (inputDeviceId != 0);
return std::make_unique<CoreAudioInternal> (*this, inputDeviceId, true, outputDeviceId != 0);
}
return std::make_unique<CoreAudioInternal> (*this, outputDeviceId, false, true);
}();
jassert (internal != nullptr);
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioObjectPropertySelectorWildcard;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal.get());
}
~CoreAudioIODevice() override
{
close();
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioObjectPropertySelectorWildcard;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal.get());
}
StringArray getOutputChannelNames() override { return internal->outChanNames; }
StringArray getInputChannelNames() override { return internal->inChanNames; }
bool isOpen() override { return isOpen_; }
Array<double> getAvailableSampleRates() override { return internal->sampleRates; }
Array<int> getAvailableBufferSizes() override { return internal->bufferSizes; }
double getCurrentSampleRate() override { return internal->getSampleRate(); }
int getCurrentBitDepth() override { return internal->bitDepth; }
int getCurrentBufferSizeSamples() override { return internal->getBufferSize(); }
int getXRunCount() const noexcept override { return internal->xruns; }
int getDefaultBufferSize() override
{
int best = 0;
for (int i = 0; best < 512 && i < internal->bufferSizes.size(); ++i)
best = internal->bufferSizes.getUnchecked(i);
if (best == 0)
best = 512;
return best;
}
String open (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double sampleRate, int bufferSizeSamples) override
{
isOpen_ = true;
internal->xruns = 0;
inputChannelsRequested = inputChannels;
outputChannelsRequested = outputChannels;
if (bufferSizeSamples <= 0)
bufferSizeSamples = getDefaultBufferSize();
if (sampleRate <= 0)
sampleRate = internal->getNominalSampleRate();
lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
JUCE_COREAUDIOLOG ("Opened: " << getName());
isOpen_ = lastError.isEmpty();
return lastError;
}
void close() override
{
isOpen_ = false;
internal->stop (false);
}
BigInteger getActiveOutputChannels() const override { return internal->activeOutputChans; }
BigInteger getActiveInputChannels() const override { return internal->activeInputChans; }
int getOutputLatencyInSamples() override
{
// this seems like a good guess at getting the latency right - comparing
// this with a round-trip measurement, it gets it to within a few millisecs
// for the built-in mac soundcard
return internal->outputLatency;
}
int getInputLatencyInSamples() override
{
return internal->inputLatency;
}
void start (AudioIODeviceCallback* callback) override
{
if (internal->start (callback))
previousCallback = callback;
}
void stop() override
{
restartDevice = false;
stopAndGetLastCallback();
}
AudioIODeviceCallback* stopAndGetLastCallback() const
{
auto* lastCallback = internal->stop (true);
if (lastCallback != nullptr)
lastCallback->audioDeviceStopped();
return lastCallback;
}
AudioIODeviceCallback* stopInternal()
{
restartDevice = true;
return stopAndGetLastCallback();
}
bool isPlaying() override
{
return internal->isPlaying();
}
String getLastError() override
{
return lastError;
}
void audioDeviceListChanged()
{
if (deviceType != nullptr)
deviceType->audioDeviceListChanged();
}
// called by callbacks (possibly off the main thread)
void restart()
{
if (restarter != nullptr)
{
restarter->restartAsync();
return;
}
{
const ScopedLock sl (closeLock);
previousCallback = stopInternal();
}
startTimer (100);
}
bool setCurrentSampleRate (double newSampleRate)
{
return internal->setNominalSampleRate (newSampleRate);
}
void setAsyncRestarter (AsyncRestarter* restarterIn)
{
restarter = restarterIn;
}
bool shouldRestartDevice() const noexcept { return restartDevice; }
WeakReference<CoreAudioIODeviceType> deviceType;
int inputIndex, outputIndex;
private:
std::unique_ptr<CoreAudioInternal> internal;
bool isOpen_ = false, restartDevice = true;
String lastError;
AudioIODeviceCallback* previousCallback = nullptr;
AsyncRestarter* restarter = nullptr;
BigInteger inputChannelsRequested, outputChannelsRequested;
CriticalSection closeLock;
void timerCallback() override
{
stopTimer();
stopInternal();
internal->updateDetailsFromDevice();
open (inputChannelsRequested, outputChannelsRequested,
getCurrentSampleRate(), getCurrentBufferSizeSamples());
start (previousCallback);
}
static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
{
switch (pa->mSelector)
{
case kAudioHardwarePropertyDevices:
static_cast<CoreAudioInternal*> (inClientData)->deviceDetailsChanged();
break;
case kAudioHardwarePropertyDefaultOutputDevice:
case kAudioHardwarePropertyDefaultInputDevice:
case kAudioHardwarePropertyDefaultSystemOutputDevice:
break;
}
return noErr;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice)
};
//==============================================================================
class AudioIODeviceCombiner : public AudioIODevice,
private AsyncRestarter,
private Thread,
private Timer
{
public:
AudioIODeviceCombiner (const String& deviceName, CoreAudioIODeviceType* deviceType)
: AudioIODevice (deviceName, "CoreAudio"),
Thread (deviceName),
owner (deviceType)
{
}
~AudioIODeviceCombiner() override
{
close();
devices.clear();
}
void addDevice (std::unique_ptr<CoreAudioIODevice> device, bool useInputs, bool useOutputs)
{
jassert (device != nullptr);
jassert (! isOpen());
jassert (! device->isOpen());
auto* devicePtr = device.get();
devices.add (std::make_unique<DeviceWrapper> (*this, std::move (device), useInputs, useOutputs));
if (currentSampleRate == 0)
currentSampleRate = devicePtr->getCurrentSampleRate();
if (currentBufferSize == 0)
currentBufferSize = devicePtr->getCurrentBufferSizeSamples();
}
Array<AudioIODevice*> getDevices() const
{
Array<AudioIODevice*> devs;
for (auto* d : devices)
devs.add (d->device.get());
return devs;
}
StringArray getOutputChannelNames() override
{
StringArray names;
for (auto* d : devices)
names.addArray (d->getOutputChannelNames());
names.appendNumbersToDuplicates (false, true);
return names;
}
StringArray getInputChannelNames() override
{
StringArray names;
for (auto* d : devices)
names.addArray (d->getInputChannelNames());
names.appendNumbersToDuplicates (false, true);
return names;
}
Array<double> getAvailableSampleRates() override
{
Array<double> commonRates;
bool first = true;
for (auto* d : devices)
{
auto rates = d->device->getAvailableSampleRates();
if (first)
{
first = false;
commonRates = rates;
}
else
{
commonRates.removeValuesNotIn (rates);
}
}
return commonRates;
}
Array<int> getAvailableBufferSizes() override
{
Array<int> commonSizes;
bool first = true;
for (auto* d : devices)
{
auto sizes = d->device->getAvailableBufferSizes();
if (first)
{
first = false;
commonSizes = sizes;
}
else
{
commonSizes.removeValuesNotIn (sizes);
}
}
return commonSizes;
}
bool isOpen() override { return active; }
bool isPlaying() override { return callback != nullptr; }
double getCurrentSampleRate() override { return currentSampleRate; }
int getCurrentBufferSizeSamples() override { return currentBufferSize; }
int getCurrentBitDepth() override
{
int depth = 32;
for (auto* d : devices)
depth = jmin (depth, d->device->getCurrentBitDepth());
return depth;
}
int getDefaultBufferSize() override
{
int size = 0;
for (auto* d : devices)
size = jmax (size, d->device->getDefaultBufferSize());
return size;
}
String open (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double sampleRate, int bufferSize) override
{
inputChannelsRequested = inputChannels;
outputChannelsRequested = outputChannels;
sampleRateRequested = sampleRate;
bufferSizeRequested = bufferSize;
close();
active = true;
if (bufferSize <= 0)
bufferSize = getDefaultBufferSize();
if (sampleRate <= 0)
{
auto rates = getAvailableSampleRates();
for (int i = 0; i < rates.size() && sampleRate < 44100.0; ++i)
sampleRate = rates.getUnchecked(i);
}
currentSampleRate = sampleRate;
currentBufferSize = bufferSize;
const int fifoSize = bufferSize * 3 + 1;
int totalInputChanIndex = 0, totalOutputChanIndex = 0;
int chanIndex = 0;
for (auto* d : devices)
{
BigInteger ins (inputChannels >> totalInputChanIndex);
BigInteger outs (outputChannels >> totalOutputChanIndex);
int numIns = d->getInputChannelNames().size();
int numOuts = d->getOutputChannelNames().size();
totalInputChanIndex += numIns;
totalOutputChanIndex += numOuts;
String err = d->open (ins, outs, sampleRate, bufferSize,
chanIndex, fifoSize);
if (err.isNotEmpty())
{
close();
lastError = err;
return err;
}
chanIndex += d->numInputChans + d->numOutputChans;
}
fifos.setSize (chanIndex, fifoSize);
fifoReadPointers = fifos.getArrayOfReadPointers();
fifoWritePointers = fifos.getArrayOfWritePointers();
fifos.clear();
startThread (9);
threadInitialised.wait();
return {};
}
void close() override
{
stop();
stopThread (10000);
fifos.clear();
active = false;
for (auto* d : devices)
d->close();
}
void restart (AudioIODeviceCallback* cb)
{
const ScopedLock sl (closeLock);
close();
auto newSampleRate = sampleRateRequested;
auto newBufferSize = bufferSizeRequested;
for (auto* d : devices)
{
auto deviceSampleRate = d->getCurrentSampleRate();
if (deviceSampleRate != sampleRateRequested)
{
if (! getAvailableSampleRates().contains (deviceSampleRate))
return;
for (auto* d2 : devices)
if (d2 != d)
d2->setCurrentSampleRate (deviceSampleRate);
newSampleRate = deviceSampleRate;
break;
}
}
for (auto* d : devices)
{
auto deviceBufferSize = d->getCurrentBufferSizeSamples();
if (deviceBufferSize != bufferSizeRequested)
{
if (! getAvailableBufferSizes().contains (deviceBufferSize))
return;
newBufferSize = deviceBufferSize;
break;
}
}
open (inputChannelsRequested, outputChannelsRequested,
newSampleRate, newBufferSize);
start (cb);
}
void restartAsync() override
{
{
const ScopedLock sl (closeLock);
if (active)
{
if (callback != nullptr)
previousCallback = callback;
close();
}
}
startTimer (100);
}
BigInteger getActiveOutputChannels() const override
{
BigInteger chans;
int start = 0;
for (auto* d : devices)
{
auto numChans = d->getOutputChannelNames().size();
if (numChans > 0)
{
chans |= (d->device->getActiveOutputChannels() << start);
start += numChans;
}
}
return chans;
}
BigInteger getActiveInputChannels() const override
{
BigInteger chans;
int start = 0;
for (auto* d : devices)
{
auto numChans = d->getInputChannelNames().size();
if (numChans > 0)
{
chans |= (d->device->getActiveInputChannels() << start);
start += numChans;
}
}
return chans;
}
int getOutputLatencyInSamples() override
{
int lat = 0;
for (auto* d : devices)
lat = jmax (lat, d->device->getOutputLatencyInSamples());
return lat + currentBufferSize * 2;
}
int getInputLatencyInSamples() override
{
int lat = 0;
for (auto* d : devices)
lat = jmax (lat, d->device->getInputLatencyInSamples());
return lat + currentBufferSize * 2;
}
void start (AudioIODeviceCallback* newCallback) override
{
const auto shouldStart = [&]
{
const ScopedLock sl (callbackLock);
return callback != newCallback;
}();
if (shouldStart)
{
stop();
fifos.clear();
for (auto* d : devices)
d->start();
if (newCallback != nullptr)
newCallback->audioDeviceAboutToStart (this);
const ScopedLock sl (callbackLock);
previousCallback = std::exchange (callback, newCallback);
}
}
void stop() override { shutdown ({}); }
String getLastError() override
{
return lastError;
}
private:
WeakReference<CoreAudioIODeviceType> owner;
CriticalSection callbackLock;
AudioIODeviceCallback* callback = nullptr;
AudioIODeviceCallback* previousCallback = nullptr;
double currentSampleRate = 0;
int currentBufferSize = 0;
bool active = false;
String lastError;
AudioBuffer<float> fifos;
const float** fifoReadPointers = nullptr;
float** fifoWritePointers = nullptr;
WaitableEvent threadInitialised;
CriticalSection closeLock;
BigInteger inputChannelsRequested, outputChannelsRequested;
double sampleRateRequested = 44100;
int bufferSizeRequested = 512;
void run() override
{
auto numSamples = currentBufferSize;
AudioBuffer<float> buffer (fifos.getNumChannels(), numSamples);
buffer.clear();
Array<const float*> inputChans;
Array<float*> outputChans;
for (auto* d : devices)
{
for (int j = 0; j < d->numInputChans; ++j) inputChans.add (buffer.getReadPointer (d->inputIndex + j));
for (int j = 0; j < d->numOutputChans; ++j) outputChans.add (buffer.getWritePointer (d->outputIndex + j));
}
auto numInputChans = inputChans.size();
auto numOutputChans = outputChans.size();
inputChans.add (nullptr);
outputChans.add (nullptr);
auto blockSizeMs = jmax (1, (int) (1000 * numSamples / currentSampleRate));
jassert (numInputChans + numOutputChans == buffer.getNumChannels());
threadInitialised.signal();
while (! threadShouldExit())
{
readInput (buffer, numSamples, blockSizeMs);
bool didCallback = true;
{
const ScopedLock sl (callbackLock);
if (callback != nullptr)
callback->audioDeviceIOCallback ((const float**) inputChans.getRawDataPointer(), numInputChans,
outputChans.getRawDataPointer(), numOutputChans, numSamples);
else
didCallback = false;
}
if (didCallback)
{
pushOutputData (buffer, numSamples, blockSizeMs);
}
else
{
for (int i = 0; i < numOutputChans; ++i)
FloatVectorOperations::clear (outputChans[i], numSamples);
reset();
}
}
}
void timerCallback() override
{
stopTimer();
restart (previousCallback);
}
void shutdown (const String& error)
{
AudioIODeviceCallback* lastCallback = nullptr;
{
const ScopedLock sl (callbackLock);
std::swap (callback, lastCallback);
}
for (auto* d : devices)
d->device->stopInternal();
if (lastCallback != nullptr)
{
if (error.isNotEmpty())
lastCallback->audioDeviceError (error);
else
lastCallback->audioDeviceStopped();
}
}
void reset()
{
for (auto* d : devices)
d->reset();
}
void underrun()
{
}
void readInput (AudioBuffer<float>& buffer, const int numSamples, const int blockSizeMs)
{
for (auto* d : devices)
d->done = (d->numInputChans == 0 || d->isWaitingForInput);
float totalWaitTimeMs = blockSizeMs * 5.0f;
constexpr int numReadAttempts = 6;
auto sumPower2s = [] (int maxPower) { return (1 << (maxPower + 1)) - 1; };
float waitTime = totalWaitTimeMs / (float) sumPower2s (numReadAttempts - 2);
for (int numReadAttemptsRemaining = numReadAttempts;;)
{
bool anySamplesRemaining = false;
for (auto* d : devices)
{
if (! d->done)
{
if (d->isInputReady (numSamples))
{
d->readInput (buffer, numSamples);
d->done = true;
}
else
{
anySamplesRemaining = true;
}
}
}
if (! anySamplesRemaining)
return;
if (--numReadAttemptsRemaining == 0)
break;
wait (jmax (1, roundToInt (waitTime)));
waitTime *= 2.0f;
}
for (auto* d : devices)
if (! d->done)
for (int i = 0; i < d->numInputChans; ++i)
buffer.clear (d->inputIndex + i, 0, numSamples);
}
void pushOutputData (AudioBuffer<float>& buffer, const int numSamples, const int blockSizeMs)
{
for (auto* d : devices)
d->done = (d->numOutputChans == 0);
for (int tries = 5;;)
{
bool anyRemaining = false;
for (auto* d : devices)
{
if (! d->done)
{
if (d->isOutputReady (numSamples))
{
d->pushOutputData (buffer, numSamples);
d->done = true;
}
else
{
anyRemaining = true;
}
}
}
if ((! anyRemaining) || --tries == 0)
return;
wait (blockSizeMs);
}
}
void handleAudioDeviceAboutToStart (AudioIODevice* device)
{
const ScopedLock sl (callbackLock);
auto newSampleRate = device->getCurrentSampleRate();
auto commonRates = getAvailableSampleRates();
if (! commonRates.contains (newSampleRate))
{
commonRates.sort();
if (newSampleRate < commonRates.getFirst() || newSampleRate > commonRates.getLast())
{
newSampleRate = jlimit (commonRates.getFirst(), commonRates.getLast(), newSampleRate);
}
else
{
for (auto it = commonRates.begin(); it < commonRates.end() - 1; ++it)
{
if (it[0] < newSampleRate && it[1] > newSampleRate)
{
newSampleRate = newSampleRate - it[0] < it[1] - newSampleRate ? it[0] : it[1];
break;
}
}
}
}
currentSampleRate = newSampleRate;
bool anySampleRateChanges = false;
for (auto* d : devices)
{
if (d->getCurrentSampleRate() != currentSampleRate)
{
d->setCurrentSampleRate (currentSampleRate);
anySampleRateChanges = true;
}
}
if (anySampleRateChanges && owner != nullptr)
owner->audioDeviceListChanged();
if (callback != nullptr)
callback->audioDeviceAboutToStart (device);
}
void handleAudioDeviceStopped() { shutdown ({}); }
void handleAudioDeviceError (const String& errorMessage) { shutdown (errorMessage.isNotEmpty() ? errorMessage : String ("unknown")); }
//==============================================================================
struct DeviceWrapper : private AudioIODeviceCallback
{
DeviceWrapper (AudioIODeviceCombiner& cd, std::unique_ptr<CoreAudioIODevice> d, bool useIns, bool useOuts)
: owner (cd), device (std::move (d)),
useInputs (useIns), useOutputs (useOuts)
{
device->setAsyncRestarter (&owner);
}
~DeviceWrapper() override
{
close();
}
String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
double sampleRate, int bufferSize, int channelIndex, int fifoSize)
{
inputFifo.setTotalSize (fifoSize);
outputFifo.setTotalSize (fifoSize);
inputFifo.reset();
outputFifo.reset();
auto err = device->open (useInputs ? inputChannels : BigInteger(),
useOutputs ? outputChannels : BigInteger(),
sampleRate, bufferSize);
numInputChans = useInputs ? device->getActiveInputChannels().countNumberOfSetBits() : 0;
numOutputChans = useOutputs ? device->getActiveOutputChannels().countNumberOfSetBits() : 0;
isWaitingForInput = numInputChans > 0;
inputIndex = channelIndex;
outputIndex = channelIndex + numInputChans;
return err;
}
void close()
{
device->close();
}
void start()
{
reset();
device->start (this);
}
void reset()
{
inputFifo.reset();
outputFifo.reset();
}
StringArray getOutputChannelNames() const { return useOutputs ? device->getOutputChannelNames() : StringArray(); }
StringArray getInputChannelNames() const { return useInputs ? device->getInputChannelNames() : StringArray(); }
bool isInputReady (int numSamples) const noexcept
{
return numInputChans == 0 || inputFifo.getNumReady() >= numSamples;
}
void readInput (AudioBuffer<float>& destBuffer, int numSamples)
{
if (numInputChans == 0)
return;
int start1, size1, start2, size2;
inputFifo.prepareToRead (numSamples, start1, size1, start2, size2);
for (int i = 0; i < numInputChans; ++i)
{
auto index = inputIndex + i;
auto dest = destBuffer.getWritePointer (index);
auto src = owner.fifoReadPointers[index];
if (size1 > 0) FloatVectorOperations::copy (dest, src + start1, size1);
if (size2 > 0) FloatVectorOperations::copy (dest + size1, src + start2, size2);
}
inputFifo.finishedRead (size1 + size2);
}
bool isOutputReady (int numSamples) const noexcept
{
return numOutputChans == 0 || outputFifo.getFreeSpace() >= numSamples;
}
void pushOutputData (AudioBuffer<float>& srcBuffer, int numSamples)
{
if (numOutputChans == 0)
return;
int start1, size1, start2, size2;
outputFifo.prepareToWrite (numSamples, start1, size1, start2, size2);
for (int i = 0; i < numOutputChans; ++i)
{
auto index = outputIndex + i;
auto dest = owner.fifoWritePointers[index];
auto src = srcBuffer.getReadPointer (index);
if (size1 > 0) FloatVectorOperations::copy (dest + start1, src, size1);
if (size2 > 0) FloatVectorOperations::copy (dest + start2, src + size1, size2);
}
outputFifo.finishedWrite (size1 + size2);
}
void audioDeviceIOCallback (const float** inputChannelData, int numInputChannels,
float** outputChannelData, int numOutputChannels,
int numSamples) override
{
if (numInputChannels > 0)
{
isWaitingForInput = false;
int start1, size1, start2, size2;
inputFifo.prepareToWrite (numSamples, start1, size1, start2, size2);
if (size1 + size2 < numSamples)
{
inputFifo.reset();
inputFifo.prepareToWrite (numSamples, start1, size1, start2, size2);
}
for (int i = 0; i < numInputChannels; ++i)
{
auto dest = owner.fifoWritePointers[inputIndex + i];
auto src = inputChannelData[i];
if (size1 > 0) FloatVectorOperations::copy (dest + start1, src, size1);
if (size2 > 0) FloatVectorOperations::copy (dest + start2, src + size1, size2);
}
auto totalSize = size1 + size2;
inputFifo.finishedWrite (totalSize);
if (numSamples > totalSize)
{
auto samplesRemaining = numSamples - totalSize;
for (int i = 0; i < numInputChans; ++i)
FloatVectorOperations::clear (owner.fifoWritePointers[inputIndex + i] + totalSize, samplesRemaining);
owner.underrun();
}
}
if (numOutputChannels > 0)
{
int start1, size1, start2, size2;
outputFifo.prepareToRead (numSamples, start1, size1, start2, size2);
if (size1 + size2 < numSamples)
{
Thread::sleep (1);
outputFifo.prepareToRead (numSamples, start1, size1, start2, size2);
}
for (int i = 0; i < numOutputChannels; ++i)
{
auto dest = outputChannelData[i];
auto src = owner.fifoReadPointers[outputIndex + i];
if (size1 > 0) FloatVectorOperations::copy (dest, src + start1, size1);
if (size2 > 0) FloatVectorOperations::copy (dest + size1, src + start2, size2);
}
auto totalSize = size1 + size2;
outputFifo.finishedRead (totalSize);
if (numSamples > totalSize)
{
auto samplesRemaining = numSamples - totalSize;
for (int i = 0; i < numOutputChannels; ++i)
FloatVectorOperations::clear (outputChannelData[i] + totalSize, samplesRemaining);
owner.underrun();
}
}
owner.notify();
}
double getCurrentSampleRate() { return device->getCurrentSampleRate(); }
bool setCurrentSampleRate (double newSampleRate) { return device->setCurrentSampleRate (newSampleRate); }
int getCurrentBufferSizeSamples() { return device->getCurrentBufferSizeSamples(); }
void audioDeviceAboutToStart (AudioIODevice* d) override { owner.handleAudioDeviceAboutToStart (d); }
void audioDeviceStopped() override { owner.handleAudioDeviceStopped(); }
void audioDeviceError (const String& errorMessage) override { owner.handleAudioDeviceError (errorMessage); }
AudioIODeviceCombiner& owner;
std::unique_ptr<CoreAudioIODevice> device;
int inputIndex = 0, numInputChans = 0, outputIndex = 0, numOutputChans = 0;
bool useInputs = false, useOutputs = false;
std::atomic<bool> isWaitingForInput { false };
AbstractFifo inputFifo { 32 }, outputFifo { 32 };
bool done = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DeviceWrapper)
};
OwnedArray<DeviceWrapper> devices;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioIODeviceCombiner)
};
//==============================================================================
class CoreAudioIODeviceType : public AudioIODeviceType,
private AsyncUpdater
{
public:
CoreAudioIODeviceType() : AudioIODeviceType ("CoreAudio")
{
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioHardwarePropertyDevices;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, this);
}
~CoreAudioIODeviceType() override
{
cancelPendingUpdate();
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioHardwarePropertyDevices;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, this);
}
//==============================================================================
void scanForDevices() override
{
hasScanned = true;
inputDeviceNames.clear();
outputDeviceNames.clear();
inputIds.clear();
outputIds.clear();
UInt32 size;
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioHardwarePropertyDevices;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
if (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, nullptr, &size) == noErr)
{
HeapBlock<AudioDeviceID> devs;
devs.calloc (size, 1);
if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, nullptr, &size, devs) == noErr)
{
auto num = (int) size / (int) sizeof (AudioDeviceID);
for (int i = 0; i < num; ++i)
{
char name[1024];
size = sizeof (name);
pa.mSelector = kAudioDevicePropertyDeviceName;
if (AudioObjectGetPropertyData (devs[i], &pa, 0, nullptr, &size, name) == noErr)
{
auto nameString = String::fromUTF8 (name, (int) strlen (name));
auto numIns = getNumChannels (devs[i], true);
auto numOuts = getNumChannels (devs[i], false);
if (numIns > 0)
{
inputDeviceNames.add (nameString);
inputIds.add (devs[i]);
}
if (numOuts > 0)
{
outputDeviceNames.add (nameString);
outputIds.add (devs[i]);
}
}
}
}
}
inputDeviceNames.appendNumbersToDuplicates (false, true);
outputDeviceNames.appendNumbersToDuplicates (false, true);
}
StringArray getDeviceNames (bool wantInputNames) const override
{
jassert (hasScanned); // need to call scanForDevices() before doing this
return wantInputNames ? inputDeviceNames
: outputDeviceNames;
}
int getDefaultDeviceIndex (bool forInput) const override
{
jassert (hasScanned); // need to call scanForDevices() before doing this
AudioDeviceID deviceID;
UInt32 size = sizeof (deviceID);
// if they're asking for any input channels at all, use the default input, so we
// get the built-in mic rather than the built-in output with no inputs..
AudioObjectPropertyAddress pa;
pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice
: kAudioHardwarePropertyDefaultOutputDevice;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, nullptr, &size, &deviceID) == noErr)
{
if (forInput)
{
for (int i = inputIds.size(); --i >= 0;)
if (inputIds[i] == deviceID)
return i;
}
else
{
for (int i = outputIds.size(); --i >= 0;)
if (outputIds[i] == deviceID)
return i;
}
}
return 0;
}
int getIndexOfDevice (AudioIODevice* device, bool asInput) const override
{
jassert (hasScanned); // need to call scanForDevices() before doing this
if (auto* d = dynamic_cast<CoreAudioIODevice*> (device))
return asInput ? d->inputIndex
: d->outputIndex;
if (auto* d = dynamic_cast<AudioIODeviceCombiner*> (device))
{
for (auto* dev : d->getDevices())
{
auto index = getIndexOfDevice (dev, asInput);
if (index >= 0)
return index;
}
}
return -1;
}
bool hasSeparateInputsAndOutputs() const override { return true; }
AudioIODevice* createDevice (const String& outputDeviceName,
const String& inputDeviceName) override
{
jassert (hasScanned); // need to call scanForDevices() before doing this
auto inputIndex = inputDeviceNames.indexOf (inputDeviceName);
auto outputIndex = outputDeviceNames.indexOf (outputDeviceName);
auto inputDeviceID = inputIds[inputIndex];
auto outputDeviceID = outputIds[outputIndex];
if (inputDeviceID == 0 && outputDeviceID == 0)
return nullptr;
auto combinedName = outputDeviceName.isEmpty() ? inputDeviceName
: outputDeviceName;
if (inputDeviceID == outputDeviceID)
return std::make_unique<CoreAudioIODevice> (this, combinedName, inputDeviceID, inputIndex, outputDeviceID, outputIndex).release();
auto in = inputDeviceID != 0 ? std::make_unique<CoreAudioIODevice> (this, inputDeviceName, inputDeviceID, inputIndex, 0, -1)
: nullptr;
auto out = outputDeviceID != 0 ? std::make_unique<CoreAudioIODevice> (this, outputDeviceName, 0, -1, outputDeviceID, outputIndex)
: nullptr;
if (in == nullptr) return out.release();
if (out == nullptr) return in.release();
auto combo = std::make_unique<AudioIODeviceCombiner> (combinedName, this);
combo->addDevice (std::move (in), true, false);
combo->addDevice (std::move (out), false, true);
return combo.release();
}
void audioDeviceListChanged()
{
scanForDevices();
callDeviceChangeListeners();
}
//==============================================================================
private:
StringArray inputDeviceNames, outputDeviceNames;
Array<AudioDeviceID> inputIds, outputIds;
bool hasScanned = false;
void handleAsyncUpdate() override
{
audioDeviceListChanged();
}
static int getNumChannels (AudioDeviceID deviceID, bool input)
{
int total = 0;
UInt32 size;
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyStreamConfiguration;
pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
pa.mElement = juceAudioObjectPropertyElementMain;
if (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, nullptr, &size) == noErr)
{
HeapBlock<AudioBufferList> bufList;
bufList.calloc (size, 1);
if (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &size, bufList) == noErr)
{
auto numStreams = (int) bufList->mNumberBuffers;
for (int i = 0; i < numStreams; ++i)
total += bufList->mBuffers[i].mNumberChannels;
}
}
return total;
}
static OSStatus hardwareListenerProc (AudioDeviceID, UInt32, const AudioObjectPropertyAddress*, void* clientData)
{
static_cast<CoreAudioIODeviceType*> (clientData)->triggerAsyncUpdate();
return noErr;
}
JUCE_DECLARE_WEAK_REFERENCEABLE (CoreAudioIODeviceType)
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType)
};
};
#undef JUCE_COREAUDIOLOG
} // namespace juce
|