aboutsummaryrefslogtreecommitdiffstats
path: root/Alc/alc.cpp
blob: 8109f202b765354a7b73a21c108d4491d6766edb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
/**
 * OpenAL cross platform audio library
 * Copyright (C) 1999-2007 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 "version.h"

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <ctype.h>
#include <signal.h>

#include <cmath>
#include <atomic>
#include <mutex>
#include <thread>
#include <vector>
#include <string>
#include <numeric>
#include <algorithm>

#include "alMain.h"
#include "alcontext.h"
#include "alSource.h"
#include "alListener.h"
#include "alSource.h"
#include "alBuffer.h"
#include "alFilter.h"
#include "alEffect.h"
#include "alAuxEffectSlot.h"
#include "alError.h"
#include "mastering.h"
#include "bformatdec.h"
#include "uhjfilter.h"
#include "alu.h"
#include "alconfig.h"
#include "ringbuffer.h"
#include "filters/splitter.h"
#include "bs2b.h"

#include "fpu_modes.h"
#include "cpu_caps.h"
#include "compat.h"
#include "threads.h"
#include "almalloc.h"

#include "backends/base.h"
#include "backends/null.h"
#include "backends/loopback.h"
#ifdef HAVE_JACK
#include "backends/jack.h"
#endif
#ifdef HAVE_PULSEAUDIO
#include "backends/pulseaudio.h"
#endif
#ifdef HAVE_ALSA
#include "backends/alsa.h"
#endif
#ifdef HAVE_WASAPI
#include "backends/wasapi.h"
#endif
#ifdef HAVE_COREAUDIO
#include "backends/coreaudio.h"
#endif
#ifdef HAVE_OPENSL
#include "backends/opensl.h"
#endif
#ifdef HAVE_SOLARIS
#include "backends/solaris.h"
#endif
#ifdef HAVE_SNDIO
#include "backends/sndio.h"
#endif
#ifdef HAVE_OSS
#include "backends/oss.h"
#endif
#ifdef HAVE_QSA
#include "backends/qsa.h"
#endif
#ifdef HAVE_DSOUND
#include "backends/dsound.h"
#endif
#ifdef HAVE_WINMM
#include "backends/winmm.h"
#endif
#ifdef HAVE_PORTAUDIO
#include "backends/portaudio.h"
#endif
#ifdef HAVE_SDL2
#include "backends/sdl2.h"
#endif
#ifdef HAVE_WAVE
#include "backends/wave.h"
#endif


namespace {

/************************************************
 * Backends
 ************************************************/
struct BackendInfo {
    const char *name;
    BackendFactory& (*getFactory)(void);
};

BackendInfo BackendList[] = {
#ifdef HAVE_JACK
    { "jack", JackBackendFactory::getFactory },
#endif
#ifdef HAVE_PULSEAUDIO
    { "pulse", PulseBackendFactory::getFactory },
#endif
#ifdef HAVE_ALSA
    { "alsa", AlsaBackendFactory::getFactory },
#endif
#ifdef HAVE_WASAPI
    { "wasapi", WasapiBackendFactory::getFactory },
#endif
#ifdef HAVE_COREAUDIO
    { "core", CoreAudioBackendFactory::getFactory },
#endif
#ifdef HAVE_OPENSL
    { "opensl", OSLBackendFactory::getFactory },
#endif
#ifdef HAVE_SOLARIS
    { "solaris", SolarisBackendFactory::getFactory },
#endif
#ifdef HAVE_SNDIO
    { "sndio", SndIOBackendFactory::getFactory },
#endif
#ifdef HAVE_OSS
    { "oss", OSSBackendFactory::getFactory },
#endif
#ifdef HAVE_QSA
    { "qsa", QSABackendFactory::getFactory },
#endif
#ifdef HAVE_DSOUND
    { "dsound", DSoundBackendFactory::getFactory },
#endif
#ifdef HAVE_WINMM
    { "winmm", WinMMBackendFactory::getFactory },
#endif
#ifdef HAVE_PORTAUDIO
    { "port", PortBackendFactory::getFactory },
#endif
#ifdef HAVE_SDL2
    { "sdl2", SDL2BackendFactory::getFactory },
#endif

    { "null", NullBackendFactory::getFactory },
#ifdef HAVE_WAVE
    { "wave", WaveBackendFactory::getFactory },
#endif
};
ALsizei BackendListSize = static_cast<ALsizei>(COUNTOF(BackendList));

BackendInfo PlaybackBackend;
BackendInfo CaptureBackend;


/************************************************
 * Functions, enums, and errors
 ************************************************/
#define DECL(x) { #x, (ALCvoid*)(x) }
constexpr struct {
    const ALCchar *funcName;
    ALCvoid *address;
} alcFunctions[] = {
    DECL(alcCreateContext),
    DECL(alcMakeContextCurrent),
    DECL(alcProcessContext),
    DECL(alcSuspendContext),
    DECL(alcDestroyContext),
    DECL(alcGetCurrentContext),
    DECL(alcGetContextsDevice),
    DECL(alcOpenDevice),
    DECL(alcCloseDevice),
    DECL(alcGetError),
    DECL(alcIsExtensionPresent),
    DECL(alcGetProcAddress),
    DECL(alcGetEnumValue),
    DECL(alcGetString),
    DECL(alcGetIntegerv),
    DECL(alcCaptureOpenDevice),
    DECL(alcCaptureCloseDevice),
    DECL(alcCaptureStart),
    DECL(alcCaptureStop),
    DECL(alcCaptureSamples),

    DECL(alcSetThreadContext),
    DECL(alcGetThreadContext),

    DECL(alcLoopbackOpenDeviceSOFT),
    DECL(alcIsRenderFormatSupportedSOFT),
    DECL(alcRenderSamplesSOFT),

    DECL(alcDevicePauseSOFT),
    DECL(alcDeviceResumeSOFT),

    DECL(alcGetStringiSOFT),
    DECL(alcResetDeviceSOFT),

    DECL(alcGetInteger64vSOFT),

    DECL(alEnable),
    DECL(alDisable),
    DECL(alIsEnabled),
    DECL(alGetString),
    DECL(alGetBooleanv),
    DECL(alGetIntegerv),
    DECL(alGetFloatv),
    DECL(alGetDoublev),
    DECL(alGetBoolean),
    DECL(alGetInteger),
    DECL(alGetFloat),
    DECL(alGetDouble),
    DECL(alGetError),
    DECL(alIsExtensionPresent),
    DECL(alGetProcAddress),
    DECL(alGetEnumValue),
    DECL(alListenerf),
    DECL(alListener3f),
    DECL(alListenerfv),
    DECL(alListeneri),
    DECL(alListener3i),
    DECL(alListeneriv),
    DECL(alGetListenerf),
    DECL(alGetListener3f),
    DECL(alGetListenerfv),
    DECL(alGetListeneri),
    DECL(alGetListener3i),
    DECL(alGetListeneriv),
    DECL(alGenSources),
    DECL(alDeleteSources),
    DECL(alIsSource),
    DECL(alSourcef),
    DECL(alSource3f),
    DECL(alSourcefv),
    DECL(alSourcei),
    DECL(alSource3i),
    DECL(alSourceiv),
    DECL(alGetSourcef),
    DECL(alGetSource3f),
    DECL(alGetSourcefv),
    DECL(alGetSourcei),
    DECL(alGetSource3i),
    DECL(alGetSourceiv),
    DECL(alSourcePlayv),
    DECL(alSourceStopv),
    DECL(alSourceRewindv),
    DECL(alSourcePausev),
    DECL(alSourcePlay),
    DECL(alSourceStop),
    DECL(alSourceRewind),
    DECL(alSourcePause),
    DECL(alSourceQueueBuffers),
    DECL(alSourceUnqueueBuffers),
    DECL(alGenBuffers),
    DECL(alDeleteBuffers),
    DECL(alIsBuffer),
    DECL(alBufferData),
    DECL(alBufferf),
    DECL(alBuffer3f),
    DECL(alBufferfv),
    DECL(alBufferi),
    DECL(alBuffer3i),
    DECL(alBufferiv),
    DECL(alGetBufferf),
    DECL(alGetBuffer3f),
    DECL(alGetBufferfv),
    DECL(alGetBufferi),
    DECL(alGetBuffer3i),
    DECL(alGetBufferiv),
    DECL(alDopplerFactor),
    DECL(alDopplerVelocity),
    DECL(alSpeedOfSound),
    DECL(alDistanceModel),

    DECL(alGenFilters),
    DECL(alDeleteFilters),
    DECL(alIsFilter),
    DECL(alFilteri),
    DECL(alFilteriv),
    DECL(alFilterf),
    DECL(alFilterfv),
    DECL(alGetFilteri),
    DECL(alGetFilteriv),
    DECL(alGetFilterf),
    DECL(alGetFilterfv),
    DECL(alGenEffects),
    DECL(alDeleteEffects),
    DECL(alIsEffect),
    DECL(alEffecti),
    DECL(alEffectiv),
    DECL(alEffectf),
    DECL(alEffectfv),
    DECL(alGetEffecti),
    DECL(alGetEffectiv),
    DECL(alGetEffectf),
    DECL(alGetEffectfv),
    DECL(alGenAuxiliaryEffectSlots),
    DECL(alDeleteAuxiliaryEffectSlots),
    DECL(alIsAuxiliaryEffectSlot),
    DECL(alAuxiliaryEffectSloti),
    DECL(alAuxiliaryEffectSlotiv),
    DECL(alAuxiliaryEffectSlotf),
    DECL(alAuxiliaryEffectSlotfv),
    DECL(alGetAuxiliaryEffectSloti),
    DECL(alGetAuxiliaryEffectSlotiv),
    DECL(alGetAuxiliaryEffectSlotf),
    DECL(alGetAuxiliaryEffectSlotfv),

    DECL(alDeferUpdatesSOFT),
    DECL(alProcessUpdatesSOFT),

    DECL(alSourcedSOFT),
    DECL(alSource3dSOFT),
    DECL(alSourcedvSOFT),
    DECL(alGetSourcedSOFT),
    DECL(alGetSource3dSOFT),
    DECL(alGetSourcedvSOFT),
    DECL(alSourcei64SOFT),
    DECL(alSource3i64SOFT),
    DECL(alSourcei64vSOFT),
    DECL(alGetSourcei64SOFT),
    DECL(alGetSource3i64SOFT),
    DECL(alGetSourcei64vSOFT),

    DECL(alGetStringiSOFT),

    DECL(alBufferStorageSOFT),
    DECL(alMapBufferSOFT),
    DECL(alUnmapBufferSOFT),
    DECL(alFlushMappedBufferSOFT),

    DECL(alEventControlSOFT),
    DECL(alEventCallbackSOFT),
    DECL(alGetPointerSOFT),
    DECL(alGetPointervSOFT),
};
#undef DECL

#define DECL(x) { #x, (x) }
constexpr struct {
    const ALCchar *enumName;
    ALCenum value;
} alcEnumerations[] = {
    DECL(ALC_INVALID),
    DECL(ALC_FALSE),
    DECL(ALC_TRUE),

    DECL(ALC_MAJOR_VERSION),
    DECL(ALC_MINOR_VERSION),
    DECL(ALC_ATTRIBUTES_SIZE),
    DECL(ALC_ALL_ATTRIBUTES),
    DECL(ALC_DEFAULT_DEVICE_SPECIFIER),
    DECL(ALC_DEVICE_SPECIFIER),
    DECL(ALC_ALL_DEVICES_SPECIFIER),
    DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER),
    DECL(ALC_EXTENSIONS),
    DECL(ALC_FREQUENCY),
    DECL(ALC_REFRESH),
    DECL(ALC_SYNC),
    DECL(ALC_MONO_SOURCES),
    DECL(ALC_STEREO_SOURCES),
    DECL(ALC_CAPTURE_DEVICE_SPECIFIER),
    DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER),
    DECL(ALC_CAPTURE_SAMPLES),
    DECL(ALC_CONNECTED),

    DECL(ALC_EFX_MAJOR_VERSION),
    DECL(ALC_EFX_MINOR_VERSION),
    DECL(ALC_MAX_AUXILIARY_SENDS),

    DECL(ALC_FORMAT_CHANNELS_SOFT),
    DECL(ALC_FORMAT_TYPE_SOFT),

    DECL(ALC_MONO_SOFT),
    DECL(ALC_STEREO_SOFT),
    DECL(ALC_QUAD_SOFT),
    DECL(ALC_5POINT1_SOFT),
    DECL(ALC_6POINT1_SOFT),
    DECL(ALC_7POINT1_SOFT),
    DECL(ALC_BFORMAT3D_SOFT),

    DECL(ALC_BYTE_SOFT),
    DECL(ALC_UNSIGNED_BYTE_SOFT),
    DECL(ALC_SHORT_SOFT),
    DECL(ALC_UNSIGNED_SHORT_SOFT),
    DECL(ALC_INT_SOFT),
    DECL(ALC_UNSIGNED_INT_SOFT),
    DECL(ALC_FLOAT_SOFT),

    DECL(ALC_HRTF_SOFT),
    DECL(ALC_DONT_CARE_SOFT),
    DECL(ALC_HRTF_STATUS_SOFT),
    DECL(ALC_HRTF_DISABLED_SOFT),
    DECL(ALC_HRTF_ENABLED_SOFT),
    DECL(ALC_HRTF_DENIED_SOFT),
    DECL(ALC_HRTF_REQUIRED_SOFT),
    DECL(ALC_HRTF_HEADPHONES_DETECTED_SOFT),
    DECL(ALC_HRTF_UNSUPPORTED_FORMAT_SOFT),
    DECL(ALC_NUM_HRTF_SPECIFIERS_SOFT),
    DECL(ALC_HRTF_SPECIFIER_SOFT),
    DECL(ALC_HRTF_ID_SOFT),

    DECL(ALC_AMBISONIC_LAYOUT_SOFT),
    DECL(ALC_AMBISONIC_SCALING_SOFT),
    DECL(ALC_AMBISONIC_ORDER_SOFT),
    DECL(ALC_ACN_SOFT),
    DECL(ALC_FUMA_SOFT),
    DECL(ALC_N3D_SOFT),
    DECL(ALC_SN3D_SOFT),

    DECL(ALC_OUTPUT_LIMITER_SOFT),

    DECL(ALC_NO_ERROR),
    DECL(ALC_INVALID_DEVICE),
    DECL(ALC_INVALID_CONTEXT),
    DECL(ALC_INVALID_ENUM),
    DECL(ALC_INVALID_VALUE),
    DECL(ALC_OUT_OF_MEMORY),


    DECL(AL_INVALID),
    DECL(AL_NONE),
    DECL(AL_FALSE),
    DECL(AL_TRUE),

    DECL(AL_SOURCE_RELATIVE),
    DECL(AL_CONE_INNER_ANGLE),
    DECL(AL_CONE_OUTER_ANGLE),
    DECL(AL_PITCH),
    DECL(AL_POSITION),
    DECL(AL_DIRECTION),
    DECL(AL_VELOCITY),
    DECL(AL_LOOPING),
    DECL(AL_BUFFER),
    DECL(AL_GAIN),
    DECL(AL_MIN_GAIN),
    DECL(AL_MAX_GAIN),
    DECL(AL_ORIENTATION),
    DECL(AL_REFERENCE_DISTANCE),
    DECL(AL_ROLLOFF_FACTOR),
    DECL(AL_CONE_OUTER_GAIN),
    DECL(AL_MAX_DISTANCE),
    DECL(AL_SEC_OFFSET),
    DECL(AL_SAMPLE_OFFSET),
    DECL(AL_BYTE_OFFSET),
    DECL(AL_SOURCE_TYPE),
    DECL(AL_STATIC),
    DECL(AL_STREAMING),
    DECL(AL_UNDETERMINED),
    DECL(AL_METERS_PER_UNIT),
    DECL(AL_LOOP_POINTS_SOFT),
    DECL(AL_DIRECT_CHANNELS_SOFT),

    DECL(AL_DIRECT_FILTER),
    DECL(AL_AUXILIARY_SEND_FILTER),
    DECL(AL_AIR_ABSORPTION_FACTOR),
    DECL(AL_ROOM_ROLLOFF_FACTOR),
    DECL(AL_CONE_OUTER_GAINHF),
    DECL(AL_DIRECT_FILTER_GAINHF_AUTO),
    DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO),
    DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO),

    DECL(AL_SOURCE_STATE),
    DECL(AL_INITIAL),
    DECL(AL_PLAYING),
    DECL(AL_PAUSED),
    DECL(AL_STOPPED),

    DECL(AL_BUFFERS_QUEUED),
    DECL(AL_BUFFERS_PROCESSED),

    DECL(AL_FORMAT_MONO8),
    DECL(AL_FORMAT_MONO16),
    DECL(AL_FORMAT_MONO_FLOAT32),
    DECL(AL_FORMAT_MONO_DOUBLE_EXT),
    DECL(AL_FORMAT_STEREO8),
    DECL(AL_FORMAT_STEREO16),
    DECL(AL_FORMAT_STEREO_FLOAT32),
    DECL(AL_FORMAT_STEREO_DOUBLE_EXT),
    DECL(AL_FORMAT_MONO_IMA4),
    DECL(AL_FORMAT_STEREO_IMA4),
    DECL(AL_FORMAT_MONO_MSADPCM_SOFT),
    DECL(AL_FORMAT_STEREO_MSADPCM_SOFT),
    DECL(AL_FORMAT_QUAD8_LOKI),
    DECL(AL_FORMAT_QUAD16_LOKI),
    DECL(AL_FORMAT_QUAD8),
    DECL(AL_FORMAT_QUAD16),
    DECL(AL_FORMAT_QUAD32),
    DECL(AL_FORMAT_51CHN8),
    DECL(AL_FORMAT_51CHN16),
    DECL(AL_FORMAT_51CHN32),
    DECL(AL_FORMAT_61CHN8),
    DECL(AL_FORMAT_61CHN16),
    DECL(AL_FORMAT_61CHN32),
    DECL(AL_FORMAT_71CHN8),
    DECL(AL_FORMAT_71CHN16),
    DECL(AL_FORMAT_71CHN32),
    DECL(AL_FORMAT_REAR8),
    DECL(AL_FORMAT_REAR16),
    DECL(AL_FORMAT_REAR32),
    DECL(AL_FORMAT_MONO_MULAW),
    DECL(AL_FORMAT_MONO_MULAW_EXT),
    DECL(AL_FORMAT_STEREO_MULAW),
    DECL(AL_FORMAT_STEREO_MULAW_EXT),
    DECL(AL_FORMAT_QUAD_MULAW),
    DECL(AL_FORMAT_51CHN_MULAW),
    DECL(AL_FORMAT_61CHN_MULAW),
    DECL(AL_FORMAT_71CHN_MULAW),
    DECL(AL_FORMAT_REAR_MULAW),
    DECL(AL_FORMAT_MONO_ALAW_EXT),
    DECL(AL_FORMAT_STEREO_ALAW_EXT),

    DECL(AL_FORMAT_BFORMAT2D_8),
    DECL(AL_FORMAT_BFORMAT2D_16),
    DECL(AL_FORMAT_BFORMAT2D_FLOAT32),
    DECL(AL_FORMAT_BFORMAT2D_MULAW),
    DECL(AL_FORMAT_BFORMAT3D_8),
    DECL(AL_FORMAT_BFORMAT3D_16),
    DECL(AL_FORMAT_BFORMAT3D_FLOAT32),
    DECL(AL_FORMAT_BFORMAT3D_MULAW),

    DECL(AL_FREQUENCY),
    DECL(AL_BITS),
    DECL(AL_CHANNELS),
    DECL(AL_SIZE),
    DECL(AL_UNPACK_BLOCK_ALIGNMENT_SOFT),
    DECL(AL_PACK_BLOCK_ALIGNMENT_SOFT),

    DECL(AL_SOURCE_RADIUS),

    DECL(AL_STEREO_ANGLES),

    DECL(AL_UNUSED),
    DECL(AL_PENDING),
    DECL(AL_PROCESSED),

    DECL(AL_NO_ERROR),
    DECL(AL_INVALID_NAME),
    DECL(AL_INVALID_ENUM),
    DECL(AL_INVALID_VALUE),
    DECL(AL_INVALID_OPERATION),
    DECL(AL_OUT_OF_MEMORY),

    DECL(AL_VENDOR),
    DECL(AL_VERSION),
    DECL(AL_RENDERER),
    DECL(AL_EXTENSIONS),

    DECL(AL_DOPPLER_FACTOR),
    DECL(AL_DOPPLER_VELOCITY),
    DECL(AL_DISTANCE_MODEL),
    DECL(AL_SPEED_OF_SOUND),
    DECL(AL_SOURCE_DISTANCE_MODEL),
    DECL(AL_DEFERRED_UPDATES_SOFT),
    DECL(AL_GAIN_LIMIT_SOFT),

    DECL(AL_INVERSE_DISTANCE),
    DECL(AL_INVERSE_DISTANCE_CLAMPED),
    DECL(AL_LINEAR_DISTANCE),
    DECL(AL_LINEAR_DISTANCE_CLAMPED),
    DECL(AL_EXPONENT_DISTANCE),
    DECL(AL_EXPONENT_DISTANCE_CLAMPED),

    DECL(AL_FILTER_TYPE),
    DECL(AL_FILTER_NULL),
    DECL(AL_FILTER_LOWPASS),
    DECL(AL_FILTER_HIGHPASS),
    DECL(AL_FILTER_BANDPASS),

    DECL(AL_LOWPASS_GAIN),
    DECL(AL_LOWPASS_GAINHF),

    DECL(AL_HIGHPASS_GAIN),
    DECL(AL_HIGHPASS_GAINLF),

    DECL(AL_BANDPASS_GAIN),
    DECL(AL_BANDPASS_GAINHF),
    DECL(AL_BANDPASS_GAINLF),

    DECL(AL_EFFECT_TYPE),
    DECL(AL_EFFECT_NULL),
    DECL(AL_EFFECT_REVERB),
    DECL(AL_EFFECT_EAXREVERB),
    DECL(AL_EFFECT_CHORUS),
    DECL(AL_EFFECT_DISTORTION),
    DECL(AL_EFFECT_ECHO),
    DECL(AL_EFFECT_FLANGER),
    DECL(AL_EFFECT_PITCH_SHIFTER),
    DECL(AL_EFFECT_FREQUENCY_SHIFTER),
#if 0
    DECL(AL_EFFECT_VOCAL_MORPHER),
#endif
    DECL(AL_EFFECT_RING_MODULATOR),
    DECL(AL_EFFECT_AUTOWAH),
    DECL(AL_EFFECT_COMPRESSOR),
    DECL(AL_EFFECT_EQUALIZER),
    DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT),
    DECL(AL_EFFECT_DEDICATED_DIALOGUE),

    DECL(AL_EFFECTSLOT_EFFECT),
    DECL(AL_EFFECTSLOT_GAIN),
    DECL(AL_EFFECTSLOT_AUXILIARY_SEND_AUTO),
    DECL(AL_EFFECTSLOT_NULL),

    DECL(AL_EAXREVERB_DENSITY),
    DECL(AL_EAXREVERB_DIFFUSION),
    DECL(AL_EAXREVERB_GAIN),
    DECL(AL_EAXREVERB_GAINHF),
    DECL(AL_EAXREVERB_GAINLF),
    DECL(AL_EAXREVERB_DECAY_TIME),
    DECL(AL_EAXREVERB_DECAY_HFRATIO),
    DECL(AL_EAXREVERB_DECAY_LFRATIO),
    DECL(AL_EAXREVERB_REFLECTIONS_GAIN),
    DECL(AL_EAXREVERB_REFLECTIONS_DELAY),
    DECL(AL_EAXREVERB_REFLECTIONS_PAN),
    DECL(AL_EAXREVERB_LATE_REVERB_GAIN),
    DECL(AL_EAXREVERB_LATE_REVERB_DELAY),
    DECL(AL_EAXREVERB_LATE_REVERB_PAN),
    DECL(AL_EAXREVERB_ECHO_TIME),
    DECL(AL_EAXREVERB_ECHO_DEPTH),
    DECL(AL_EAXREVERB_MODULATION_TIME),
    DECL(AL_EAXREVERB_MODULATION_DEPTH),
    DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF),
    DECL(AL_EAXREVERB_HFREFERENCE),
    DECL(AL_EAXREVERB_LFREFERENCE),
    DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR),
    DECL(AL_EAXREVERB_DECAY_HFLIMIT),

    DECL(AL_REVERB_DENSITY),
    DECL(AL_REVERB_DIFFUSION),
    DECL(AL_REVERB_GAIN),
    DECL(AL_REVERB_GAINHF),
    DECL(AL_REVERB_DECAY_TIME),
    DECL(AL_REVERB_DECAY_HFRATIO),
    DECL(AL_REVERB_REFLECTIONS_GAIN),
    DECL(AL_REVERB_REFLECTIONS_DELAY),
    DECL(AL_REVERB_LATE_REVERB_GAIN),
    DECL(AL_REVERB_LATE_REVERB_DELAY),
    DECL(AL_REVERB_AIR_ABSORPTION_GAINHF),
    DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR),
    DECL(AL_REVERB_DECAY_HFLIMIT),

    DECL(AL_CHORUS_WAVEFORM),
    DECL(AL_CHORUS_PHASE),
    DECL(AL_CHORUS_RATE),
    DECL(AL_CHORUS_DEPTH),
    DECL(AL_CHORUS_FEEDBACK),
    DECL(AL_CHORUS_DELAY),

    DECL(AL_DISTORTION_EDGE),
    DECL(AL_DISTORTION_GAIN),
    DECL(AL_DISTORTION_LOWPASS_CUTOFF),
    DECL(AL_DISTORTION_EQCENTER),
    DECL(AL_DISTORTION_EQBANDWIDTH),

    DECL(AL_ECHO_DELAY),
    DECL(AL_ECHO_LRDELAY),
    DECL(AL_ECHO_DAMPING),
    DECL(AL_ECHO_FEEDBACK),
    DECL(AL_ECHO_SPREAD),

    DECL(AL_FLANGER_WAVEFORM),
    DECL(AL_FLANGER_PHASE),
    DECL(AL_FLANGER_RATE),
    DECL(AL_FLANGER_DEPTH),
    DECL(AL_FLANGER_FEEDBACK),
    DECL(AL_FLANGER_DELAY),

    DECL(AL_FREQUENCY_SHIFTER_FREQUENCY),
    DECL(AL_FREQUENCY_SHIFTER_LEFT_DIRECTION),
    DECL(AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION),

    DECL(AL_RING_MODULATOR_FREQUENCY),
    DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF),
    DECL(AL_RING_MODULATOR_WAVEFORM),

    DECL(AL_PITCH_SHIFTER_COARSE_TUNE),
    DECL(AL_PITCH_SHIFTER_FINE_TUNE),

    DECL(AL_COMPRESSOR_ONOFF),

    DECL(AL_EQUALIZER_LOW_GAIN),
    DECL(AL_EQUALIZER_LOW_CUTOFF),
    DECL(AL_EQUALIZER_MID1_GAIN),
    DECL(AL_EQUALIZER_MID1_CENTER),
    DECL(AL_EQUALIZER_MID1_WIDTH),
    DECL(AL_EQUALIZER_MID2_GAIN),
    DECL(AL_EQUALIZER_MID2_CENTER),
    DECL(AL_EQUALIZER_MID2_WIDTH),
    DECL(AL_EQUALIZER_HIGH_GAIN),
    DECL(AL_EQUALIZER_HIGH_CUTOFF),

    DECL(AL_DEDICATED_GAIN),

    DECL(AL_AUTOWAH_ATTACK_TIME),
    DECL(AL_AUTOWAH_RELEASE_TIME),
    DECL(AL_AUTOWAH_RESONANCE),
    DECL(AL_AUTOWAH_PEAK_GAIN),

    DECL(AL_NUM_RESAMPLERS_SOFT),
    DECL(AL_DEFAULT_RESAMPLER_SOFT),
    DECL(AL_SOURCE_RESAMPLER_SOFT),
    DECL(AL_RESAMPLER_NAME_SOFT),

    DECL(AL_SOURCE_SPATIALIZE_SOFT),
    DECL(AL_AUTO_SOFT),

    DECL(AL_MAP_READ_BIT_SOFT),
    DECL(AL_MAP_WRITE_BIT_SOFT),
    DECL(AL_MAP_PERSISTENT_BIT_SOFT),
    DECL(AL_PRESERVE_DATA_BIT_SOFT),

    DECL(AL_EVENT_CALLBACK_FUNCTION_SOFT),
    DECL(AL_EVENT_CALLBACK_USER_PARAM_SOFT),
    DECL(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT),
    DECL(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT),
    DECL(AL_EVENT_TYPE_ERROR_SOFT),
    DECL(AL_EVENT_TYPE_PERFORMANCE_SOFT),
    DECL(AL_EVENT_TYPE_DEPRECATED_SOFT),
};
#undef DECL

constexpr ALCchar alcNoError[] = "No Error";
constexpr ALCchar alcErrInvalidDevice[] = "Invalid Device";
constexpr ALCchar alcErrInvalidContext[] = "Invalid Context";
constexpr ALCchar alcErrInvalidEnum[] = "Invalid Enum";
constexpr ALCchar alcErrInvalidValue[] = "Invalid Value";
constexpr ALCchar alcErrOutOfMemory[] = "Out of Memory";


/************************************************
 * Global variables
 ************************************************/

/* Enumerated device names */
constexpr ALCchar alcDefaultName[] = "OpenAL Soft\0";

std::string alcAllDevicesList;
std::string alcCaptureDeviceList;

/* Default is always the first in the list */
std::string alcDefaultAllDevicesSpecifier;
std::string alcCaptureDefaultDeviceSpecifier;

/* Default context extensions */
constexpr ALchar alExtList[] =
    "AL_EXT_ALAW "
    "AL_EXT_BFORMAT "
    "AL_EXT_DOUBLE "
    "AL_EXT_EXPONENT_DISTANCE "
    "AL_EXT_FLOAT32 "
    "AL_EXT_IMA4 "
    "AL_EXT_LINEAR_DISTANCE "
    "AL_EXT_MCFORMATS "
    "AL_EXT_MULAW "
    "AL_EXT_MULAW_BFORMAT "
    "AL_EXT_MULAW_MCFORMATS "
    "AL_EXT_OFFSET "
    "AL_EXT_source_distance_model "
    "AL_EXT_SOURCE_RADIUS "
    "AL_EXT_STEREO_ANGLES "
    "AL_LOKI_quadriphonic "
    "AL_SOFT_block_alignment "
    "AL_SOFT_deferred_updates "
    "AL_SOFT_direct_channels "
    "AL_SOFTX_effect_chain "
    "AL_SOFTX_events "
    "AL_SOFTX_filter_gain_ex "
    "AL_SOFT_gain_clamp_ex "
    "AL_SOFT_loop_points "
    "AL_SOFTX_map_buffer "
    "AL_SOFT_MSADPCM "
    "AL_SOFT_source_latency "
    "AL_SOFT_source_length "
    "AL_SOFT_source_resampler "
    "AL_SOFT_source_spatialize";

std::atomic<ALCenum> LastNullDeviceError{ALC_NO_ERROR};

/* Thread-local current context */
void ReleaseThreadCtx(ALCcontext *context)
{
    auto ref = DecrementRef(&context->ref);
    TRACEREF("%p decreasing refcount to %u\n", context, ref);
    ERR("Context %p current for thread being destroyed, possible leak!\n", context);
}

std::atomic<void(*)(ALCcontext*)> ThreadCtxProc{ReleaseThreadCtx};
class ThreadCtx {
    ALCcontext *ctx{nullptr};

public:
    ~ThreadCtx()
    {
        auto destruct = ThreadCtxProc.load();
        if(destruct && ctx)
            destruct(ctx);
        ctx = nullptr;
    }

    ALCcontext *get() const noexcept { return ctx; }
    void set(ALCcontext *ctx_) noexcept { ctx = ctx_; }
};
thread_local ThreadCtx LocalContext;
/* Process-wide current context */
std::atomic<ALCcontext*> GlobalContext{nullptr};

/* Flag to trap ALC device errors */
bool TrapALCError{false};

/* One-time configuration init control */
std::once_flag alc_config_once{};

/* Default effect that applies to sources that don't have an effect on send 0 */
ALeffect DefaultEffect;

/* Flag to specify if alcSuspendContext/alcProcessContext should defer/process
 * updates.
 */
bool SuspendDefers{true};


/************************************************
 * ALC information
 ************************************************/
constexpr ALCchar alcNoDeviceExtList[] =
    "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
    "ALC_EXT_thread_local_context ALC_SOFT_loopback";
constexpr ALCchar alcExtensionList[] =
    "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
    "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
    "ALC_EXT_thread_local_context ALC_SOFT_device_clock ALC_SOFT_HRTF "
    "ALC_SOFT_loopback ALC_SOFT_output_limiter ALC_SOFT_pause_device";
constexpr ALCint alcMajorVersion = 1;
constexpr ALCint alcMinorVersion = 1;

constexpr ALCint alcEFXMajorVersion = 1;
constexpr ALCint alcEFXMinorVersion = 0;


/************************************************
 * Device lists
 ************************************************/
std::atomic<ALCdevice*> DeviceList{nullptr};

std::recursive_mutex ListLock;

} // namespace

/* Mixing thread piority level */
ALint RTPrioLevel;

FILE *gLogFile{stderr};
#ifdef _DEBUG
LogLevel gLogLevel{LogWarning};
#else
LogLevel gLogLevel{LogError};
#endif

/************************************************
 * Library initialization
 ************************************************/
#if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/)
{
    switch(reason)
    {
        case DLL_PROCESS_ATTACH:
            /* Pin the DLL so we won't get unloaded until the process terminates */
            GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
                               (WCHAR*)module, &module);
            break;

        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}
#endif

static void alc_initconfig(void)
{
    const char *devs, *str;
    int capfilter;
    float valf;
    int i, n;

    str = getenv("ALSOFT_LOGLEVEL");
    if(str)
    {
        long lvl = strtol(str, nullptr, 0);
        if(lvl >= NoLog && lvl <= LogRef)
            gLogLevel = static_cast<LogLevel>(lvl);
    }

    str = getenv("ALSOFT_LOGFILE");
    if(str && str[0])
    {
#ifdef _WIN32
        std::wstring wname{utf8_to_wstr(str)};
        FILE *logfile = _wfopen(wname.c_str(), L"wt");
#else
        FILE *logfile = fopen(str, "wt");
#endif
        if(logfile) gLogFile = logfile;
        else ERR("Failed to open log file '%s'\n", str);
    }

    TRACE("Initializing library v%s-%s %s\n", ALSOFT_VERSION,
          ALSOFT_GIT_COMMIT_HASH, ALSOFT_GIT_BRANCH);
    {
        std::string names;
        if(BackendListSize > 0)
            names += BackendList[0].name;
        for(i = 1;i < BackendListSize;i++)
        {
            names += ", ";
            names += BackendList[i].name;
        }
        TRACE("Supported backends: %s\n", names.c_str());
    }
    ReadALConfig();

    str = getenv("__ALSOFT_SUSPEND_CONTEXT");
    if(str && *str)
    {
        if(strcasecmp(str, "ignore") == 0)
        {
            SuspendDefers = false;
            TRACE("Selected context suspend behavior, \"ignore\"\n");
        }
        else
            ERR("Unhandled context suspend behavior setting: \"%s\"\n", str);
    }

    capfilter = 0;
#if defined(HAVE_SSE4_1)
    capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
#elif defined(HAVE_SSE3)
    capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
#elif defined(HAVE_SSE2)
    capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2;
#elif defined(HAVE_SSE)
    capfilter |= CPU_CAP_SSE;
#endif
#ifdef HAVE_NEON
    capfilter |= CPU_CAP_NEON;
#endif
    if(ConfigValueStr(nullptr, nullptr, "disable-cpu-exts", &str))
    {
        if(strcasecmp(str, "all") == 0)
            capfilter = 0;
        else
        {
            const char *next = str;
            do {
                str = next;
                while(isspace(str[0]))
                    str++;
                next = strchr(str, ',');

                if(!str[0] || str[0] == ',')
                    continue;

                size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
                while(len > 0 && isspace(str[len-1]))
                    len--;
                if(len == 3 && strncasecmp(str, "sse", len) == 0)
                    capfilter &= ~CPU_CAP_SSE;
                else if(len == 4 && strncasecmp(str, "sse2", len) == 0)
                    capfilter &= ~CPU_CAP_SSE2;
                else if(len == 4 && strncasecmp(str, "sse3", len) == 0)
                    capfilter &= ~CPU_CAP_SSE3;
                else if(len == 6 && strncasecmp(str, "sse4.1", len) == 0)
                    capfilter &= ~CPU_CAP_SSE4_1;
                else if(len == 4 && strncasecmp(str, "neon", len) == 0)
                    capfilter &= ~CPU_CAP_NEON;
                else
                    WARN("Invalid CPU extension \"%s\"\n", str);
            } while(next++);
        }
    }
    FillCPUCaps(capfilter);

#ifdef _WIN32
    RTPrioLevel = 1;
#else
    RTPrioLevel = 0;
#endif
    ConfigValueInt(nullptr, nullptr, "rt-prio", &RTPrioLevel);

    aluInit();
    aluInitMixer();

    str = getenv("ALSOFT_TRAP_ERROR");
    if(str && (strcasecmp(str, "true") == 0 || strtol(str, nullptr, 0) == 1))
    {
        TrapALError  = AL_TRUE;
        TrapALCError = true;
    }
    else
    {
        str = getenv("ALSOFT_TRAP_AL_ERROR");
        if(str && (strcasecmp(str, "true") == 0 || strtol(str, nullptr, 0) == 1))
            TrapALError = AL_TRUE;
        TrapALError = GetConfigValueBool(nullptr, nullptr, "trap-al-error", TrapALError);

        str = getenv("ALSOFT_TRAP_ALC_ERROR");
        if(str && (strcasecmp(str, "true") == 0 || strtol(str, nullptr, 0) == 1))
            TrapALCError = true;
        TrapALCError = !!GetConfigValueBool(nullptr, nullptr, "trap-alc-error", TrapALCError);
    }

    if(ConfigValueFloat(nullptr, "reverb", "boost", &valf))
        ReverbBoost *= std::pow(10.0f, valf / 20.0f);

    if(((devs=getenv("ALSOFT_DRIVERS")) && devs[0]) ||
       ConfigValueStr(nullptr, nullptr, "drivers", &devs))
    {
        int n;
        size_t len;
        const char *next = devs;
        int endlist, delitem;

        i = 0;
        do {
            devs = next;
            while(isspace(devs[0]))
                devs++;
            next = strchr(devs, ',');

            delitem = (devs[0] == '-');
            if(devs[0] == '-') devs++;

            if(!devs[0] || devs[0] == ',')
            {
                endlist = 0;
                continue;
            }
            endlist = 1;

            len = (next ? (static_cast<size_t>(next-devs)) : strlen(devs));
            while(len > 0 && isspace(devs[len-1]))
                len--;
#ifdef HAVE_WASAPI
            /* HACK: For backwards compatibility, convert backend references of
             * mmdevapi to wasapi. This should eventually be removed.
             */
            if(len == 8 && strncmp(devs, "mmdevapi", len) == 0)
            {
                devs = "wasapi";
                len = 6;
            }
#endif
            for(n = i;n < BackendListSize;n++)
            {
                if(len == strlen(BackendList[n].name) &&
                   strncmp(BackendList[n].name, devs, len) == 0)
                {
                    if(delitem)
                    {
                        for(;n+1 < BackendListSize;n++)
                            BackendList[n] = BackendList[n+1];
                        BackendListSize--;
                    }
                    else
                    {
                        BackendInfo Bkp = BackendList[n];
                        for(;n > i;n--)
                            BackendList[n] = BackendList[n-1];
                        BackendList[n] = Bkp;

                        i++;
                    }
                    break;
                }
            }
        } while(next++);

        if(endlist)
            BackendListSize = i;
    }

    for(n = i = 0;i < BackendListSize && (!PlaybackBackend.name || !CaptureBackend.name);i++)
    {
        BackendList[n] = BackendList[i];

        BackendFactory &factory = BackendList[n].getFactory();
        if(!factory.init())
        {
            WARN("Failed to initialize backend \"%s\"\n", BackendList[n].name);
            continue;
        }

        TRACE("Initialized backend \"%s\"\n", BackendList[n].name);
        if(!PlaybackBackend.name && factory.querySupport(BackendType::Playback))
        {
            PlaybackBackend = BackendList[n];
            TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
        }
        if(!CaptureBackend.name && factory.querySupport(BackendType::Capture))
        {
            CaptureBackend = BackendList[n];
            TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
        }
        n++;
    }
    BackendListSize = n;

    LoopbackBackendFactory::getFactory().init();

    if(!PlaybackBackend.name)
        WARN("No playback backend available!\n");
    if(!CaptureBackend.name)
        WARN("No capture backend available!\n");

    if(ConfigValueStr(nullptr, nullptr, "excludefx", &str))
    {
        const char *next = str;
        do {
            str = next;
            next = strchr(str, ',');

            if(!str[0] || next == str)
                continue;

            size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
            for(size_t n{0u};n < countof(gEffectList);n++)
            {
                if(len == strlen(gEffectList[n].name) &&
                   strncmp(gEffectList[n].name, str, len) == 0)
                    DisabledEffects[gEffectList[n].type] = AL_TRUE;
            }
        } while(next++);
    }

    InitEffect(&DefaultEffect);
    str = getenv("ALSOFT_DEFAULT_REVERB");
    if((str && str[0]) || ConfigValueStr(nullptr, nullptr, "default-reverb", &str))
        LoadReverbPreset(str, &DefaultEffect);
}
#define DO_INITCONFIG() std::call_once(alc_config_once, [](){alc_initconfig();})


/************************************************
 * Device enumeration
 ************************************************/
static void ProbeDevices(std::string *list, BackendInfo *backendinfo, DevProbe type)
{
    DO_INITCONFIG();

    std::lock_guard<std::recursive_mutex> _{ListLock};
    list->clear();
    if(backendinfo->getFactory)
        backendinfo->getFactory().probe(type, list);
}
static void ProbeAllDevicesList(void)
{ ProbeDevices(&alcAllDevicesList, &PlaybackBackend, ALL_DEVICE_PROBE); }
static void ProbeCaptureDeviceList(void)
{ ProbeDevices(&alcCaptureDeviceList, &CaptureBackend, CAPTURE_DEVICE_PROBE); }


/************************************************
 * Device format information
 ************************************************/
const ALCchar *DevFmtTypeString(DevFmtType type) noexcept
{
    switch(type)
    {
    case DevFmtByte: return "Signed Byte";
    case DevFmtUByte: return "Unsigned Byte";
    case DevFmtShort: return "Signed Short";
    case DevFmtUShort: return "Unsigned Short";
    case DevFmtInt: return "Signed Int";
    case DevFmtUInt: return "Unsigned Int";
    case DevFmtFloat: return "Float";
    }
    return "(unknown type)";
}
const ALCchar *DevFmtChannelsString(DevFmtChannels chans) noexcept
{
    switch(chans)
    {
    case DevFmtMono: return "Mono";
    case DevFmtStereo: return "Stereo";
    case DevFmtQuad: return "Quadraphonic";
    case DevFmtX51: return "5.1 Surround";
    case DevFmtX51Rear: return "5.1 Surround (Rear)";
    case DevFmtX61: return "6.1 Surround";
    case DevFmtX71: return "7.1 Surround";
    case DevFmtAmbi3D: return "Ambisonic 3D";
    }
    return "(unknown channels)";
}

ALsizei BytesFromDevFmt(DevFmtType type) noexcept
{
    switch(type)
    {
    case DevFmtByte: return sizeof(ALbyte);
    case DevFmtUByte: return sizeof(ALubyte);
    case DevFmtShort: return sizeof(ALshort);
    case DevFmtUShort: return sizeof(ALushort);
    case DevFmtInt: return sizeof(ALint);
    case DevFmtUInt: return sizeof(ALuint);
    case DevFmtFloat: return sizeof(ALfloat);
    }
    return 0;
}
ALsizei ChannelsFromDevFmt(DevFmtChannels chans, ALsizei ambiorder) noexcept
{
    switch(chans)
    {
    case DevFmtMono: return 1;
    case DevFmtStereo: return 2;
    case DevFmtQuad: return 4;
    case DevFmtX51: return 6;
    case DevFmtX51Rear: return 6;
    case DevFmtX61: return 7;
    case DevFmtX71: return 8;
    case DevFmtAmbi3D: return (ambiorder+1) * (ambiorder+1);
    }
    return 0;
}

static ALboolean DecomposeDevFormat(ALenum format, DevFmtChannels *chans, DevFmtType *type)
{
    static const struct {
        ALenum format;
        DevFmtChannels channels;
        DevFmtType type;
    } list[] = {
        { AL_FORMAT_MONO8,        DevFmtMono, DevFmtUByte },
        { AL_FORMAT_MONO16,       DevFmtMono, DevFmtShort },
        { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },

        { AL_FORMAT_STEREO8,        DevFmtStereo, DevFmtUByte },
        { AL_FORMAT_STEREO16,       DevFmtStereo, DevFmtShort },
        { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },

        { AL_FORMAT_QUAD8,  DevFmtQuad, DevFmtUByte },
        { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
        { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },

        { AL_FORMAT_51CHN8,  DevFmtX51, DevFmtUByte },
        { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
        { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },

        { AL_FORMAT_61CHN8,  DevFmtX61, DevFmtUByte },
        { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
        { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },

        { AL_FORMAT_71CHN8,  DevFmtX71, DevFmtUByte },
        { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
        { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
    };
    ALuint i;

    for(i = 0;i < COUNTOF(list);i++)
    {
        if(list[i].format == format)
        {
            *chans = list[i].channels;
            *type  = list[i].type;
            return AL_TRUE;
        }
    }

    return AL_FALSE;
}

static ALCboolean IsValidALCType(ALCenum type)
{
    switch(type)
    {
        case ALC_BYTE_SOFT:
        case ALC_UNSIGNED_BYTE_SOFT:
        case ALC_SHORT_SOFT:
        case ALC_UNSIGNED_SHORT_SOFT:
        case ALC_INT_SOFT:
        case ALC_UNSIGNED_INT_SOFT:
        case ALC_FLOAT_SOFT:
            return ALC_TRUE;
    }
    return ALC_FALSE;
}

static ALCboolean IsValidALCChannels(ALCenum channels)
{
    switch(channels)
    {
        case ALC_MONO_SOFT:
        case ALC_STEREO_SOFT:
        case ALC_QUAD_SOFT:
        case ALC_5POINT1_SOFT:
        case ALC_6POINT1_SOFT:
        case ALC_7POINT1_SOFT:
        case ALC_BFORMAT3D_SOFT:
            return ALC_TRUE;
    }
    return ALC_FALSE;
}

static ALCboolean IsValidAmbiLayout(ALCenum layout)
{
    switch(layout)
    {
        case ALC_ACN_SOFT:
        case ALC_FUMA_SOFT:
            return ALC_TRUE;
    }
    return ALC_FALSE;
}

static ALCboolean IsValidAmbiScaling(ALCenum scaling)
{
    switch(scaling)
    {
        case ALC_N3D_SOFT:
        case ALC_SN3D_SOFT:
        case ALC_FUMA_SOFT:
            return ALC_TRUE;
    }
    return ALC_FALSE;
}

/************************************************
 * Miscellaneous ALC helpers
 ************************************************/

/* SetDefaultWFXChannelOrder
 *
 * Sets the default channel order used by WaveFormatEx.
 */
void SetDefaultWFXChannelOrder(ALCdevice *device)
{
    std::fill(std::begin(device->RealOut.ChannelName), std::end(device->RealOut.ChannelName),
        InvalidChannel);

    switch(device->FmtChans)
    {
    case DevFmtMono:
        device->RealOut.ChannelName[0] = FrontCenter;
        break;
    case DevFmtStereo:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        break;
    case DevFmtQuad:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = BackLeft;
        device->RealOut.ChannelName[3] = BackRight;
        break;
    case DevFmtX51:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = FrontCenter;
        device->RealOut.ChannelName[3] = LFE;
        device->RealOut.ChannelName[4] = SideLeft;
        device->RealOut.ChannelName[5] = SideRight;
        break;
    case DevFmtX51Rear:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = FrontCenter;
        device->RealOut.ChannelName[3] = LFE;
        device->RealOut.ChannelName[4] = BackLeft;
        device->RealOut.ChannelName[5] = BackRight;
        break;
    case DevFmtX61:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = FrontCenter;
        device->RealOut.ChannelName[3] = LFE;
        device->RealOut.ChannelName[4] = BackCenter;
        device->RealOut.ChannelName[5] = SideLeft;
        device->RealOut.ChannelName[6] = SideRight;
        break;
    case DevFmtX71:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = FrontCenter;
        device->RealOut.ChannelName[3] = LFE;
        device->RealOut.ChannelName[4] = BackLeft;
        device->RealOut.ChannelName[5] = BackRight;
        device->RealOut.ChannelName[6] = SideLeft;
        device->RealOut.ChannelName[7] = SideRight;
        break;
    case DevFmtAmbi3D:
        device->RealOut.ChannelName[0] = Aux0;
        if(device->mAmbiOrder > 0)
        {
            device->RealOut.ChannelName[1] = Aux1;
            device->RealOut.ChannelName[2] = Aux2;
            device->RealOut.ChannelName[3] = Aux3;
        }
        if(device->mAmbiOrder > 1)
        {
            device->RealOut.ChannelName[4] = Aux4;
            device->RealOut.ChannelName[5] = Aux5;
            device->RealOut.ChannelName[6] = Aux6;
            device->RealOut.ChannelName[7] = Aux7;
            device->RealOut.ChannelName[8] = Aux8;
        }
        if(device->mAmbiOrder > 2)
        {
            device->RealOut.ChannelName[9]  = Aux9;
            device->RealOut.ChannelName[10] = Aux10;
            device->RealOut.ChannelName[11] = Aux11;
            device->RealOut.ChannelName[12] = Aux12;
            device->RealOut.ChannelName[13] = Aux13;
            device->RealOut.ChannelName[14] = Aux14;
            device->RealOut.ChannelName[15] = Aux15;
        }
        break;
    }
}

/* SetDefaultChannelOrder
 *
 * Sets the default channel order used by most non-WaveFormatEx-based APIs.
 */
void SetDefaultChannelOrder(ALCdevice *device)
{
    std::fill(std::begin(device->RealOut.ChannelName), std::end(device->RealOut.ChannelName),
        InvalidChannel);

    switch(device->FmtChans)
    {
    case DevFmtX51Rear:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = BackLeft;
        device->RealOut.ChannelName[3] = BackRight;
        device->RealOut.ChannelName[4] = FrontCenter;
        device->RealOut.ChannelName[5] = LFE;
        return;
    case DevFmtX71:
        device->RealOut.ChannelName[0] = FrontLeft;
        device->RealOut.ChannelName[1] = FrontRight;
        device->RealOut.ChannelName[2] = BackLeft;
        device->RealOut.ChannelName[3] = BackRight;
        device->RealOut.ChannelName[4] = FrontCenter;
        device->RealOut.ChannelName[5] = LFE;
        device->RealOut.ChannelName[6] = SideLeft;
        device->RealOut.ChannelName[7] = SideRight;
        return;

    /* Same as WFX order */
    case DevFmtMono:
    case DevFmtStereo:
    case DevFmtQuad:
    case DevFmtX51:
    case DevFmtX61:
    case DevFmtAmbi3D:
        SetDefaultWFXChannelOrder(device);
        break;
    }
}


/* ALCcontext_DeferUpdates
 *
 * Defers/suspends updates for the given context's listener and sources. This
 * does *NOT* stop mixing, but rather prevents certain property changes from
 * taking effect.
 */
void ALCcontext_DeferUpdates(ALCcontext *context)
{
    context->DeferUpdates.store(true);
}

/* ALCcontext_ProcessUpdates
 *
 * Resumes update processing after being deferred.
 */
void ALCcontext_ProcessUpdates(ALCcontext *context)
{
    std::lock_guard<std::mutex> _{context->PropLock};
    if(context->DeferUpdates.exchange(false))
    {
        /* Tell the mixer to stop applying updates, then wait for any active
         * updating to finish, before providing updates.
         */
        context->HoldUpdates.store(true, std::memory_order_release);
        while((context->UpdateCount.load(std::memory_order_acquire)&1) != 0)
            std::this_thread::yield();

        if(!context->PropsClean.test_and_set(std::memory_order_acq_rel))
            UpdateContextProps(context);
        if(!context->Listener.PropsClean.test_and_set(std::memory_order_acq_rel))
            UpdateListenerProps(context);
        UpdateAllEffectSlotProps(context);
        UpdateAllSourceProps(context);

        /* Now with all updates declared, let the mixer continue applying them
         * so they all happen at once.
         */
        context->HoldUpdates.store(false, std::memory_order_release);
    }
}


/* alcSetError
 *
 * Stores the latest ALC device error
 */
static void alcSetError(ALCdevice *device, ALCenum errorCode)
{
    WARN("Error generated on device %p, code 0x%04x\n", device, errorCode);
    if(TrapALCError)
    {
#ifdef _WIN32
        /* DebugBreak() will cause an exception if there is no debugger */
        if(IsDebuggerPresent())
            DebugBreak();
#elif defined(SIGTRAP)
        raise(SIGTRAP);
#endif
    }

    if(device)
        device->LastError.store(errorCode);
    else
        LastNullDeviceError.store(errorCode);
}


static std::unique_ptr<Compressor> CreateDeviceLimiter(const ALCdevice *device, const ALfloat threshold)
{
    return CompressorInit(device->RealOut.NumChannels, device->Frequency,
        AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, 0.002f,
        0.0f, 0.0f, threshold, INFINITY, 0.0f, 0.020f, 0.200f);
}

/* UpdateClockBase
 *
 * Updates the device's base clock time with however many samples have been
 * done. This is used so frequency changes on the device don't cause the time
 * to jump forward or back. Must not be called while the device is running/
 * mixing.
 */
static inline void UpdateClockBase(ALCdevice *device)
{
    using std::chrono::seconds;
    using std::chrono::nanoseconds;
    using std::chrono::duration_cast;

    IncrementRef(&device->MixCount);
    device->ClockBase += duration_cast<nanoseconds>(seconds{device->SamplesDone}) /
                         device->Frequency;
    device->SamplesDone = 0;
    IncrementRef(&device->MixCount);
}

/* UpdateDeviceParams
 *
 * Updates device parameters according to the attribute list (caller is
 * responsible for holding the list lock).
 */
static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
{
    HrtfRequestMode hrtf_userreq = Hrtf_Default;
    HrtfRequestMode hrtf_appreq = Hrtf_Default;
    ALCenum gainLimiter = device->LimiterState;
    const ALsizei old_sends = device->NumAuxSends;
    ALsizei new_sends = device->NumAuxSends;
    DevFmtChannels oldChans;
    DevFmtType oldType;
    ALboolean update_failed;
    ALCsizei hrtf_id = -1;
    ALCcontext *context;
    ALCuint oldFreq;
    int val;

    if((!attrList || !attrList[0]) && device->Type == Loopback)
    {
        WARN("Missing attributes for loopback device\n");
        return ALC_INVALID_VALUE;
    }

    // Check for attributes
    if(attrList && attrList[0])
    {
        ALCenum alayout = AL_NONE;
        ALCenum ascale = AL_NONE;
        ALCenum schans = AL_NONE;
        ALCenum stype = AL_NONE;
        ALCsizei attrIdx = 0;
        ALCsizei aorder = 0;
        ALCuint freq = 0;

        const char *devname{nullptr};
        const bool loopback{device->Type == Loopback};
        if(!loopback)
        {
            devname = device->DeviceName.c_str();
            /* If a context is already running on the device, stop playback so
             * the device attributes can be updated.
             */
            if((device->Flags&DEVICE_RUNNING))
                device->Backend->stop();
            device->Flags &= ~DEVICE_RUNNING;
        }

        auto numMono = static_cast<ALsizei>(device->NumMonoSources);
        auto numStereo = static_cast<ALsizei>(device->NumStereoSources);
        auto numSends = ALsizei{old_sends};

#define TRACE_ATTR(a, v) TRACE("%s = %d\n", #a, v)
        while(attrList[attrIdx])
        {
            switch(attrList[attrIdx])
            {
            case ALC_FORMAT_CHANNELS_SOFT:
                schans = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_FORMAT_CHANNELS_SOFT, schans);
                break;

            case ALC_FORMAT_TYPE_SOFT:
                stype = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_FORMAT_TYPE_SOFT, stype);
                break;

            case ALC_FREQUENCY:
                freq = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_FREQUENCY, freq);
                break;

            case ALC_AMBISONIC_LAYOUT_SOFT:
                alayout = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_AMBISONIC_LAYOUT_SOFT, alayout);
                break;

            case ALC_AMBISONIC_SCALING_SOFT:
                ascale = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_AMBISONIC_SCALING_SOFT, ascale);
                break;

            case ALC_AMBISONIC_ORDER_SOFT:
                aorder = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_AMBISONIC_ORDER_SOFT, aorder);
                break;

            case ALC_MONO_SOURCES:
                numMono = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_MONO_SOURCES, numMono);
                numMono = maxi(numMono, 0);
                break;

            case ALC_STEREO_SOURCES:
                numStereo = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_STEREO_SOURCES, numStereo);
                numStereo = maxi(numStereo, 0);
                break;

            case ALC_MAX_AUXILIARY_SENDS:
                numSends = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_MAX_AUXILIARY_SENDS, numSends);
                numSends = clampi(numSends, 0, MAX_SENDS);
                break;

            case ALC_HRTF_SOFT:
                TRACE_ATTR(ALC_HRTF_SOFT, attrList[attrIdx + 1]);
                if(attrList[attrIdx + 1] == ALC_FALSE)
                    hrtf_appreq = Hrtf_Disable;
                else if(attrList[attrIdx + 1] == ALC_TRUE)
                    hrtf_appreq = Hrtf_Enable;
                else
                    hrtf_appreq = Hrtf_Default;
                break;

            case ALC_HRTF_ID_SOFT:
                hrtf_id = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_HRTF_ID_SOFT, hrtf_id);
                break;

            case ALC_OUTPUT_LIMITER_SOFT:
                gainLimiter = attrList[attrIdx + 1];
                TRACE_ATTR(ALC_OUTPUT_LIMITER_SOFT, gainLimiter);
                break;

            default:
                TRACE("0x%04X = %d (0x%x)\n", attrList[attrIdx],
                    attrList[attrIdx + 1], attrList[attrIdx + 1]);
                break;
            }

            attrIdx += 2;
        }
#undef TRACE_ATTR

        if(loopback)
        {
            if(!schans || !stype || !freq)
            {
                WARN("Missing format for loopback device\n");
                return ALC_INVALID_VALUE;
            }
            if(!IsValidALCChannels(schans) || !IsValidALCType(stype) || freq < MIN_OUTPUT_RATE)
                return ALC_INVALID_VALUE;
            if(schans == ALC_BFORMAT3D_SOFT)
            {
                if(!alayout || !ascale || !aorder)
                {
                    WARN("Missing ambisonic info for loopback device\n");
                    return ALC_INVALID_VALUE;
                }
                if(!IsValidAmbiLayout(alayout) || !IsValidAmbiScaling(ascale))
                    return ALC_INVALID_VALUE;
                if(aorder < 1 || aorder > MAX_AMBI_ORDER)
                    return ALC_INVALID_VALUE;
                if((alayout == ALC_FUMA_SOFT || ascale == ALC_FUMA_SOFT) && aorder > 3)
                    return ALC_INVALID_VALUE;
            }
        }

        if((device->Flags&DEVICE_RUNNING))
            device->Backend->stop();
        device->Flags &= ~DEVICE_RUNNING;

        UpdateClockBase(device);

        if(!loopback)
        {
            device->NumUpdates = DEFAULT_NUM_UPDATES;
            device->UpdateSize = DEFAULT_UPDATE_SIZE;
            device->Frequency = DEFAULT_OUTPUT_RATE;

            ConfigValueUInt(devname, nullptr, "frequency", &freq);
            if(freq < 1)
                device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
            else
            {
                freq = maxi(freq, MIN_OUTPUT_RATE);

                device->NumUpdates = (device->NumUpdates*freq + device->NumUpdates/2) /
                                     device->Frequency;

                device->Frequency = freq;
                device->Flags |= DEVICE_FREQUENCY_REQUEST;
            }

            ConfigValueUInt(devname, nullptr, "periods", &device->NumUpdates);
            device->NumUpdates = clampu(device->NumUpdates, 2, 16);

            ConfigValueUInt(devname, nullptr, "period_size", &device->UpdateSize);
            device->UpdateSize = clampu(device->UpdateSize, 64, 8192);
            /* SSE and Neon do best with the update size being a multiple of 4. */
            if((CPUCapFlags&(CPU_CAP_SSE|CPU_CAP_NEON)) != 0)
                device->UpdateSize = (device->UpdateSize+3u)&~3u;
        }
        else
        {
            device->Frequency = freq;
            device->FmtChans = static_cast<DevFmtChannels>(schans);
            device->FmtType = static_cast<DevFmtType>(stype);
            if(schans == ALC_BFORMAT3D_SOFT)
            {
                device->mAmbiOrder = aorder;
                device->mAmbiLayout = static_cast<AmbiLayout>(alayout);
                device->mAmbiScale = static_cast<AmbiNorm>(ascale);
            }
        }

        if(numMono > INT_MAX-numStereo)
            numMono = INT_MAX-numStereo;
        numMono += numStereo;
        if(ConfigValueInt(devname, nullptr, "sources", &numMono))
        {
            if(numMono <= 0)
                numMono = 256;
        }
        else
            numMono = maxi(numMono, 256);
        numStereo = mini(numStereo, numMono);
        numMono -= numStereo;
        device->SourcesMax = numMono + numStereo;

        device->NumMonoSources = numMono;
        device->NumStereoSources = numStereo;

        if(ConfigValueInt(devname, nullptr, "sends", &new_sends))
            new_sends = mini(numSends, clampi(new_sends, 0, MAX_SENDS));
        else
            new_sends = numSends;
    }

    if((device->Flags&DEVICE_RUNNING))
        return ALC_NO_ERROR;

    device->Uhj_Encoder = nullptr;
    device->Bs2b = nullptr;

    device->Limiter = nullptr;
    device->ChannelDelay.clear();
    device->ChannelDelay.shrink_to_fit();

    device->Dry.Buffer = nullptr;
    device->Dry.NumChannels = 0;
    device->RealOut.Buffer = nullptr;
    device->RealOut.NumChannels = 0;
    device->MixBuffer.clear();
    device->MixBuffer.shrink_to_fit();

    UpdateClockBase(device);
    device->FixedLatency = std::chrono::nanoseconds::zero();

    device->DitherSeed = DITHER_RNG_SEED;

    /*************************************************************************
     * Update device format request if HRTF is requested
     */
    device->HrtfStatus = ALC_HRTF_DISABLED_SOFT;
    if(device->Type != Loopback)
    {
        const char *hrtf;
        if(ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf", &hrtf))
        {
            if(strcasecmp(hrtf, "true") == 0)
                hrtf_userreq = Hrtf_Enable;
            else if(strcasecmp(hrtf, "false") == 0)
                hrtf_userreq = Hrtf_Disable;
            else if(strcasecmp(hrtf, "auto") != 0)
                ERR("Unexpected hrtf value: %s\n", hrtf);
        }

        if(hrtf_userreq == Hrtf_Enable || (hrtf_userreq != Hrtf_Disable && hrtf_appreq == Hrtf_Enable))
        {
            HrtfEntry *hrtf{nullptr};
            if(device->HrtfList.empty())
                device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
            if(!device->HrtfList.empty())
            {
                if(hrtf_id >= 0 && static_cast<size_t>(hrtf_id) < device->HrtfList.size())
                    hrtf = GetLoadedHrtf(device->HrtfList[hrtf_id].hrtf);
                else
                    hrtf = GetLoadedHrtf(device->HrtfList.front().hrtf);
            }

            if(hrtf)
            {
                device->FmtChans = DevFmtStereo;
                device->Frequency = hrtf->sampleRate;
                device->Flags |= DEVICE_CHANNELS_REQUEST | DEVICE_FREQUENCY_REQUEST;
                if(HrtfEntry *oldhrtf{device->mHrtf})
                    oldhrtf->DecRef();
                device->mHrtf = hrtf;
            }
            else
            {
                hrtf_userreq = Hrtf_Default;
                hrtf_appreq = Hrtf_Disable;
                device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT;
            }
        }
    }

    oldFreq  = device->Frequency;
    oldChans = device->FmtChans;
    oldType  = device->FmtType;

    TRACE("Pre-reset: %s%s, %s%s, %s%uhz, %u update size x%d\n",
        (device->Flags&DEVICE_CHANNELS_REQUEST)?"*":"", DevFmtChannelsString(device->FmtChans),
        (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)?"*":"", DevFmtTypeString(device->FmtType),
        (device->Flags&DEVICE_FREQUENCY_REQUEST)?"*":"", device->Frequency,
        device->UpdateSize, device->NumUpdates
    );

    if(device->Backend->reset() == ALC_FALSE)
        return ALC_INVALID_DEVICE;

    if(device->FmtChans != oldChans && (device->Flags&DEVICE_CHANNELS_REQUEST))
    {
        ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans),
            DevFmtChannelsString(device->FmtChans));
        device->Flags &= ~DEVICE_CHANNELS_REQUEST;
    }
    if(device->FmtType != oldType && (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST))
    {
        ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType),
            DevFmtTypeString(device->FmtType));
        device->Flags &= ~DEVICE_SAMPLE_TYPE_REQUEST;
    }
    if(device->Frequency != oldFreq && (device->Flags&DEVICE_FREQUENCY_REQUEST))
    {
        ERR("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency);
        device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
    }

    if((device->UpdateSize&3) != 0)
    {
        if((CPUCapFlags&CPU_CAP_SSE))
            WARN("SSE performs best with multiple of 4 update sizes (%u)\n", device->UpdateSize);
        if((CPUCapFlags&CPU_CAP_NEON))
            WARN("NEON performs best with multiple of 4 update sizes (%u)\n", device->UpdateSize);
    }

    TRACE("Post-reset: %s, %s, %uhz, %u update size x%d\n",
        DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
        device->Frequency, device->UpdateSize, device->NumUpdates
    );

    aluInitRenderer(device, hrtf_id, hrtf_appreq, hrtf_userreq);
    TRACE("Channel config, Main: %d, Real: %d\n", device->Dry.NumChannels,
        device->RealOut.NumChannels);

    /* Allocate extra channels for any post-filter output. */
    const ALsizei num_chans{device->Dry.NumChannels + device->RealOut.NumChannels};

    TRACE("Allocating %d channels, " SZFMT " bytes\n", num_chans,
          num_chans*sizeof(device->MixBuffer[0]));
    device->MixBuffer.resize(num_chans);

    device->Dry.Buffer = &reinterpret_cast<ALfloat(&)[BUFFERSIZE]>(device->MixBuffer[0]);
    if(device->RealOut.NumChannels != 0)
        device->RealOut.Buffer = device->Dry.Buffer + device->Dry.NumChannels;
    else
    {
        device->RealOut.Buffer = device->Dry.Buffer;
        device->RealOut.NumChannels = device->Dry.NumChannels;
    }

    device->NumAuxSends = new_sends;
    TRACE("Max sources: %d (%d + %d), effect slots: %d, sends: %d\n",
          device->SourcesMax, device->NumMonoSources, device->NumStereoSources,
          device->AuxiliaryEffectSlotMax, device->NumAuxSends);

    device->DitherDepth = 0.0f;
    if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "dither", 1))
    {
        ALint depth = 0;
        ConfigValueInt(device->DeviceName.c_str(), nullptr, "dither-depth", &depth);
        if(depth <= 0)
        {
            switch(device->FmtType)
            {
                case DevFmtByte:
                case DevFmtUByte:
                    depth = 8;
                    break;
                case DevFmtShort:
                case DevFmtUShort:
                    depth = 16;
                    break;
                case DevFmtInt:
                case DevFmtUInt:
                case DevFmtFloat:
                    break;
            }
        }

        if(depth > 0)
        {
            depth = clampi(depth, 2, 24);
            device->DitherDepth = std::pow(2.0f, static_cast<ALfloat>(depth-1));
        }
    }
    if(!(device->DitherDepth > 0.0f))
        TRACE("Dithering disabled\n");
    else
        TRACE("Dithering enabled (%d-bit, %g)\n", float2int(std::log2(device->DitherDepth)+0.5f)+1,
              device->DitherDepth);

    device->LimiterState = gainLimiter;
    if(ConfigValueBool(device->DeviceName.c_str(), nullptr, "output-limiter", &val))
        gainLimiter = val ? ALC_TRUE : ALC_FALSE;

    /* Valid values for gainLimiter are ALC_DONT_CARE_SOFT, ALC_TRUE, and
     * ALC_FALSE. For ALC_DONT_CARE_SOFT, use the limiter for integer-based
     * output (where samples must be clamped), and don't for floating-point
     * (which can take unclamped samples).
     */
    if(gainLimiter == ALC_DONT_CARE_SOFT)
    {
        switch(device->FmtType)
        {
            case DevFmtByte:
            case DevFmtUByte:
            case DevFmtShort:
            case DevFmtUShort:
            case DevFmtInt:
            case DevFmtUInt:
                gainLimiter = ALC_TRUE;
                break;
            case DevFmtFloat:
                gainLimiter = ALC_FALSE;
                break;
        }
    }
    if(gainLimiter != ALC_FALSE)
    {
        ALfloat thrshld = 1.0f;
        switch(device->FmtType)
        {
            case DevFmtByte:
            case DevFmtUByte:
                thrshld = 127.0f / 128.0f;
                break;
            case DevFmtShort:
            case DevFmtUShort:
                thrshld = 32767.0f / 32768.0f;
                break;
            case DevFmtInt:
            case DevFmtUInt:
            case DevFmtFloat:
                break;
        }
        if(device->DitherDepth > 0.0f)
            thrshld -= 1.0f / device->DitherDepth;

        auto limiter = CreateDeviceLimiter(device, std::log10(thrshld) * 20.0f);
        /* Convert the lookahead from samples to nanosamples to nanoseconds. */
        device->FixedLatency += std::chrono::duration_cast<std::chrono::nanoseconds>(
            std::chrono::seconds(limiter->getLookAhead())) / device->Frequency;
        device->Limiter = std::move(limiter);
    }
    TRACE("Output limiter %s\n", device->Limiter ? "enabled" : "disabled");

    aluSelectPostProcess(device);

    TRACE("Fixed device latency: %ldns\n", (long)device->FixedLatency.count());

    /* Need to delay returning failure until replacement Send arrays have been
     * allocated with the appropriate size.
     */
    update_failed = AL_FALSE;
    FPUCtl mixer_mode{};
    context = device->ContextList.load();
    while(context)
    {
        if(context->DefaultSlot)
        {
            ALeffectslot *slot = context->DefaultSlot.get();
            aluInitEffectPanning(slot, device);

            EffectState *state{slot->Effect.State};
            state->mOutBuffer = device->Dry.Buffer;
            state->mOutChannels = device->Dry.NumChannels;
            if(state->deviceUpdate(device) == AL_FALSE)
                update_failed = AL_TRUE;
            else
                UpdateEffectSlotProps(slot, context);
        }

        std::unique_lock<std::mutex> proplock{context->PropLock};
        std::unique_lock<std::mutex> slotlock{context->EffectSlotLock};
        for(auto &sublist : context->EffectSlotList)
        {
            uint64_t usemask = ~sublist.FreeMask;
            while(usemask)
            {
                ALsizei idx = CTZ64(usemask);
                ALeffectslot *slot = sublist.EffectSlots + idx;

                usemask &= ~(1_u64 << idx);

                aluInitEffectPanning(slot, device);

                EffectState *state{slot->Effect.State};
                state->mOutBuffer = device->Dry.Buffer;
                state->mOutChannels = device->Dry.NumChannels;
                if(state->deviceUpdate(device) == AL_FALSE)
                    update_failed = AL_TRUE;
                else
                    UpdateEffectSlotProps(slot, context);
            }
        }
        slotlock.unlock();

        std::unique_lock<std::mutex> srclock{context->SourceLock};
        for(auto &sublist : context->SourceList)
        {
            uint64_t usemask = ~sublist.FreeMask;
            while(usemask)
            {
                ALsizei idx = CTZ64(usemask);
                ALsource *source = sublist.Sources + idx;

                usemask &= ~(1_u64 << idx);

                if(old_sends != device->NumAuxSends)
                {
                    ALsizei s;
                    for(s = device->NumAuxSends;s < old_sends;s++)
                    {
                        if(source->Send[s].Slot)
                            DecrementRef(&source->Send[s].Slot->ref);
                        source->Send[s].Slot = nullptr;
                    }
                    source->Send.resize(device->NumAuxSends);
                    source->Send.shrink_to_fit();
                    for(s = old_sends;s < device->NumAuxSends;s++)
                    {
                        source->Send[s].Slot = nullptr;
                        source->Send[s].Gain = 1.0f;
                        source->Send[s].GainHF = 1.0f;
                        source->Send[s].HFReference = LOWPASSFREQREF;
                        source->Send[s].GainLF = 1.0f;
                        source->Send[s].LFReference = HIGHPASSFREQREF;
                    }
                }

                source->PropsClean.clear(std::memory_order_release);
            }
        }

        /* Clear any pre-existing voice property structs, in case the number of
         * auxiliary sends is changing. Active sources will have updates
         * respecified in UpdateAllSourceProps.
         */
        ALvoiceProps *vprops{context->FreeVoiceProps.exchange(nullptr, std::memory_order_acq_rel)};
        while(vprops)
        {
            ALvoiceProps *next = vprops->next.load(std::memory_order_relaxed);
            delete vprops;
            vprops = next;
        }

        AllocateVoices(context, context->MaxVoices, old_sends);
        auto voices_end = context->Voices + context->VoiceCount.load(std::memory_order_relaxed);
        std::for_each(context->Voices, voices_end,
            [device](ALvoice *voice) -> void
            {
                delete voice->Update.exchange(nullptr, std::memory_order_acq_rel);

                /* Force the voice to stopped if it was stopping. */
                ALvoice::State vstate{ALvoice::Stopping};
                voice->PlayState.compare_exchange_strong(vstate, ALvoice::Stopped,
                    std::memory_order_acquire, std::memory_order_acquire);
                if(voice->SourceID.load(std::memory_order_relaxed) == 0u)
                    return;

                if(device->AvgSpeakerDist > 0.0f)
                {
                    /* Reinitialize the NFC filters for new parameters. */
                    ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
                                 (device->AvgSpeakerDist * device->Frequency);
                    std::for_each(voice->Direct.Params, voice->Direct.Params+voice->NumChannels,
                        [w1](DirectParams &params) noexcept -> void
                        { params.NFCtrlFilter.init(w1); }
                    );
                }
            }
        );
        srclock.unlock();

        context->PropsClean.test_and_set(std::memory_order_release);
        UpdateContextProps(context);
        context->Listener.PropsClean.test_and_set(std::memory_order_release);
        UpdateListenerProps(context);
        UpdateAllSourceProps(context);

        context = context->next.load(std::memory_order_relaxed);
    }
    mixer_mode.leave();
    if(update_failed)
        return ALC_INVALID_DEVICE;

    if(!(device->Flags&DEVICE_PAUSED))
    {
        if(device->Backend->start() == ALC_FALSE)
            return ALC_INVALID_DEVICE;
        device->Flags |= DEVICE_RUNNING;
    }

    return ALC_NO_ERROR;
}


ALCdevice::ALCdevice(DeviceType type) : Type{type}
{
}

/* ALCdevice::~ALCdevice
 *
 * Frees the device structure, and destroys any objects the app failed to
 * delete. Called once there's no more references on the device.
 */
ALCdevice::~ALCdevice()
{
    TRACE("%p\n", this);

    Backend = nullptr;

    size_t count{std::accumulate(BufferList.cbegin(), BufferList.cend(), size_t{0u},
        [](size_t cur, const BufferSubList &sublist) noexcept -> size_t
        { return cur + POPCNT64(~sublist.FreeMask); }
    )};
    if(count > 0)
        WARN(SZFMT " Buffer%s not deleted\n", count, (count==1)?"":"s");

    count = std::accumulate(EffectList.cbegin(), EffectList.cend(), size_t{0u},
        [](size_t cur, const EffectSubList &sublist) noexcept -> size_t
        { return cur + POPCNT64(~sublist.FreeMask); }
    );
    if(count > 0)
        WARN(SZFMT " Effect%s not deleted\n", count, (count==1)?"":"s");

    count = std::accumulate(FilterList.cbegin(), FilterList.cend(), size_t{0u},
        [](size_t cur, const FilterSubList &sublist) noexcept -> size_t
        { return cur + POPCNT64(~sublist.FreeMask); }
    );
    if(count > 0)
        WARN(SZFMT " Filter%s not deleted\n", count, (count==1)?"":"s");

    if(mHrtf)
        mHrtf->DecRef();
    mHrtf = nullptr;
}


static void ALCdevice_IncRef(ALCdevice *device)
{
    auto ref = IncrementRef(&device->ref);
    TRACEREF("%p increasing refcount to %u\n", device, ref);
}

static void ALCdevice_DecRef(ALCdevice *device)
{
    auto ref = DecrementRef(&device->ref);
    TRACEREF("%p decreasing refcount to %u\n", device, ref);
    if(ref == 0) delete device;
}

/* Simple RAII device reference. Takes the reference of the provided ALCdevice,
 * and decrements it when leaving scope. Movable (transfer reference) but not
 * copyable (no new references).
 */
class DeviceRef {
    ALCdevice *mDev{nullptr};

    void reset() noexcept
    {
        if(mDev)
            ALCdevice_DecRef(mDev);
        mDev = nullptr;
    }

public:
    DeviceRef() noexcept = default;
    DeviceRef(DeviceRef&& rhs) noexcept : mDev{rhs.mDev}
    { rhs.mDev = nullptr; }
    explicit DeviceRef(ALCdevice *dev) noexcept : mDev(dev) { }
    ~DeviceRef() { reset(); }

    DeviceRef& operator=(const DeviceRef&) = delete;
    DeviceRef& operator=(DeviceRef&& rhs) noexcept
    {
        reset();
        mDev = rhs.mDev;
        rhs.mDev = nullptr;
        return *this;
    }

    operator bool() const noexcept { return mDev != nullptr; }

    ALCdevice* operator->() noexcept { return mDev; }
    ALCdevice* get() noexcept { return mDev; }

    ALCdevice* release() noexcept
    {
        ALCdevice *ret{mDev};
        mDev = nullptr;
        return ret;
    }
};


/* VerifyDevice
 *
 * Checks if the device handle is valid, and returns a new reference if so.
 */
static DeviceRef VerifyDevice(ALCdevice *device)
{
    std::lock_guard<std::recursive_mutex> _{ListLock};
    ALCdevice *tmpDevice{DeviceList.load()};
    while(tmpDevice)
    {
        if(tmpDevice == device)
        {
            ALCdevice_IncRef(tmpDevice);
            return DeviceRef{tmpDevice};
        }
        tmpDevice = tmpDevice->next.load(std::memory_order_relaxed);
    }

    return DeviceRef{};
}


ALCcontext::ALCcontext(ALCdevice *device) : Device{device}
{
    PropsClean.test_and_set(std::memory_order_relaxed);
}

/* InitContext
 *
 * Initializes context fields
 */
static ALvoid InitContext(ALCcontext *Context)
{
    ALlistener &listener = Context->Listener;
    ALeffectslotArray *auxslots;

    //Validate Context
    if(!Context->DefaultSlot)
        auxslots = ALeffectslot::CreatePtrArray(0);
    else
    {
        auxslots = ALeffectslot::CreatePtrArray(1);
        (*auxslots)[0] = Context->DefaultSlot.get();
    }
    Context->ActiveAuxSlots.store(auxslots, std::memory_order_relaxed);

    //Set globals
    Context->mDistanceModel = DistanceModel::Default;
    Context->SourceDistanceModel = AL_FALSE;
    Context->DopplerFactor = 1.0f;
    Context->DopplerVelocity = 1.0f;
    Context->SpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
    Context->MetersPerUnit = AL_DEFAULT_METERS_PER_UNIT;

    Context->ExtensionList = alExtList;


    listener.Params.Matrix = alu::Matrix::Identity();
    listener.Params.Velocity = alu::Vector{};
    listener.Params.Gain = listener.Gain;
    listener.Params.MetersPerUnit = Context->MetersPerUnit;
    listener.Params.DopplerFactor = Context->DopplerFactor;
    listener.Params.SpeedOfSound = Context->SpeedOfSound * Context->DopplerVelocity;
    listener.Params.ReverbSpeedOfSound = listener.Params.SpeedOfSound *
                                         listener.Params.MetersPerUnit;
    listener.Params.SourceDistanceModel = Context->SourceDistanceModel;
    listener.Params.mDistanceModel = Context->mDistanceModel;


    Context->AsyncEvents = CreateRingBuffer(511, sizeof(AsyncEvent), false);
    StartEventThrd(Context);
}


/* ALCcontext::~ALCcontext()
 *
 * Cleans up the context, and destroys any remaining objects the app failed to
 * delete. Called once there's no more references on the context.
 */
ALCcontext::~ALCcontext()
{
    TRACE("%p\n", this);

    ALcontextProps *cprops{Update.exchange(nullptr, std::memory_order_relaxed)};
    if(cprops)
    {
        TRACE("Freed unapplied context update %p\n", cprops);
        al_free(cprops);
    }
    size_t count{0};
    cprops = FreeContextProps.exchange(nullptr, std::memory_order_acquire);
    while(cprops)
    {
        ALcontextProps *next{cprops->next.load(std::memory_order_relaxed)};
        al_free(cprops);
        cprops = next;
        ++count;
    }
    TRACE("Freed " SZFMT " context property object%s\n", count, (count==1)?"":"s");

    count = std::accumulate(SourceList.cbegin(), SourceList.cend(), size_t{0u},
        [](size_t cur, const SourceSubList &sublist) noexcept -> size_t
        { return cur + POPCNT64(~sublist.FreeMask); }
    );
    if(count > 0)
        WARN(SZFMT " Source%s not deleted\n", count, (count==1)?"":"s");
    SourceList.clear();
    NumSources = 0;

    count = 0;
    ALeffectslotProps *eprops{FreeEffectslotProps.exchange(nullptr, std::memory_order_acquire)};
    while(eprops)
    {
        ALeffectslotProps *next{eprops->next.load(std::memory_order_relaxed)};
        if(eprops->State) eprops->State->DecRef();
        al_free(eprops);
        eprops = next;
        ++count;
    }
    TRACE("Freed " SZFMT " AuxiliaryEffectSlot property object%s\n", count, (count==1)?"":"s");

    delete ActiveAuxSlots.exchange(nullptr, std::memory_order_relaxed);
    DefaultSlot = nullptr;

    count = std::accumulate(EffectSlotList.cbegin(), EffectSlotList.cend(), size_t{0u},
        [](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t
        { return cur + POPCNT64(~sublist.FreeMask); }
    );
    if(count > 0)
        WARN(SZFMT " AuxiliaryEffectSlot%s not deleted\n", count, (count==1)?"":"s");
    EffectSlotList.clear();
    NumEffectSlots = 0;

    count = 0;
    ALvoiceProps *vprops{FreeVoiceProps.exchange(nullptr, std::memory_order_acquire)};
    while(vprops)
    {
        ALvoiceProps *next{vprops->next.load(std::memory_order_relaxed)};
        delete vprops;
        vprops = next;
        ++count;
    }
    TRACE("Freed " SZFMT " voice property object%s\n", count, (count==1)?"":"s");

    std::for_each(Voices, Voices + MaxVoices, DeinitVoice);
    al_free(Voices);
    Voices = nullptr;
    VoiceCount.store(0, std::memory_order_relaxed);
    MaxVoices = 0;

    ALlistenerProps *lprops{Listener.Update.exchange(nullptr, std::memory_order_relaxed)};
    if(lprops)
    {
        TRACE("Freed unapplied listener update %p\n", lprops);
        al_free(lprops);
    }
    count = 0;
    lprops = FreeListenerProps.exchange(nullptr, std::memory_order_acquire);
    while(lprops)
    {
        ALlistenerProps *next{lprops->next.load(std::memory_order_relaxed)};
        al_free(lprops);
        lprops = next;
        ++count;
    }
    TRACE("Freed " SZFMT " listener property object%s\n", count, (count==1)?"":"s");

    if(AsyncEvents)
    {
        count = 0;
        auto evt_vec = AsyncEvents->getReadVector();
        while(evt_vec.first.len > 0)
        {
            reinterpret_cast<AsyncEvent*>(evt_vec.first.buf)->~AsyncEvent();
            evt_vec.first.buf += sizeof(AsyncEvent);
            evt_vec.first.len -= 1;
            ++count;
        }
        while(evt_vec.second.len > 0)
        {
            reinterpret_cast<AsyncEvent*>(evt_vec.second.buf)->~AsyncEvent();
            evt_vec.second.buf += sizeof(AsyncEvent);
            evt_vec.second.len -= 1;
            ++count;
        }
        if(count > 0)
            TRACE("Destructed " SZFMT " orphaned event%s\n", count, (count==1)?"":"s");
    }

    ALCdevice_DecRef(Device);
}

/* ReleaseContext
 *
 * Removes the context reference from the given device and removes it from
 * being current on the running thread or globally. Returns true if other
 * contexts still exist on the device.
 */
static bool ReleaseContext(ALCcontext *context, ALCdevice *device)
{
    if(LocalContext.get() == context)
    {
        WARN("%p released while current on thread\n", context);
        LocalContext.set(nullptr);
        ALCcontext_DecRef(context);
    }

    ALCcontext *origctx{context};
    if(GlobalContext.compare_exchange_strong(origctx, nullptr))
        ALCcontext_DecRef(context);

    bool ret{true};
    { BackendLockGuard _{*device->Backend};
        origctx = context;
        ALCcontext *newhead{context->next.load(std::memory_order_relaxed)};
        if(!device->ContextList.compare_exchange_strong(origctx, newhead))
        {
            ALCcontext *list;
            do {
                /* origctx is what the desired context failed to match. Try
                * swapping out the next one in the list.
                */
                list = origctx;
                origctx = context;
            } while(!list->next.compare_exchange_strong(origctx, newhead));
        }
        else
            ret = !!newhead;
    }

    /* Make sure the context is finished and no longer processing in the mixer
     * before sending the message queue kill event. The backend's lock does
     * this, although waiting for a non-odd mix count would work too.
     */

    StopEventThrd(context);

    ALCcontext_DecRef(context);
    return ret;
}

static void ALCcontext_IncRef(ALCcontext *context)
{
    auto ref = IncrementRef(&context->ref);
    TRACEREF("%p increasing refcount to %u\n", context, ref);
}

void ALCcontext_DecRef(ALCcontext *context)
{
    auto ref = DecrementRef(&context->ref);
    TRACEREF("%p decreasing refcount to %u\n", context, ref);
    if(ref == 0) delete context;
}

/* VerifyContext
 *
 * Checks if the given context is valid, returning a new reference to it if so.
 */
static ContextRef VerifyContext(ALCcontext *context)
{
    std::lock_guard<std::recursive_mutex> _{ListLock};
    ALCdevice *dev{DeviceList.load()};
    while(dev)
    {
        ALCcontext *ctx = dev->ContextList.load(std::memory_order_acquire);
        while(ctx)
        {
            if(ctx == context)
            {
                ALCcontext_IncRef(ctx);
                return ContextRef{ctx};
            }
            ctx = ctx->next.load(std::memory_order_relaxed);
        }
        dev = dev->next.load(std::memory_order_relaxed);
    }

    return ContextRef{};
}


/* GetContextRef
 *
 * Returns a new reference to the currently active context for this thread.
 */
ContextRef GetContextRef(void)
{
    ALCcontext *context{LocalContext.get()};
    if(context)
        ALCcontext_IncRef(context);
    else
    {
        std::lock_guard<std::recursive_mutex> _{ListLock};
        context = GlobalContext.load(std::memory_order_acquire);
        if(context) ALCcontext_IncRef(context);
    }
    return ContextRef{context};
}


void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends)
{
    ALCdevice *device{context->Device};
    const ALsizei num_sends{device->NumAuxSends};

    if(num_voices == context->MaxVoices && num_sends == old_sends)
        return;

    /* Allocate the voice pointers, voices, and the voices' stored source
     * property set (including the dynamically-sized Send[] array) in one
     * chunk.
     */
    const size_t sizeof_voice{RoundUp(ALvoice::Sizeof(num_sends), 16)};
    const size_t size{sizeof(ALvoice*) + sizeof_voice};

    auto voices = static_cast<ALvoice**>(al_calloc(16, RoundUp(size*num_voices, 16)));
    auto voice = reinterpret_cast<ALvoice*>(reinterpret_cast<char*>(voices) + RoundUp(num_voices*sizeof(ALvoice*), 16));

    auto viter = voices;
    if(context->Voices)
    {
        const ALsizei v_count = mini(context->VoiceCount.load(std::memory_order_relaxed),
                                     num_voices);
        const ALsizei s_count = mini(old_sends, num_sends);

        /* Copy the old voice data to the new storage. */
        auto copy_voice = [&voice,num_sends,sizeof_voice,s_count](ALvoice *old_voice) -> ALvoice*
        {
            voice = new (voice) ALvoice{static_cast<size_t>(num_sends)};

            /* Make sure the old voice's Update (if any) is cleared so it
             * doesn't get deleted on deinit.
             */
            voice->Update.store(old_voice->Update.exchange(nullptr, std::memory_order_relaxed),
                                std::memory_order_relaxed);

            voice->SourceID.store(old_voice->SourceID.load(std::memory_order_relaxed),
                                  std::memory_order_relaxed);
            voice->PlayState.store(old_voice->PlayState.load(std::memory_order_relaxed),
                                   std::memory_order_relaxed);

            voice->Props = old_voice->Props;
            /* Clear extraneous property set sends. */
            std::fill(std::begin(voice->Props.Send)+s_count, std::end(voice->Props.Send),
                ALvoiceProps::SendData{});

            voice->position.store(old_voice->position.load(std::memory_order_relaxed),
                                  std::memory_order_relaxed);
            voice->position_fraction.store(
                old_voice->position_fraction.load(std::memory_order_relaxed),
                std::memory_order_relaxed);

            voice->current_buffer.store(old_voice->current_buffer.load(std::memory_order_relaxed),
                std::memory_order_relaxed);
            voice->loop_buffer.store(old_voice->loop_buffer.load(std::memory_order_relaxed),
                std::memory_order_relaxed);

            voice->Frequency = old_voice->Frequency;
            voice->Channels = old_voice->Channels;
            voice->NumChannels = old_voice->NumChannels;
            voice->SampleSize = old_voice->SampleSize;

            voice->Step = old_voice->Step;
            voice->Resampler = old_voice->Resampler;

            voice->Flags = old_voice->Flags;

            voice->Offset = old_voice->Offset;

            std::copy(std::begin(old_voice->PrevSamples), std::end(old_voice->PrevSamples),
                      std::begin(voice->PrevSamples));

            voice->ResampleState = old_voice->ResampleState;

            voice->Direct = old_voice->Direct;
            std::copy_n(old_voice->Send.begin(), s_count, voice->Send.begin());

            /* Set this voice's reference. */
            ALvoice *ret = voice;
            /* Increment pointer to the next storage space. */
            voice = reinterpret_cast<ALvoice*>(reinterpret_cast<char*>(voice) + sizeof_voice);
            return ret;
        };
        viter = std::transform(context->Voices, context->Voices+v_count, viter, copy_voice);

        /* Deinit old voices. */
        auto voices_end = context->Voices + context->MaxVoices;
        std::for_each(context->Voices, voices_end, DeinitVoice);
    }
    /* Finish setting the voices and references. */
    auto init_voice = [&voice,num_sends,sizeof_voice]() -> ALvoice*
    {
        ALvoice *ret = new (voice) ALvoice{static_cast<size_t>(num_sends)};
        voice = reinterpret_cast<ALvoice*>(reinterpret_cast<char*>(voice) + sizeof_voice);
        return ret;
    };
    std::generate(viter, voices+num_voices, init_voice);

    al_free(context->Voices);
    context->Voices = voices;
    context->MaxVoices = num_voices;
    context->VoiceCount = mini(context->VoiceCount.load(std::memory_order_relaxed), num_voices);
}


/************************************************
 * Standard ALC functions
 ************************************************/

/* alcGetError
 *
 * Return last ALC generated error code for the given device
 */
ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
{
    DeviceRef dev{VerifyDevice(device)};
    if(dev) return dev->LastError.exchange(ALC_NO_ERROR);
    return LastNullDeviceError.exchange(ALC_NO_ERROR);
}


/* alcSuspendContext
 *
 * Suspends updates for the given context
 */
ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *context)
{
    if(!SuspendDefers)
        return;

    ContextRef ctx{VerifyContext(context)};
    if(!ctx)
        alcSetError(nullptr, ALC_INVALID_CONTEXT);
    else
        ALCcontext_DeferUpdates(ctx.get());
}

/* alcProcessContext
 *
 * Resumes processing updates for the given context
 */
ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *context)
{
    if(!SuspendDefers)
        return;

    ContextRef ctx{VerifyContext(context)};
    if(!ctx)
        alcSetError(nullptr, ALC_INVALID_CONTEXT);
    else
        ALCcontext_ProcessUpdates(ctx.get());
}


/* alcGetString
 *
 * Returns information about the device, and error strings
 */
ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param)
{
    const ALCchar *value = nullptr;
    DeviceRef dev;

    switch(param)
    {
    case ALC_NO_ERROR:
        value = alcNoError;
        break;

    case ALC_INVALID_ENUM:
        value = alcErrInvalidEnum;
        break;

    case ALC_INVALID_VALUE:
        value = alcErrInvalidValue;
        break;

    case ALC_INVALID_DEVICE:
        value = alcErrInvalidDevice;
        break;

    case ALC_INVALID_CONTEXT:
        value = alcErrInvalidContext;
        break;

    case ALC_OUT_OF_MEMORY:
        value = alcErrOutOfMemory;
        break;

    case ALC_DEVICE_SPECIFIER:
        value = alcDefaultName;
        break;

    case ALC_ALL_DEVICES_SPECIFIER:
        dev = VerifyDevice(Device);
        if(dev)
            value = dev->DeviceName.c_str();
        else
        {
            ProbeAllDevicesList();
            value = alcAllDevicesList.c_str();
        }
        break;

    case ALC_CAPTURE_DEVICE_SPECIFIER:
        dev = VerifyDevice(Device);
        if(dev)
            value = dev->DeviceName.c_str();
        else
        {
            ProbeCaptureDeviceList();
            value = alcCaptureDeviceList.c_str();
        }
        break;

    /* Default devices are always first in the list */
    case ALC_DEFAULT_DEVICE_SPECIFIER:
        value = alcDefaultName;
        break;

    case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
        if(alcAllDevicesList.empty())
            ProbeAllDevicesList();

        /* Copy first entry as default. */
        alcDefaultAllDevicesSpecifier = alcAllDevicesList.c_str();
        value = alcDefaultAllDevicesSpecifier.c_str();
        break;

    case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
        if(alcCaptureDeviceList.empty())
            ProbeCaptureDeviceList();

        /* Copy first entry as default. */
        alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceList.c_str();
        value = alcCaptureDefaultDeviceSpecifier.c_str();
        break;

    case ALC_EXTENSIONS:
        dev = VerifyDevice(Device);
        if(dev) value = alcExtensionList;
        else value = alcNoDeviceExtList;
        break;

    case ALC_HRTF_SPECIFIER_SOFT:
        dev = VerifyDevice(Device);
        if(!dev)
            alcSetError(nullptr, ALC_INVALID_DEVICE);
        else
        {
            std::lock_guard<std::mutex> _{dev->StateLock};
            value = (dev->mHrtf ? dev->HrtfName.c_str() : "");
        }
        break;

    default:
        dev = VerifyDevice(Device);
        alcSetError(dev.get(), ALC_INVALID_ENUM);
        break;
    }

    return value;
}


static inline ALCsizei NumAttrsForDevice(ALCdevice *device)
{
    if(device->Type == Capture) return 9;
    if(device->Type != Loopback) return 29;
    if(device->FmtChans == DevFmtAmbi3D)
        return 35;
    return 29;
}

static ALCsizei GetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values)
{
    ALCsizei i;

    if(size <= 0 || values == nullptr)
    {
        alcSetError(device, ALC_INVALID_VALUE);
        return 0;
    }

    if(!device)
    {
        switch(param)
        {
            case ALC_MAJOR_VERSION:
                values[0] = alcMajorVersion;
                return 1;
            case ALC_MINOR_VERSION:
                values[0] = alcMinorVersion;
                return 1;

            case ALC_ATTRIBUTES_SIZE:
            case ALC_ALL_ATTRIBUTES:
            case ALC_FREQUENCY:
            case ALC_REFRESH:
            case ALC_SYNC:
            case ALC_MONO_SOURCES:
            case ALC_STEREO_SOURCES:
            case ALC_CAPTURE_SAMPLES:
            case ALC_FORMAT_CHANNELS_SOFT:
            case ALC_FORMAT_TYPE_SOFT:
            case ALC_AMBISONIC_LAYOUT_SOFT:
            case ALC_AMBISONIC_SCALING_SOFT:
            case ALC_AMBISONIC_ORDER_SOFT:
            case ALC_MAX_AMBISONIC_ORDER_SOFT:
                alcSetError(nullptr, ALC_INVALID_DEVICE);
                return 0;

            default:
                alcSetError(nullptr, ALC_INVALID_ENUM);
                return 0;
        }
        return 0;
    }

    if(device->Type == Capture)
    {
        switch(param)
        {
            case ALC_ATTRIBUTES_SIZE:
                values[0] = NumAttrsForDevice(device);
                return 1;

            case ALC_ALL_ATTRIBUTES:
                i = 0;
                if(size < NumAttrsForDevice(device))
                    alcSetError(device, ALC_INVALID_VALUE);
                else
                {
                    std::lock_guard<std::mutex> _{device->StateLock};
                    values[i++] = ALC_MAJOR_VERSION;
                    values[i++] = alcMajorVersion;
                    values[i++] = ALC_MINOR_VERSION;
                    values[i++] = alcMinorVersion;
                    values[i++] = ALC_CAPTURE_SAMPLES;
                    values[i++] = device->Backend->availableSamples();
                    values[i++] = ALC_CONNECTED;
                    values[i++] = device->Connected.load(std::memory_order_relaxed);
                    values[i++] = 0;
                }
                return i;

            case ALC_MAJOR_VERSION:
                values[0] = alcMajorVersion;
                return 1;
            case ALC_MINOR_VERSION:
                values[0] = alcMinorVersion;
                return 1;

            case ALC_CAPTURE_SAMPLES:
                { std::lock_guard<std::mutex> _{device->StateLock};
                    values[0] = device->Backend->availableSamples();
                }
                return 1;

            case ALC_CONNECTED:
                { std::lock_guard<std::mutex> _{device->StateLock};
                    values[0] = device->Connected.load(std::memory_order_acquire);
                }
                return 1;

            default:
                alcSetError(device, ALC_INVALID_ENUM);
                return 0;
        }
        return 0;
    }

    /* render device */
    switch(param)
    {
        case ALC_ATTRIBUTES_SIZE:
            values[0] = NumAttrsForDevice(device);
            return 1;

        case ALC_ALL_ATTRIBUTES:
            i = 0;
            if(size < NumAttrsForDevice(device))
                alcSetError(device, ALC_INVALID_VALUE);
            else
            {
                std::lock_guard<std::mutex> _{device->StateLock};
                values[i++] = ALC_MAJOR_VERSION;
                values[i++] = alcMajorVersion;
                values[i++] = ALC_MINOR_VERSION;
                values[i++] = alcMinorVersion;
                values[i++] = ALC_EFX_MAJOR_VERSION;
                values[i++] = alcEFXMajorVersion;
                values[i++] = ALC_EFX_MINOR_VERSION;
                values[i++] = alcEFXMinorVersion;

                values[i++] = ALC_FREQUENCY;
                values[i++] = device->Frequency;
                if(device->Type != Loopback)
                {
                    values[i++] = ALC_REFRESH;
                    values[i++] = device->Frequency / device->UpdateSize;

                    values[i++] = ALC_SYNC;
                    values[i++] = ALC_FALSE;
                }
                else
                {
                    if(device->FmtChans == DevFmtAmbi3D)
                    {
                        values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
                        values[i++] = static_cast<ALCint>(device->mAmbiLayout);

                        values[i++] = ALC_AMBISONIC_SCALING_SOFT;
                        values[i++] = static_cast<ALCint>(device->mAmbiScale);

                        values[i++] = ALC_AMBISONIC_ORDER_SOFT;
                        values[i++] = device->mAmbiOrder;
                    }

                    values[i++] = ALC_FORMAT_CHANNELS_SOFT;
                    values[i++] = device->FmtChans;

                    values[i++] = ALC_FORMAT_TYPE_SOFT;
                    values[i++] = device->FmtType;
                }

                values[i++] = ALC_MONO_SOURCES;
                values[i++] = device->NumMonoSources;

                values[i++] = ALC_STEREO_SOURCES;
                values[i++] = device->NumStereoSources;

                values[i++] = ALC_MAX_AUXILIARY_SENDS;
                values[i++] = device->NumAuxSends;

                values[i++] = ALC_HRTF_SOFT;
                values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);

                values[i++] = ALC_HRTF_STATUS_SOFT;
                values[i++] = device->HrtfStatus;

                values[i++] = ALC_OUTPUT_LIMITER_SOFT;
                values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE;

                values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT;
                values[i++] = MAX_AMBI_ORDER;

                values[i++] = 0;
            }
            return i;

        case ALC_MAJOR_VERSION:
            values[0] = alcMajorVersion;
            return 1;

        case ALC_MINOR_VERSION:
            values[0] = alcMinorVersion;
            return 1;

        case ALC_EFX_MAJOR_VERSION:
            values[0] = alcEFXMajorVersion;
            return 1;

        case ALC_EFX_MINOR_VERSION:
            values[0] = alcEFXMinorVersion;
            return 1;

        case ALC_FREQUENCY:
            values[0] = device->Frequency;
            return 1;

        case ALC_REFRESH:
            if(device->Type == Loopback)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            { std::lock_guard<std::mutex> _{device->StateLock};
                values[0] = device->Frequency / device->UpdateSize;
            }
            return 1;

        case ALC_SYNC:
            if(device->Type == Loopback)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            values[0] = ALC_FALSE;
            return 1;

        case ALC_FORMAT_CHANNELS_SOFT:
            if(device->Type != Loopback)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            values[0] = device->FmtChans;
            return 1;

        case ALC_FORMAT_TYPE_SOFT:
            if(device->Type != Loopback)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            values[0] = device->FmtType;
            return 1;

        case ALC_AMBISONIC_LAYOUT_SOFT:
            if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            values[0] = static_cast<ALCint>(device->mAmbiLayout);
            return 1;

        case ALC_AMBISONIC_SCALING_SOFT:
            if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            values[0] = static_cast<ALCint>(device->mAmbiScale);
            return 1;

        case ALC_AMBISONIC_ORDER_SOFT:
            if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
            {
                alcSetError(device, ALC_INVALID_DEVICE);
                return 0;
            }
            values[0] = device->mAmbiOrder;
            return 1;

        case ALC_MONO_SOURCES:
            values[0] = device->NumMonoSources;
            return 1;

        case ALC_STEREO_SOURCES:
            values[0] = device->NumStereoSources;
            return 1;

        case ALC_MAX_AUXILIARY_SENDS:
            values[0] = device->NumAuxSends;
            return 1;

        case ALC_CONNECTED:
            { std::lock_guard<std::mutex> _{device->StateLock};
                values[0] = device->Connected.load(std::memory_order_acquire);
            }
            return 1;

        case ALC_HRTF_SOFT:
            values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
            return 1;

        case ALC_HRTF_STATUS_SOFT:
            values[0] = device->HrtfStatus;
            return 1;

        case ALC_NUM_HRTF_SPECIFIERS_SOFT:
            { std::lock_guard<std::mutex> _{device->StateLock};
                device->HrtfList.clear();
                device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
                values[0] = static_cast<ALCint>(device->HrtfList.size());
            }
            return 1;

        case ALC_OUTPUT_LIMITER_SOFT:
            values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE;
            return 1;

        case ALC_MAX_AMBISONIC_ORDER_SOFT:
            values[0] = MAX_AMBI_ORDER;
            return 1;

        default:
            alcSetError(device, ALC_INVALID_ENUM);
            return 0;
    }
    return 0;
}

/* alcGetIntegerv
 *
 * Returns information about the device and the version of OpenAL
 */
ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values)
{
    DeviceRef dev{VerifyDevice(device)};
    if(size <= 0 || values == nullptr)
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    else
        GetIntegerv(dev.get(), param, size, values);
}

ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values)
{
    DeviceRef dev{VerifyDevice(device)};
    if(size <= 0 || values == nullptr)
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    else if(!dev || dev->Type == Capture)
    {
        al::vector<ALCint> ivals(size);
        size = GetIntegerv(dev.get(), pname, size, ivals.data());
        std::copy(ivals.begin(), ivals.begin()+size, values);
    }
    else /* render device */
    {
        switch(pname)
        {
            case ALC_ATTRIBUTES_SIZE:
                *values = NumAttrsForDevice(dev.get())+4;
                break;

            case ALC_ALL_ATTRIBUTES:
                if(size < NumAttrsForDevice(dev.get())+4)
                    alcSetError(dev.get(), ALC_INVALID_VALUE);
                else
                {
                    ALsizei i{0};
                    std::lock_guard<std::mutex> _{dev->StateLock};
                    values[i++] = ALC_FREQUENCY;
                    values[i++] = dev->Frequency;

                    if(dev->Type != Loopback)
                    {
                        values[i++] = ALC_REFRESH;
                        values[i++] = dev->Frequency / dev->UpdateSize;

                        values[i++] = ALC_SYNC;
                        values[i++] = ALC_FALSE;
                    }
                    else
                    {
                        if(dev->FmtChans == DevFmtAmbi3D)
                        {
                            values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
                            values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiLayout);

                            values[i++] = ALC_AMBISONIC_SCALING_SOFT;
                            values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiScale);

                            values[i++] = ALC_AMBISONIC_ORDER_SOFT;
                            values[i++] = dev->mAmbiOrder;
                        }

                        values[i++] = ALC_FORMAT_CHANNELS_SOFT;
                        values[i++] = dev->FmtChans;

                        values[i++] = ALC_FORMAT_TYPE_SOFT;
                        values[i++] = dev->FmtType;
                    }

                    values[i++] = ALC_MONO_SOURCES;
                    values[i++] = dev->NumMonoSources;

                    values[i++] = ALC_STEREO_SOURCES;
                    values[i++] = dev->NumStereoSources;

                    values[i++] = ALC_MAX_AUXILIARY_SENDS;
                    values[i++] = dev->NumAuxSends;

                    values[i++] = ALC_HRTF_SOFT;
                    values[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE);

                    values[i++] = ALC_HRTF_STATUS_SOFT;
                    values[i++] = dev->HrtfStatus;

                    values[i++] = ALC_OUTPUT_LIMITER_SOFT;
                    values[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE;

                    ClockLatency clock{GetClockLatency(dev.get())};
                    values[i++] = ALC_DEVICE_CLOCK_SOFT;
                    values[i++] = clock.ClockTime.count();

                    values[i++] = ALC_DEVICE_LATENCY_SOFT;
                    values[i++] = clock.Latency.count();

                    values[i++] = 0;
                }
                break;

            case ALC_DEVICE_CLOCK_SOFT:
                { std::lock_guard<std::mutex> _{dev->StateLock};
                    using std::chrono::seconds;
                    using std::chrono::nanoseconds;
                    using std::chrono::duration_cast;

                    nanoseconds basecount;
                    ALuint samplecount;
                    ALuint refcount;
                    do {
                        while(((refcount=ReadRef(&dev->MixCount))&1) != 0)
                            std::this_thread::yield();
                        basecount = dev->ClockBase;
                        samplecount = dev->SamplesDone;
                    } while(refcount != ReadRef(&dev->MixCount));
                    *values = (duration_cast<nanoseconds>(seconds{samplecount})/dev->Frequency +
                        basecount).count();
                }
                break;

            case ALC_DEVICE_LATENCY_SOFT:
                { std::lock_guard<std::mutex> _{dev->StateLock};
                    ClockLatency clock{GetClockLatency(dev.get())};
                    *values = clock.Latency.count();
                }
                break;

            case ALC_DEVICE_CLOCK_LATENCY_SOFT:
                if(size < 2)
                    alcSetError(dev.get(), ALC_INVALID_VALUE);
                else
                {
                    std::lock_guard<std::mutex> _{dev->StateLock};
                    ClockLatency clock{GetClockLatency(dev.get())};
                    values[0] = clock.ClockTime.count();
                    values[1] = clock.Latency.count();
                }
                break;

            default:
                al::vector<ALCint> ivals(size);
                size = GetIntegerv(dev.get(), pname, size, ivals.data());
                std::copy(ivals.begin(), ivals.begin()+size, values);
                break;
        }
    }
}


/* alcIsExtensionPresent
 *
 * Determines if there is support for a particular extension
 */
ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!extName)
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    else
    {
        size_t len = strlen(extName);
        const char *ptr = (dev ? alcExtensionList : alcNoDeviceExtList);
        while(ptr && *ptr)
        {
            if(strncasecmp(ptr, extName, len) == 0 &&
               (ptr[len] == '\0' || isspace(ptr[len])))
                return ALC_TRUE;

            if((ptr=strchr(ptr, ' ')) != nullptr)
            {
                do {
                    ++ptr;
                } while(isspace(*ptr));
            }
        }
    }
    return ALC_FALSE;
}


/* alcGetProcAddress
 *
 * Retrieves the function address for a particular extension function
 */
ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
{
    if(!funcName)
    {
        DeviceRef dev{VerifyDevice(device)};
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    }
    else
    {
        for(const auto &func : alcFunctions)
        {
            if(strcmp(func.funcName, funcName) == 0)
                return func.address;
        }
    }

    return nullptr;
}


/* alcGetEnumValue
 *
 * Get the value for a particular ALC enumeration name
 */
ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
{
    if(!enumName)
    {
        DeviceRef dev{VerifyDevice(device)};
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    }
    else
    {
        for(const auto &enm : alcEnumerations)
        {
            if(strcmp(enm.enumName, enumName) == 0)
                return enm.value;
        }
    }

    return 0;
}


/* alcCreateContext
 *
 * Create and attach a context to the given device.
 */
ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
{
    /* Explicitly hold the list lock while taking the StateLock in case the
     * device is asynchronously destroyed, to ensure this new context is
     * properly cleaned up after being made.
     */
    std::unique_lock<std::recursive_mutex> listlock{ListLock};
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type == Capture || !dev->Connected.load(std::memory_order_relaxed))
    {
        listlock.unlock();
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
        return nullptr;
    }
    std::unique_lock<std::mutex> statelock{dev->StateLock};
    listlock.unlock();

    dev->LastError.store(ALC_NO_ERROR);

    ContextRef ALContext{new ALCcontext{dev.get()}};
    ALCdevice_IncRef(ALContext->Device);

    ALCenum err{UpdateDeviceParams(dev.get(), attrList)};
    if(err != ALC_NO_ERROR)
    {
        alcSetError(dev.get(), err);
        if(err == ALC_INVALID_DEVICE)
            aluHandleDisconnect(dev.get(), "Device update failure");
        statelock.unlock();

        return nullptr;
    }
    AllocateVoices(ALContext.get(), 256, dev->NumAuxSends);

    if(DefaultEffect.type != AL_EFFECT_NULL && dev->Type == Playback)
    {
        void *ptr{al_calloc(16, sizeof(ALeffectslot))};
        ALContext->DefaultSlot = std::unique_ptr<ALeffectslot>{new (ptr) ALeffectslot{}};
        if(InitEffectSlot(ALContext->DefaultSlot.get()) == AL_NO_ERROR)
            aluInitEffectPanning(ALContext->DefaultSlot.get(), dev.get());
        else
        {
            ALContext->DefaultSlot = nullptr;
            ERR("Failed to initialize the default effect slot\n");
        }
    }

    InitContext(ALContext.get());

    ALfloat valf{};
    if(ConfigValueFloat(dev->DeviceName.c_str(), nullptr, "volume-adjust", &valf))
    {
        if(!std::isfinite(valf))
            ERR("volume-adjust must be finite: %f\n", valf);
        else
        {
            ALfloat db = clampf(valf, -24.0f, 24.0f);
            if(db != valf)
                WARN("volume-adjust clamped: %f, range: +/-%f\n", valf, 24.0f);
            ALContext->GainBoost = std::pow(10.0f, db/20.0f);
            TRACE("volume-adjust gain: %f\n", ALContext->GainBoost);
        }
    }
    UpdateListenerProps(ALContext.get());

    {
        ALCcontext *head = dev->ContextList.load();
        do {
            ALContext->next.store(head, std::memory_order_relaxed);
        } while(!dev->ContextList.compare_exchange_weak(head, ALContext.get()));
        ALCcontext_IncRef(ALContext.get());
    }
    statelock.unlock();

    if(ALContext->DefaultSlot)
    {
        if(InitializeEffect(ALContext.get(), ALContext->DefaultSlot.get(), &DefaultEffect) == AL_NO_ERROR)
            UpdateEffectSlotProps(ALContext->DefaultSlot.get(), ALContext.get());
        else
            ERR("Failed to initialize the default effect\n");
    }

    TRACE("Created context %p\n", ALContext.get());
    return ALContext.get();
}

/* alcDestroyContext
 *
 * Remove a context from its device
 */
ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
{
    std::unique_lock<std::recursive_mutex> listlock{ListLock};
    ContextRef ctx{VerifyContext(context)};
    if(!ctx)
    {
        listlock.unlock();
        alcSetError(nullptr, ALC_INVALID_CONTEXT);
        return;
    }

    ALCdevice* Device{ctx->Device};
    if(Device)
    {
        std::lock_guard<std::mutex> _{Device->StateLock};
        if(!ReleaseContext(ctx.get(), Device))
        {
            Device->Backend->stop();
            Device->Flags &= ~DEVICE_RUNNING;
        }
    }
    listlock.unlock();
}


/* alcGetCurrentContext
 *
 * Returns the currently active context on the calling thread
 */
ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void)
{
    ALCcontext *Context{LocalContext.get()};
    if(!Context) Context = GlobalContext.load();
    return Context;
}

/* alcGetThreadContext
 *
 * Returns the currently active thread-local context
 */
ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
{
    return LocalContext.get();
}


/* alcMakeContextCurrent
 *
 * Makes the given context the active process-wide context, and removes the
 * thread-local context for the calling thread.
 */
ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
{
    /* context must be valid or nullptr */
    ContextRef ctx;
    if(context)
    {
        ctx = VerifyContext(context);
        if(!ctx)
        {
            alcSetError(nullptr, ALC_INVALID_CONTEXT);
            return ALC_FALSE;
        }
    }
    /* Release this reference (if any) to store it in the GlobalContext
     * pointer. Take ownership of the reference (if any) that was previously
     * stored there.
     */
    ctx = ContextRef{GlobalContext.exchange(ctx.release())};

    /* Reset (decrement) the previous global reference by replacing it with the
     * thread-local context. Take ownership of the thread-local context
     * reference (if any), clearing the storage to null.
     */
    ctx = ContextRef{LocalContext.get()};
    if(ctx) LocalContext.set(nullptr);
    /* Reset (decrement) the previous thread-local reference. */

    return ALC_TRUE;
}

/* alcSetThreadContext
 *
 * Makes the given context the active context for the current thread
 */
ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
{
    /* context must be valid or nullptr */
    ContextRef ctx;
    if(context)
    {
        ctx = VerifyContext(context);
        if(!ctx)
        {
            alcSetError(nullptr, ALC_INVALID_CONTEXT);
            return ALC_FALSE;
        }
    }
    /* context's reference count is already incremented */
    ContextRef old{LocalContext.get()};
    LocalContext.set(ctx.release());

    return ALC_TRUE;
}


/* alcGetContextsDevice
 *
 * Returns the device that a particular context is attached to
 */
ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
{
    ContextRef ctx{VerifyContext(Context)};
    if(!ctx)
    {
        alcSetError(nullptr, ALC_INVALID_CONTEXT);
        return nullptr;
    }
    return ctx->Device;
}


/* alcOpenDevice
 *
 * Opens the named device.
 */
ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
{
    DO_INITCONFIG();

    if(!PlaybackBackend.name)
    {
        alcSetError(nullptr, ALC_INVALID_VALUE);
        return nullptr;
    }

    if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0
#ifdef _WIN32
        /* Some old Windows apps hardcode these expecting OpenAL to use a
         * specific audio API, even when they're not enumerated. Creative's
         * router effectively ignores them too.
         */
        || strcasecmp(deviceName, "DirectSound3D") == 0 || strcasecmp(deviceName, "DirectSound") == 0
        || strcasecmp(deviceName, "MMSYSTEM") == 0
#endif
    ))
        deviceName = nullptr;

    DeviceRef device{new ALCdevice{Playback}};

    //Set output format
    device->FmtChans = DevFmtChannelsDefault;
    device->FmtType = DevFmtTypeDefault;
    device->Frequency = DEFAULT_OUTPUT_RATE;
    device->UpdateSize = DEFAULT_UPDATE_SIZE;
    device->NumUpdates = DEFAULT_NUM_UPDATES;
    device->LimiterState = ALC_TRUE;

    device->SourcesMax = 256;
    device->AuxiliaryEffectSlotMax = 64;
    device->NumAuxSends = DEFAULT_SENDS;

    const ALCchar *fmt{};
    if(ConfigValueStr(deviceName, nullptr, "channels", &fmt))
    {
        static constexpr struct ChannelMap {
            const char name[16];
            DevFmtChannels chans;
            ALsizei order;
        } chanlist[] = {
            { "mono",       DevFmtMono,   0 },
            { "stereo",     DevFmtStereo, 0 },
            { "quad",       DevFmtQuad,   0 },
            { "surround51", DevFmtX51,    0 },
            { "surround61", DevFmtX61,    0 },
            { "surround71", DevFmtX71,    0 },
            { "surround51rear", DevFmtX51Rear, 0 },
            { "ambi1", DevFmtAmbi3D, 1 },
            { "ambi2", DevFmtAmbi3D, 2 },
            { "ambi3", DevFmtAmbi3D, 3 },
        };

        auto iter = std::find_if(std::begin(chanlist), std::end(chanlist),
            [fmt](const ChannelMap &entry) -> bool
            { return strcasecmp(entry.name, fmt) == 0; }
        );
        if(iter == std::end(chanlist))
            ERR("Unsupported channels: %s\n", fmt);
        else
        {
            device->FmtChans = iter->chans;
            device->mAmbiOrder = iter->order;
            device->Flags |= DEVICE_CHANNELS_REQUEST;
        }
    }
    if(ConfigValueStr(deviceName, nullptr, "sample-type", &fmt))
    {
        static constexpr struct TypeMap {
            const char name[16];
            DevFmtType type;
        } typelist[] = {
            { "int8",    DevFmtByte   },
            { "uint8",   DevFmtUByte  },
            { "int16",   DevFmtShort  },
            { "uint16",  DevFmtUShort },
            { "int32",   DevFmtInt    },
            { "uint32",  DevFmtUInt   },
            { "float32", DevFmtFloat  },
        };

        auto iter = std::find_if(std::begin(typelist), std::end(typelist),
            [fmt](const TypeMap &entry) -> bool
            { return strcasecmp(entry.name, fmt) == 0; }
        );
        if(iter == std::end(typelist))
            ERR("Unsupported sample-type: %s\n", fmt);
        else
        {
            device->FmtType = iter->type;
            device->Flags |= DEVICE_SAMPLE_TYPE_REQUEST;
        }
    }

    ALuint freq{};
    if(ConfigValueUInt(deviceName, nullptr, "frequency", &freq) && freq > 0)
    {
        if(freq < MIN_OUTPUT_RATE)
        {
            ERR("%uhz request clamped to %uhz minimum\n", freq, MIN_OUTPUT_RATE);
            freq = MIN_OUTPUT_RATE;
        }
        device->NumUpdates = (device->NumUpdates*freq + device->Frequency/2) / device->Frequency;
        device->Frequency = freq;
        device->Flags |= DEVICE_FREQUENCY_REQUEST;
    }

    ConfigValueUInt(deviceName, nullptr, "periods", &device->NumUpdates);
    device->NumUpdates = clampu(device->NumUpdates, 2, 16);

    ConfigValueUInt(deviceName, nullptr, "period_size", &device->UpdateSize);
    device->UpdateSize = clampu(device->UpdateSize, 64, 8192);
    if((CPUCapFlags&(CPU_CAP_SSE|CPU_CAP_NEON)) != 0)
        device->UpdateSize = (device->UpdateSize+3u)&~3u;

    ConfigValueUInt(deviceName, nullptr, "sources", &device->SourcesMax);
    if(device->SourcesMax == 0) device->SourcesMax = 256;

    ConfigValueUInt(deviceName, nullptr, "slots", &device->AuxiliaryEffectSlotMax);
    if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 64;
    else device->AuxiliaryEffectSlotMax = minu(device->AuxiliaryEffectSlotMax, INT_MAX);

    if(ConfigValueInt(deviceName, nullptr, "sends", &device->NumAuxSends))
        device->NumAuxSends = clampi(
            DEFAULT_SENDS, 0, clampi(device->NumAuxSends, 0, MAX_SENDS)
        );

    device->NumStereoSources = 1;
    device->NumMonoSources = device->SourcesMax - device->NumStereoSources;

    device->Backend = PlaybackBackend.getFactory().createBackend(device.get(),
        BackendType::Playback);
    if(!device->Backend)
    {
        alcSetError(nullptr, ALC_OUT_OF_MEMORY);
        return nullptr;
    }

    // Find a playback device to open
    ALCenum err{device->Backend->open(deviceName)};
    if(err != ALC_NO_ERROR)
    {
        alcSetError(nullptr, err);
        return nullptr;
    }

    if(ConfigValueStr(device->DeviceName.c_str(), nullptr, "ambi-format", &fmt))
    {
        if(strcasecmp(fmt, "fuma") == 0)
        {
            if(device->mAmbiOrder > 3)
                ERR("FuMa is incompatible with %d%s order ambisonics (up to third-order only)\n",
                    device->mAmbiOrder,
                    (((device->mAmbiOrder%100)/10) == 1) ? "th" :
                    ((device->mAmbiOrder%10) == 1) ? "st" :
                    ((device->mAmbiOrder%10) == 2) ? "nd" :
                    ((device->mAmbiOrder%10) == 3) ? "rd" : "th");
            else
            {
                device->mAmbiLayout = AmbiLayout::FuMa;
                device->mAmbiScale = AmbiNorm::FuMa;
            }
        }
        else if(strcasecmp(fmt, "ambix") == 0 || strcasecmp(fmt, "acn+sn3d") == 0)
        {
            device->mAmbiLayout = AmbiLayout::ACN;
            device->mAmbiScale = AmbiNorm::SN3D;
        }
        else if(strcasecmp(fmt, "acn+n3d") == 0)
        {
            device->mAmbiLayout = AmbiLayout::ACN;
            device->mAmbiScale = AmbiNorm::N3D;
        }
        else
            ERR("Unsupported ambi-format: %s\n", fmt);
    }

    {
        ALCdevice *head{DeviceList.load()};
        do {
            device->next.store(head, std::memory_order_relaxed);
        } while(!DeviceList.compare_exchange_weak(head, device.get()));
        ALCdevice_IncRef(device.get());
    }

    TRACE("Created device %p, \"%s\"\n", device.get(), device->DeviceName.c_str());
    return device.get();
}

/* alcCloseDevice
 *
 * Closes the given device.
 */
ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device)
{
    std::unique_lock<std::recursive_mutex> listlock{ListLock};
    ALCdevice *iter{DeviceList.load()};
    do {
        if(iter == device)
            break;
        iter = iter->next.load(std::memory_order_relaxed);
    } while(iter != nullptr);
    if(!iter || iter->Type == Capture)
    {
        alcSetError(iter, ALC_INVALID_DEVICE);
        return ALC_FALSE;
    }
    std::unique_lock<std::mutex> statelock{device->StateLock};

    ALCdevice *origdev{device};
    ALCdevice *nextdev{device->next.load(std::memory_order_relaxed)};
    if(!DeviceList.compare_exchange_strong(origdev, nextdev))
    {
        ALCdevice *list;
        do {
            list = origdev;
            origdev = device;
        } while(!list->next.compare_exchange_strong(origdev, nextdev));
    }
    listlock.unlock();

    ALCcontext *ctx{device->ContextList.load()};
    while(ctx != nullptr)
    {
        ALCcontext *next = ctx->next.load(std::memory_order_relaxed);
        WARN("Releasing context %p\n", ctx);
        ReleaseContext(ctx, device);
        ctx = next;
    }
    if((device->Flags&DEVICE_RUNNING))
        device->Backend->stop();
    device->Flags &= ~DEVICE_RUNNING;
    statelock.unlock();

    ALCdevice_DecRef(device);

    return ALC_TRUE;
}


/************************************************
 * ALC capture functions
 ************************************************/
ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples)
{
    DO_INITCONFIG();

    if(!CaptureBackend.name)
    {
        alcSetError(nullptr, ALC_INVALID_VALUE);
        return nullptr;
    }

    if(samples <= 0)
    {
        alcSetError(nullptr, ALC_INVALID_VALUE);
        return nullptr;
    }

    if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0))
        deviceName = nullptr;

    DeviceRef device{new ALCdevice{Capture}};

    device->Frequency = frequency;
    device->Flags |= DEVICE_FREQUENCY_REQUEST;

    if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
    {
        alcSetError(nullptr, ALC_INVALID_ENUM);
        return nullptr;
    }
    device->Flags |= DEVICE_CHANNELS_REQUEST | DEVICE_SAMPLE_TYPE_REQUEST;

    device->UpdateSize = samples;
    device->NumUpdates = 1;

    device->Backend = CaptureBackend.getFactory().createBackend(device.get(),
        BackendType::Capture);
    if(!device->Backend)
    {
        alcSetError(nullptr, ALC_OUT_OF_MEMORY);
        return nullptr;
    }

    TRACE("Capture format: %s, %s, %uhz, %u update size x%d\n",
        DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
        device->Frequency, device->UpdateSize, device->NumUpdates
    );
    ALCenum err{device->Backend->open(deviceName)};
    if(err != ALC_NO_ERROR)
    {
        alcSetError(nullptr, err);
        return nullptr;
    }

    {
        ALCdevice *head{DeviceList.load()};
        do {
            device->next.store(head, std::memory_order_relaxed);
        } while(!DeviceList.compare_exchange_weak(head, device.get()));
        ALCdevice_IncRef(device.get());
    }

    TRACE("Created device %p, \"%s\"\n", device.get(), device->DeviceName.c_str());
    return device.get();
}

ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device)
{
    std::unique_lock<std::recursive_mutex> listlock{ListLock};

    ALCdevice *iter{DeviceList.load()};
    do {
        if(iter == device)
            break;
        iter = iter->next.load(std::memory_order_relaxed);
    } while(iter != nullptr);
    if(!iter || iter->Type != Capture)
    {
        alcSetError(iter, ALC_INVALID_DEVICE);
        return ALC_FALSE;
    }

    ALCdevice *origdev{device};
    ALCdevice *nextdev{device->next.load(std::memory_order_relaxed)};
    if(!DeviceList.compare_exchange_strong(origdev, nextdev))
    {
        ALCdevice *list;
        do {
            list = origdev;
            origdev = device;
        } while(!list->next.compare_exchange_strong(origdev, nextdev));
    }
    listlock.unlock();

    { std::lock_guard<std::mutex> _{device->StateLock};
        if((device->Flags&DEVICE_RUNNING))
            device->Backend->stop();
        device->Flags &= ~DEVICE_RUNNING;
    }

    ALCdevice_DecRef(device);

    return ALC_TRUE;
}

ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Capture)
    {
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
        return;
    }

    std::lock_guard<std::mutex> _{dev->StateLock};
    if(!dev->Connected.load(std::memory_order_acquire))
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
    else if(!(dev->Flags&DEVICE_RUNNING))
    {
        if(dev->Backend->start())
            dev->Flags |= DEVICE_RUNNING;
        else
        {
            aluHandleDisconnect(dev.get(), "Device start failure");
            alcSetError(dev.get(), ALC_INVALID_DEVICE);
        }
    }
}

ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Capture)
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
    else
    {
        std::lock_guard<std::mutex> _{dev->StateLock};
        if((dev->Flags&DEVICE_RUNNING))
            dev->Backend->stop();
        dev->Flags &= ~DEVICE_RUNNING;
    }
}

ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Capture)
    {
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
        return;
    }

    ALCenum err{ALC_INVALID_VALUE};
    { std::lock_guard<std::mutex> _{dev->StateLock};
        BackendBase *backend{dev->Backend.get()};
        if(samples >= 0 && backend->availableSamples() >= static_cast<ALCuint>(samples))
            err = backend->captureSamples(buffer, samples);
    }
    if(err != ALC_NO_ERROR)
        alcSetError(dev.get(), err);
}


/************************************************
 * ALC loopback functions
 ************************************************/

/* alcLoopbackOpenDeviceSOFT
 *
 * Open a loopback device, for manual rendering.
 */
ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName)
{
    DO_INITCONFIG();

    /* Make sure the device name, if specified, is us. */
    if(deviceName && strcmp(deviceName, alcDefaultName) != 0)
    {
        alcSetError(nullptr, ALC_INVALID_VALUE);
        return nullptr;
    }

    DeviceRef device{new ALCdevice{Loopback}};

    device->SourcesMax = 256;
    device->AuxiliaryEffectSlotMax = 64;
    device->NumAuxSends = DEFAULT_SENDS;

    //Set output format
    device->NumUpdates = 0;
    device->UpdateSize = 0;

    device->Frequency = DEFAULT_OUTPUT_RATE;
    device->FmtChans = DevFmtChannelsDefault;
    device->FmtType = DevFmtTypeDefault;

    ConfigValueUInt(nullptr, nullptr, "sources", &device->SourcesMax);
    if(device->SourcesMax == 0) device->SourcesMax = 256;

    ConfigValueUInt(nullptr, nullptr, "slots", &device->AuxiliaryEffectSlotMax);
    if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 64;
    else device->AuxiliaryEffectSlotMax = minu(device->AuxiliaryEffectSlotMax, INT_MAX);

    if(ConfigValueInt(nullptr, nullptr, "sends", &device->NumAuxSends))
        device->NumAuxSends = clampi(
            DEFAULT_SENDS, 0, clampi(device->NumAuxSends, 0, MAX_SENDS)
        );

    device->NumStereoSources = 1;
    device->NumMonoSources = device->SourcesMax - device->NumStereoSources;

    device->Backend = LoopbackBackendFactory::getFactory().createBackend(device.get(),
        BackendType::Playback);
    if(!device->Backend)
    {
        alcSetError(nullptr, ALC_OUT_OF_MEMORY);
        return nullptr;
    }

    // Open the "backend"
    device->Backend->open("Loopback");

    {
        ALCdevice *head{DeviceList.load()};
        do {
            device->next.store(head, std::memory_order_relaxed);
        } while(!DeviceList.compare_exchange_weak(head, device.get()));
        ALCdevice_IncRef(device.get());
    }

    TRACE("Created device %p\n", device.get());
    return device.get();
}

/* alcIsRenderFormatSupportedSOFT
 *
 * Determines if the loopback device supports the given format for rendering.
 */
ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Loopback)
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
    else if(freq <= 0)
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    else
    {
        if(IsValidALCType(type) && IsValidALCChannels(channels) && freq >= MIN_OUTPUT_RATE)
            return ALC_TRUE;
    }

    return ALC_FALSE;
}

/* alcRenderSamplesSOFT
 *
 * Renders some samples into a buffer, using the format last set by the
 * attributes given to alcCreateContext.
 */
FORCE_ALIGN ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Loopback)
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
    else if(samples < 0 || (samples > 0 && buffer == nullptr))
        alcSetError(dev.get(), ALC_INVALID_VALUE);
    else
    {
        BackendLockGuard _{*device->Backend};
        aluMixData(dev.get(), buffer, samples);
    }
}


/************************************************
 * ALC DSP pause/resume functions
 ************************************************/

/* alcDevicePauseSOFT
 *
 * Pause the DSP to stop audio processing.
 */
ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Playback)
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
    else
    {
        std::lock_guard<std::mutex> _{dev->StateLock};
        if((dev->Flags&DEVICE_RUNNING))
            dev->Backend->stop();
        dev->Flags &= ~DEVICE_RUNNING;
        dev->Flags |= DEVICE_PAUSED;
    }
}

/* alcDeviceResumeSOFT
 *
 * Resume the DSP to restart audio processing.
 */
ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type != Playback)
    {
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
        return;
    }

    std::lock_guard<std::mutex> _{dev->StateLock};
    if(!(dev->Flags&DEVICE_PAUSED))
        return;
    dev->Flags &= ~DEVICE_PAUSED;
    if(dev->ContextList.load() == nullptr)
        return;

    if(dev->Backend->start() == ALC_FALSE)
    {
        aluHandleDisconnect(dev.get(), "Device start failure");
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
        return;
    }
    dev->Flags |= DEVICE_RUNNING;
}


/************************************************
 * ALC HRTF functions
 ************************************************/

/* alcGetStringiSOFT
 *
 * Gets a string parameter at the given index.
 */
ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index)
{
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type == Capture)
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
    else switch(paramName)
    {
        case ALC_HRTF_SPECIFIER_SOFT:
            if(index >= 0 && static_cast<size_t>(index) < dev->HrtfList.size())
                return dev->HrtfList[index].name.c_str();
            alcSetError(dev.get(), ALC_INVALID_VALUE);
            break;

        default:
            alcSetError(dev.get(), ALC_INVALID_ENUM);
            break;
    }

    return nullptr;
}

/* alcResetDeviceSOFT
 *
 * Resets the given device output, using the specified attribute list.
 */
ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs)
{
    std::unique_lock<std::recursive_mutex> listlock{ListLock};
    DeviceRef dev{VerifyDevice(device)};
    if(!dev || dev->Type == Capture)
    {
        listlock.unlock();
        alcSetError(dev.get(), ALC_INVALID_DEVICE);
        return ALC_FALSE;
    }
    std::lock_guard<std::mutex> _{dev->StateLock};
    listlock.unlock();

    /* Force the backend to stop mixing first since we're resetting. Also reset
     * the connected state so lost devices can attempt recover.
     */
    if((dev->Flags&DEVICE_RUNNING))
        dev->Backend->stop();
    dev->Flags &= ~DEVICE_RUNNING;
    device->Connected.store(true);

    ALCenum err{UpdateDeviceParams(dev.get(), attribs)};
    if(LIKELY(err == ALC_NO_ERROR)) return ALC_TRUE;

    alcSetError(dev.get(), err);
    if(err == ALC_INVALID_DEVICE)
        aluHandleDisconnect(dev.get(), "Device start failure");
    return ALC_FALSE;
}