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
|
/* $Id: coreaudio.c $ */
/** @file
* VBox audio devices: Mac OS X CoreAudio audio driver
*/
/*
* Copyright (C) 2010-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#define LOG_GROUP LOG_GROUP_DEV_AUDIO
#include <VBox/log.h>
#include <iprt/asm.h>
#include <iprt/mem.h>
#include <iprt/cdefs.h>
#define AUDIO_CAP "coreaudio"
#include "vl_vbox.h"
#include "audio.h"
#include "audio_int.h"
#include <CoreAudio/CoreAudio.h>
#include <CoreServices/CoreServices.h>
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioConverter.h>
/* todo:
* - maybe make sure the threads are immediately stopped if playing/recording stops
*/
/* Most of this is based on:
* http://developer.apple.com/mac/library/technotes/tn2004/tn2097.html
* http://developer.apple.com/mac/library/technotes/tn2002/tn2091.html
* http://developer.apple.com/mac/library/qa/qa2007/qa1533.html
* http://developer.apple.com/mac/library/qa/qa2001/qa1317.html
* http://developer.apple.com/mac/library/documentation/AudioUnit/Reference/AUComponentServicesReference/Reference/reference.html
*/
/*#define CA_EXTENSIVE_LOGGING*/
/*******************************************************************************
*
* IO Ring Buffer section
*
******************************************************************************/
/* Implementation of a lock free ring buffer which could be used in a multi
* threaded environment. Note that only the acquire, release and getter
* functions are threading aware. So don't use reset if the ring buffer is
* still in use. */
typedef struct IORINGBUFFER
{
/* The current read position in the buffer */
uint32_t uReadPos;
/* The current write position in the buffer */
uint32_t uWritePos;
/* How much space of the buffer is currently in use */
volatile uint32_t cBufferUsed;
/* How big is the buffer */
uint32_t cBufSize;
/* The buffer itself */
char *pBuffer;
} IORINGBUFFER;
/* Pointer to an ring buffer structure */
typedef IORINGBUFFER* PIORINGBUFFER;
static void IORingBufferCreate(PIORINGBUFFER *ppBuffer, uint32_t cSize)
{
PIORINGBUFFER pTmpBuffer;
AssertPtr(ppBuffer);
*ppBuffer = NULL;
pTmpBuffer = RTMemAllocZ(sizeof(IORINGBUFFER));
if (pTmpBuffer)
{
pTmpBuffer->pBuffer = RTMemAlloc(cSize);
if(pTmpBuffer->pBuffer)
{
pTmpBuffer->cBufSize = cSize;
*ppBuffer = pTmpBuffer;
}
else
RTMemFree(pTmpBuffer);
}
}
static void IORingBufferDestroy(PIORINGBUFFER pBuffer)
{
if (pBuffer)
{
if (pBuffer->pBuffer)
RTMemFree(pBuffer->pBuffer);
RTMemFree(pBuffer);
}
}
DECL_FORCE_INLINE(void) IORingBufferReset(PIORINGBUFFER pBuffer)
{
AssertPtr(pBuffer);
pBuffer->uReadPos = 0;
pBuffer->uWritePos = 0;
pBuffer->cBufferUsed = 0;
}
DECL_FORCE_INLINE(uint32_t) IORingBufferFree(PIORINGBUFFER pBuffer)
{
AssertPtr(pBuffer);
return pBuffer->cBufSize - ASMAtomicReadU32(&pBuffer->cBufferUsed);
}
DECL_FORCE_INLINE(uint32_t) IORingBufferUsed(PIORINGBUFFER pBuffer)
{
AssertPtr(pBuffer);
return ASMAtomicReadU32(&pBuffer->cBufferUsed);
}
DECL_FORCE_INLINE(uint32_t) IORingBufferSize(PIORINGBUFFER pBuffer)
{
AssertPtr(pBuffer);
return pBuffer->cBufSize;
}
static void IORingBufferAquireReadBlock(PIORINGBUFFER pBuffer, uint32_t cReqSize, char **ppStart, uint32_t *pcSize)
{
uint32_t uUsed = 0;
uint32_t uSize = 0;
AssertPtr(pBuffer);
*ppStart = 0;
*pcSize = 0;
/* How much is in use? */
uUsed = ASMAtomicReadU32(&pBuffer->cBufferUsed);
if (uUsed > 0)
{
/* Get the size out of the requested size, the read block till the end
* of the buffer & the currently used size. */
uSize = RT_MIN(cReqSize, RT_MIN(pBuffer->cBufSize - pBuffer->uReadPos, uUsed));
if (uSize > 0)
{
/* Return the pointer address which point to the current read
* position. */
*ppStart = pBuffer->pBuffer + pBuffer->uReadPos;
*pcSize = uSize;
}
}
}
DECL_FORCE_INLINE(void) IORingBufferReleaseReadBlock(PIORINGBUFFER pBuffer, uint32_t cSize)
{
AssertPtr(pBuffer);
/* Split at the end of the buffer. */
pBuffer->uReadPos = (pBuffer->uReadPos + cSize) % pBuffer->cBufSize;
ASMAtomicSubU32(&pBuffer->cBufferUsed, cSize);
}
static void IORingBufferAquireWriteBlock(PIORINGBUFFER pBuffer, uint32_t cReqSize, char **ppStart, uint32_t *pcSize)
{
uint32_t uFree;
uint32_t uSize;
AssertPtr(pBuffer);
*ppStart = 0;
*pcSize = 0;
/* How much is free? */
uFree = pBuffer->cBufSize - ASMAtomicReadU32(&pBuffer->cBufferUsed);
if (uFree > 0)
{
/* Get the size out of the requested size, the write block till the end
* of the buffer & the currently free size. */
uSize = RT_MIN(cReqSize, RT_MIN(pBuffer->cBufSize - pBuffer->uWritePos, uFree));
if (uSize > 0)
{
/* Return the pointer address which point to the current write
* position. */
*ppStart = pBuffer->pBuffer + pBuffer->uWritePos;
*pcSize = uSize;
}
}
}
DECL_FORCE_INLINE(void) IORingBufferReleaseWriteBlock(PIORINGBUFFER pBuffer, uint32_t cSize)
{
AssertPtr(pBuffer);
/* Split at the end of the buffer. */
pBuffer->uWritePos = (pBuffer->uWritePos + cSize) % pBuffer->cBufSize;
ASMAtomicAddU32(&pBuffer->cBufferUsed, cSize);
}
/*******************************************************************************
*
* Helper function section
*
******************************************************************************/
#if DEBUG
static void caDebugOutputAudioStreamBasicDescription(const char *pszDesc, const AudioStreamBasicDescription *pStreamDesc)
{
char pszSampleRate[32];
Log(("%s AudioStreamBasicDescription:\n", pszDesc));
Log(("CoreAudio: Format ID: %RU32 (%c%c%c%c)\n", pStreamDesc->mFormatID, RT_BYTE4(pStreamDesc->mFormatID), RT_BYTE3(pStreamDesc->mFormatID), RT_BYTE2(pStreamDesc->mFormatID), RT_BYTE1(pStreamDesc->mFormatID)));
Log(("CoreAudio: Flags: %RU32", pStreamDesc->mFormatFlags));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsFloat)
Log((" Float"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsBigEndian)
Log((" BigEndian"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsSignedInteger)
Log((" SignedInteger"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsPacked)
Log((" Packed"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsAlignedHigh)
Log((" AlignedHigh"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsNonInterleaved)
Log((" NonInterleaved"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagIsNonMixable)
Log((" NonMixable"));
if (pStreamDesc->mFormatFlags & kAudioFormatFlagsAreAllClear)
Log((" AllClear"));
Log(("\n"));
snprintf(pszSampleRate, 32, "%.2f", (float)pStreamDesc->mSampleRate);
Log(("CoreAudio: SampleRate: %s\n", pszSampleRate));
Log(("CoreAudio: ChannelsPerFrame: %RU32\n", pStreamDesc->mChannelsPerFrame));
Log(("CoreAudio: FramesPerPacket: %RU32\n", pStreamDesc->mFramesPerPacket));
Log(("CoreAudio: BitsPerChannel: %RU32\n", pStreamDesc->mBitsPerChannel));
Log(("CoreAudio: BytesPerFrame: %RU32\n", pStreamDesc->mBytesPerFrame));
Log(("CoreAudio: BytesPerPacket: %RU32\n", pStreamDesc->mBytesPerPacket));
}
#endif /* DEBUG */
static void caPCMInfoToAudioStreamBasicDescription(struct audio_pcm_info *pInfo, AudioStreamBasicDescription *pStreamDesc)
{
pStreamDesc->mFormatID = kAudioFormatLinearPCM;
pStreamDesc->mFormatFlags = kAudioFormatFlagIsPacked;
pStreamDesc->mFramesPerPacket = 1;
pStreamDesc->mSampleRate = (Float64)pInfo->freq;
pStreamDesc->mChannelsPerFrame = pInfo->nchannels;
pStreamDesc->mBitsPerChannel = pInfo->bits;
if (pInfo->sign == 1)
pStreamDesc->mFormatFlags |= kAudioFormatFlagIsSignedInteger;
pStreamDesc->mBytesPerFrame = pStreamDesc->mChannelsPerFrame * (pStreamDesc->mBitsPerChannel / 8);
pStreamDesc->mBytesPerPacket = pStreamDesc->mFramesPerPacket * pStreamDesc->mBytesPerFrame;
}
static OSStatus caSetFrameBufferSize(AudioDeviceID device, bool fInput, UInt32 cReqSize, UInt32 *pcActSize)
{
OSStatus err = noErr;
UInt32 cSize = 0;
AudioValueRange *pRange = NULL;
size_t a = 0;
Float64 cMin = -1;
Float64 cMax = -1;
/* First try to set the new frame buffer size. */
AudioDeviceSetProperty(device,
NULL,
0,
fInput,
kAudioDevicePropertyBufferFrameSize,
sizeof(cReqSize),
&cReqSize);
/* Check if it really was set. */
cSize = sizeof(*pcActSize);
err = AudioDeviceGetProperty(device,
0,
fInput,
kAudioDevicePropertyBufferFrameSize,
&cSize,
pcActSize);
if (RT_UNLIKELY(err != noErr))
return err;
/* If both sizes are the same, we are done. */
if (cReqSize == *pcActSize)
return noErr;
/* If not we have to check the limits of the device. First get the size of
the buffer size range property. */
err = AudioDeviceGetPropertyInfo(device,
0,
fInput,
kAudioDevicePropertyBufferSizeRange,
&cSize,
NULL);
if (RT_UNLIKELY(err != noErr))
return err;
pRange = RTMemAllocZ(cSize);
if (RT_VALID_PTR(pRange))
{
err = AudioDeviceGetProperty(device,
0,
fInput,
kAudioDevicePropertyBufferSizeRange,
&cSize,
pRange);
if (RT_LIKELY(err == noErr))
{
for (a=0; a < cSize/sizeof(AudioValueRange); ++a)
{
/* Search for the absolute minimum. */
if ( pRange[a].mMinimum < cMin
|| cMin == -1)
cMin = pRange[a].mMinimum;
/* Search for the best maximum which isn't bigger than
cReqSize. */
if (pRange[a].mMaximum < cReqSize)
{
if (pRange[a].mMaximum > cMax)
cMax = pRange[a].mMaximum;
}
}
if (cMax == -1)
cMax = cMin;
cReqSize = cMax;
/* First try to set the new frame buffer size. */
AudioDeviceSetProperty(device,
NULL,
0,
fInput,
kAudioDevicePropertyBufferFrameSize,
sizeof(cReqSize),
&cReqSize);
/* Check if it really was set. */
cSize = sizeof(*pcActSize);
err = AudioDeviceGetProperty(device,
0,
fInput,
kAudioDevicePropertyBufferFrameSize,
&cSize,
pcActSize);
}
}
else
return notEnoughMemoryErr;
RTMemFree(pRange);
return err;
}
DECL_FORCE_INLINE(bool) caIsRunning(AudioDeviceID deviceID)
{
OSStatus err = noErr;
UInt32 uFlag = 0;
UInt32 uSize = sizeof(uFlag);
err = AudioDeviceGetProperty(deviceID,
0,
0,
kAudioDevicePropertyDeviceIsRunning,
&uSize,
&uFlag);
if (err != kAudioHardwareNoError)
LogRel(("CoreAudio: Could not determine whether the device is running (%RI32)\n", err));
return uFlag >= 1;
}
static char* caCFStringToCString(const CFStringRef pCFString)
{
char *pszResult = NULL;
CFIndex cLen;
#if 0
/**
* CFStringGetCStringPtr doesn't reliably return requested string instead return depends on "many factors" (not clear which)
* ( please follow the link
* http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
* for more details). Branch below allocates memory using mechanisms which hasn't got single method for memory free:
* RTStrDup - RTStrFree
* RTMemAllocZTag - RTMemFree
* which aren't compatible, opposite to CFStringGetCStringPtr CFStringGetCString has well defined
* behaviour and confident return value.
*/
const char *pszTmp = NULL;
/* First try to get the pointer directly. */
pszTmp = CFStringGetCStringPtr(pCFString, kCFStringEncodingUTF8);
if (pszTmp)
{
/* On success make a copy */
pszResult = RTStrDup(pszTmp);
}
else
{
/* If the pointer isn't available directly, we have to make a copy. */
cLen = CFStringGetLength(pCFString) + 1;
pszResult = RTMemAllocZTag(cLen * sizeof(char), RTSTR_TAG);
if (!CFStringGetCString(pCFString, pszResult, cLen, kCFStringEncodingUTF8))
{
RTStrFree(pszResult);
pszResult = NULL;
}
}
#else
/* If the pointer isn't available directly, we have to make a copy. */
cLen = CFStringGetLength(pCFString) + 1;
pszResult = RTMemAllocZTag(cLen * sizeof(char), RTSTR_TAG);
if (!CFStringGetCString(pCFString, pszResult, cLen, kCFStringEncodingUTF8))
{
RTStrFree(pszResult);
pszResult = NULL;
}
#endif
return pszResult;
}
static AudioDeviceID caDeviceUIDtoID(const char* pszUID)
{
OSStatus err = noErr;
UInt32 uSize;
AudioValueTranslation translation;
CFStringRef strUID;
AudioDeviceID audioId;
/* Create a CFString out of our CString */
strUID = CFStringCreateWithCString(NULL,
pszUID,
kCFStringEncodingMacRoman);
/* Fill the translation structure */
translation.mInputData = &strUID;
translation.mInputDataSize = sizeof(CFStringRef);
translation.mOutputData = &audioId;
translation.mOutputDataSize = sizeof(AudioDeviceID);
uSize = sizeof(AudioValueTranslation);
/* Fetch the translation from the UID to the audio Id */
err = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID,
&uSize,
&translation);
/* Release the temporary CFString */
CFRelease(strUID);
if (RT_LIKELY(err == noErr))
return audioId;
/* Return the unknown device on error */
return kAudioDeviceUnknown;
}
/*******************************************************************************
*
* Global structures section
*
******************************************************************************/
/* Initialization status indicator used for the recreation of the AudioUnits. */
#define CA_STATUS_UNINIT UINT32_C(0) /* The device is uninitialized */
#define CA_STATUS_IN_INIT UINT32_C(1) /* The device is currently initializing */
#define CA_STATUS_INIT UINT32_C(2) /* The device is initialized */
#define CA_STATUS_IN_UNINIT UINT32_C(3) /* The device is currently uninitializing */
#define CA_STATUS_REINIT UINT32_C(4) /* The device has to be reinitialized */
/* Error code which indicates "End of data" */
static const OSStatus caConverterEOFDErr = 0x656F6664; /* 'eofd' */
struct
{
const char *pszOutputDeviceUID;
const char *pszInputDeviceUID;
} conf =
{
INIT_FIELD(.pszOutputDeviceUID =) NULL,
INIT_FIELD(.pszInputDeviceUID =) NULL
};
typedef struct caVoiceOut
{
/* HW voice output structure defined by VBox */
HWVoiceOut hw;
/* Stream description which is default on the device */
AudioStreamBasicDescription deviceFormat;
/* Stream description which is selected for using by VBox */
AudioStreamBasicDescription streamFormat;
/* The audio device ID of the currently used device */
AudioDeviceID audioDeviceId;
/* The AudioUnit used */
AudioUnit audioUnit;
/* A ring buffer for transferring data to the playback thread */
PIORINGBUFFER pBuf;
/* Initialization status tracker. Used when some of the device parameters
* or the device itself is changed during the runtime. */
volatile uint32_t status;
} caVoiceOut;
typedef struct caVoiceIn
{
/* HW voice input structure defined by VBox */
HWVoiceIn hw;
/* Stream description which is default on the device */
AudioStreamBasicDescription deviceFormat;
/* Stream description which is selected for using by VBox */
AudioStreamBasicDescription streamFormat;
/* The audio device ID of the currently used device */
AudioDeviceID audioDeviceId;
/* The AudioUnit used */
AudioUnit audioUnit;
/* The audio converter if necessary */
AudioConverterRef converter;
/* A temporary position value used in the caConverterCallback function */
uint32_t rpos;
/* The ratio between the device & the stream sample rate */
Float64 sampleRatio;
/* An extra buffer used for render the audio data in the recording thread */
AudioBufferList bufferList;
/* A ring buffer for transferring data from the recording thread */
PIORINGBUFFER pBuf;
/* Initialization status tracker. Used when some of the device parameters
* or the device itself is changed during the runtime. */
volatile uint32_t status;
} caVoiceIn;
#ifdef CA_EXTENSIVE_LOGGING
# define CA_EXT_DEBUG_LOG(a) Log2(a)
#else
# define CA_EXT_DEBUG_LOG(a) do {} while(0)
#endif
/*******************************************************************************
*
* CoreAudio output section
*
******************************************************************************/
/* We need some forward declarations */
static int coreaudio_run_out(HWVoiceOut *hw);
static int coreaudio_write(SWVoiceOut *sw, void *buf, int len);
static int coreaudio_ctl_out(HWVoiceOut *hw, int cmd, ...);
static void coreaudio_fini_out(HWVoiceOut *hw);
static int coreaudio_init_out(HWVoiceOut *hw, audsettings_t *as);
static int caInitOutput(HWVoiceOut *hw);
static void caReinitOutput(HWVoiceOut *hw);
/* Callback for getting notified when the default output device was changed */
static DECLCALLBACK(OSStatus) caPlaybackDefaultDeviceChanged(AudioHardwarePropertyID inPropertyID,
void *inClientData)
{
OSStatus err = noErr;
UInt32 uSize = 0;
UInt32 ad = 0;
bool fRun = false;
caVoiceOut *caVoice = (caVoiceOut *) inClientData;
switch (inPropertyID)
{
case kAudioHardwarePropertyDefaultOutputDevice:
{
/* This listener is called on every change of the hardware
* device. So check if the default device has really changed. */
uSize = sizeof(caVoice->audioDeviceId);
err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
&uSize,
&ad);
if (caVoice->audioDeviceId != ad)
{
Log2(("CoreAudio: [Output] Default output device changed!\n"));
/* We move the reinitialization to the next output event.
* This make sure this thread isn't blocked and the
* reinitialization is done when necessary only. */
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_REINIT);
}
break;
}
}
return noErr;
}
/* Callback for getting notified when some of the properties of an audio device has changed */
static DECLCALLBACK(OSStatus) caPlaybackAudioDevicePropertyChanged(AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
void *inClientData)
{
switch (inPropertyID)
{
#ifdef DEBUG
case kAudioDeviceProcessorOverload:
{
Log2(("CoreAudio: [Output] Processor overload detected!\n"));
break;
}
#endif /* DEBUG */
default: break;
}
return noErr;
}
/* Callback to feed audio output buffer */
static DECLCALLBACK(OSStatus) caPlaybackCallback(void* inRefCon,
AudioUnitRenderActionFlags* ioActionFlags,
const AudioTimeStamp* inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList* ioData)
{
uint32_t csAvail = 0;
uint32_t cbToRead = 0;
uint32_t csToRead = 0;
uint32_t csReads = 0;
char *pcSrc = NULL;
caVoiceOut *caVoice = (caVoiceOut *) inRefCon;
if (ASMAtomicReadU32(&caVoice->status) != CA_STATUS_INIT)
return noErr;
/* How much space is used in the ring buffer? */
csAvail = IORingBufferUsed(caVoice->pBuf) >> caVoice->hw.info.shift; /* bytes -> samples */
/* How much space is available in the core audio buffer. Use the smaller
* size of the too. */
csAvail = RT_MIN(csAvail, ioData->mBuffers[0].mDataByteSize >> caVoice->hw.info.shift);
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] Start reading buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail << caVoice->hw.info.shift));
/* Iterate as long as data is available */
while(csReads < csAvail)
{
/* How much is left? */
csToRead = csAvail - csReads;
cbToRead = csToRead << caVoice->hw.info.shift; /* samples -> bytes */
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] Try reading %RU32 samples (%RU32 bytes)\n", csToRead, cbToRead));
/* Try to acquire the necessary block from the ring buffer. */
IORingBufferAquireReadBlock(caVoice->pBuf, cbToRead, &pcSrc, &cbToRead);
/* How much to we get? */
csToRead = cbToRead >> caVoice->hw.info.shift; /* bytes -> samples */
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] There are %RU32 samples (%RU32 bytes) available\n", csToRead, cbToRead));
/* Break if nothing is used anymore. */
if (RT_UNLIKELY(cbToRead == 0))
break;
/* Copy the data from our ring buffer to the core audio buffer. */
memcpy((char*)ioData->mBuffers[0].mData + (csReads << caVoice->hw.info.shift), pcSrc, cbToRead);
/* Release the read buffer, so it could be used for new data. */
IORingBufferReleaseReadBlock(caVoice->pBuf, cbToRead);
/* How much have we reads so far. */
csReads += csToRead;
}
/* Write the bytes to the core audio buffer which where really written. */
ioData->mBuffers[0].mDataByteSize = csReads << caVoice->hw.info.shift; /* samples -> bytes */
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] Finished reading buffer with %RU32 samples (%RU32 bytes)\n", csReads, csReads << caVoice->hw.info.shift));
return noErr;
}
static int caInitOutput(HWVoiceOut *hw)
{
OSStatus err = noErr;
UInt32 uSize = 0; /* temporary size of properties */
UInt32 uFlag = 0; /* for setting flags */
CFStringRef name; /* for the temporary device name fetching */
char *pszName = NULL;
char *pszUID = NULL;
ComponentDescription cd; /* description for an audio component */
Component cp; /* an audio component */
AURenderCallbackStruct cb; /* holds the callback structure */
UInt32 cFrames; /* default frame count */
UInt32 cSamples; /* samples count */
caVoiceOut *caVoice = (caVoiceOut *) hw;
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_IN_INIT);
if (caVoice->audioDeviceId == kAudioDeviceUnknown)
{
/* Fetch the default audio output device currently in use */
uSize = sizeof(caVoice->audioDeviceId);
err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
&uSize,
&caVoice->audioDeviceId);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Unable to find default output device (%RI32)\n", err));
return -1;
}
}
/* Try to get the name of the output device and log it. It's not fatal if
* it fails. */
uSize = sizeof(CFStringRef);
err = AudioDeviceGetProperty(caVoice->audioDeviceId,
0,
0,
kAudioObjectPropertyName,
&uSize,
&name);
if (RT_LIKELY(err == noErr))
{
pszName = caCFStringToCString(name);
CFRelease(name);
err = AudioDeviceGetProperty(caVoice->audioDeviceId,
0,
0,
kAudioDevicePropertyDeviceUID,
&uSize,
&name);
if (RT_LIKELY(err == noErr))
{
pszUID = caCFStringToCString(name);
CFRelease(name);
if (pszName && pszUID)
LogRel(("CoreAudio: Using output device: %s (UID: %s)\n", pszName, pszUID));
RTMemFree(pszUID);
}
RTMemFree(pszName);
}
else
LogRel(("CoreAudio: [Output] Unable to get output device name (%RI32)\n", err));
/* Get the default frames buffer size, so that we can setup our internal
* buffers. */
uSize = sizeof(cFrames);
err = AudioDeviceGetProperty(caVoice->audioDeviceId,
0,
false,
kAudioDevicePropertyBufferFrameSize,
&uSize,
&cFrames);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to get frame buffer size of the audio device (%RI32)\n", err));
return -1;
}
/* Set the frame buffer size and honor any minimum/maximum restrictions on
the device. */
err = caSetFrameBufferSize(caVoice->audioDeviceId,
false,
cFrames,
&cFrames);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to set frame buffer size on the audio device (%RI32)\n", err));
return -1;
}
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_HALOutput;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;
/* Try to find the default HAL output component. */
cp = FindNextComponent(NULL, &cd);
if (RT_UNLIKELY(cp == 0))
{
LogRel(("CoreAudio: [Output] Failed to find HAL output component\n"));
return -1;
}
/* Open the default HAL output component. */
err = OpenAComponent(cp, &caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to open output component (%RI32)\n", err));
return -1;
}
/* Switch the I/O mode for output to on. */
uFlag = 1;
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Output,
0,
&uFlag,
sizeof(uFlag));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to set output I/O mode enabled (%RI32)\n", err));
return -1;
}
/* Set the default audio output device as the device for the new AudioUnit. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Output,
0,
&caVoice->audioDeviceId,
sizeof(caVoice->audioDeviceId));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to set current device (%RI32)\n", err));
return -1;
}
/* CoreAudio will inform us on a second thread when it needs more data for
* output. Therefor register an callback function which will provide the new
* data. */
cb.inputProc = caPlaybackCallback;
cb.inputProcRefCon = caVoice;
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input,
0,
&cb,
sizeof(cb));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to set callback (%RI32)\n", err));
return -1;
}
/* Set the quality of the output render to the maximum. */
/* uFlag = kRenderQuality_High;*/
/* err = AudioUnitSetProperty(caVoice->audioUnit,*/
/* kAudioUnitProperty_RenderQuality,*/
/* kAudioUnitScope_Global,*/
/* 0,*/
/* &uFlag,*/
/* sizeof(uFlag));*/
/* Not fatal */
/* if (RT_UNLIKELY(err != noErr))*/
/* LogRel(("CoreAudio: [Output] Failed to set the render quality to the maximum (%RI32)\n", err));*/
/* Fetch the current stream format of the device. */
uSize = sizeof(caVoice->deviceFormat);
err = AudioUnitGetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&caVoice->deviceFormat,
&uSize);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to get device format (%RI32)\n", err));
return -1;
}
/* Create an AudioStreamBasicDescription based on the audio settings of
* VirtualBox. */
caPCMInfoToAudioStreamBasicDescription(&caVoice->hw.info, &caVoice->streamFormat);
#if DEBUG
caDebugOutputAudioStreamBasicDescription("CoreAudio: [Output] device", &caVoice->deviceFormat);
caDebugOutputAudioStreamBasicDescription("CoreAudio: [Output] output", &caVoice->streamFormat);
#endif /* DEBUG */
/* Set the device format description for the stream. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&caVoice->streamFormat,
sizeof(caVoice->streamFormat));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to set stream format (%RI32)\n", err));
return -1;
}
uSize = sizeof(caVoice->deviceFormat);
err = AudioUnitGetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&caVoice->deviceFormat,
&uSize);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to get device format (%RI32)\n", err));
return -1;
}
/* Also set the frame buffer size off the device on our AudioUnit. This
should make sure that the frames count which we receive in the render
thread is as we like. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global,
0,
&cFrames,
sizeof(cFrames));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to set maximum frame buffer size on the AudioUnit (%RI32)\n", err));
return -1;
}
/* Finally initialize the new AudioUnit. */
err = AudioUnitInitialize(caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to initialize the AudioUnit (%RI32)\n", err));
return -1;
}
/* There are buggy devices (e.g. my Bluetooth headset) which doesn't honor
* the frame buffer size set in the previous calls. So finally get the
* frame buffer size after the AudioUnit was initialized. */
uSize = sizeof(cFrames);
err = AudioUnitGetProperty(caVoice->audioUnit,
kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global,
0,
&cFrames,
&uSize);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to get maximum frame buffer size from the AudioUnit (%RI32)\n", err));
return -1;
}
/* Create the internal ring buffer. */
cSamples = cFrames * caVoice->streamFormat.mChannelsPerFrame;
IORingBufferCreate(&caVoice->pBuf, cSamples << hw->info.shift);
if (!RT_VALID_PTR(caVoice->pBuf))
{
LogRel(("CoreAudio: [Output] Failed to create internal ring buffer\n"));
AudioUnitUninitialize(caVoice->audioUnit);
return -1;
}
if ( hw->samples != 0
&& hw->samples != (int32_t)cSamples)
LogRel(("CoreAudio: [Output] Warning! After recreation, the CoreAudio ring buffer doesn't has the same size as the device buffer (%RU32 vs. %RU32).\n", cSamples, (uint32_t)hw->samples));
#ifdef DEBUG
err = AudioDeviceAddPropertyListener(caVoice->audioDeviceId,
0,
false,
kAudioDeviceProcessorOverload,
caPlaybackAudioDevicePropertyChanged,
caVoice);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Output] Failed to add the processor overload listener (%RI32)\n", err));
#endif /* DEBUG */
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_INIT);
Log(("CoreAudio: [Output] Frame count: %RU32\n", cFrames));
return 0;
}
static void caReinitOutput(HWVoiceOut *hw)
{
caVoiceOut *caVoice = (caVoiceOut *) hw;
coreaudio_fini_out(&caVoice->hw);
caInitOutput(&caVoice->hw);
coreaudio_ctl_out(&caVoice->hw, VOICE_ENABLE);
}
static int coreaudio_run_out(HWVoiceOut *hw)
{
uint32_t csAvail = 0;
uint32_t cbToWrite = 0;
uint32_t csToWrite = 0;
uint32_t csWritten = 0;
char *pcDst = NULL;
st_sample_t *psSrc = NULL;
caVoiceOut *caVoice = (caVoiceOut *) hw;
/* Check if the audio device should be reinitialized. If so do it. */
if (ASMAtomicReadU32(&caVoice->status) == CA_STATUS_REINIT)
caReinitOutput(&caVoice->hw);
/* We return the live count in the case we are not initialized. This should
* prevent any under runs. */
if (ASMAtomicReadU32(&caVoice->status) != CA_STATUS_INIT)
return audio_pcm_hw_get_live_out(hw);
/* Make sure the device is running */
coreaudio_ctl_out(&caVoice->hw, VOICE_ENABLE);
/* How much space is available in the ring buffer */
csAvail = IORingBufferFree(caVoice->pBuf) >> hw->info.shift; /* bytes -> samples */
/* How much data is available. Use the smaller size of the too. */
csAvail = RT_MIN(csAvail, (uint32_t)audio_pcm_hw_get_live_out(hw));
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] Start writing buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail << hw->info.shift));
/* Iterate as long as data is available */
while (csWritten < csAvail)
{
/* How much is left? Split request at the end of our samples buffer. */
csToWrite = RT_MIN(csAvail - csWritten, (uint32_t)(hw->samples - hw->rpos));
cbToWrite = csToWrite << hw->info.shift; /* samples -> bytes */
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] Try writing %RU32 samples (%RU32 bytes)\n", csToWrite, cbToWrite));
/* Try to acquire the necessary space from the ring buffer. */
IORingBufferAquireWriteBlock(caVoice->pBuf, cbToWrite, &pcDst, &cbToWrite);
/* How much to we get? */
csToWrite = cbToWrite >> hw->info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] There is space for %RU32 samples (%RU32 bytes) available\n", csToWrite, cbToWrite));
/* Break if nothing is free anymore. */
if (RT_UNLIKELY(cbToWrite == 0))
break;
/* Copy the data from our mix buffer to the ring buffer. */
psSrc = hw->mix_buf + hw->rpos;
hw->clip((uint8_t*)pcDst, psSrc, csToWrite);
/* Release the ring buffer, so the read thread could start reading this data. */
IORingBufferReleaseWriteBlock(caVoice->pBuf, cbToWrite);
hw->rpos = (hw->rpos + csToWrite) % hw->samples;
/* How much have we written so far. */
csWritten += csToWrite;
}
CA_EXT_DEBUG_LOG(("CoreAudio: [Output] Finished writing buffer with %RU32 samples (%RU32 bytes)\n", csWritten, csWritten << hw->info.shift));
/* Return the count of samples we have processed. */
return csWritten;
}
static int coreaudio_write(SWVoiceOut *sw, void *buf, int len)
{
return audio_pcm_sw_write (sw, buf, len);
}
static int coreaudio_ctl_out(HWVoiceOut *hw, int cmd, ...)
{
OSStatus err = noErr;
uint32_t status;
caVoiceOut *caVoice = (caVoiceOut *) hw;
status = ASMAtomicReadU32(&caVoice->status);
if (!( status == CA_STATUS_INIT
|| status == CA_STATUS_REINIT))
return 0;
switch (cmd)
{
case VOICE_ENABLE:
{
/* Only start the device if it is actually stopped */
if (!caIsRunning(caVoice->audioDeviceId))
{
err = AudioUnitReset(caVoice->audioUnit,
kAudioUnitScope_Input,
0);
IORingBufferReset(caVoice->pBuf);
err = AudioOutputUnitStart(caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to start playback (%RI32)\n", err));
return -1;
}
}
break;
}
case VOICE_DISABLE:
{
/* Only stop the device if it is actually running */
if (caIsRunning(caVoice->audioDeviceId))
{
err = AudioOutputUnitStop(caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to stop playback (%RI32)\n", err));
return -1;
}
err = AudioUnitReset(caVoice->audioUnit,
kAudioUnitScope_Input,
0);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Output] Failed to reset AudioUnit (%RI32)\n", err));
return -1;
}
}
break;
}
}
return 0;
}
static void coreaudio_fini_out(HWVoiceOut *hw)
{
int rc = 0;
uint32_t status;
OSStatus err = noErr;
caVoiceOut *caVoice = (caVoiceOut *) hw;
status = ASMAtomicReadU32(&caVoice->status);
if (!( status == CA_STATUS_INIT
|| status == CA_STATUS_REINIT))
return;
rc = coreaudio_ctl_out(hw, VOICE_DISABLE);
if (RT_LIKELY(rc == 0))
{
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_IN_UNINIT);
#ifdef DEBUG
err = AudioDeviceRemovePropertyListener(caVoice->audioDeviceId,
0,
false,
kAudioDeviceProcessorOverload,
caPlaybackAudioDevicePropertyChanged);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Output] Failed to remove the processor overload listener (%RI32)\n", err));
#endif /* DEBUG */
err = AudioUnitUninitialize(caVoice->audioUnit);
if (RT_LIKELY(err == noErr))
{
err = CloseComponent(caVoice->audioUnit);
if (RT_LIKELY(err == noErr))
{
IORingBufferDestroy(caVoice->pBuf);
caVoice->audioUnit = NULL;
caVoice->audioDeviceId = kAudioDeviceUnknown;
caVoice->pBuf = NULL;
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_UNINIT);
}
else
LogRel(("CoreAudio: [Output] Failed to close the AudioUnit (%RI32)\n", err));
}
else
LogRel(("CoreAudio: [Output] Failed to uninitialize the AudioUnit (%RI32)\n", err));
}
else
LogRel(("CoreAudio: [Output] Failed to stop playback (%RI32)\n", err));
}
static int coreaudio_init_out(HWVoiceOut *hw, audsettings_t *as)
{
OSStatus err = noErr;
int rc = 0;
bool fDeviceByUser = false; /* use we a device which was set by the user? */
caVoiceOut *caVoice = (caVoiceOut *) hw;
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_UNINIT);
caVoice->audioUnit = NULL;
caVoice->audioDeviceId = kAudioDeviceUnknown;
hw->samples = 0;
/* Initialize the hardware info section with the audio settings */
audio_pcm_init_info(&hw->info, as);
/* Try to find the audio device set by the user. Use
* export VBOX_COREAUDIO_OUTPUT_DEVICE_UID=AppleHDAEngineOutput:0
* to set it. */
if (conf.pszOutputDeviceUID)
{
caVoice->audioDeviceId = caDeviceUIDtoID(conf.pszOutputDeviceUID);
/* Not fatal */
if (caVoice->audioDeviceId == kAudioDeviceUnknown)
LogRel(("CoreAudio: [Output] Unable to find output device %s. Falling back to the default audio device. \n", conf.pszOutputDeviceUID));
else
fDeviceByUser = true;
}
rc = caInitOutput(hw);
if (RT_UNLIKELY(rc != 0))
return rc;
/* The samples have to correspond to the internal ring buffer size. */
hw->samples = (IORingBufferSize(caVoice->pBuf) >> hw->info.shift) / caVoice->streamFormat.mChannelsPerFrame;
/* When the devices isn't forced by the user, we want default device change
* notifications. */
if (!fDeviceByUser)
{
err = AudioHardwareAddPropertyListener(kAudioHardwarePropertyDefaultOutputDevice,
caPlaybackDefaultDeviceChanged,
caVoice);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Output] Failed to add the default device changed listener (%RI32)\n", err));
}
Log(("CoreAudio: [Output] HW samples: %d\n", hw->samples));
return 0;
}
/*******************************************************************************
*
* CoreAudio input section
*
******************************************************************************/
/* We need some forward declarations */
static int coreaudio_run_in(HWVoiceIn *hw);
static int coreaudio_read(SWVoiceIn *sw, void *buf, int size);
static int coreaudio_ctl_in(HWVoiceIn *hw, int cmd, ...);
static void coreaudio_fini_in(HWVoiceIn *hw);
static int coreaudio_init_in(HWVoiceIn *hw, audsettings_t *as);
static int caInitInput(HWVoiceIn *hw);
static void caReinitInput(HWVoiceIn *hw);
/* Callback for getting notified when the default input device was changed */
static DECLCALLBACK(OSStatus) caRecordingDefaultDeviceChanged(AudioHardwarePropertyID inPropertyID,
void *inClientData)
{
OSStatus err = noErr;
UInt32 uSize = 0;
UInt32 ad = 0;
bool fRun = false;
caVoiceIn *caVoice = (caVoiceIn *) inClientData;
switch (inPropertyID)
{
case kAudioHardwarePropertyDefaultInputDevice:
{
/* This listener is called on every change of the hardware
* device. So check if the default device has really changed. */
uSize = sizeof(caVoice->audioDeviceId);
err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
&uSize,
&ad);
if (caVoice->audioDeviceId != ad)
{
Log2(("CoreAudio: [Input] Default input device changed!\n"));
/* We move the reinitialization to the next input event.
* This make sure this thread isn't blocked and the
* reinitialization is done when necessary only. */
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_REINIT);
}
break;
}
}
return noErr;
}
/* Callback for getting notified when some of the properties of an audio device has changed */
static DECLCALLBACK(OSStatus) caRecordingAudioDevicePropertyChanged(AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
void *inClientData)
{
caVoiceIn *caVoice = (caVoiceIn *) inClientData;
switch (inPropertyID)
{
#ifdef DEBUG
case kAudioDeviceProcessorOverload:
{
Log2(("CoreAudio: [Input] Processor overload detected!\n"));
break;
}
#endif /* DEBUG */
case kAudioDevicePropertyNominalSampleRate:
{
Log2(("CoreAudio: [Input] Sample rate changed!\n"));
/* We move the reinitialization to the next input event.
* This make sure this thread isn't blocked and the
* reinitialization is done when necessary only. */
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_REINIT);
break;
}
default: break;
}
return noErr;
}
/* Callback to convert audio input data from one format to another */
static DECLCALLBACK(OSStatus) caConverterCallback(AudioConverterRef inAudioConverter,
UInt32 *ioNumberDataPackets,
AudioBufferList *ioData,
AudioStreamPacketDescription **outDataPacketDescription,
void *inUserData)
{
/* In principle we had to check here if the source is non interleaved & if
* so go through all buffers not only the first one like now. */
UInt32 cSize = 0;
caVoiceIn *caVoice = (caVoiceIn *) inUserData;
const AudioBufferList *pBufferList = &caVoice->bufferList;
if (ASMAtomicReadU32(&caVoice->status) != CA_STATUS_INIT)
return noErr;
/* Log2(("converting .... ################ %RU32 %RU32 %RU32 %RU32 %RU32\n", *ioNumberDataPackets, bufferList->mBuffers[i].mNumberChannels, bufferList->mNumberBuffers, bufferList->mBuffers[i].mDataByteSize, ioData->mNumberBuffers));*/
/* Use the lower one of the packets to process & the available packets in
* the buffer */
cSize = RT_MIN(*ioNumberDataPackets * caVoice->deviceFormat.mBytesPerPacket,
pBufferList->mBuffers[0].mDataByteSize - caVoice->rpos);
/* Set the new size on output, so the caller know what we have processed. */
*ioNumberDataPackets = cSize / caVoice->deviceFormat.mBytesPerPacket;
/* If no data is available anymore we return with an error code. This error
* code will be returned from AudioConverterFillComplexBuffer. */
if (*ioNumberDataPackets == 0)
{
ioData->mBuffers[0].mDataByteSize = 0;
ioData->mBuffers[0].mData = NULL;
return caConverterEOFDErr;
}
else
{
ioData->mBuffers[0].mNumberChannels = pBufferList->mBuffers[0].mNumberChannels;
ioData->mBuffers[0].mDataByteSize = cSize;
ioData->mBuffers[0].mData = (char*)pBufferList->mBuffers[0].mData + caVoice->rpos;
caVoice->rpos += cSize;
/* Log2(("converting .... ################ %RU32 %RU32\n", size, caVoice->rpos));*/
}
return noErr;
}
/* Callback to feed audio input buffer */
static DECLCALLBACK(OSStatus) caRecordingCallback(void* inRefCon,
AudioUnitRenderActionFlags* ioActionFlags,
const AudioTimeStamp* inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList* ioData)
{
OSStatus err = noErr;
uint32_t csAvail = 0;
uint32_t csToWrite = 0;
uint32_t cbToWrite = 0;
uint32_t csWritten = 0;
char *pcDst = NULL;
AudioBufferList tmpList;
UInt32 ioOutputDataPacketSize = 0;
caVoiceIn *caVoice = (caVoiceIn *) inRefCon;
if (ASMAtomicReadU32(&caVoice->status) != CA_STATUS_INIT)
return noErr;
/* If nothing is pending return immediately. */
if (inNumberFrames == 0)
return noErr;
/* Are we using an converter? */
if (RT_VALID_PTR(caVoice->converter))
{
/* Firstly render the data as usual */
caVoice->bufferList.mBuffers[0].mNumberChannels = caVoice->deviceFormat.mChannelsPerFrame;
caVoice->bufferList.mBuffers[0].mDataByteSize = caVoice->deviceFormat.mBytesPerFrame * inNumberFrames;
caVoice->bufferList.mBuffers[0].mData = RTMemAlloc(caVoice->bufferList.mBuffers[0].mDataByteSize);
err = AudioUnitRender(caVoice->audioUnit,
ioActionFlags,
inTimeStamp,
inBusNumber,
inNumberFrames,
&caVoice->bufferList);
if(RT_UNLIKELY(err != noErr))
{
Log(("CoreAudio: [Input] Failed to render audio data (%RI32)\n", err));
RTMemFree(caVoice->bufferList.mBuffers[0].mData);
return err;
}
/* How much space is free in the ring buffer? */
csAvail = IORingBufferFree(caVoice->pBuf) >> caVoice->hw.info.shift; /* bytes -> samples */
/* How much space is used in the core audio buffer. Use the smaller size of
* the too. */
csAvail = RT_MIN(csAvail, (uint32_t)((caVoice->bufferList.mBuffers[0].mDataByteSize / caVoice->deviceFormat.mBytesPerFrame) * caVoice->sampleRatio));
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Start writing buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail << caVoice->hw.info.shift));
/* Initialize the temporary output buffer */
tmpList.mNumberBuffers = 1;
tmpList.mBuffers[0].mNumberChannels = caVoice->streamFormat.mChannelsPerFrame;
/* Set the read position to zero. */
caVoice->rpos = 0;
/* Iterate as long as data is available */
while(csWritten < csAvail)
{
/* How much is left? */
csToWrite = csAvail - csWritten;
cbToWrite = csToWrite << caVoice->hw.info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Try writing %RU32 samples (%RU32 bytes)\n", csToWrite, cbToWrite));
/* Try to acquire the necessary space from the ring buffer. */
IORingBufferAquireWriteBlock(caVoice->pBuf, cbToWrite, &pcDst, &cbToWrite);
/* How much to we get? */
csToWrite = cbToWrite >> caVoice->hw.info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] There is space for %RU32 samples (%RU32 bytes) available\n", csToWrite, cbToWrite));
/* Break if nothing is free anymore. */
if (RT_UNLIKELY(cbToWrite == 0))
break;
/* Now set how much space is available for output */
ioOutputDataPacketSize = cbToWrite / caVoice->streamFormat.mBytesPerPacket;
/* Set our ring buffer as target. */
tmpList.mBuffers[0].mDataByteSize = cbToWrite;
tmpList.mBuffers[0].mData = pcDst;
AudioConverterReset(caVoice->converter);
err = AudioConverterFillComplexBuffer(caVoice->converter,
caConverterCallback,
caVoice,
&ioOutputDataPacketSize,
&tmpList,
NULL);
if( RT_UNLIKELY(err != noErr)
&& err != caConverterEOFDErr)
{
Log(("CoreAudio: [Input] Failed to convert audio data (%RI32:%c%c%c%c)\n", err, RT_BYTE4(err), RT_BYTE3(err), RT_BYTE2(err), RT_BYTE1(err)));
break;
}
/* Check in any case what processed size is returned. It could be
* much littler than we expected. */
cbToWrite = ioOutputDataPacketSize * caVoice->streamFormat.mBytesPerPacket;
csToWrite = cbToWrite >> caVoice->hw.info.shift;
/* Release the ring buffer, so the main thread could start reading this data. */
IORingBufferReleaseWriteBlock(caVoice->pBuf, cbToWrite);
csWritten += csToWrite;
/* If the error is "End of Data" it means there is no data anymore
* which could be converted. So end here now. */
if (err == caConverterEOFDErr)
break;
}
/* Cleanup */
RTMemFree(caVoice->bufferList.mBuffers[0].mData);
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Finished writing buffer with %RU32 samples (%RU32 bytes)\n", csWritten, csWritten << caVoice->hw.info.shift));
}
else
{
caVoice->bufferList.mBuffers[0].mNumberChannels = caVoice->streamFormat.mChannelsPerFrame;
caVoice->bufferList.mBuffers[0].mDataByteSize = caVoice->streamFormat.mBytesPerFrame * inNumberFrames;
caVoice->bufferList.mBuffers[0].mData = RTMemAlloc(caVoice->bufferList.mBuffers[0].mDataByteSize);
err = AudioUnitRender(caVoice->audioUnit,
ioActionFlags,
inTimeStamp,
inBusNumber,
inNumberFrames,
&caVoice->bufferList);
if(RT_UNLIKELY(err != noErr))
{
Log(("CoreAudio: [Input] Failed to render audio data (%RI32)\n", err));
RTMemFree(caVoice->bufferList.mBuffers[0].mData);
return err;
}
/* How much space is free in the ring buffer? */
csAvail = IORingBufferFree(caVoice->pBuf) >> caVoice->hw.info.shift; /* bytes -> samples */
/* How much space is used in the core audio buffer. Use the smaller size of
* the too. */
csAvail = RT_MIN(csAvail, caVoice->bufferList.mBuffers[0].mDataByteSize >> caVoice->hw.info.shift);
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Start writing buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail << caVoice->hw.info.shift));
/* Iterate as long as data is available */
while(csWritten < csAvail)
{
/* How much is left? */
csToWrite = csAvail - csWritten;
cbToWrite = csToWrite << caVoice->hw.info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Try writing %RU32 samples (%RU32 bytes)\n", csToWrite, cbToWrite));
/* Try to acquire the necessary space from the ring buffer. */
IORingBufferAquireWriteBlock(caVoice->pBuf, cbToWrite, &pcDst, &cbToWrite);
/* How much to we get? */
csToWrite = cbToWrite >> caVoice->hw.info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] There is space for %RU32 samples (%RU32 bytes) available\n", csToWrite, cbToWrite));
/* Break if nothing is free anymore. */
if (RT_UNLIKELY(cbToWrite == 0))
break;
/* Copy the data from the core audio buffer to the ring buffer. */
memcpy(pcDst, (char*)caVoice->bufferList.mBuffers[0].mData + (csWritten << caVoice->hw.info.shift), cbToWrite);
/* Release the ring buffer, so the main thread could start reading this data. */
IORingBufferReleaseWriteBlock(caVoice->pBuf, cbToWrite);
csWritten += csToWrite;
}
/* Cleanup */
RTMemFree(caVoice->bufferList.mBuffers[0].mData);
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Finished writing buffer with %RU32 samples (%RU32 bytes)\n", csWritten, csWritten << caVoice->hw.info.shift));
}
return err;
}
static int caInitInput(HWVoiceIn *hw)
{
OSStatus err = noErr;
int rc = -1;
UInt32 uSize = 0; /* temporary size of properties */
UInt32 uFlag = 0; /* for setting flags */
CFStringRef name; /* for the temporary device name fetching */
char *pszName = NULL;
char *pszUID = NULL;
ComponentDescription cd; /* description for an audio component */
Component cp; /* an audio component */
AURenderCallbackStruct cb; /* holds the callback structure */
UInt32 cFrames; /* default frame count */
const SInt32 channelMap[2] = {0, 0}; /* Channel map for mono -> stereo */
UInt32 cSamples; /* samples count */
caVoiceIn *caVoice = (caVoiceIn *) hw;
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_IN_INIT);
if (caVoice->audioDeviceId == kAudioDeviceUnknown)
{
/* Fetch the default audio output device currently in use */
uSize = sizeof(caVoice->audioDeviceId);
err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
&uSize,
&caVoice->audioDeviceId);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Unable to find default input device (%RI32)\n", err));
return -1;
}
}
/* Try to get the name of the input device and log it. It's not fatal if
* it fails. */
uSize = sizeof(CFStringRef);
err = AudioDeviceGetProperty(caVoice->audioDeviceId,
0,
0,
kAudioObjectPropertyName,
&uSize,
&name);
if (RT_LIKELY(err == noErr))
{
pszName = caCFStringToCString(name);
CFRelease(name);
err = AudioDeviceGetProperty(caVoice->audioDeviceId,
0,
0,
kAudioDevicePropertyDeviceUID,
&uSize,
&name);
if (RT_LIKELY(err == noErr))
{
pszUID = caCFStringToCString(name);
CFRelease(name);
if (pszName && pszUID)
LogRel(("CoreAudio: Using input device: %s (UID: %s)\n", pszName, pszUID));
if (pszUID)
RTMemFree(pszUID);
}
if (pszName)
RTMemFree(pszName);
}
else
LogRel(("CoreAudio: [Input] Unable to get input device name (%RI32)\n", err));
/* Get the default frames buffer size, so that we can setup our internal
* buffers. */
uSize = sizeof(cFrames);
err = AudioDeviceGetProperty(caVoice->audioDeviceId,
0,
true,
kAudioDevicePropertyBufferFrameSize,
&uSize,
&cFrames);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to get frame buffer size of the audio device (%RI32)\n", err));
return -1;
}
/* Set the frame buffer size and honor any minimum/maximum restrictions on
the device. */
err = caSetFrameBufferSize(caVoice->audioDeviceId,
true,
cFrames,
&cFrames);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set frame buffer size on the audio device (%RI32)\n", err));
return -1;
}
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_HALOutput;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;
/* Try to find the default HAL output component. */
cp = FindNextComponent(NULL, &cd);
if (RT_UNLIKELY(cp == 0))
{
LogRel(("CoreAudio: [Input] Failed to find HAL output component\n"));
return -1;
}
/* Open the default HAL output component. */
err = OpenAComponent(cp, &caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to open output component (%RI32)\n", err));
return -1;
}
/* Switch the I/O mode for input to on. */
uFlag = 1;
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Input,
1,
&uFlag,
sizeof(uFlag));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set input I/O mode enabled (%RI32)\n", err));
return -1;
}
/* Switch the I/O mode for output to off. This is important, as this is a
* pure input stream. */
uFlag = 0;
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Output,
0,
&uFlag,
sizeof(uFlag));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set output I/O mode disabled (%RI32)\n", err));
return -1;
}
/* Set the default audio input device as the device for the new AudioUnit. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global,
0,
&caVoice->audioDeviceId,
sizeof(caVoice->audioDeviceId));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set current device (%RI32)\n", err));
return -1;
}
/* CoreAudio will inform us on a second thread for new incoming audio data.
* Therefor register an callback function, which will process the new data.
* */
cb.inputProc = caRecordingCallback;
cb.inputProcRefCon = caVoice;
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioOutputUnitProperty_SetInputCallback,
kAudioUnitScope_Global,
0,
&cb,
sizeof(cb));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set callback (%RI32)\n", err));
return -1;
}
/* Fetch the current stream format of the device. */
uSize = sizeof(caVoice->deviceFormat);
err = AudioUnitGetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
1,
&caVoice->deviceFormat,
&uSize);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to get device format (%RI32)\n", err));
return -1;
}
/* Create an AudioStreamBasicDescription based on the audio settings of
* VirtualBox. */
caPCMInfoToAudioStreamBasicDescription(&caVoice->hw.info, &caVoice->streamFormat);
#if DEBUG
caDebugOutputAudioStreamBasicDescription("CoreAudio: [Input] device", &caVoice->deviceFormat);
caDebugOutputAudioStreamBasicDescription("CoreAudio: [Input] input", &caVoice->streamFormat);
#endif /* DEBUG */
/* If the frequency of the device is different from the requested one we
* need a converter. The same count if the number of channels is different. */
if ( caVoice->deviceFormat.mSampleRate != caVoice->streamFormat.mSampleRate
|| caVoice->deviceFormat.mChannelsPerFrame != caVoice->streamFormat.mChannelsPerFrame)
{
err = AudioConverterNew(&caVoice->deviceFormat,
&caVoice->streamFormat,
&caVoice->converter);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to create the audio converter (%RI32)\n", err));
return -1;
}
if (caVoice->deviceFormat.mChannelsPerFrame == 1 &&
caVoice->streamFormat.mChannelsPerFrame == 2)
{
/* If the channel count is different we have to tell this the converter
and supply a channel mapping. For now we only support mapping
from mono to stereo. For all other cases the core audio defaults
are used, which means dropping additional channels in most
cases. */
err = AudioConverterSetProperty(caVoice->converter,
kAudioConverterChannelMap,
sizeof(channelMap),
channelMap);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to add a channel mapper to the audio converter (%RI32)\n", err));
return -1;
}
}
/* Set sample rate converter quality to maximum */
/* uFlag = kAudioConverterQuality_Max;*/
/* err = AudioConverterSetProperty(caVoice->converter,*/
/* kAudioConverterSampleRateConverterQuality,*/
/* sizeof(uFlag),*/
/* &uFlag);*/
/* Not fatal */
/* if (RT_UNLIKELY(err != noErr))*/
/* LogRel(("CoreAudio: [Input] Failed to set the audio converter quality to the maximum (%RI32)\n", err));*/
Log(("CoreAudio: [Input] Converter in use\n"));
/* Set the new format description for the stream. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output,
1,
&caVoice->deviceFormat,
sizeof(caVoice->deviceFormat));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set stream format (%RI32)\n", err));
return -1;
}
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
1,
&caVoice->deviceFormat,
sizeof(caVoice->deviceFormat));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set stream format (%RI32)\n", err));
return -1;
}
}
else
{
/* Set the new format description for the stream. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output,
1,
&caVoice->streamFormat,
sizeof(caVoice->streamFormat));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set stream format (%RI32)\n", err));
return -1;
}
}
/* Also set the frame buffer size off the device on our AudioUnit. This
should make sure that the frames count which we receive in the render
thread is as we like. */
err = AudioUnitSetProperty(caVoice->audioUnit,
kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global,
1,
&cFrames,
sizeof(cFrames));
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to set maximum frame buffer size on the AudioUnit (%RI32)\n", err));
return -1;
}
/* Finally initialize the new AudioUnit. */
err = AudioUnitInitialize(caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to initialize the AudioUnit (%RI32)\n", err));
return -1;
}
uSize = sizeof(caVoice->deviceFormat);
err = AudioUnitGetProperty(caVoice->audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output,
1,
&caVoice->deviceFormat,
&uSize);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to get device format (%RI32)\n", err));
return -1;
}
/* There are buggy devices (e.g. my Bluetooth headset) which doesn't honor
* the frame buffer size set in the previous calls. So finally get the
* frame buffer size after the AudioUnit was initialized. */
uSize = sizeof(cFrames);
err = AudioUnitGetProperty(caVoice->audioUnit,
kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global,
0,
&cFrames,
&uSize);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to get maximum frame buffer size from the AudioUnit (%RI32)\n", err));
return -1;
}
/* Calculate the ratio between the device and the stream sample rate. */
caVoice->sampleRatio = caVoice->streamFormat.mSampleRate / caVoice->deviceFormat.mSampleRate;
/* Set to zero first */
caVoice->pBuf = NULL;
/* Create the AudioBufferList structure with one buffer. */
caVoice->bufferList.mNumberBuffers = 1;
/* Initialize the buffer to nothing. */
caVoice->bufferList.mBuffers[0].mNumberChannels = caVoice->streamFormat.mChannelsPerFrame;
caVoice->bufferList.mBuffers[0].mDataByteSize = 0;
caVoice->bufferList.mBuffers[0].mData = NULL;
/* Make sure that the ring buffer is big enough to hold the recording
* data. Compare the maximum frames per slice value with the frames
* necessary when using the converter where the sample rate could differ.
* The result is always multiplied by the channels per frame to get the
* samples count. */
cSamples = RT_MAX(cFrames,
(cFrames * caVoice->deviceFormat.mBytesPerFrame * caVoice->sampleRatio) / caVoice->streamFormat.mBytesPerFrame)
* caVoice->streamFormat.mChannelsPerFrame;
if ( hw->samples != 0
&& hw->samples != (int32_t)cSamples)
LogRel(("CoreAudio: [Input] Warning! After recreation, the CoreAudio ring buffer doesn't has the same size as the device buffer (%RU32 vs. %RU32).\n", cSamples, (uint32_t)hw->samples));
/* Create the internal ring buffer. */
IORingBufferCreate(&caVoice->pBuf, cSamples << hw->info.shift);
if (RT_VALID_PTR(caVoice->pBuf))
rc = 0;
else
LogRel(("CoreAudio: [Input] Failed to create internal ring buffer\n"));
if (rc != 0)
{
if (caVoice->pBuf)
IORingBufferDestroy(caVoice->pBuf);
AudioUnitUninitialize(caVoice->audioUnit);
return -1;
}
#ifdef DEBUG
err = AudioDeviceAddPropertyListener(caVoice->audioDeviceId,
0,
true,
kAudioDeviceProcessorOverload,
caRecordingAudioDevicePropertyChanged,
caVoice);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Input] Failed to add the processor overload listener (%RI32)\n", err));
#endif /* DEBUG */
err = AudioDeviceAddPropertyListener(caVoice->audioDeviceId,
0,
true,
kAudioDevicePropertyNominalSampleRate,
caRecordingAudioDevicePropertyChanged,
caVoice);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Input] Failed to add the sample rate changed listener (%RI32)\n", err));
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_INIT);
Log(("CoreAudio: [Input] Frame count: %RU32\n", cFrames));
return 0;
}
static void caReinitInput(HWVoiceIn *hw)
{
caVoiceIn *caVoice = (caVoiceIn *) hw;
coreaudio_fini_in(&caVoice->hw);
caInitInput(&caVoice->hw);
coreaudio_ctl_in(&caVoice->hw, VOICE_ENABLE);
}
static int coreaudio_run_in(HWVoiceIn *hw)
{
uint32_t csAvail = 0;
uint32_t cbToRead = 0;
uint32_t csToRead = 0;
uint32_t csReads = 0;
char *pcSrc;
st_sample_t *psDst;
caVoiceIn *caVoice = (caVoiceIn *) hw;
/* Check if the audio device should be reinitialized. If so do it. */
if (ASMAtomicReadU32(&caVoice->status) == CA_STATUS_REINIT)
caReinitInput(&caVoice->hw);
if (ASMAtomicReadU32(&caVoice->status) != CA_STATUS_INIT)
return 0;
/* How much space is used in the ring buffer? */
csAvail = IORingBufferUsed(caVoice->pBuf) >> hw->info.shift; /* bytes -> samples */
/* How much space is available in the mix buffer. Use the smaller size of
* the too. */
csAvail = RT_MIN(csAvail, (uint32_t)(hw->samples - audio_pcm_hw_get_live_in (hw)));
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Start reading buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail << caVoice->hw.info.shift));
/* Iterate as long as data is available */
while (csReads < csAvail)
{
/* How much is left? Split request at the end of our samples buffer. */
csToRead = RT_MIN(csAvail - csReads, (uint32_t)(hw->samples - hw->wpos));
cbToRead = csToRead << hw->info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Try reading %RU32 samples (%RU32 bytes)\n", csToRead, cbToRead));
/* Try to acquire the necessary block from the ring buffer. */
IORingBufferAquireReadBlock(caVoice->pBuf, cbToRead, &pcSrc, &cbToRead);
/* How much to we get? */
csToRead = cbToRead >> hw->info.shift;
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] There are %RU32 samples (%RU32 bytes) available\n", csToRead, cbToRead));
/* Break if nothing is used anymore. */
if (cbToRead == 0)
break;
/* Copy the data from our ring buffer to the mix buffer. */
psDst = hw->conv_buf + hw->wpos;
hw->conv(psDst, pcSrc, csToRead, &nominal_volume);
/* Release the read buffer, so it could be used for new data. */
IORingBufferReleaseReadBlock(caVoice->pBuf, cbToRead);
hw->wpos = (hw->wpos + csToRead) % hw->samples;
/* How much have we reads so far. */
csReads += csToRead;
}
CA_EXT_DEBUG_LOG(("CoreAudio: [Input] Finished reading buffer with %RU32 samples (%RU32 bytes)\n", csReads, csReads << caVoice->hw.info.shift));
return csReads;
}
static int coreaudio_read(SWVoiceIn *sw, void *buf, int size)
{
return audio_pcm_sw_read (sw, buf, size);
}
static int coreaudio_ctl_in(HWVoiceIn *hw, int cmd, ...)
{
OSStatus err = noErr;
uint32_t status;
caVoiceIn *caVoice = (caVoiceIn *) hw;
status = ASMAtomicReadU32(&caVoice->status);
if (!( status == CA_STATUS_INIT
|| status == CA_STATUS_REINIT))
return 0;
switch (cmd)
{
case VOICE_ENABLE:
{
/* Only start the device if it is actually stopped */
if (!caIsRunning(caVoice->audioDeviceId))
{
IORingBufferReset(caVoice->pBuf);
err = AudioOutputUnitStart(caVoice->audioUnit);
}
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to start recording (%RI32)\n", err));
return -1;
}
break;
}
case VOICE_DISABLE:
{
/* Only stop the device if it is actually running */
if (caIsRunning(caVoice->audioDeviceId))
{
err = AudioOutputUnitStop(caVoice->audioUnit);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to stop recording (%RI32)\n", err));
return -1;
}
err = AudioUnitReset(caVoice->audioUnit,
kAudioUnitScope_Input,
0);
if (RT_UNLIKELY(err != noErr))
{
LogRel(("CoreAudio: [Input] Failed to reset AudioUnit (%RI32)\n", err));
return -1;
}
}
break;
}
}
return 0;
}
static void coreaudio_fini_in(HWVoiceIn *hw)
{
int rc = 0;
OSStatus err = noErr;
uint32_t status;
caVoiceIn *caVoice = (caVoiceIn *) hw;
status = ASMAtomicReadU32(&caVoice->status);
if (!( status == CA_STATUS_INIT
|| status == CA_STATUS_REINIT))
return;
rc = coreaudio_ctl_in(hw, VOICE_DISABLE);
if (RT_LIKELY(rc == 0))
{
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_IN_UNINIT);
#ifdef DEBUG
err = AudioDeviceRemovePropertyListener(caVoice->audioDeviceId,
0,
true,
kAudioDeviceProcessorOverload,
caRecordingAudioDevicePropertyChanged);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Input] Failed to remove the processor overload listener (%RI32)\n", err));
#endif /* DEBUG */
err = AudioDeviceRemovePropertyListener(caVoice->audioDeviceId,
0,
true,
kAudioDevicePropertyNominalSampleRate,
caRecordingAudioDevicePropertyChanged);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Input] Failed to remove the sample rate changed listener (%RI32)\n", err));
if (caVoice->converter)
{
AudioConverterDispose(caVoice->converter);
caVoice->converter = NULL;
}
err = AudioUnitUninitialize(caVoice->audioUnit);
if (RT_LIKELY(err == noErr))
{
err = CloseComponent(caVoice->audioUnit);
if (RT_LIKELY(err == noErr))
{
IORingBufferDestroy(caVoice->pBuf);
caVoice->audioUnit = NULL;
caVoice->audioDeviceId = kAudioDeviceUnknown;
caVoice->pBuf = NULL;
caVoice->sampleRatio = 1;
caVoice->rpos = 0;
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_UNINIT);
}
else
LogRel(("CoreAudio: [Input] Failed to close the AudioUnit (%RI32)\n", err));
}
else
LogRel(("CoreAudio: [Input] Failed to uninitialize the AudioUnit (%RI32)\n", err));
}
else
LogRel(("CoreAudio: [Input] Failed to stop recording (%RI32)\n", err));
}
static int coreaudio_init_in(HWVoiceIn *hw, audsettings_t *as)
{
OSStatus err = noErr;
int rc = -1;
bool fDeviceByUser = false;
caVoiceIn *caVoice = (caVoiceIn *) hw;
ASMAtomicXchgU32(&caVoice->status, CA_STATUS_UNINIT);
caVoice->audioUnit = NULL;
caVoice->audioDeviceId = kAudioDeviceUnknown;
caVoice->converter = NULL;
caVoice->sampleRatio = 1;
caVoice->rpos = 0;
hw->samples = 0;
/* Initialize the hardware info section with the audio settings */
audio_pcm_init_info(&hw->info, as);
/* Try to find the audio device set by the user */
if (conf.pszInputDeviceUID)
{
caVoice->audioDeviceId = caDeviceUIDtoID(conf.pszInputDeviceUID);
/* Not fatal */
if (caVoice->audioDeviceId == kAudioDeviceUnknown)
LogRel(("CoreAudio: [Input] Unable to find input device %s. Falling back to the default audio device. \n", conf.pszInputDeviceUID));
else
fDeviceByUser = true;
}
rc = caInitInput(hw);
if (RT_UNLIKELY(rc != 0))
return rc;
/* The samples have to correspond to the internal ring buffer size. */
hw->samples = (IORingBufferSize(caVoice->pBuf) >> hw->info.shift) / caVoice->streamFormat.mChannelsPerFrame;
/* When the devices isn't forced by the user, we want default device change
* notifications. */
if (!fDeviceByUser)
{
err = AudioHardwareAddPropertyListener(kAudioHardwarePropertyDefaultInputDevice,
caRecordingDefaultDeviceChanged,
caVoice);
/* Not Fatal */
if (RT_UNLIKELY(err != noErr))
LogRel(("CoreAudio: [Input] Failed to add the default device changed listener (%RI32)\n", err));
}
Log(("CoreAudio: [Input] HW samples: %d\n", hw->samples));
return 0;
}
/*******************************************************************************
*
* CoreAudio global section
*
******************************************************************************/
static void *coreaudio_audio_init(void)
{
return &conf;
}
static void coreaudio_audio_fini(void *opaque)
{
NOREF(opaque);
}
static struct audio_option coreaudio_options[] =
{
{"OutputDeviceUID", AUD_OPT_STR, &conf.pszOutputDeviceUID,
"UID of the output device to use", NULL, 0},
{"InputDeviceUID", AUD_OPT_STR, &conf.pszInputDeviceUID,
"UID of the input device to use", NULL, 0},
{NULL, 0, NULL, NULL, NULL, 0}
};
static struct audio_pcm_ops coreaudio_pcm_ops =
{
coreaudio_init_out,
coreaudio_fini_out,
coreaudio_run_out,
coreaudio_write,
coreaudio_ctl_out,
coreaudio_init_in,
coreaudio_fini_in,
coreaudio_run_in,
coreaudio_read,
coreaudio_ctl_in
};
struct audio_driver coreaudio_audio_driver =
{
INIT_FIELD(name =) "coreaudio",
INIT_FIELD(descr =)
"CoreAudio http://developer.apple.com/audio/coreaudio.html",
INIT_FIELD(options =) coreaudio_options,
INIT_FIELD(init =) coreaudio_audio_init,
INIT_FIELD(fini =) coreaudio_audio_fini,
INIT_FIELD(pcm_ops =) &coreaudio_pcm_ops,
INIT_FIELD(can_be_default =) 1,
INIT_FIELD(max_voices_out =) 1,
INIT_FIELD(max_voices_in =) 1,
INIT_FIELD(voice_size_out =) sizeof(caVoiceOut),
INIT_FIELD(voice_size_in =) sizeof(caVoiceIn)
};
|