1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
|
/**
* OpenAL cross platform audio library
* Copyright (C) 2011 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include "wasapi.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <wtypes.h>
#include <mmdeviceapi.h>
#include <audiosessiontypes.h>
#include <audioclient.h>
#include <spatialaudioclient.h>
#include <cguid.h>
#include <devpropdef.h>
#include <mmreg.h>
#include <propsys.h>
#include <propkey.h>
#include <devpkey.h>
#ifndef _WAVEFORMATEXTENSIBLE_
#include <ks.h>
#include <ksmedia.h>
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstring>
#include <deque>
#include <functional>
#include <future>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "albit.h"
#include "alc/alconfig.h"
#include "alnumeric.h"
#include "alspan.h"
#include "althrd_setname.h"
#include "comptr.h"
#include "core/converter.h"
#include "core/device.h"
#include "core/helpers.h"
#include "core/logging.h"
#include "ringbuffer.h"
#include "strutils.h"
#if defined(ALSOFT_UWP)
#include <winrt/Windows.Media.Core.h> // !!This is important!!
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Devices.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Devices.Enumeration.h>
#include <winrt/Windows.Media.Devices.h>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Media::Devices;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Media::Devices;
#endif
/* Some headers seem to define these as macros for __uuidof, which is annoying
* since some headers don't declare them at all. Hopefully the ifdef is enough
* to tell if they need to be declared.
*/
#ifndef KSDATAFORMAT_SUBTYPE_PCM
DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
#endif
#ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
#endif
#if !defined(ALSOFT_UWP)
DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
#endif
namespace {
using std::chrono::nanoseconds;
using std::chrono::milliseconds;
using std::chrono::seconds;
using ReferenceTime = std::chrono::duration<REFERENCE_TIME,std::ratio<1,10'000'000>>;
constexpr ReferenceTime operator "" _reftime(unsigned long long int n) noexcept
{ return ReferenceTime{static_cast<REFERENCE_TIME>(n)}; }
#define MONO SPEAKER_FRONT_CENTER
#define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
#define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
#define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
#define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
#define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
#define X7DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
#define X7DOT1DOT4 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT|SPEAKER_TOP_FRONT_LEFT|SPEAKER_TOP_FRONT_RIGHT|SPEAKER_TOP_BACK_LEFT|SPEAKER_TOP_BACK_RIGHT)
constexpr inline DWORD MaskFromTopBits(DWORD b) noexcept
{
b |= b>>1;
b |= b>>2;
b |= b>>4;
b |= b>>8;
b |= b>>16;
return b;
}
constexpr DWORD MonoMask{MaskFromTopBits(MONO)};
constexpr DWORD StereoMask{MaskFromTopBits(STEREO)};
constexpr DWORD QuadMask{MaskFromTopBits(QUAD)};
constexpr DWORD X51Mask{MaskFromTopBits(X5DOT1)};
constexpr DWORD X51RearMask{MaskFromTopBits(X5DOT1REAR)};
constexpr DWORD X61Mask{MaskFromTopBits(X6DOT1)};
constexpr DWORD X71Mask{MaskFromTopBits(X7DOT1)};
constexpr DWORD X714Mask{MaskFromTopBits(X7DOT1DOT4)};
#ifndef _MSC_VER
constexpr AudioObjectType operator|(AudioObjectType lhs, AudioObjectType rhs) noexcept
{ return static_cast<AudioObjectType>(lhs | al::to_underlying(rhs)); }
#endif
constexpr AudioObjectType ChannelMask_Mono{AudioObjectType_FrontCenter};
constexpr AudioObjectType ChannelMask_Stereo{AudioObjectType_FrontLeft
| AudioObjectType_FrontRight};
constexpr AudioObjectType ChannelMask_Quad{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
| AudioObjectType_BackLeft | AudioObjectType_BackRight};
constexpr AudioObjectType ChannelMask_X51{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
| AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
| AudioObjectType_SideRight};
constexpr AudioObjectType ChannelMask_X51Rear{AudioObjectType_FrontLeft
| AudioObjectType_FrontRight | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency
| AudioObjectType_BackLeft | AudioObjectType_BackRight};
constexpr AudioObjectType ChannelMask_X61{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
| AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
| AudioObjectType_SideRight | AudioObjectType_BackCenter};
constexpr AudioObjectType ChannelMask_X71{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
| AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
| AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight};
constexpr AudioObjectType ChannelMask_X714{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
| AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
| AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight
| AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft
| AudioObjectType_TopBackRight};
constexpr char DevNameHead[] = "OpenAL Soft on ";
constexpr size_t DevNameHeadLen{std::size(DevNameHead) - 1};
template<typename... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template<typename... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
template<typename T>
constexpr auto as_unsigned(T value) noexcept
{
using UT = std::make_unsigned_t<T>;
return static_cast<UT>(value);
}
/* Scales the given reftime value, rounding the result. */
template<typename T>
constexpr uint RefTime2Samples(const ReferenceTime &val, T srate) noexcept
{
const auto retval = (val*srate + ReferenceTime{seconds{1}}/2) / seconds{1};
return static_cast<uint>(std::min<decltype(retval)>(retval, std::numeric_limits<uint>::max()));
}
class GuidPrinter {
char mMsg[64];
public:
GuidPrinter(const GUID &guid)
{
std::snprintf(mMsg, std::size(mMsg), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
DWORD{guid.Data1}, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2],
guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
}
const char *c_str() const { return mMsg; }
};
struct PropVariant {
PROPVARIANT mProp;
public:
PropVariant() { PropVariantInit(&mProp); }
~PropVariant() { clear(); }
void clear() { PropVariantClear(&mProp); }
PROPVARIANT* get() noexcept { return &mProp; }
PROPVARIANT& operator*() noexcept { return mProp; }
const PROPVARIANT& operator*() const noexcept { return mProp; }
PROPVARIANT* operator->() noexcept { return &mProp; }
const PROPVARIANT* operator->() const noexcept { return &mProp; }
};
struct DevMap {
std::string name;
std::string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
std::wstring devid;
template<typename T0, typename T1, typename T2>
DevMap(T0&& name_, T1&& guid_, T2&& devid_)
: name{std::forward<T0>(name_)}
, endpoint_guid{std::forward<T1>(guid_)}
, devid{std::forward<T2>(devid_)}
{ }
/* To prevent GCC from complaining it doesn't want to inline this. */
~DevMap();
};
DevMap::~DevMap() = default;
bool checkName(const al::span<DevMap> list, const std::string_view name)
{
auto match_name = [name](const DevMap &entry) -> bool { return entry.name == name; };
return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
}
struct DeviceList {
auto lock() noexcept(noexcept(mMutex.lock())) { return mMutex.lock(); }
auto unlock() noexcept(noexcept(mMutex.unlock())) { return mMutex.unlock(); }
private:
std::mutex mMutex;
std::vector<DevMap> mPlayback;
std::vector<DevMap> mCapture;
std::wstring mPlaybackDefaultId;
std::wstring mCaptureDefaultId;
friend struct DeviceListLock;
};
struct DeviceListLock : public std::unique_lock<DeviceList> {
using std::unique_lock<DeviceList>::unique_lock;
auto& getPlaybackList() const noexcept { return mutex()->mPlayback; }
auto& getCaptureList() const noexcept { return mutex()->mCapture; }
void setPlaybackDefaultId(std::wstring_view devid) const { mutex()->mPlaybackDefaultId = devid; }
std::wstring_view getPlaybackDefaultId() const noexcept { return mutex()->mPlaybackDefaultId; }
void setCaptureDefaultId(std::wstring_view devid) const { mutex()->mCaptureDefaultId = devid; }
std::wstring_view getCaptureDefaultId() const noexcept { return mutex()->mCaptureDefaultId; }
};
DeviceList gDeviceList;
#if defined(ALSOFT_UWP)
enum EDataFlow {
eRender = 0,
eCapture = (eRender + 1),
eAll = (eCapture + 1),
EDataFlow_enum_count = (eAll + 1)
};
#endif
#if defined(ALSOFT_UWP)
using DeviceHandle = Windows::Devices::Enumeration::DeviceInformation;
using EventRegistrationToken = winrt::event_token;
#else
using DeviceHandle = ComPtr<IMMDevice>;
#endif
using NameGUIDPair = std::pair<std::string,std::string>;
static NameGUIDPair GetDeviceNameAndGuid(const DeviceHandle &device)
{
static constexpr char UnknownName[]{"Unknown Device Name"};
static constexpr char UnknownGuid[]{"Unknown Device GUID"};
#if !defined(ALSOFT_UWP)
std::string name, guid;
ComPtr<IPropertyStore> ps;
HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
if(FAILED(hr))
{
WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
return std::make_pair(UnknownName, UnknownGuid);
}
PropVariant pvprop;
hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(DEVPKEY_Device_FriendlyName), pvprop.get());
if(FAILED(hr))
WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr);
else if(pvprop->vt == VT_LPWSTR)
name = wstr_to_utf8(pvprop->pwszVal);
else
WARN("Unexpected Device_FriendlyName PROPVARIANT type: 0x%04x\n", pvprop->vt);
pvprop.clear();
hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(PKEY_AudioEndpoint_GUID), pvprop.get());
if(FAILED(hr))
WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr);
else if(pvprop->vt == VT_LPWSTR)
guid = wstr_to_utf8(pvprop->pwszVal);
else
WARN("Unexpected AudioEndpoint_GUID PROPVARIANT type: 0x%04x\n", pvprop->vt);
#else
std::string name{wstr_to_utf8(device.Name())};
std::string guid;
// device->Id is DeviceInterfacePath: \\?\SWD#MMDEVAPI#{0.0.0.00000000}.{a21c17a0-fc1d-405e-ab5a-b513422b57d1}#{e6327cad-dcec-4949-ae8a-991e976a79d2}
auto devIfPath = device.Id();
if(auto devIdStart = wcsstr(devIfPath.data(), L"}."))
{
devIdStart += 2; // L"}."
if(auto devIdStartEnd = wcschr(devIdStart, L'#'))
{
std::wstring wDevId{devIdStart, static_cast<size_t>(devIdStartEnd - devIdStart)};
guid = wstr_to_utf8(wDevId.c_str());
std::transform(guid.begin(), guid.end(), guid.begin(),
[](char ch) { return static_cast<char>(std::toupper(ch)); });
}
}
#endif
if(name.empty()) name = UnknownName;
if(guid.empty()) guid = UnknownGuid;
return std::make_pair(std::move(name), std::move(guid));
}
#if !defined(ALSOFT_UWP)
EndpointFormFactor GetDeviceFormfactor(IMMDevice *device)
{
ComPtr<IPropertyStore> ps;
HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
if(FAILED(hr))
{
WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
return UnknownFormFactor;
}
EndpointFormFactor formfactor{UnknownFormFactor};
PropVariant pvform;
hr = ps->GetValue(PKEY_AudioEndpoint_FormFactor, pvform.get());
if(FAILED(hr))
WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr);
else if(pvform->vt == VT_UI4)
formfactor = static_cast<EndpointFormFactor>(pvform->ulVal);
else if(pvform->vt != VT_EMPTY)
WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform->vt);
return formfactor;
}
#endif
#if defined(ALSOFT_UWP)
struct DeviceHelper final : public IActivateAudioInterfaceCompletionHandler
#else
struct DeviceHelper final : private IMMNotificationClient
#endif
{
DeviceHelper()
{
#if defined(ALSOFT_UWP)
/* TODO: UWP also needs to watch for device added/removed events and
* dynamically add/remove devices from the lists.
*/
mActiveClientEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
mRenderDeviceChangedToken = MediaDevice::DefaultAudioRenderDeviceChanged([this](const IInspectable& /*sender*/, const DefaultAudioRenderDeviceChangedEventArgs& args) {
if (args.Role() == AudioDeviceRole::Default)
{
const std::string msg{ "Default playback device changed: " +
wstr_to_utf8(args.Id())};
alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback,
msg);
}
});
mCaptureDeviceChangedToken = MediaDevice::DefaultAudioCaptureDeviceChanged([this](const IInspectable& /*sender*/, const DefaultAudioCaptureDeviceChangedEventArgs& args) {
if (args.Role() == AudioDeviceRole::Default)
{
const std::string msg{ "Default capture device changed: " +
wstr_to_utf8(args.Id()) };
alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture,
msg);
}
});
#endif
}
~DeviceHelper()
{
#if defined(ALSOFT_UWP)
MediaDevice::DefaultAudioRenderDeviceChanged(mRenderDeviceChangedToken);
MediaDevice::DefaultAudioCaptureDeviceChanged(mCaptureDeviceChangedToken);
if(mActiveClientEvent != nullptr)
CloseHandle(mActiveClientEvent);
mActiveClientEvent = nullptr;
#else
if(mEnumerator)
mEnumerator->UnregisterEndpointNotificationCallback(this);
mEnumerator = nullptr;
#endif
}
/** -------------------------- IUnknown ----------------------------- */
std::atomic<ULONG> mRefCount{1};
STDMETHODIMP_(ULONG) AddRef() noexcept override { return mRefCount.fetch_add(1u) + 1u; }
STDMETHODIMP_(ULONG) Release() noexcept override { return mRefCount.fetch_sub(1u) - 1u; }
STDMETHODIMP QueryInterface(const IID& IId, void **UnknownPtrPtr) noexcept override
{
// Three rules of QueryInterface:
// https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
// 1. Objects must have identity.
// 2. The set of interfaces on an object instance must be static.
// 3. It must be possible to query successfully for any interface on an object from any other interface.
// If ppvObject(the address) is nullptr, then this method returns E_POINTER.
if(!UnknownPtrPtr)
return E_POINTER;
// https://docs.microsoft.com/en-us/windows/win32/com/implementing-reference-counting
// Whenever a client calls a method(or API function), such as QueryInterface, that returns a new interface
// pointer, the method being called is responsible for incrementing the reference count through the returned
// pointer. For example, when a client first creates an object, it receives an interface pointer to an object
// that, from the client's point of view, has a reference count of one. If the client then calls AddRef on the
// interface pointer, the reference count becomes two. The client must call Release twice on the interface
// pointer to drop all of its references to the object.
#if defined(ALSOFT_UWP)
if(IId == __uuidof(IActivateAudioInterfaceCompletionHandler))
{
*UnknownPtrPtr = static_cast<IActivateAudioInterfaceCompletionHandler*>(this);
AddRef();
return S_OK;
}
#else
if(IId == __uuidof(IMMNotificationClient))
{
*UnknownPtrPtr = static_cast<IMMNotificationClient*>(this);
AddRef();
return S_OK;
}
#endif
else if(IId == __uuidof(IAgileObject) || IId == __uuidof(IUnknown))
{
*UnknownPtrPtr = static_cast<IUnknown*>(this);
AddRef();
return S_OK;
}
// This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
*UnknownPtrPtr = nullptr;
return E_NOINTERFACE;
}
#if defined(ALSOFT_UWP)
/** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
HRESULT ActivateCompleted(IActivateAudioInterfaceAsyncOperation*) override
{
SetEvent(mActiveClientEvent);
// Need to return S_OK
return S_OK;
}
#else
/** ----------------------- IMMNotificationClient ------------ */
STDMETHODIMP OnDeviceStateChanged(LPCWSTR /*pwstrDeviceId*/, DWORD /*dwNewState*/) noexcept override { return S_OK; }
STDMETHODIMP OnDeviceAdded(LPCWSTR pwstrDeviceId) noexcept override
{
ComPtr<IMMDevice> device;
HRESULT hr{mEnumerator->GetDevice(pwstrDeviceId, al::out_ptr(device))};
if(FAILED(hr))
{
ERR("Failed to get device: 0x%08lx\n", hr);
return S_OK;
}
ComPtr<IMMEndpoint> endpoint;
hr = device->QueryInterface(__uuidof(IMMEndpoint), al::out_ptr(endpoint));
if(FAILED(hr))
{
ERR("Failed to get device endpoint: 0x%08lx\n", hr);
return S_OK;
}
EDataFlow flowdir{};
hr = endpoint->GetDataFlow(&flowdir);
if(FAILED(hr))
{
ERR("Failed to get endpoint data flow: 0x%08lx\n", hr);
return S_OK;
}
auto devlock = DeviceListLock{gDeviceList};
auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
if(AddDevice(device, pwstrDeviceId, list))
{
const auto devtype = (flowdir==eRender) ? alc::DeviceType::Playback
: alc::DeviceType::Capture;
const std::string msg{"Device added: "+list.back().name};
alc::Event(alc::EventType::DeviceAdded, devtype, msg);
}
return S_OK;
}
STDMETHODIMP OnDeviceRemoved(LPCWSTR pwstrDeviceId) noexcept override
{
auto devlock = DeviceListLock{gDeviceList};
for(auto flowdir : std::array{eRender, eCapture})
{
auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
auto devtype = (flowdir==eRender)?alc::DeviceType::Playback : alc::DeviceType::Capture;
/* Find the ID in the list to remove. */
auto iter = std::find_if(list.begin(), list.end(),
[pwstrDeviceId](const DevMap &entry) noexcept
{ return pwstrDeviceId == entry.devid; });
if(iter == list.end()) continue;
TRACE("Removing device \"%s\", \"%s\", \"%ls\"\n", iter->name.c_str(),
iter->endpoint_guid.c_str(), iter->devid.c_str());
std::string msg{"Device removed: "+std::move(iter->name)};
list.erase(iter);
alc::Event(alc::EventType::DeviceRemoved, devtype, msg);
}
return S_OK;
}
STDMETHODIMP OnPropertyValueChanged(LPCWSTR /*pwstrDeviceId*/, const PROPERTYKEY /*key*/) noexcept override { return S_OK; }
STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) noexcept override
{
if(role != eMultimedia)
return S_OK;
const std::wstring_view devid{pwstrDefaultDeviceId ? pwstrDefaultDeviceId
: std::wstring_view{}};
if(flow == eRender)
{
DeviceListLock{gDeviceList}.setPlaybackDefaultId(devid);
const std::string msg{"Default playback device changed: " + wstr_to_utf8(devid)};
alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
}
else if(flow == eCapture)
{
DeviceListLock{gDeviceList}.setCaptureDefaultId(devid);
const std::string msg{"Default capture device changed: " + wstr_to_utf8(devid)};
alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
}
return S_OK;
}
#endif
/** -------------------------- DeviceHelper ----------------------------- */
HRESULT init()
{
#if !defined(ALSOFT_UWP)
HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
__uuidof(IMMDeviceEnumerator), al::out_ptr(mEnumerator))};
if(SUCCEEDED(hr))
mEnumerator->RegisterEndpointNotificationCallback(this);
else
WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
return hr;
#else
return S_OK;
#endif
}
HRESULT openDevice(std::wstring_view devid, EDataFlow flow, DeviceHandle& device)
{
#if !defined(ALSOFT_UWP)
HRESULT hr{E_FAIL};
if(mEnumerator)
{
if(devid.empty())
hr = mEnumerator->GetDefaultAudioEndpoint(flow, eMultimedia, al::out_ptr(device));
else
hr = mEnumerator->GetDevice(devid.data(), al::out_ptr(device));
}
return hr;
#else
const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
auto devIfPath =
devid.empty() ? (flow == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole) : MediaDevice::GetDefaultAudioCaptureId(deviceRole))
: winrt::hstring(devid.data());
if (devIfPath.empty())
return E_POINTER;
auto&& deviceInfo = DeviceInformation::CreateFromIdAsync(devIfPath, nullptr, DeviceInformationKind::DeviceInterface).get();
if (!deviceInfo)
return E_NOINTERFACE;
device = deviceInfo;
return S_OK;
#endif
}
#if !defined(ALSOFT_UWP)
static HRESULT activateAudioClient(_In_ DeviceHandle &device, REFIID iid, void **ppv)
{ return device->Activate(iid, CLSCTX_INPROC_SERVER, nullptr, ppv); }
#else
HRESULT activateAudioClient(_In_ DeviceHandle &device, _In_ REFIID iid, void **ppv)
{
ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
HRESULT hr{ActivateAudioInterfaceAsync(device.Id().data(), iid, nullptr, this,
al::out_ptr(asyncOp))};
if(FAILED(hr))
return hr;
/* I don't like waiting for INFINITE time, but the activate operation
* can take an indefinite amount of time since it can require user
* input.
*/
DWORD res{WaitForSingleObjectEx(mActiveClientEvent, INFINITE, FALSE)};
if(res != WAIT_OBJECT_0)
{
ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
return E_FAIL;
}
HRESULT hrActivateRes{E_FAIL};
ComPtr<IUnknown> punkAudioIface;
hr = asyncOp->GetActivateResult(&hrActivateRes, al::out_ptr(punkAudioIface));
if(SUCCEEDED(hr)) hr = hrActivateRes;
if(FAILED(hr)) return hr;
return punkAudioIface->QueryInterface(iid, ppv);
}
#endif
std::wstring probeDevices(EDataFlow flowdir, std::vector<DevMap> &list)
{
std::wstring defaultId;
std::vector<DevMap>{}.swap(list);
#if !defined(ALSOFT_UWP)
ComPtr<IMMDeviceCollection> coll;
HRESULT hr{mEnumerator->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE,
al::out_ptr(coll))};
if(FAILED(hr))
{
ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
return defaultId;
}
UINT count{0};
hr = coll->GetCount(&count);
if(SUCCEEDED(hr) && count > 0)
list.reserve(count);
ComPtr<IMMDevice> device;
hr = mEnumerator->GetDefaultAudioEndpoint(flowdir, eMultimedia, al::out_ptr(device));
if(SUCCEEDED(hr))
{
if(WCHAR *devid{GetDeviceId(device.get())})
{
defaultId = devid;
CoTaskMemFree(devid);
}
device = nullptr;
}
for(UINT i{0};i < count;++i)
{
hr = coll->Item(i, al::out_ptr(device));
if(FAILED(hr))
continue;
if(WCHAR *devid{GetDeviceId(device.get())})
{
std::ignore = AddDevice(device, devid, list);
CoTaskMemFree(devid);
}
device = nullptr;
}
#else
const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
auto DefaultAudioId = flowdir == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole)
: MediaDevice::GetDefaultAudioCaptureId(deviceRole);
if(!DefaultAudioId.empty())
{
auto deviceInfo = DeviceInformation::CreateFromIdAsync(DefaultAudioId, nullptr,
DeviceInformationKind::DeviceInterface).get();
if(deviceInfo)
defaultId = deviceInfo.Id().data();
}
// Get the string identifier of the audio renderer
auto AudioSelector = flowdir == eRender ? MediaDevice::GetAudioRenderSelector() : MediaDevice::GetAudioCaptureSelector();
// Setup the asynchronous callback
auto&& DeviceInfoCollection = DeviceInformation::FindAllAsync(AudioSelector, /*PropertyList*/nullptr, DeviceInformationKind::DeviceInterface).get();
if(DeviceInfoCollection)
{
try {
auto deviceCount = DeviceInfoCollection.Size();
for(unsigned int i{0};i < deviceCount;++i)
{
auto deviceInfo = DeviceInfoCollection.GetAt(i);
if(deviceInfo)
std::ignore = AddDevice(deviceInfo, deviceInfo.Id().data(), list);
}
}
catch (const winrt::hresult_error& /*ex*/) {
}
}
#endif
return defaultId;
}
private:
static bool AddDevice(const DeviceHandle &device, const WCHAR *devid, std::vector<DevMap> &list)
{
for(auto &entry : list)
{
if(entry.devid == devid)
return false;
}
auto name_guid = GetDeviceNameAndGuid(device);
int count{1};
std::string newname{name_guid.first};
while(checkName(list, newname))
{
newname = name_guid.first;
newname += " #";
newname += std::to_string(++count);
}
list.emplace_back(std::move(newname), std::move(name_guid.second), devid);
const DevMap &newentry = list.back();
TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry.name.c_str(),
newentry.endpoint_guid.c_str(), newentry.devid.c_str());
return true;
}
#if !defined(ALSOFT_UWP)
static WCHAR *GetDeviceId(IMMDevice *device)
{
WCHAR *devid;
const HRESULT hr{device->GetId(&devid)};
if(FAILED(hr))
{
ERR("Failed to get device id: %lx\n", hr);
return nullptr;
}
return devid;
}
ComPtr<IMMDeviceEnumerator> mEnumerator{nullptr};
#else
HANDLE mActiveClientEvent{nullptr};
EventRegistrationToken mRenderDeviceChangedToken;
EventRegistrationToken mCaptureDeviceChangedToken;
#endif
};
bool MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
{
*out = WAVEFORMATEXTENSIBLE{};
if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
{
*out = *CONTAINING_RECORD(in, const WAVEFORMATEXTENSIBLE, Format);
out->Format.cbSize = sizeof(*out) - sizeof(out->Format);
}
else if(in->wFormatTag == WAVE_FORMAT_PCM)
{
out->Format = *in;
out->Format.cbSize = 0;
out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
if(out->Format.nChannels == 1)
out->dwChannelMask = MONO;
else if(out->Format.nChannels == 2)
out->dwChannelMask = STEREO;
else
ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels);
out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
}
else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
{
out->Format = *in;
out->Format.cbSize = 0;
out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
if(out->Format.nChannels == 1)
out->dwChannelMask = MONO;
else if(out->Format.nChannels == 2)
out->dwChannelMask = STEREO;
else
ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
}
else
{
ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
return false;
}
return true;
}
void TraceFormat(const char *msg, const WAVEFORMATEX *format)
{
constexpr size_t fmtex_extra_size{sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)};
if(format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= fmtex_extra_size)
{
const WAVEFORMATEXTENSIBLE *fmtex{
CONTAINING_RECORD(format, const WAVEFORMATEXTENSIBLE, Format)};
TRACE("%s:\n"
" FormatTag = 0x%04x\n"
" Channels = %d\n"
" SamplesPerSec = %lu\n"
" AvgBytesPerSec = %lu\n"
" BlockAlign = %d\n"
" BitsPerSample = %d\n"
" Size = %d\n"
" Samples = %d\n"
" ChannelMask = 0x%lx\n"
" SubFormat = %s\n",
msg, fmtex->Format.wFormatTag, fmtex->Format.nChannels, fmtex->Format.nSamplesPerSec,
fmtex->Format.nAvgBytesPerSec, fmtex->Format.nBlockAlign, fmtex->Format.wBitsPerSample,
fmtex->Format.cbSize, fmtex->Samples.wReserved, fmtex->dwChannelMask,
GuidPrinter{fmtex->SubFormat}.c_str());
}
else
TRACE("%s:\n"
" FormatTag = 0x%04x\n"
" Channels = %d\n"
" SamplesPerSec = %lu\n"
" AvgBytesPerSec = %lu\n"
" BlockAlign = %d\n"
" BitsPerSample = %d\n"
" Size = %d\n",
msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec,
format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize);
}
enum class MsgType {
OpenDevice,
ResetDevice,
StartDevice,
StopDevice,
CloseDevice,
QuitThread
};
constexpr const char *GetMessageTypeName(MsgType type) noexcept
{
switch(type)
{
case MsgType::OpenDevice: return "Open Device";
case MsgType::ResetDevice: return "Reset Device";
case MsgType::StartDevice: return "Start Device";
case MsgType::StopDevice: return "Stop Device";
case MsgType::CloseDevice: return "Close Device";
case MsgType::QuitThread: break;
}
return "";
}
/* Proxy interface used by the message handler. */
struct WasapiProxy {
virtual ~WasapiProxy() = default;
virtual HRESULT openProxy(std::string_view name) = 0;
virtual void closeProxy() = 0;
virtual HRESULT resetProxy() = 0;
virtual HRESULT startProxy() = 0;
virtual void stopProxy() = 0;
struct Msg {
MsgType mType;
WasapiProxy *mProxy;
std::string_view mParam;
std::promise<HRESULT> mPromise;
explicit operator bool() const noexcept { return mType != MsgType::QuitThread; }
};
static inline std::deque<Msg> mMsgQueue;
static inline std::mutex mMsgQueueLock;
static inline std::condition_variable mMsgQueueCond;
static inline std::optional<DeviceHelper> sDeviceHelper;
std::future<HRESULT> pushMessage(MsgType type, std::string_view param={})
{
std::promise<HRESULT> promise;
std::future<HRESULT> future{promise.get_future()};
{
std::lock_guard<std::mutex> _{mMsgQueueLock};
mMsgQueue.emplace_back(Msg{type, this, param, std::move(promise)});
}
mMsgQueueCond.notify_one();
return future;
}
static std::future<HRESULT> pushMessageStatic(MsgType type)
{
std::promise<HRESULT> promise;
std::future<HRESULT> future{promise.get_future()};
{
std::lock_guard<std::mutex> _{mMsgQueueLock};
mMsgQueue.emplace_back(Msg{type, nullptr, {}, std::move(promise)});
}
mMsgQueueCond.notify_one();
return future;
}
static Msg popMessage()
{
std::unique_lock<std::mutex> lock{mMsgQueueLock};
mMsgQueueCond.wait(lock, []{return !mMsgQueue.empty();});
Msg msg{std::move(mMsgQueue.front())};
mMsgQueue.pop_front();
return msg;
}
static int messageHandler(std::promise<HRESULT> *promise);
};
int WasapiProxy::messageHandler(std::promise<HRESULT> *promise)
{
TRACE("Starting message thread\n");
ComWrapper com{COINIT_MULTITHREADED};
if(!com)
{
WARN("Failed to initialize COM: 0x%08lx\n", com.status());
promise->set_value(com.status());
return 0;
}
HRESULT hr{sDeviceHelper.emplace().init()};
promise->set_value(hr);
promise = nullptr;
if(FAILED(hr))
goto skip_loop;
{
auto devlock = DeviceListLock{gDeviceList};
auto defaultId = sDeviceHelper->probeDevices(eRender, devlock.getPlaybackList());
if(!defaultId.empty()) devlock.setPlaybackDefaultId(defaultId);
defaultId = sDeviceHelper->probeDevices(eCapture, devlock.getCaptureList());
if(!defaultId.empty()) devlock.setCaptureDefaultId(defaultId);
}
TRACE("Starting message loop\n");
while(Msg msg{popMessage()})
{
TRACE("Got message \"%s\" (0x%04x, this=%p, param=\"%.*s\")\n",
GetMessageTypeName(msg.mType), static_cast<uint>(msg.mType),
static_cast<void*>(msg.mProxy), static_cast<int>(msg.mParam.length()),
msg.mParam.data());
switch(msg.mType)
{
case MsgType::OpenDevice:
hr = msg.mProxy->openProxy(msg.mParam);
msg.mPromise.set_value(hr);
continue;
case MsgType::ResetDevice:
hr = msg.mProxy->resetProxy();
msg.mPromise.set_value(hr);
continue;
case MsgType::StartDevice:
hr = msg.mProxy->startProxy();
msg.mPromise.set_value(hr);
continue;
case MsgType::StopDevice:
msg.mProxy->stopProxy();
msg.mPromise.set_value(S_OK);
continue;
case MsgType::CloseDevice:
msg.mProxy->closeProxy();
msg.mPromise.set_value(S_OK);
continue;
case MsgType::QuitThread:
break;
}
ERR("Unexpected message: %u\n", static_cast<uint>(msg.mType));
msg.mPromise.set_value(E_FAIL);
}
TRACE("Message loop finished\n");
skip_loop:
sDeviceHelper.reset();
return 0;
}
struct WasapiPlayback final : public BackendBase, WasapiProxy {
WasapiPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
~WasapiPlayback() override;
int mixerProc();
int mixerSpatialProc();
void open(std::string_view name) override;
HRESULT openProxy(std::string_view name) override;
void closeProxy() override;
bool reset() override;
HRESULT resetProxy() override;
void start() override;
HRESULT startProxy() override;
void stop() override;
void stopProxy() override;
ClockLatency getClockLatency() override;
void prepareFormat(WAVEFORMATEXTENSIBLE &OutputType);
void finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType);
HRESULT mOpenStatus{E_FAIL};
DeviceHandle mMMDev{nullptr};
struct PlainDevice {
ComPtr<IAudioClient> mClient{nullptr};
ComPtr<IAudioRenderClient> mRender{nullptr};
};
struct SpatialDevice {
ComPtr<ISpatialAudioClient> mClient{nullptr};
ComPtr<ISpatialAudioObjectRenderStream> mRender{nullptr};
AudioObjectType mStaticMask{};
};
std::variant<std::monostate,PlainDevice,SpatialDevice> mAudio;
HANDLE mNotifyEvent{nullptr};
UINT32 mOrigBufferSize{}, mOrigUpdateSize{};
std::unique_ptr<char[]> mResampleBuffer{};
uint mBufferFilled{0};
SampleConverterPtr mResampler;
WAVEFORMATEXTENSIBLE mFormat{};
std::atomic<UINT32> mPadding{0u};
std::mutex mMutex;
std::atomic<bool> mKillNow{true};
std::thread mThread;
DEF_NEWDEL(WasapiPlayback)
};
WasapiPlayback::~WasapiPlayback()
{
if(SUCCEEDED(mOpenStatus))
pushMessage(MsgType::CloseDevice).wait();
mOpenStatus = E_FAIL;
if(mNotifyEvent != nullptr)
CloseHandle(mNotifyEvent);
mNotifyEvent = nullptr;
}
FORCE_ALIGN int WasapiPlayback::mixerProc()
{
ComWrapper com{COINIT_MULTITHREADED};
if(!com)
{
ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
return 1;
}
auto &audio = std::get<PlainDevice>(mAudio);
SetRTPriority();
althrd_setname(MIXER_THREAD_NAME);
const uint frame_size{mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8u};
const uint update_size{mOrigUpdateSize};
const UINT32 buffer_len{mOrigBufferSize};
const void *resbufferptr{};
mBufferFilled = 0;
while(!mKillNow.load(std::memory_order_relaxed))
{
UINT32 written;
HRESULT hr{audio.mClient->GetCurrentPadding(&written)};
if(FAILED(hr))
{
ERR("Failed to get padding: 0x%08lx\n", hr);
mDevice->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr);
break;
}
mPadding.store(written, std::memory_order_relaxed);
uint len{buffer_len - written};
if(len < update_size)
{
DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
if(res != WAIT_OBJECT_0)
ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
continue;
}
BYTE *buffer;
hr = audio.mRender->GetBuffer(len, &buffer);
if(SUCCEEDED(hr))
{
if(mResampler)
{
std::lock_guard<std::mutex> _{mMutex};
for(UINT32 done{0};done < len;)
{
if(mBufferFilled == 0)
{
mDevice->renderSamples(mResampleBuffer.get(), mDevice->UpdateSize,
mFormat.Format.nChannels);
resbufferptr = mResampleBuffer.get();
mBufferFilled = mDevice->UpdateSize;
}
uint got{mResampler->convert(&resbufferptr, &mBufferFilled, buffer, len-done)};
buffer += got*frame_size;
done += got;
mPadding.store(written + done, std::memory_order_relaxed);
}
}
else
{
std::lock_guard<std::mutex> _{mMutex};
mDevice->renderSamples(buffer, len, mFormat.Format.nChannels);
mPadding.store(written + len, std::memory_order_relaxed);
}
hr = audio.mRender->ReleaseBuffer(len, 0);
}
if(FAILED(hr))
{
ERR("Failed to buffer data: 0x%08lx\n", hr);
mDevice->handleDisconnect("Failed to send playback samples: 0x%08lx", hr);
break;
}
}
mPadding.store(0u, std::memory_order_release);
return 0;
}
FORCE_ALIGN int WasapiPlayback::mixerSpatialProc()
{
ComWrapper com{COINIT_MULTITHREADED};
if(!com)
{
ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
return 1;
}
auto &audio = std::get<SpatialDevice>(mAudio);
SetRTPriority();
althrd_setname(MIXER_THREAD_NAME);
std::vector<ComPtr<ISpatialAudioObject>> channels;
std::vector<float*> buffers;
std::vector<float*> resbuffers;
std::vector<const void*> tmpbuffers;
/* TODO: Set mPadding appropriately. There doesn't seem to be a way to
* update it dynamically based on the stream, so a fixed size may be the
* best we can do.
*/
mPadding.store(mOrigBufferSize-mOrigUpdateSize, std::memory_order_release);
mBufferFilled = 0;
while(!mKillNow.load(std::memory_order_relaxed))
{
if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 1000, FALSE)}; res != WAIT_OBJECT_0)
{
ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
HRESULT hr{audio.mRender->Reset()};
if(FAILED(hr))
{
ERR("ISpatialAudioObjectRenderStream::Reset failed: 0x%08lx\n", hr);
mDevice->handleDisconnect("Device lost: 0x%08lx", hr);
break;
}
}
UINT32 dynamicCount{}, framesToDo{};
HRESULT hr{audio.mRender->BeginUpdatingAudioObjects(&dynamicCount, &framesToDo)};
if(SUCCEEDED(hr))
{
if(channels.empty()) UNLIKELY
{
auto flags = as_unsigned(audio.mStaticMask);
channels.reserve(as_unsigned(al::popcount(flags)));
while(flags)
{
auto id = decltype(flags){1} << al::countr_zero(flags);
flags &= ~id;
channels.emplace_back();
audio.mRender->ActivateSpatialAudioObject(static_cast<AudioObjectType>(id),
al::out_ptr(channels.back()));
}
buffers.resize(channels.size());
if(mResampler)
{
tmpbuffers.resize(buffers.size());
resbuffers.resize(buffers.size());
for(size_t i{0};i < tmpbuffers.size();++i)
resbuffers[i] = reinterpret_cast<float*>(mResampleBuffer.get()) +
mDevice->UpdateSize*i;
}
}
/* We have to call to get each channel's buffer individually every
* update, unfortunately.
*/
std::transform(channels.cbegin(), channels.cend(), buffers.begin(),
[](const ComPtr<ISpatialAudioObject> &obj) -> float*
{
BYTE *buffer{};
UINT32 size{};
obj->GetBuffer(&buffer, &size);
return reinterpret_cast<float*>(buffer);
});
if(!mResampler)
mDevice->renderSamples(buffers, framesToDo);
else
{
std::lock_guard<std::mutex> _{mMutex};
for(UINT32 pos{0};pos < framesToDo;)
{
if(mBufferFilled == 0)
{
mDevice->renderSamples(resbuffers, mDevice->UpdateSize);
std::copy(resbuffers.cbegin(), resbuffers.cend(), tmpbuffers.begin());
mBufferFilled = mDevice->UpdateSize;
}
const uint got{mResampler->convertPlanar(tmpbuffers.data(), &mBufferFilled,
reinterpret_cast<void*const*>(buffers.data()), framesToDo-pos)};
for(auto &buf : buffers)
buf += got;
pos += got;
}
}
hr = audio.mRender->EndUpdatingAudioObjects();
}
if(FAILED(hr))
ERR("Failed to update playback objects: 0x%08lx\n", hr);
}
mPadding.store(0u, std::memory_order_release);
return 0;
}
void WasapiPlayback::open(std::string_view name)
{
if(SUCCEEDED(mOpenStatus))
throw al::backend_exception{al::backend_error::DeviceError,
"Unexpected duplicate open call"};
mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if(mNotifyEvent == nullptr)
{
ERR("Failed to create notify events: %lu\n", GetLastError());
throw al::backend_exception{al::backend_error::DeviceError,
"Failed to create notify events"};
}
if(name.length() >= DevNameHeadLen
&& std::strncmp(name.data(), DevNameHead, DevNameHeadLen) == 0)
{
name = name.substr(DevNameHeadLen);
}
mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
if(FAILED(mOpenStatus))
throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
mOpenStatus};
}
HRESULT WasapiPlayback::openProxy(std::string_view name)
{
std::string devname;
std::wstring devid;
if(!name.empty())
{
auto devlock = DeviceListLock{gDeviceList};
auto list = al::span{devlock.getPlaybackList()};
auto iter = std::find_if(list.cbegin(), list.cend(),
[name](const DevMap &entry) -> bool
{ return entry.name == name || entry.endpoint_guid == name; });
if(iter == list.cend())
{
const std::wstring wname{utf8_to_wstr(name)};
iter = std::find_if(list.cbegin(), list.cend(),
[&wname](const DevMap &entry) -> bool
{ return entry.devid == wname; });
}
if(iter == list.cend())
{
WARN("Failed to find device name matching \"%.*s\"\n", static_cast<int>(name.length()),
name.data());
return E_FAIL;
}
devname = iter->name;
devid = iter->devid;
}
HRESULT hr{sDeviceHelper->openDevice(devid, eRender, mMMDev)};
if(FAILED(hr))
{
WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
return hr;
}
if(!devname.empty())
mDevice->DeviceName = DevNameHead + std::move(devname);
else
mDevice->DeviceName = DevNameHead + GetDeviceNameAndGuid(mMMDev).first;
return S_OK;
}
void WasapiPlayback::closeProxy()
{
mAudio.emplace<std::monostate>();
mMMDev = nullptr;
}
void WasapiPlayback::prepareFormat(WAVEFORMATEXTENSIBLE &OutputType)
{
bool isRear51{false};
if(!mDevice->Flags.test(FrequencyRequest))
mDevice->Frequency = OutputType.Format.nSamplesPerSec;
if(!mDevice->Flags.test(ChannelsRequest))
{
/* If not requesting a channel configuration, auto-select given what
* fits the mask's lsb (to ensure no gaps in the output channels). If
* there's no mask, we can only assume mono or stereo.
*/
const uint32_t chancount{OutputType.Format.nChannels};
const DWORD chanmask{OutputType.dwChannelMask};
if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
mDevice->FmtChans = DevFmtX714;
else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
mDevice->FmtChans = DevFmtX71;
else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
mDevice->FmtChans = DevFmtX61;
else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
mDevice->FmtChans = DevFmtX51;
else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
{
mDevice->FmtChans = DevFmtX51;
isRear51 = true;
}
else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
mDevice->FmtChans = DevFmtQuad;
else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
mDevice->FmtChans = DevFmtStereo;
else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
mDevice->FmtChans = DevFmtMono;
else
ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
}
else
{
const uint32_t chancount{OutputType.Format.nChannels};
const DWORD chanmask{OutputType.dwChannelMask};
isRear51 = (chancount == 6 && (chanmask&X51RearMask) == X5DOT1REAR);
}
OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
switch(mDevice->FmtChans)
{
case DevFmtMono:
OutputType.Format.nChannels = 1;
OutputType.dwChannelMask = MONO;
break;
case DevFmtAmbi3D:
mDevice->FmtChans = DevFmtStereo;
/*fall-through*/
case DevFmtStereo:
OutputType.Format.nChannels = 2;
OutputType.dwChannelMask = STEREO;
break;
case DevFmtQuad:
OutputType.Format.nChannels = 4;
OutputType.dwChannelMask = QUAD;
break;
case DevFmtX51:
OutputType.Format.nChannels = 6;
OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
break;
case DevFmtX61:
OutputType.Format.nChannels = 7;
OutputType.dwChannelMask = X6DOT1;
break;
case DevFmtX71:
case DevFmtX3D71:
OutputType.Format.nChannels = 8;
OutputType.dwChannelMask = X7DOT1;
break;
case DevFmtX714:
OutputType.Format.nChannels = 12;
OutputType.dwChannelMask = X7DOT1DOT4;
break;
}
switch(mDevice->FmtType)
{
case DevFmtByte:
mDevice->FmtType = DevFmtUByte;
/* fall-through */
case DevFmtUByte:
OutputType.Format.wBitsPerSample = 8;
OutputType.Samples.wValidBitsPerSample = 8;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtUShort:
mDevice->FmtType = DevFmtShort;
/* fall-through */
case DevFmtShort:
OutputType.Format.wBitsPerSample = 16;
OutputType.Samples.wValidBitsPerSample = 16;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtUInt:
mDevice->FmtType = DevFmtInt;
/* fall-through */
case DevFmtInt:
OutputType.Format.wBitsPerSample = 32;
OutputType.Samples.wValidBitsPerSample = 32;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtFloat:
OutputType.Format.wBitsPerSample = 32;
OutputType.Samples.wValidBitsPerSample = 32;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
break;
}
OutputType.Format.nSamplesPerSec = mDevice->Frequency;
OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
OutputType.Format.wBitsPerSample / 8);
OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
OutputType.Format.nBlockAlign;
}
void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType)
{
if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "wasapi", "allow-resampler", true))
mDevice->Frequency = OutputType.Format.nSamplesPerSec;
else
mDevice->Frequency = minu(mDevice->Frequency, OutputType.Format.nSamplesPerSec);
const uint32_t chancount{OutputType.Format.nChannels};
const DWORD chanmask{OutputType.dwChannelMask};
/* Don't update the channel format if the requested format fits what's
* supported.
*/
bool chansok{false};
if(mDevice->Flags.test(ChannelsRequest))
{
/* When requesting a channel configuration, make sure it fits the
* mask's lsb (to ensure no gaps in the output channels). If there's no
* mask, assume the request fits with enough channels.
*/
switch(mDevice->FmtChans)
{
case DevFmtMono:
chansok = (chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask));
break;
case DevFmtStereo:
chansok = (chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask));
break;
case DevFmtQuad:
chansok = (chancount >= 4 && ((chanmask&QuadMask) == QUAD || !chanmask));
break;
case DevFmtX51:
chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
|| (chanmask&X51RearMask) == X5DOT1REAR || !chanmask));
break;
case DevFmtX61:
chansok = (chancount >= 7 && ((chanmask&X61Mask) == X6DOT1 || !chanmask));
break;
case DevFmtX71:
case DevFmtX3D71:
chansok = (chancount >= 8 && ((chanmask&X71Mask) == X7DOT1 || !chanmask));
break;
case DevFmtX714:
chansok = (chancount >= 12 && ((chanmask&X714Mask) == X7DOT1DOT4 || !chanmask));
case DevFmtAmbi3D:
break;
}
}
if(!chansok)
{
if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
mDevice->FmtChans = DevFmtX714;
else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
mDevice->FmtChans = DevFmtX71;
else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
mDevice->FmtChans = DevFmtX61;
else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
|| (chanmask&X51RearMask) == X5DOT1REAR))
mDevice->FmtChans = DevFmtX51;
else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
mDevice->FmtChans = DevFmtQuad;
else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
mDevice->FmtChans = DevFmtStereo;
else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
mDevice->FmtChans = DevFmtMono;
else
{
ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels,
OutputType.dwChannelMask);
mDevice->FmtChans = DevFmtStereo;
OutputType.Format.nChannels = 2;
OutputType.dwChannelMask = STEREO;
}
}
if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
{
if(OutputType.Format.wBitsPerSample == 8)
mDevice->FmtType = DevFmtUByte;
else if(OutputType.Format.wBitsPerSample == 16)
mDevice->FmtType = DevFmtShort;
else if(OutputType.Format.wBitsPerSample == 32)
mDevice->FmtType = DevFmtInt;
else
{
mDevice->FmtType = DevFmtShort;
OutputType.Format.wBitsPerSample = 16;
}
}
else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
{
mDevice->FmtType = DevFmtFloat;
OutputType.Format.wBitsPerSample = 32;
}
else
{
ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str());
mDevice->FmtType = DevFmtShort;
if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
OutputType.Format.wBitsPerSample = 16;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
}
OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
}
bool WasapiPlayback::reset()
{
HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
if(FAILED(hr))
throw al::backend_exception{al::backend_error::DeviceError, "0x%08lx", hr};
return true;
}
HRESULT WasapiPlayback::resetProxy()
{
if(GetConfigValueBool(mDevice->DeviceName.c_str(), "wasapi", "spatial-api", false))
{
auto &audio = mAudio.emplace<SpatialDevice>();
HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(ISpatialAudioClient),
al::out_ptr(audio.mClient))};
if(FAILED(hr))
{
ERR("Failed to activate spatial audio client: 0x%08lx\n", hr);
goto no_spatial;
}
ComPtr<IAudioFormatEnumerator> fmtenum;
hr = audio.mClient->GetSupportedAudioObjectFormatEnumerator(al::out_ptr(fmtenum));
if(FAILED(hr))
{
ERR("Failed to get format enumerator: 0x%08lx\n", hr);
goto no_spatial;
}
UINT32 fmtcount{};
hr = fmtenum->GetCount(&fmtcount);
if(FAILED(hr) || fmtcount == 0)
{
ERR("Failed to get format count: 0x%08lx\n", hr);
goto no_spatial;
}
WAVEFORMATEX *preferredFormat{};
hr = fmtenum->GetFormat(0, &preferredFormat);
if(FAILED(hr))
{
ERR("Failed to get preferred format: 0x%08lx\n", hr);
goto no_spatial;
}
TraceFormat("Preferred mix format", preferredFormat);
UINT32 maxFrames{};
hr = audio.mClient->GetMaxFrameCount(preferredFormat, &maxFrames);
if(FAILED(hr))
ERR("Failed to get max frames: 0x%08lx\n", hr);
else
TRACE("Max sample frames: %u\n", maxFrames);
for(UINT32 i{1};i < fmtcount;++i)
{
WAVEFORMATEX *otherFormat{};
hr = fmtenum->GetFormat(i, &otherFormat);
if(FAILED(hr))
ERR("Failed to format %u: 0x%08lx\n", i+1, hr);
else
{
TraceFormat("Other mix format", otherFormat);
UINT32 otherMaxFrames{};
hr = audio.mClient->GetMaxFrameCount(otherFormat, &otherMaxFrames);
if(FAILED(hr))
ERR("Failed to get max frames: 0x%08lx\n", hr);
else
TRACE("Max sample frames: %u\n", otherMaxFrames);
}
}
WAVEFORMATEXTENSIBLE OutputType;
if(!MakeExtensible(&OutputType, preferredFormat))
goto no_spatial;
/* Force 32-bit float. This is currently required for planar output. */
if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE
&& OutputType.Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT)
{
OutputType.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
OutputType.Format.cbSize = 0;
}
if(OutputType.Format.wBitsPerSample != 32)
{
OutputType.Format.nAvgBytesPerSec = OutputType.Format.nAvgBytesPerSec * 32u
/ OutputType.Format.wBitsPerSample;
OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nBlockAlign * 32
/ OutputType.Format.wBitsPerSample);
OutputType.Format.wBitsPerSample = 32;
}
OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
/* Match the output rate if not requesting anything specific. */
if(!mDevice->Flags.test(FrequencyRequest))
mDevice->Frequency = OutputType.Format.nSamplesPerSec;
bool isRear51{false};
if(!mDevice->Flags.test(ChannelsRequest))
{
const uint32_t chancount{OutputType.Format.nChannels};
const DWORD chanmask{OutputType.dwChannelMask};
if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
mDevice->FmtChans = DevFmtX714;
else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
mDevice->FmtChans = DevFmtX71;
else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
mDevice->FmtChans = DevFmtX61;
else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
mDevice->FmtChans = DevFmtX51;
else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
{
mDevice->FmtChans = DevFmtX51;
isRear51 = true;
}
else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
mDevice->FmtChans = DevFmtQuad;
else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
mDevice->FmtChans = DevFmtStereo;
/* HACK: Don't autoselect mono. Wine returns this and makes the
* audio terrible.
*/
else if(!(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask)))
ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
}
else
{
const uint32_t chancount{OutputType.Format.nChannels};
const DWORD chanmask{OutputType.dwChannelMask};
isRear51 = (chancount == 6 && (chanmask&X51RearMask) == X5DOT1REAR);
}
auto getTypeMask = [isRear51](DevFmtChannels chans) noexcept
{
switch(chans)
{
case DevFmtMono: return ChannelMask_Mono;
case DevFmtStereo: return ChannelMask_Stereo;
case DevFmtQuad: return ChannelMask_Quad;
case DevFmtX51: return isRear51 ? ChannelMask_X51Rear : ChannelMask_X51;
case DevFmtX61: return ChannelMask_X61;
case DevFmtX3D71:
case DevFmtX71: return ChannelMask_X71;
case DevFmtX714: return ChannelMask_X714;
case DevFmtAmbi3D:
break;
}
return ChannelMask_Stereo;
};
SpatialAudioObjectRenderStreamActivationParams streamParams{};
streamParams.ObjectFormat = &OutputType.Format;
streamParams.StaticObjectTypeMask = getTypeMask(mDevice->FmtChans);
streamParams.Category = AudioCategory_Media;
streamParams.EventHandle = mNotifyEvent;
PropVariant paramProp{};
paramProp->vt = VT_BLOB;
paramProp->blob.cbSize = sizeof(streamParams);
paramProp->blob.pBlobData = reinterpret_cast<BYTE*>(&streamParams);
hr = audio.mClient->ActivateSpatialAudioStream(paramProp.get(),
__uuidof(ISpatialAudioObjectRenderStream), al::out_ptr(audio.mRender));
if(FAILED(hr))
{
ERR("Failed to activate spatial audio stream: 0x%08lx\n", hr);
goto no_spatial;
}
audio.mStaticMask = streamParams.StaticObjectTypeMask;
mFormat = OutputType;
mDevice->FmtType = DevFmtFloat;
mDevice->Flags.reset(DirectEar).set(Virtualization);
if(streamParams.StaticObjectTypeMask == ChannelMask_Stereo)
mDevice->FmtChans = DevFmtStereo;
if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "wasapi", "allow-resampler", true))
mDevice->Frequency = OutputType.Format.nSamplesPerSec;
else
mDevice->Frequency = minu(mDevice->Frequency, OutputType.Format.nSamplesPerSec);
setDefaultWFXChannelOrder();
/* FIXME: Get the real update and buffer size. Presumably the actual
* device is configured once ActivateSpatialAudioStream succeeds, and
* an IAudioClient from the same IMMDevice accesses the same device
* configuration. This isn't obviously correct, but for now assume
* IAudioClient::GetDevicePeriod returns the current device period time
* that ISpatialAudioObjectRenderStream will try to wake up at.
*
* Unfortunately this won't get the buffer size of the
* ISpatialAudioObjectRenderStream, so we only assume there's two
* periods.
*/
mOrigUpdateSize = mDevice->UpdateSize;
mOrigBufferSize = mOrigUpdateSize*2;
ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
ComPtr<IAudioClient> tmpClient;
hr = sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
al::out_ptr(tmpClient));
if(FAILED(hr))
ERR("Failed to activate audio client: 0x%08lx\n", hr);
else
{
hr = tmpClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(per_time), nullptr);
if(FAILED(hr))
ERR("Failed to get device period: 0x%08lx\n", hr);
else
{
mOrigUpdateSize = RefTime2Samples(per_time, mFormat.Format.nSamplesPerSec);
mOrigBufferSize = mOrigUpdateSize*2;
}
}
tmpClient = nullptr;
mDevice->UpdateSize = RefTime2Samples(per_time, mDevice->Frequency);
mDevice->BufferSize = mDevice->UpdateSize*2;
mResampler = nullptr;
mResampleBuffer = nullptr;
mBufferFilled = 0;
if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
{
const auto flags = as_unsigned(streamParams.StaticObjectTypeMask);
const auto channelCount = as_unsigned(al::popcount(flags));
mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType,
channelCount, mDevice->Frequency, mFormat.Format.nSamplesPerSec,
Resampler::FastBSinc24);
mResampleBuffer = std::make_unique<char[]>(size_t{mDevice->UpdateSize} * channelCount *
mFormat.Format.wBitsPerSample / 8);
TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
mFormat.Format.nSamplesPerSec, mOrigUpdateSize, mDevice->Frequency,
mDevice->UpdateSize);
}
return S_OK;
}
no_spatial:
mDevice->Flags.reset(Virtualization);
auto &audio = mAudio.emplace<PlainDevice>();
HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
al::out_ptr(audio.mClient))};
if(FAILED(hr))
{
ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
return hr;
}
WAVEFORMATEX *wfx;
hr = audio.mClient->GetMixFormat(&wfx);
if(FAILED(hr))
{
ERR("Failed to get mix format: 0x%08lx\n", hr);
return hr;
}
TraceFormat("Device mix format", wfx);
WAVEFORMATEXTENSIBLE OutputType;
if(!MakeExtensible(&OutputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
const ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
const ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
prepareFormat(OutputType);
TraceFormat("Requesting playback format", &OutputType.Format);
hr = audio.mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
if(FAILED(hr))
{
WARN("Failed to check format support: 0x%08lx\n", hr);
hr = audio.mClient->GetMixFormat(&wfx);
}
if(FAILED(hr))
{
ERR("Failed to find a supported format: 0x%08lx\n", hr);
return hr;
}
if(wfx != nullptr)
{
TraceFormat("Got playback format", wfx);
if(!MakeExtensible(&OutputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
finalizeFormat(OutputType);
}
mFormat = OutputType;
#if !defined(ALSOFT_UWP)
const EndpointFormFactor formfactor{GetDeviceFormfactor(mMMDev.get())};
mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
#else
mDevice->Flags.set(DirectEar, false);
#endif
setDefaultWFXChannelOrder();
hr = audio.mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
buf_time.count(), 0, &OutputType.Format, nullptr);
if(FAILED(hr))
{
ERR("Failed to initialize audio client: 0x%08lx\n", hr);
return hr;
}
UINT32 buffer_len{};
ReferenceTime min_per{};
hr = audio.mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
if(SUCCEEDED(hr))
hr = audio.mClient->GetBufferSize(&buffer_len);
if(FAILED(hr))
{
ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
return hr;
}
hr = audio.mClient->SetEventHandle(mNotifyEvent);
if(FAILED(hr))
{
ERR("Failed to set event handle: 0x%08lx\n", hr);
return hr;
}
/* Find the nearest multiple of the period size to the update size */
if(min_per < per_time)
min_per *= maxi64((per_time + min_per/2) / min_per, 1);
mOrigBufferSize = buffer_len;
mOrigUpdateSize = minu(RefTime2Samples(min_per, mFormat.Format.nSamplesPerSec), buffer_len/2);
mDevice->BufferSize = static_cast<uint>(uint64_t{buffer_len} * mDevice->Frequency /
mFormat.Format.nSamplesPerSec);
mDevice->UpdateSize = minu(RefTime2Samples(min_per, mDevice->Frequency),
mDevice->BufferSize/2);
mResampler = nullptr;
mResampleBuffer = nullptr;
mBufferFilled = 0;
if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
{
mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType,
mFormat.Format.nChannels, mDevice->Frequency, mFormat.Format.nSamplesPerSec,
Resampler::FastBSinc24);
mResampleBuffer = std::make_unique<char[]>(size_t{mDevice->UpdateSize} *
mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8);
TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
mFormat.Format.nSamplesPerSec, mOrigUpdateSize, mDevice->Frequency,
mDevice->UpdateSize);
}
return hr;
}
void WasapiPlayback::start()
{
const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
if(FAILED(hr))
throw al::backend_exception{al::backend_error::DeviceError,
"Failed to start playback: 0x%lx", hr};
}
HRESULT WasapiPlayback::startProxy()
{
ResetEvent(mNotifyEvent);
auto mstate_fallback = [](std::monostate) -> HRESULT
{ return E_FAIL; };
auto start_plain = [&](PlainDevice &audio) -> HRESULT
{
HRESULT hr{audio.mClient->Start()};
if(FAILED(hr))
{
ERR("Failed to start audio client: 0x%08lx\n", hr);
return hr;
}
hr = audio.mClient->GetService(__uuidof(IAudioRenderClient), al::out_ptr(audio.mRender));
if(SUCCEEDED(hr))
{
try {
mKillNow.store(false, std::memory_order_release);
mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this};
}
catch(...) {
audio.mRender = nullptr;
ERR("Failed to start thread\n");
hr = E_FAIL;
}
}
if(FAILED(hr))
audio.mClient->Stop();
return hr;
};
auto start_spatial = [&](SpatialDevice &audio) -> HRESULT
{
HRESULT hr{audio.mRender->Start()};
if(FAILED(hr))
{
ERR("Failed to start spatial audio stream: 0x%08lx\n", hr);
return hr;
}
try {
mKillNow.store(false, std::memory_order_release);
mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerSpatialProc), this};
}
catch(...) {
ERR("Failed to start thread\n");
hr = E_FAIL;
}
if(FAILED(hr))
{
audio.mRender->Stop();
audio.mRender->Reset();
}
return hr;
};
return std::visit(overloaded{mstate_fallback, start_plain, start_spatial}, mAudio);
}
void WasapiPlayback::stop()
{ pushMessage(MsgType::StopDevice).wait(); }
void WasapiPlayback::stopProxy()
{
if(!mThread.joinable())
return;
mKillNow.store(true, std::memory_order_release);
mThread.join();
auto mstate_fallback = [](std::monostate) -> void
{ };
auto stop_plain = [](PlainDevice &audio) -> void
{
audio.mRender = nullptr;
audio.mClient->Stop();
};
auto stop_spatial = [](SpatialDevice &audio) -> void
{
audio.mRender->Stop();
audio.mRender->Reset();
};
std::visit(overloaded{mstate_fallback, stop_plain, stop_spatial}, mAudio);
}
ClockLatency WasapiPlayback::getClockLatency()
{
ClockLatency ret;
std::lock_guard<std::mutex> _{mMutex};
ret.ClockTime = GetDeviceClockTime(mDevice);
ret.Latency = seconds{mPadding.load(std::memory_order_relaxed)};
ret.Latency /= mFormat.Format.nSamplesPerSec;
if(mResampler)
{
auto extra = mResampler->currentInputDelay();
ret.Latency += std::chrono::duration_cast<nanoseconds>(extra) / mDevice->Frequency;
ret.Latency += nanoseconds{seconds{mBufferFilled}} / mDevice->Frequency;
}
return ret;
}
struct WasapiCapture final : public BackendBase, WasapiProxy {
WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
~WasapiCapture() override;
int recordProc();
void open(std::string_view name) override;
HRESULT openProxy(std::string_view name) override;
void closeProxy() override;
HRESULT resetProxy() override;
void start() override;
HRESULT startProxy() override;
void stop() override;
void stopProxy() override;
void captureSamples(std::byte *buffer, uint samples) override;
uint availableSamples() override;
HRESULT mOpenStatus{E_FAIL};
DeviceHandle mMMDev{nullptr};
ComPtr<IAudioClient> mClient{nullptr};
ComPtr<IAudioCaptureClient> mCapture{nullptr};
HANDLE mNotifyEvent{nullptr};
ChannelConverter mChannelConv{};
SampleConverterPtr mSampleConv;
RingBufferPtr mRing;
std::atomic<bool> mKillNow{true};
std::thread mThread;
DEF_NEWDEL(WasapiCapture)
};
WasapiCapture::~WasapiCapture()
{
if(SUCCEEDED(mOpenStatus))
pushMessage(MsgType::CloseDevice).wait();
mOpenStatus = E_FAIL;
if(mNotifyEvent != nullptr)
CloseHandle(mNotifyEvent);
mNotifyEvent = nullptr;
}
FORCE_ALIGN int WasapiCapture::recordProc()
{
ComWrapper com{COINIT_MULTITHREADED};
if(!com)
{
ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
return 1;
}
althrd_setname(RECORD_THREAD_NAME);
std::vector<float> samples;
while(!mKillNow.load(std::memory_order_relaxed))
{
UINT32 avail;
HRESULT hr{mCapture->GetNextPacketSize(&avail)};
if(FAILED(hr))
ERR("Failed to get next packet size: 0x%08lx\n", hr);
else if(avail > 0)
{
UINT32 numsamples;
DWORD flags;
BYTE *rdata;
hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
if(FAILED(hr))
ERR("Failed to get capture buffer: 0x%08lx\n", hr);
else
{
if(mChannelConv.is_active())
{
samples.resize(numsamples*2);
mChannelConv.convert(rdata, samples.data(), numsamples);
rdata = reinterpret_cast<BYTE*>(samples.data());
}
auto data = mRing->getWriteVector();
size_t dstframes;
if(mSampleConv)
{
const void *srcdata{rdata};
uint srcframes{numsamples};
dstframes = mSampleConv->convert(&srcdata, &srcframes, data.first.buf,
static_cast<uint>(minz(data.first.len, INT_MAX)));
if(srcframes > 0 && dstframes == data.first.len && data.second.len > 0)
{
/* If some source samples remain, all of the first dest
* block was filled, and there's space in the second
* dest block, do another run for the second block.
*/
dstframes += mSampleConv->convert(&srcdata, &srcframes, data.second.buf,
static_cast<uint>(minz(data.second.len, INT_MAX)));
}
}
else
{
const uint framesize{mDevice->frameSizeFromFmt()};
size_t len1{minz(data.first.len, numsamples)};
size_t len2{minz(data.second.len, numsamples-len1)};
memcpy(data.first.buf, rdata, len1*framesize);
if(len2 > 0)
memcpy(data.second.buf, rdata+len1*framesize, len2*framesize);
dstframes = len1 + len2;
}
mRing->writeAdvance(dstframes);
hr = mCapture->ReleaseBuffer(numsamples);
if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
}
}
if(FAILED(hr))
{
mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr);
break;
}
DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
if(res != WAIT_OBJECT_0)
ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
}
return 0;
}
void WasapiCapture::open(std::string_view name)
{
if(SUCCEEDED(mOpenStatus))
throw al::backend_exception{al::backend_error::DeviceError,
"Unexpected duplicate open call"};
mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if(mNotifyEvent == nullptr)
{
ERR("Failed to create notify events: %lu\n", GetLastError());
throw al::backend_exception{al::backend_error::DeviceError,
"Failed to create notify events"};
}
if(name.length() >= DevNameHeadLen
&& std::strncmp(name.data(), DevNameHead, DevNameHeadLen) == 0)
{
name = name.substr(DevNameHeadLen);
}
mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
if(FAILED(mOpenStatus))
throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
mOpenStatus};
HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
if(FAILED(hr))
{
if(hr == E_OUTOFMEMORY)
throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"};
}
}
HRESULT WasapiCapture::openProxy(std::string_view name)
{
std::string devname;
std::wstring devid;
if(!name.empty())
{
auto devlock = DeviceListLock{gDeviceList};
auto devlist = al::span{devlock.getCaptureList()};
auto iter = std::find_if(devlist.cbegin(), devlist.cend(),
[name](const DevMap &entry) -> bool
{ return entry.name == name || entry.endpoint_guid == name; });
if(iter == devlist.cend())
{
const std::wstring wname{utf8_to_wstr(name)};
iter = std::find_if(devlist.cbegin(), devlist.cend(),
[&wname](const DevMap &entry) -> bool
{ return entry.devid == wname; });
}
if(iter == devlist.cend())
{
WARN("Failed to find device name matching \"%.*s\"\n", static_cast<int>(name.length()),
name.data());
return E_FAIL;
}
devname = iter->name;
devid = iter->devid;
}
HRESULT hr{sDeviceHelper->openDevice(devid, eCapture, mMMDev)};
if(FAILED(hr))
{
WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
return hr;
}
mClient = nullptr;
if(!devname.empty())
mDevice->DeviceName = DevNameHead + std::move(devname);
else
mDevice->DeviceName = DevNameHead + GetDeviceNameAndGuid(mMMDev).first;
return S_OK;
}
void WasapiCapture::closeProxy()
{
mClient = nullptr;
mMMDev = nullptr;
}
HRESULT WasapiCapture::resetProxy()
{
mClient = nullptr;
HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
al::out_ptr(mClient))};
if(FAILED(hr))
{
ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
return hr;
}
WAVEFORMATEX *wfx;
hr = mClient->GetMixFormat(&wfx);
if(FAILED(hr))
{
ERR("Failed to get capture format: 0x%08lx\n", hr);
return hr;
}
TraceFormat("Device capture format", wfx);
WAVEFORMATEXTENSIBLE InputType{};
if(!MakeExtensible(&InputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
const bool isRear51{InputType.Format.nChannels == 6
&& (InputType.dwChannelMask&X51RearMask) == X5DOT1REAR};
// Make sure buffer is at least 100ms in size
ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
InputType = {};
InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
switch(mDevice->FmtChans)
{
case DevFmtMono:
InputType.Format.nChannels = 1;
InputType.dwChannelMask = MONO;
break;
case DevFmtStereo:
InputType.Format.nChannels = 2;
InputType.dwChannelMask = STEREO;
break;
case DevFmtQuad:
InputType.Format.nChannels = 4;
InputType.dwChannelMask = QUAD;
break;
case DevFmtX51:
InputType.Format.nChannels = 6;
InputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
break;
case DevFmtX61:
InputType.Format.nChannels = 7;
InputType.dwChannelMask = X6DOT1;
break;
case DevFmtX71:
InputType.Format.nChannels = 8;
InputType.dwChannelMask = X7DOT1;
break;
case DevFmtX714:
InputType.Format.nChannels = 12;
InputType.dwChannelMask = X7DOT1DOT4;
break;
case DevFmtX3D71:
case DevFmtAmbi3D:
return E_FAIL;
}
switch(mDevice->FmtType)
{
/* NOTE: Signedness doesn't matter, the converter will handle it. */
case DevFmtByte:
case DevFmtUByte:
InputType.Format.wBitsPerSample = 8;
InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtShort:
case DevFmtUShort:
InputType.Format.wBitsPerSample = 16;
InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtInt:
case DevFmtUInt:
InputType.Format.wBitsPerSample = 32;
InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtFloat:
InputType.Format.wBitsPerSample = 32;
InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
break;
}
InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
InputType.Format.nSamplesPerSec = mDevice->Frequency;
InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
InputType.Format.wBitsPerSample / 8);
InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
InputType.Format.nBlockAlign;
InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
TraceFormat("Requesting capture format", &InputType.Format);
hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx);
if(FAILED(hr))
{
WARN("Failed to check capture format support: 0x%08lx\n", hr);
hr = mClient->GetMixFormat(&wfx);
}
if(FAILED(hr))
{
ERR("Failed to find a supported capture format: 0x%08lx\n", hr);
return hr;
}
mSampleConv = nullptr;
mChannelConv = {};
if(wfx != nullptr)
{
TraceFormat("Got capture format", wfx);
if(!MakeExtensible(&InputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
-> bool
{
switch(device->FmtChans)
{
/* If the device wants mono, we can handle any input. */
case DevFmtMono:
return true;
/* If the device wants stereo, we can handle mono or stereo input. */
case DevFmtStereo:
return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
|| (chancount == 1 && (chanmask&MonoMask) == MONO);
/* Otherwise, the device must match the input type. */
case DevFmtQuad:
return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
/* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
case DevFmtX51:
return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
|| (chanmask&X51RearMask) == X5DOT1REAR));
case DevFmtX61:
return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
case DevFmtX71:
case DevFmtX3D71:
return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
case DevFmtX714:
return (chancount == 12 && (chanmask == 0 || (chanmask&X714Mask) == X7DOT1DOT4));
case DevFmtAmbi3D:
return (chanmask == 0 && chancount == device->channelsFromFmt());
}
return false;
};
if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
{
ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels,
(InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
InputType.Format.nSamplesPerSec);
return E_FAIL;
}
}
DevFmtType srcType{};
if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
{
if(InputType.Format.wBitsPerSample == 8)
srcType = DevFmtUByte;
else if(InputType.Format.wBitsPerSample == 16)
srcType = DevFmtShort;
else if(InputType.Format.wBitsPerSample == 32)
srcType = DevFmtInt;
else
{
ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample);
return E_FAIL;
}
}
else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
{
if(InputType.Format.wBitsPerSample == 32)
srcType = DevFmtFloat;
else
{
ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample);
return E_FAIL;
}
}
else
{
ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str());
return E_FAIL;
}
if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
{
uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
/* Exclude LFE from the downmix. */
if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
{
constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
chanmask &= ~(1u << lfeidx);
}
mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
mDevice->FmtChans};
TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType));
/* The channel converter always outputs float, so change the input type
* for the resampler/type-converter.
*/
srcType = DevFmtFloat;
}
else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
{
mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
srcType = DevFmtFloat;
}
if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
{
mSampleConv = SampleConverter::Create(srcType, mDevice->FmtType,
mDevice->channelsFromFmt(), InputType.Format.nSamplesPerSec, mDevice->Frequency,
Resampler::FastBSinc24);
if(!mSampleConv)
{
ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
return E_FAIL;
}
TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
}
hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
buf_time.count(), 0, &InputType.Format, nullptr);
if(FAILED(hr))
{
ERR("Failed to initialize audio client: 0x%08lx\n", hr);
return hr;
}
UINT32 buffer_len{};
ReferenceTime min_per{};
hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
if(SUCCEEDED(hr))
hr = mClient->GetBufferSize(&buffer_len);
if(FAILED(hr))
{
ERR("Failed to get buffer size: 0x%08lx\n", hr);
return hr;
}
mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency);
mDevice->BufferSize = buffer_len;
mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
hr = mClient->SetEventHandle(mNotifyEvent);
if(FAILED(hr))
{
ERR("Failed to set event handle: 0x%08lx\n", hr);
return hr;
}
return hr;
}
void WasapiCapture::start()
{
const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
if(FAILED(hr))
throw al::backend_exception{al::backend_error::DeviceError,
"Failed to start recording: 0x%lx", hr};
}
HRESULT WasapiCapture::startProxy()
{
ResetEvent(mNotifyEvent);
HRESULT hr{mClient->Start()};
if(FAILED(hr))
{
ERR("Failed to start audio client: 0x%08lx\n", hr);
return hr;
}
hr = mClient->GetService(__uuidof(IAudioCaptureClient), al::out_ptr(mCapture));
if(SUCCEEDED(hr))
{
try {
mKillNow.store(false, std::memory_order_release);
mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this};
}
catch(...) {
mCapture = nullptr;
ERR("Failed to start thread\n");
hr = E_FAIL;
}
}
if(FAILED(hr))
{
mClient->Stop();
mClient->Reset();
}
return hr;
}
void WasapiCapture::stop()
{ pushMessage(MsgType::StopDevice).wait(); }
void WasapiCapture::stopProxy()
{
if(!mCapture || !mThread.joinable())
return;
mKillNow.store(true, std::memory_order_release);
mThread.join();
mCapture = nullptr;
mClient->Stop();
mClient->Reset();
}
void WasapiCapture::captureSamples(std::byte *buffer, uint samples)
{ mRing->read(buffer, samples); }
uint WasapiCapture::availableSamples()
{ return static_cast<uint>(mRing->readSpace()); }
} // namespace
bool WasapiBackendFactory::init()
{
static HRESULT InitResult{E_FAIL};
if(FAILED(InitResult)) try
{
std::promise<HRESULT> promise;
auto future = promise.get_future();
std::thread{&WasapiProxy::messageHandler, &promise}.detach();
InitResult = future.get();
}
catch(...) {
}
return SUCCEEDED(InitResult);
}
bool WasapiBackendFactory::querySupport(BackendType type)
{ return type == BackendType::Playback || type == BackendType::Capture; }
std::string WasapiBackendFactory::probe(BackendType type)
{
std::string outnames;
auto devlock = DeviceListLock{gDeviceList};
switch(type)
{
case BackendType::Playback:
{
auto defaultId = devlock.getPlaybackDefaultId();
for(const DevMap &entry : devlock.getPlaybackList())
{
if(entry.devid != defaultId)
{
/* +1 to also append the null char (to ensure a null-
* separated list and double-null terminated list).
*/
outnames.append(DevNameHead).append(entry.name.c_str(), entry.name.length()+1);
continue;
}
/* Default device goes first. */
std::string name{DevNameHead + entry.name};
outnames.insert(0, name.c_str(), name.length()+1);
}
}
break;
case BackendType::Capture:
{
auto defaultId = devlock.getCaptureDefaultId();
for(const DevMap &entry : devlock.getCaptureList())
{
if(entry.devid != defaultId)
{
outnames.append(DevNameHead).append(entry.name.c_str(), entry.name.length()+1);
continue;
}
std::string name{DevNameHead + entry.name};
outnames.insert(0, name.c_str(), name.length()+1);
}
}
break;
}
return outnames;
}
BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
{
if(type == BackendType::Playback)
return BackendPtr{new WasapiPlayback{device}};
if(type == BackendType::Capture)
return BackendPtr{new WasapiCapture{device}};
return nullptr;
}
BackendFactory &WasapiBackendFactory::getFactory()
{
static WasapiBackendFactory factory{};
return factory;
}
alc::EventSupport WasapiBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
{
switch(eventType)
{
case alc::EventType::DefaultDeviceChanged:
return alc::EventSupport::FullSupport;
case alc::EventType::DeviceAdded:
case alc::EventType::DeviceRemoved:
#if !defined(ALSOFT_UWP)
return alc::EventSupport::FullSupport;
#endif
case alc::EventType::Count:
break;
}
return alc::EventSupport::NoSupport;
}
|