summaryrefslogtreecommitdiffstats
path: root/src/VBox/Devices/Audio/DrvAudio.cpp
blob: 2257033e10adb74ab1893685bf2ac6bb914b1808 (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
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
/* $Id: DrvAudio.cpp $ */
/** @file
 * Intermediate audio driver - Connects the audio device emulation with the host backend.
 */

/*
 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DRV_AUDIO
#include <VBox/log.h>
#include <VBox/vmm/pdm.h>
#include <VBox/err.h>
#include <VBox/vmm/mm.h>
#include <VBox/vmm/pdmaudioifs.h>
#include <VBox/vmm/pdmaudioinline.h>
#include <VBox/vmm/pdmaudiohostenuminline.h>

#include <iprt/alloc.h>
#include <iprt/asm-math.h>
#include <iprt/assert.h>
#include <iprt/circbuf.h>
#include <iprt/req.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/uuid.h>

#include "VBoxDD.h"

#include <ctype.h>
#include <stdlib.h>

#include "AudioHlp.h"
#include "AudioMixBuffer.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** @name PDMAUDIOSTREAM_STS_XXX - Used internally by DRVAUDIOSTREAM::fStatus.
 * @{ */
/** No flags being set. */
#define PDMAUDIOSTREAM_STS_NONE                 UINT32_C(0)
/** Set if the stream is enabled, clear if disabled. */
#define PDMAUDIOSTREAM_STS_ENABLED              RT_BIT_32(0)
/** Set if the stream is paused.
 * Requires the ENABLED status to be set when used. */
#define PDMAUDIOSTREAM_STS_PAUSED               RT_BIT_32(1)
/** Output only: Set when the stream is draining.
 * Requires the ENABLED status to be set when used. */
#define PDMAUDIOSTREAM_STS_PENDING_DISABLE      RT_BIT_32(2)

/** Set if the backend for the stream has been created.
 *
 * This is generally always set after stream creation, but
 * can be cleared if the re-initialization of the stream fails later on.
 * Asynchronous init may still be incomplete, see
 * PDMAUDIOSTREAM_STS_BACKEND_READY. */
#define PDMAUDIOSTREAM_STS_BACKEND_CREATED      RT_BIT_32(3)
/** The backend is ready (PDMIHOSTAUDIO::pfnStreamInitAsync is done).
 * Requires the BACKEND_CREATED status to be set.  */
#define PDMAUDIOSTREAM_STS_BACKEND_READY        RT_BIT_32(4)
/** Set if the stream needs to be re-initialized by the device (i.e. call
 * PDMIAUDIOCONNECTOR::pfnStreamReInit). (The other status bits are preserved
 * and are worked as normal while in this state, so that the stream can
 * resume operation where it left off.)  */
#define PDMAUDIOSTREAM_STS_NEED_REINIT          RT_BIT_32(5)
/** Validation mask for PDMIAUDIOCONNECTOR. */
#define PDMAUDIOSTREAM_STS_VALID_MASK           UINT32_C(0x0000003f)
/** Asserts the validity of the given stream status mask for PDMIAUDIOCONNECTOR. */
#define PDMAUDIOSTREAM_STS_ASSERT_VALID(a_fStreamStatus) do { \
        AssertMsg(!((a_fStreamStatus) & ~PDMAUDIOSTREAM_STS_VALID_MASK), ("%#x\n", (a_fStreamStatus))); \
        Assert(!((a_fStreamStatus) & PDMAUDIOSTREAM_STS_PAUSED)          || ((a_fStreamStatus) & PDMAUDIOSTREAM_STS_ENABLED)); \
        Assert(!((a_fStreamStatus) & PDMAUDIOSTREAM_STS_PENDING_DISABLE) || ((a_fStreamStatus) & PDMAUDIOSTREAM_STS_ENABLED)); \
        Assert(!((a_fStreamStatus) & PDMAUDIOSTREAM_STS_BACKEND_READY)   || ((a_fStreamStatus) & PDMAUDIOSTREAM_STS_BACKEND_CREATED)); \
    } while (0)

/** @} */

/**
 * Experimental code for destroying all streams in a disabled direction rather
 * than just disabling them.
 *
 * Cannot be enabled yet because the code isn't complete and DrvAudio will
 * behave differently (incorrectly), see @bugref{9558#c5} for details.
 */
#if defined(DOXYGEN_RUNNING) || 0
# define DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
#endif


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Audio stream context.
 *
 * Needed for separating data from the guest and host side (per stream).
 */
typedef struct DRVAUDIOSTREAMCTX
{
    /** The stream's audio configuration. */
    PDMAUDIOSTREAMCFG   Cfg;
} DRVAUDIOSTREAMCTX;

/**
 * Capture state of a stream wrt backend.
 */
typedef enum DRVAUDIOCAPTURESTATE
{
    /** Invalid zero value.   */
    DRVAUDIOCAPTURESTATE_INVALID = 0,
    /** No capturing or pre-buffering.   */
    DRVAUDIOCAPTURESTATE_NO_CAPTURE,
    /** Regular capturing. */
    DRVAUDIOCAPTURESTATE_CAPTURING,
    /** Returning silence till the backend buffer has reched the configured
     *  pre-buffering level. */
    DRVAUDIOCAPTURESTATE_PREBUF,
    /** End of valid values. */
    DRVAUDIOCAPTURESTATE_END
} DRVAUDIOCAPTURESTATE;

/**
 * Play state of a stream wrt backend.
 */
typedef enum DRVAUDIOPLAYSTATE
{
    /** Invalid zero value.   */
    DRVAUDIOPLAYSTATE_INVALID = 0,
    /** No playback or pre-buffering.   */
    DRVAUDIOPLAYSTATE_NOPLAY,
    /** Playing w/o any prebuffering. */
    DRVAUDIOPLAYSTATE_PLAY,
    /** Parallel pre-buffering prior to a device switch (i.e. we're outputting to
     * the old device and pre-buffering the same data in parallel). */
    DRVAUDIOPLAYSTATE_PLAY_PREBUF,
    /** Initial pre-buffering or the pre-buffering for a device switch (if it
     * the device setup took less time than filling up the pre-buffer). */
    DRVAUDIOPLAYSTATE_PREBUF,
    /** The device initialization is taking too long, pre-buffering wraps around
     * and drops samples. */
    DRVAUDIOPLAYSTATE_PREBUF_OVERDUE,
    /** Same as play-prebuf, but we don't have a working output device any more. */
    DRVAUDIOPLAYSTATE_PREBUF_SWITCHING,
    /** Working on committing the pre-buffered data.
     * We'll typically leave this state immediately and go to PLAY, however if
     * the backend cannot handle all the pre-buffered data at once, we'll stay
     * here till it does. */
    DRVAUDIOPLAYSTATE_PREBUF_COMMITTING,
    /** End of valid values. */
    DRVAUDIOPLAYSTATE_END
} DRVAUDIOPLAYSTATE;


/**
 * Extended stream structure.
 */
typedef struct DRVAUDIOSTREAM
{
    /** The publicly visible bit. */
    PDMAUDIOSTREAM          Core;

    /** Just an extra magic to verify that we allocated the stream rather than some
     * faked up stuff from the device (DRVAUDIOSTREAM_MAGIC). */
    uintptr_t               uMagic;

    /** List entry in DRVAUDIO::LstStreams. */
    RTLISTNODE              ListEntry;

    /** Number of references to this stream.
     *  Only can be destroyed when the reference count reaches 0. */
    uint32_t volatile       cRefs;
    /** Stream status - PDMAUDIOSTREAM_STS_XXX. */
    uint32_t                fStatus;

    /** Data to backend-specific stream data.
     *  This data block will be casted by the backend to access its backend-dependent data.
     *
     *  That way the backends do not have access to the audio connector's data. */
    PPDMAUDIOBACKENDSTREAM  pBackend;

    /** Set if pfnStreamCreate returned VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED. */
    bool                    fNeedAsyncInit;
    /** The fImmediate parameter value for pfnStreamDestroy. */
    bool                    fDestroyImmediate;
    bool                    afPadding[2];

    /** Number of (re-)tries while re-initializing the stream. */
    uint32_t                cTriesReInit;

    /** The last backend state we saw.
     * This is used to detect state changes (for what that is worth).  */
    PDMHOSTAUDIOSTREAMSTATE enmLastBackendState;

    /** The pre-buffering threshold expressed in bytes. */
    uint32_t                cbPreBufThreshold;

    /** The pfnStreamInitAsync request handle. */
    PRTREQ                  hReqInitAsync;

    /** The nanosecond timestamp when the stream was started. */
    uint64_t                nsStarted;
    /** Internal stream position (as per pfnStreamPlay/pfnStreamCapture). */
    uint64_t                offInternal;

    /** Timestamp (in ns) since last trying to re-initialize.
     *  Might be 0 if has not been tried yet. */
    uint64_t                nsLastReInit;
    /** Timestamp (in ns) since last iteration. */
    uint64_t                nsLastIterated;
    /** Timestamp (in ns) since last playback / capture. */
    uint64_t                nsLastPlayedCaptured;
    /** Timestamp (in ns) since last read (input streams) or
     *  write (output streams). */
    uint64_t                nsLastReadWritten;


    /** Union for input/output specifics depending on enmDir. */
    union
    {
        /**
         * The specifics for an audio input stream.
         */
        struct
        {
            /** The capture state. */
            DRVAUDIOCAPTURESTATE enmCaptureState;

            struct
            {
                /** File for writing non-interleaved captures. */
                PAUDIOHLPFILE   pFileCapture;
            } Dbg;
            struct
            {
                uint32_t        cbBackendReadableBefore;
                uint32_t        cbBackendReadableAfter;
#ifdef VBOX_WITH_STATISTICS
                STAMPROFILE     ProfCapture;
                STAMPROFILE     ProfGetReadable;
                STAMPROFILE     ProfGetReadableBytes;
#endif
            } Stats;
        } In;

        /**
         * The specifics for an audio output stream.
         */
        struct
        {
            /** Space for pre-buffering. */
            uint8_t            *pbPreBuf;
            /** The size of the pre-buffer allocation (in bytes). */
            uint32_t            cbPreBufAlloc;
            /** The current pre-buffering read offset. */
            uint32_t            offPreBuf;
            /** Number of bytes we've pre-buffered. */
            uint32_t            cbPreBuffered;
            /** The play state. */
            DRVAUDIOPLAYSTATE   enmPlayState;

            struct
            {
                /** File for writing stream playback. */
                PAUDIOHLPFILE   pFilePlay;
            } Dbg;
            struct
            {
                uint32_t        cbBackendWritableBefore;
                uint32_t        cbBackendWritableAfter;
#ifdef VBOX_WITH_STATISTICS
                STAMPROFILE     ProfPlay;
                STAMPROFILE     ProfGetWritable;
                STAMPROFILE     ProfGetWritableBytes;
#endif
            } Stats;
        } Out;
    } RT_UNION_NM(u);
#ifdef VBOX_WITH_STATISTICS
    STAMPROFILE     StatProfGetState;
    STAMPROFILE     StatXfer;
#endif
} DRVAUDIOSTREAM;
/** Pointer to an extended stream structure. */
typedef DRVAUDIOSTREAM *PDRVAUDIOSTREAM;

/** Value for DRVAUDIOSTREAM::uMagic (Johann Sebastian Bach). */
#define DRVAUDIOSTREAM_MAGIC        UINT32_C(0x16850331)
/** Value for DRVAUDIOSTREAM::uMagic after destruction */
#define DRVAUDIOSTREAM_MAGIC_DEAD   UINT32_C(0x17500728)


/**
 * Audio driver configuration data, tweakable via CFGM.
 */
typedef struct DRVAUDIOCFG
{
    /** PCM properties to use. */
    PDMAUDIOPCMPROPS     Props;
    /** Whether using signed sample data or not.
     *  Needed in order to know whether there is a custom value set in CFGM or not.
     *  By default set to UINT8_MAX if not set to a custom value. */
    uint8_t              uSigned;
    /** Whether swapping endianess of sample data or not.
     *  Needed in order to know whether there is a custom value set in CFGM or not.
     *  By default set to UINT8_MAX if not set to a custom value. */
    uint8_t              uSwapEndian;
    /** Configures the period size (in ms).
     *  This value reflects the time in between each hardware interrupt on the
     *  backend (host) side. */
    uint32_t             uPeriodSizeMs;
    /** Configures the (ring) buffer size (in ms). Often is a multiple of uPeriodMs. */
    uint32_t             uBufferSizeMs;
    /** Configures the pre-buffering size (in ms).
     *  Time needed in buffer before the stream becomes active (pre buffering).
     *  The bigger this value is, the more latency for the stream will occur.
     *  Set to 0 to disable pre-buffering completely.
     *  By default set to UINT32_MAX if not set to a custom value. */
    uint32_t             uPreBufSizeMs;
    /** The driver's debugging configuration. */
    struct
    {
        /** Whether audio debugging is enabled or not. */
        bool             fEnabled;
        /** Where to store the debugging files. */
        char             szPathOut[RTPATH_MAX];
    } Dbg;
} DRVAUDIOCFG;
/** Pointer to tweakable audio configuration. */
typedef DRVAUDIOCFG *PDRVAUDIOCFG;
/** Pointer to const tweakable audio configuration. */
typedef DRVAUDIOCFG const *PCDRVAUDIOCFG;


/**
 * Audio driver instance data.
 *
 * @implements PDMIAUDIOCONNECTOR
 */
typedef struct DRVAUDIO
{
    /** Read/Write critical section for guarding changes to pHostDrvAudio and
     *  BackendCfg during deteach/attach.  Mostly taken in shared mode.
     * @note Locking order: Must be entered after CritSectGlobals.
     * @note Locking order: Must be entered after PDMAUDIOSTREAM::CritSect. */
    RTCRITSECTRW            CritSectHotPlug;
    /** Critical section for protecting:
     *      - LstStreams
     *      - cStreams
     *      - In.fEnabled
     *      - In.cStreamsFree
     *      - Out.fEnabled
     *      - Out.cStreamsFree
     * @note Locking order: Must be entered before PDMAUDIOSTREAM::CritSect.
     * @note Locking order: Must be entered before CritSectHotPlug. */
    RTCRITSECTRW            CritSectGlobals;
    /** List of audio streams (DRVAUDIOSTREAM). */
    RTLISTANCHOR            LstStreams;
    /** Number of streams in the list. */
    size_t                  cStreams;
    struct
    {
        /** Whether this driver's input streams are enabled or not.
         *  This flag overrides all the attached stream statuses. */
        bool                fEnabled;
        /** Max. number of free input streams.
         *  UINT32_MAX for unlimited streams. */
        uint32_t            cStreamsFree;
    } In;
    struct
    {
        /** Whether this driver's output streams are enabled or not.
         *  This flag overrides all the attached stream statuses. */
        bool                fEnabled;
        /** Max. number of free output streams.
         *  UINT32_MAX for unlimited streams. */
        uint32_t            cStreamsFree;
    } Out;

    /** Audio configuration settings retrieved from the backend.
     * The szName field is used for the DriverName config value till we get the
     * authoritative name from the backend (only for logging). */
    PDMAUDIOBACKENDCFG      BackendCfg;
    /** Our audio connector interface. */
    PDMIAUDIOCONNECTOR      IAudioConnector;
    /** Interface used by the host backend. */
    PDMIHOSTAUDIOPORT       IHostAudioPort;
    /** Pointer to the driver instance. */
    PPDMDRVINS              pDrvIns;
    /** Pointer to audio driver below us. */
    PPDMIHOSTAUDIO          pHostDrvAudio;

    /** Request pool if the backend needs it for async stream creation. */
    RTREQPOOL               hReqPool;

#ifdef VBOX_WITH_AUDIO_ENUM
    /** Handle to the timer for delayed re-enumeration of backend devices. */
    TMTIMERHANDLE           hEnumTimer;
    /** Unique name for the the disable-iteration timer.  */
    char                    szEnumTimerName[24];
#endif

    /** Input audio configuration values (static). */
    DRVAUDIOCFG             CfgIn;
    /** Output audio configuration values (static). */
    DRVAUDIOCFG             CfgOut;

    STAMCOUNTER             StatTotalStreamsCreated;
} DRVAUDIO;
/** Pointer to the instance data of an audio driver. */
typedef DRVAUDIO *PDRVAUDIO;
/** Pointer to const instance data of an audio driver. */
typedef DRVAUDIO const *PCDRVAUDIO;


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd);
static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd);
static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx);
#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
static int drvAudioStreamDestroyInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx);
static int drvAudioStreamReInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx);
#endif
static uint32_t drvAudioStreamRetainInternal(PDRVAUDIOSTREAM pStreamEx);
static uint32_t drvAudioStreamReleaseInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fMayDestroy);
static void drvAudioStreamResetInternal(PDRVAUDIOSTREAM pStreamEx);


/** Buffer size for drvAudioStreamStatusToStr.  */
# define DRVAUDIO_STATUS_STR_MAX sizeof("BACKEND_CREATED BACKEND_READY ENABLED PAUSED PENDING_DISABLED NEED_REINIT 0x12345678")

/**
 * Converts an audio stream status to a string.
 *
 * @returns pszDst
 * @param   pszDst      Buffer to convert into, at least minimum size is
 *                      DRVAUDIO_STATUS_STR_MAX.
 * @param   fStatus     Stream status flags to convert.
 */
static const char *drvAudioStreamStatusToStr(char pszDst[DRVAUDIO_STATUS_STR_MAX], uint32_t fStatus)
{
    static const struct
    {
        const char *pszMnemonic;
        uint32_t    cchMnemnonic;
        uint32_t    fFlag;
    } s_aFlags[] =
    {
        { RT_STR_TUPLE("BACKEND_CREATED "),  PDMAUDIOSTREAM_STS_BACKEND_CREATED  },
        { RT_STR_TUPLE("BACKEND_READY "),    PDMAUDIOSTREAM_STS_BACKEND_READY    },
        { RT_STR_TUPLE("ENABLED "),          PDMAUDIOSTREAM_STS_ENABLED          },
        { RT_STR_TUPLE("PAUSED "),           PDMAUDIOSTREAM_STS_PAUSED           },
        { RT_STR_TUPLE("PENDING_DISABLE "),  PDMAUDIOSTREAM_STS_PENDING_DISABLE  },
        { RT_STR_TUPLE("NEED_REINIT "),      PDMAUDIOSTREAM_STS_NEED_REINIT      },
    };
    if (!fStatus)
        strcpy(pszDst, "NONE");
    else
    {
        char *psz = pszDst;
        for (size_t i = 0; i < RT_ELEMENTS(s_aFlags); i++)
            if (fStatus & s_aFlags[i].fFlag)
            {
                memcpy(psz, s_aFlags[i].pszMnemonic, s_aFlags[i].cchMnemnonic);
                psz += s_aFlags[i].cchMnemnonic;
                fStatus &= ~s_aFlags[i].fFlag;
                if (!fStatus)
                    break;
            }
        if (fStatus == 0)
            psz[-1] = '\0';
        else
            psz += RTStrPrintf(psz, DRVAUDIO_STATUS_STR_MAX - (psz - pszDst), "%#x", fStatus);
        Assert((uintptr_t)(psz - pszDst) <= DRVAUDIO_STATUS_STR_MAX);
    }
    return pszDst;
}


/**
 * Get play state name string.
 */
static const char *drvAudioPlayStateName(DRVAUDIOPLAYSTATE enmState)
{
    switch (enmState)
    {
        case DRVAUDIOPLAYSTATE_INVALID:             return "INVALID";
        case DRVAUDIOPLAYSTATE_NOPLAY:              return "NOPLAY";
        case DRVAUDIOPLAYSTATE_PLAY:                return "PLAY";
        case DRVAUDIOPLAYSTATE_PLAY_PREBUF:         return "PLAY_PREBUF";
        case DRVAUDIOPLAYSTATE_PREBUF:              return "PREBUF";
        case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:      return "PREBUF_OVERDUE";
        case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:    return "PREBUF_SWITCHING";
        case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:   return "PREBUF_COMMITTING";
        case DRVAUDIOPLAYSTATE_END:
            break;
    }
    return "BAD";
}

#ifdef LOG_ENABLED
/**
 * Get capture state name string.
 */
static const char *drvAudioCaptureStateName(DRVAUDIOCAPTURESTATE enmState)
{
    switch (enmState)
    {
        case DRVAUDIOCAPTURESTATE_INVALID:          return "INVALID";
        case DRVAUDIOCAPTURESTATE_NO_CAPTURE:       return "NO_CAPTURE";
        case DRVAUDIOCAPTURESTATE_CAPTURING:        return "CAPTURING";
        case DRVAUDIOCAPTURESTATE_PREBUF:           return "PREBUF";
        case DRVAUDIOCAPTURESTATE_END:
            break;
    }
    return "BAD";
}
#endif

/**
 * Checks if the stream status is one that can be read from.
 *
 * @returns @c true if ready to be read from, @c false if not.
 * @param   fStatus     Stream status to evaluate, PDMAUDIOSTREAM_STS_XXX.
 * @note    Not for backend statuses (use PDMAudioStrmStatusBackendCanRead)!
 */
DECLINLINE(bool) PDMAudioStrmStatusCanRead(uint32_t fStatus)
{
    PDMAUDIOSTREAM_STS_ASSERT_VALID(fStatus);
    AssertReturn(!(fStatus & ~PDMAUDIOSTREAM_STS_VALID_MASK), false);
    return (fStatus & (  PDMAUDIOSTREAM_STS_BACKEND_CREATED
                       | PDMAUDIOSTREAM_STS_ENABLED
                       | PDMAUDIOSTREAM_STS_PAUSED
                       | PDMAUDIOSTREAM_STS_NEED_REINIT))
        == (  PDMAUDIOSTREAM_STS_BACKEND_CREATED
            | PDMAUDIOSTREAM_STS_ENABLED);
}

/**
 * Checks if the stream status is one that can be written to.
 *
 * @returns @c true if ready to be written to, @c false if not.
 * @param   fStatus     Stream status to evaluate, PDMAUDIOSTREAM_STS_XXX.
 * @note    Not for backend statuses (use PDMAudioStrmStatusBackendCanWrite)!
 */
DECLINLINE(bool) PDMAudioStrmStatusCanWrite(uint32_t fStatus)
{
    PDMAUDIOSTREAM_STS_ASSERT_VALID(fStatus);
    AssertReturn(!(fStatus & ~PDMAUDIOSTREAM_STS_VALID_MASK), false);
    return (fStatus & (  PDMAUDIOSTREAM_STS_BACKEND_CREATED
                       | PDMAUDIOSTREAM_STS_ENABLED
                       | PDMAUDIOSTREAM_STS_PAUSED
                       | PDMAUDIOSTREAM_STS_PENDING_DISABLE
                       | PDMAUDIOSTREAM_STS_NEED_REINIT))
        == (  PDMAUDIOSTREAM_STS_BACKEND_CREATED
            | PDMAUDIOSTREAM_STS_ENABLED);
}

/**
 * Checks if the stream status is a ready-to-operate one.
 *
 * @returns @c true if ready to operate, @c false if not.
 * @param   fStatus     Stream status to evaluate, PDMAUDIOSTREAM_STS_XXX.
 * @note    Not for backend statuses!
 */
DECLINLINE(bool) PDMAudioStrmStatusIsReady(uint32_t fStatus)
{
    PDMAUDIOSTREAM_STS_ASSERT_VALID(fStatus);
    AssertReturn(!(fStatus & ~PDMAUDIOSTREAM_STS_VALID_MASK), false);
    return (fStatus & (  PDMAUDIOSTREAM_STS_BACKEND_CREATED
                       | PDMAUDIOSTREAM_STS_ENABLED
                       | PDMAUDIOSTREAM_STS_NEED_REINIT))
        == (  PDMAUDIOSTREAM_STS_BACKEND_CREATED
            | PDMAUDIOSTREAM_STS_ENABLED);
}


/**
 * Wrapper around PDMIHOSTAUDIO::pfnStreamGetStatus and checks the result.
 *
 * @returns A PDMHOSTAUDIOSTREAMSTATE value.
 * @param   pThis       Pointer to the DrvAudio instance data.
 * @param   pStreamEx   The stream to get the backend status for.
 */
DECLINLINE(PDMHOSTAUDIOSTREAMSTATE) drvAudioStreamGetBackendState(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    if (pThis->pHostDrvAudio)
    {
        /* Don't call if the backend wasn't created for this stream (disabled). */
        if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
        {
            AssertPtrReturn(pThis->pHostDrvAudio->pfnStreamGetState, PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING);
            PDMHOSTAUDIOSTREAMSTATE enmState = pThis->pHostDrvAudio->pfnStreamGetState(pThis->pHostDrvAudio, pStreamEx->pBackend);
            Log9Func(("%s: %s\n", pStreamEx->Core.Cfg.szName, PDMHostAudioStreamStateGetName(enmState) ));
            Assert(   enmState > PDMHOSTAUDIOSTREAMSTATE_INVALID
                   && enmState < PDMHOSTAUDIOSTREAMSTATE_END
                   && (enmState != PDMHOSTAUDIOSTREAMSTATE_DRAINING || pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT));
            return enmState;
        }
    }
    Log9Func(("%s: not-working\n", pStreamEx->Core.Cfg.szName));
    return PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING;
}


/**
 * Worker for drvAudioStreamProcessBackendStateChange that completes draining.
 */
DECLINLINE(void) drvAudioStreamProcessBackendStateChangeWasDraining(PDRVAUDIOSTREAM pStreamEx)
{
    Log(("drvAudioStreamProcessBackendStateChange: Stream '%s': Done draining - disabling stream.\n", pStreamEx->Core.Cfg.szName));
    pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PENDING_DISABLE);
    drvAudioStreamResetInternal(pStreamEx);
}


/**
 * Processes backend state change.
 *
 * @returns the new state value.
 */
static PDMHOSTAUDIOSTREAMSTATE drvAudioStreamProcessBackendStateChange(PDRVAUDIOSTREAM pStreamEx,
                                                                       PDMHOSTAUDIOSTREAMSTATE enmNewState,
                                                                       PDMHOSTAUDIOSTREAMSTATE enmOldState)
{
    PDMAUDIODIR const           enmDir          = pStreamEx->Core.Cfg.enmDir;
#ifdef LOG_ENABLED
    DRVAUDIOPLAYSTATE const     enmPlayState    = enmDir == PDMAUDIODIR_OUT
                                                ? pStreamEx->Out.enmPlayState   : DRVAUDIOPLAYSTATE_INVALID;
    DRVAUDIOCAPTURESTATE const  enmCaptureState = enmDir == PDMAUDIODIR_IN
                                                ? pStreamEx->In.enmCaptureState : DRVAUDIOCAPTURESTATE_INVALID;
#endif
    Assert(enmNewState != enmOldState);
    Assert(enmOldState > PDMHOSTAUDIOSTREAMSTATE_INVALID && enmOldState < PDMHOSTAUDIOSTREAMSTATE_END);
    AssertReturn(enmNewState > PDMHOSTAUDIOSTREAMSTATE_INVALID && enmNewState < PDMHOSTAUDIOSTREAMSTATE_END, enmOldState);

    /*
     * Figure out what happend and how that reflects on the playback state and stuff.
     */
    switch (enmNewState)
    {
        case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
            /* Guess we're switching device. Nothing to do because the backend will tell us, right? */
            break;

        case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
        case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
            /* The stream has stopped working or is inactive.  Switch stop any draining & to noplay mode. */
            if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
                drvAudioStreamProcessBackendStateChangeWasDraining(pStreamEx);
            if (enmDir == PDMAUDIODIR_OUT)
                pStreamEx->Out.enmPlayState   = DRVAUDIOPLAYSTATE_NOPLAY;
            else
                pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_NO_CAPTURE;
            break;

        case PDMHOSTAUDIOSTREAMSTATE_OKAY:
            switch (enmOldState)
            {
                case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
                    /* Should be taken care of elsewhere, so do nothing. */
                    break;

                case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
                case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
                    /* Go back to pre-buffering/playing depending on whether it is enabled
                       or not, resetting the stream state. */
                    drvAudioStreamResetInternal(pStreamEx);
                    break;

                case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
                    /* Complete the draining. May race the iterate code. */
                    if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
                        drvAudioStreamProcessBackendStateChangeWasDraining(pStreamEx);
                    break;

                /* no default: */
                case PDMHOSTAUDIOSTREAMSTATE_OKAY: /* impossible */
                case PDMHOSTAUDIOSTREAMSTATE_INVALID:
                case PDMHOSTAUDIOSTREAMSTATE_END:
                case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
                    break;
            }
            break;

        case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
            /* We do all we need to do when issuing the DRAIN command. */
            Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE);
            break;

        /* no default: */
        case PDMHOSTAUDIOSTREAMSTATE_INVALID:
        case PDMHOSTAUDIOSTREAMSTATE_END:
        case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
            break;
    }

    if (enmDir == PDMAUDIODIR_OUT)
        LogFunc(("Output stream '%s': %s/%s -> %s/%s\n", pStreamEx->Core.Cfg.szName,
                 PDMHostAudioStreamStateGetName(enmOldState), drvAudioPlayStateName(enmPlayState),
                 PDMHostAudioStreamStateGetName(enmNewState), drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
    else
        LogFunc(("Input stream '%s': %s/%s -> %s/%s\n", pStreamEx->Core.Cfg.szName,
                 PDMHostAudioStreamStateGetName(enmOldState), drvAudioCaptureStateName(enmCaptureState),
                 PDMHostAudioStreamStateGetName(enmNewState), drvAudioCaptureStateName(pStreamEx->In.enmCaptureState) ));

    pStreamEx->enmLastBackendState = enmNewState;
    return enmNewState;
}


/**
 * This gets the backend state and handles changes compared to
 * DRVAUDIOSTREAM::enmLastBackendState (updated).
 *
 * @returns A PDMHOSTAUDIOSTREAMSTATE value.
 * @param   pThis       Pointer to the DrvAudio instance data.
 * @param   pStreamEx   The stream to get the backend status for.
 */
DECLINLINE(PDMHOSTAUDIOSTREAMSTATE) drvAudioStreamGetBackendStateAndProcessChanges(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
    if (pStreamEx->enmLastBackendState == enmBackendState)
        return enmBackendState;
    return drvAudioStreamProcessBackendStateChange(pStreamEx, enmBackendState, pStreamEx->enmLastBackendState);
}


#ifdef VBOX_WITH_AUDIO_ENUM
/**
 * Enumerates all host audio devices.
 *
 * This functionality might not be implemented by all backends and will return
 * VERR_NOT_SUPPORTED if not being supported.
 *
 * @note Must not hold the driver's critical section!
 *
 * @returns VBox status code.
 * @param   pThis               Driver instance to be called.
 * @param   fLog                Whether to print the enumerated device to the release log or not.
 * @param   pDevEnum            Where to store the device enumeration.
 *
 * @remarks This is currently ONLY used for release logging.
 */
static DECLCALLBACK(int) drvAudioDevicesEnumerateInternal(PDRVAUDIO pThis, bool fLog, PPDMAUDIOHOSTENUM pDevEnum)
{
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    int rc;

    /*
     * If the backend supports it, do a device enumeration.
     */
    if (pThis->pHostDrvAudio->pfnGetDevices)
    {
        PDMAUDIOHOSTENUM DevEnum;
        rc = pThis->pHostDrvAudio->pfnGetDevices(pThis->pHostDrvAudio, &DevEnum);
        if (RT_SUCCESS(rc))
        {
            if (fLog)
            {
                LogRel(("Audio: Found %RU16 devices for driver '%s'\n", DevEnum.cDevices, pThis->BackendCfg.szName));

                PPDMAUDIOHOSTDEV pDev;
                RTListForEach(&DevEnum.LstDevices, pDev, PDMAUDIOHOSTDEV, ListEntry)
                {
                    char szFlags[PDMAUDIOHOSTDEV_MAX_FLAGS_STRING_LEN];
                    LogRel(("Audio: Device '%s':\n"
                            "Audio:   ID              = %s\n"
                            "Audio:   Usage           = %s\n"
                            "Audio:   Flags           = %s\n"
                            "Audio:   Input channels  = %RU8\n"
                            "Audio:   Output channels = %RU8\n",
                            pDev->pszName, pDev->pszId ? pDev->pszId : "",
                            PDMAudioDirGetName(pDev->enmUsage), PDMAudioHostDevFlagsToString(szFlags, pDev->fFlags),
                            pDev->cMaxInputChannels, pDev->cMaxOutputChannels));
                }
            }

            if (pDevEnum)
                rc = PDMAudioHostEnumCopy(pDevEnum, &DevEnum, PDMAUDIODIR_INVALID /*all*/, true /*fOnlyCoreData*/);

            PDMAudioHostEnumDelete(&DevEnum);
        }
        else
        {
            if (fLog)
                LogRel(("Audio: Device enumeration for driver '%s' failed with %Rrc\n", pThis->BackendCfg.szName, rc));
            /* Not fatal. */
        }
    }
    else
    {
        rc = VERR_NOT_SUPPORTED;

        if (fLog)
            LogRel2(("Audio: Host driver '%s' does not support audio device enumeration, skipping\n", pThis->BackendCfg.szName));
    }

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    LogFunc(("Returning %Rrc\n", rc));
    return rc;
}
#endif /* VBOX_WITH_AUDIO_ENUM */


/*********************************************************************************************************************************
*   PDMIAUDIOCONNECTOR                                                                                                           *
*********************************************************************************************************************************/

/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnEnable}
 */
static DECLCALLBACK(int) drvAudioEnable(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir, bool fEnable)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    LogFlowFunc(("enmDir=%s fEnable=%d\n", PDMAudioDirGetName(enmDir), fEnable));

    /*
     * Figure which status flag variable is being updated.
     */
    bool *pfEnabled;
    if (enmDir == PDMAUDIODIR_IN)
        pfEnabled = &pThis->In.fEnabled;
    else if (enmDir == PDMAUDIODIR_OUT)
        pfEnabled = &pThis->Out.fEnabled;
    else
        AssertFailedReturn(VERR_INVALID_PARAMETER);

    /*
     * Grab the driver wide lock and check it.  Ignore call if no change.
     */
    int rc = RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
    AssertRCReturn(rc, rc);

    if (fEnable != *pfEnabled)
    {
        LogRel(("Audio: %s %s for driver '%s'\n",
                fEnable ? "Enabling" : "Disabling", PDMAudioDirGetName(enmDir), pThis->BackendCfg.szName));

        /*
         * When enabling, we must update flag before calling drvAudioStreamControlInternalBackend.
         */
        if (fEnable)
            *pfEnabled = true;

        /*
         * Update the backend status for the streams in the given direction.
         *
         * The pThis->Out.fEnable / pThis->In.fEnable status flags only reflect in the
         * direction of the backend, drivers and devices above us in the chain does not
         * know about this.  When disabled playback goes to /dev/null and we capture
         * only silence.  This means pStreamEx->fStatus holds the nominal status
         * and we'll use it to restore the operation.  (See also @bugref{9882}.)
         *
         * The DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION build time define
         * controls how this is implemented.
         */
        PDRVAUDIOSTREAM pStreamEx;
        RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
        {
            /** @todo duplex streams   */
            if (pStreamEx->Core.Cfg.enmDir == enmDir)
            {
                RTCritSectEnter(&pStreamEx->Core.CritSect);

                /*
                 * When (re-)enabling a stream, clear the disabled warning bit again.
                 */
                if (fEnable)
                    pStreamEx->Core.fWarningsShown &= ~PDMAUDIOSTREAM_WARN_FLAGS_DISABLED;

#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
                /*
                 * When enabling, we must make sure the stream has been created with the
                 * backend before enabling and maybe pausing it. When disabling we must
                 * destroy the stream. Paused includes enabled, as does draining, but we
                 * only want the former.
                 */
#else
                /*
                 * We don't need to do anything unless the stream is enabled.
                 * Paused includes enabled, as does draining, but we only want the former.
                 */
#endif
                uint32_t const fStatus = pStreamEx->fStatus;

#ifndef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
                if (fStatus & PDMAUDIOSTREAM_STS_ENABLED)
#endif
                {
                    const char *pszOperation;
                    int         rc2;
                    if (fEnable)
                    {
                        if (!(fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
                        {
#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
                            /* The backend shouldn't have been created, so do that before enabling
                               and possibly pausing the stream. */
                            if (!(fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED))
                                rc2 = drvAudioStreamReInitInternal(pThis, pStreamEx);
                            else
                                rc2 = VINF_SUCCESS;
                            pszOperation = "re-init";
                            if (RT_SUCCESS(rc2) && (fStatus & PDMAUDIOSTREAM_STS_ENABLED))
#endif
                            {
                                /** @todo r=bird: We need to redo pre-buffering OR switch to
                                 *        DRVAUDIOPLAYSTATE_PREBUF_SWITCHING playback mode when disabling
                                 *        output streams.  The former is preferred if associated with
                                 *        reporting the stream as INACTIVE. */
                                rc2 = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
                                pszOperation = "enable";
                                if (RT_SUCCESS(rc2) && (fStatus & PDMAUDIOSTREAM_STS_PAUSED))
                                {
                                    rc2 = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
                                    pszOperation = "pause";
                                }
                            }
                        }
                        else
                        {
                            rc2 = VINF_SUCCESS;
                            pszOperation = NULL;
                        }
                    }
                    else
                    {
#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
                        if (fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
                            rc2 = drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);
                        else
                            rc2 = VINF_SUCCESS;
                        pszOperation = "destroy";
#else
                        rc2 = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
                        pszOperation = "disable";
#endif
                    }
                    if (RT_FAILURE(rc2))
                    {
                        LogRel(("Audio: Failed to %s %s stream '%s': %Rrc\n",
                                pszOperation, PDMAudioDirGetName(enmDir), pStreamEx->Core.Cfg.szName, rc2));
                        if (RT_SUCCESS(rc))
                            rc = rc2;  /** @todo r=bird: This isn't entirely helpful to the caller since we'll update the status
                                        * regardless of the status code we return.  And anyway, there is nothing that can be done
                                        * about individual stream by the caller... */
                    }
                }

                RTCritSectLeave(&pStreamEx->Core.CritSect);
            }
        }

        /*
         * When disabling, we must update the status flag after the
         * drvAudioStreamControlInternalBackend(DISABLE) calls.
         */
        *pfEnabled = fEnable;
    }

    RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
    LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnIsEnabled}
 */
static DECLCALLBACK(bool) drvAudioIsEnabled(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
    AssertRCReturn(rc, false);

    bool fEnabled;
    if (enmDir == PDMAUDIODIR_IN)
        fEnabled = pThis->In.fEnabled;
    else if (enmDir == PDMAUDIODIR_OUT)
        fEnabled = pThis->Out.fEnabled;
    else
        AssertFailedStmt(fEnabled = false);

    RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
    return fEnabled;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnGetConfig}
 */
static DECLCALLBACK(int) drvAudioGetConfig(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOBACKENDCFG pCfg)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturn(rc, rc);

    if (pThis->pHostDrvAudio)
        rc = pThis->pHostDrvAudio->pfnGetConfig(pThis->pHostDrvAudio, pCfg);
    else
        rc = VERR_PDM_NO_ATTACHED_DRIVER;

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnGetStatus}
 */
static DECLCALLBACK(PDMAUDIOBACKENDSTS) drvAudioGetStatus(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturn(rc, PDMAUDIOBACKENDSTS_UNKNOWN);

    PDMAUDIOBACKENDSTS fBackendStatus;
    if (pThis->pHostDrvAudio)
    {
        if (pThis->pHostDrvAudio->pfnGetStatus)
            fBackendStatus = pThis->pHostDrvAudio->pfnGetStatus(pThis->pHostDrvAudio, enmDir);
        else
            fBackendStatus = PDMAUDIOBACKENDSTS_UNKNOWN;
    }
    else
        fBackendStatus = PDMAUDIOBACKENDSTS_NOT_ATTACHED;

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    LogFlowFunc(("LEAVE - %#x\n", fBackendStatus));
    return fBackendStatus;
}


/**
 * Frees an audio stream and its allocated resources.
 *
 * @param   pStreamEx   Audio stream to free. After this call the pointer will
 *                      not be valid anymore.
 */
static void drvAudioStreamFree(PDRVAUDIOSTREAM pStreamEx)
{
    if (pStreamEx)
    {
        LogFunc(("[%s]\n", pStreamEx->Core.Cfg.szName));
        Assert(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
        Assert(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC);

        pStreamEx->Core.uMagic    = ~PDMAUDIOSTREAM_MAGIC;
        pStreamEx->pBackend       = NULL;
        pStreamEx->uMagic         = DRVAUDIOSTREAM_MAGIC_DEAD;

        RTCritSectDelete(&pStreamEx->Core.CritSect);

        RTMemFree(pStreamEx);
    }
}


/**
 * Adjusts the request stream configuration, applying our settings.
 *
 * This also does some basic validations.
 *
 * Used by both the stream creation and stream configuration hinting code.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to the DrvAudio instance data.
 * @param   pCfg        The configuration that should be adjusted.
 * @param   pszName     Stream name to use when logging warnings and errors.
 */
static int drvAudioStreamAdjustConfig(PCDRVAUDIO pThis, PPDMAUDIOSTREAMCFG pCfg, const char *pszName)
{
    /* Get the right configuration for the stream to be created. */
    PCDRVAUDIOCFG pDrvCfg = pCfg->enmDir == PDMAUDIODIR_IN ? &pThis->CfgIn: &pThis->CfgOut;

    /* Fill in the tweakable parameters into the requested host configuration.
     * All parameters in principle can be changed and returned by the backend via the acquired configuration. */

    /*
     * PCM
     */
    if (PDMAudioPropsSampleSize(&pDrvCfg->Props) != 0) /* Anything set via custom extra-data? */
    {
        PDMAudioPropsSetSampleSize(&pCfg->Props, PDMAudioPropsSampleSize(&pDrvCfg->Props));
        LogRel2(("Audio: Using custom sample size of %RU8 bytes for stream '%s'\n",
                 PDMAudioPropsSampleSize(&pCfg->Props), pszName));
    }

    if (pDrvCfg->Props.uHz) /* Anything set via custom extra-data? */
    {
        pCfg->Props.uHz = pDrvCfg->Props.uHz;
        LogRel2(("Audio: Using custom Hz rate %RU32 for stream '%s'\n", pCfg->Props.uHz, pszName));
    }

    if (pDrvCfg->uSigned != UINT8_MAX) /* Anything set via custom extra-data? */
    {
        pCfg->Props.fSigned = RT_BOOL(pDrvCfg->uSigned);
        LogRel2(("Audio: Using custom %s sample format for stream '%s'\n",
                 pCfg->Props.fSigned ? "signed" : "unsigned", pszName));
    }

    if (pDrvCfg->uSwapEndian != UINT8_MAX) /* Anything set via custom extra-data? */
    {
        pCfg->Props.fSwapEndian = RT_BOOL(pDrvCfg->uSwapEndian);
        LogRel2(("Audio: Using custom %s endianess for samples of stream '%s'\n",
                 pCfg->Props.fSwapEndian ? "swapped" : "original", pszName));
    }

    if (PDMAudioPropsChannels(&pDrvCfg->Props) != 0) /* Anything set via custom extra-data? */
    {
        PDMAudioPropsSetChannels(&pCfg->Props, PDMAudioPropsChannels(&pDrvCfg->Props));
        LogRel2(("Audio: Using custom %RU8 channel(s) for stream '%s'\n", PDMAudioPropsChannels(&pDrvCfg->Props), pszName));
    }

    /* Validate PCM properties. */
    if (!AudioHlpPcmPropsAreValidAndSupported(&pCfg->Props))
    {
        LogRel(("Audio: Invalid custom PCM properties set for stream '%s', cannot create stream\n", pszName));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Buffer size
     */
    const char *pszWhat = "device-specific";
    if (pDrvCfg->uBufferSizeMs)
    {
        pCfg->Backend.cFramesBufferSize = PDMAudioPropsMilliToFrames(&pCfg->Props, pDrvCfg->uBufferSizeMs);
        pszWhat = "custom";
    }

    if (!pCfg->Backend.cFramesBufferSize) /* Set default buffer size if nothing explicitly is set. */
    {
        pCfg->Backend.cFramesBufferSize = PDMAudioPropsMilliToFrames(&pCfg->Props, 300 /*ms*/);
        pszWhat = "default";
    }

    LogRel2(("Audio: Using %s buffer size %RU64 ms / %RU32 frames for stream '%s'\n",
             pszWhat, PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesBufferSize),
             pCfg->Backend.cFramesBufferSize, pszName));

    /*
     * Period size
     */
    pszWhat = "device-specific";
    if (pDrvCfg->uPeriodSizeMs)
    {
        pCfg->Backend.cFramesPeriod = PDMAudioPropsMilliToFrames(&pCfg->Props, pDrvCfg->uPeriodSizeMs);
        pszWhat = "custom";
    }

    if (!pCfg->Backend.cFramesPeriod) /* Set default period size if nothing explicitly is set. */
    {
        pCfg->Backend.cFramesPeriod = pCfg->Backend.cFramesBufferSize / 4;
        pszWhat = "default";
    }

    if (pCfg->Backend.cFramesPeriod >= pCfg->Backend.cFramesBufferSize / 2)
    {
        LogRel(("Audio: Warning! Stream '%s': The stream period size (%RU64ms, %s) cannot be more than half the buffer size (%RU64ms)!\n",
                pszName, PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesPeriod), pszWhat,
                PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesBufferSize)));
        pCfg->Backend.cFramesPeriod = pCfg->Backend.cFramesBufferSize / 2;
    }

    LogRel2(("Audio: Using %s period size %RU64 ms / %RU32 frames for stream '%s'\n",
             pszWhat, PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesPeriod),
             pCfg->Backend.cFramesPeriod, pszName));

    /*
     * Pre-buffering size
     */
    pszWhat = "device-specific";
    if (pDrvCfg->uPreBufSizeMs != UINT32_MAX) /* Anything set via global / per-VM extra-data? */
    {
        pCfg->Backend.cFramesPreBuffering = PDMAudioPropsMilliToFrames(&pCfg->Props, pDrvCfg->uPreBufSizeMs);
        pszWhat = "custom";
    }
    else /* No, then either use the default or device-specific settings (if any). */
    {
        if (pCfg->Backend.cFramesPreBuffering == UINT32_MAX) /* Set default pre-buffering size if nothing explicitly is set. */
        {
            /* Pre-buffer 50% for both output & input. Capping both at 200ms.
               The 50% reasoning being that we need to have sufficient slack space
               in both directions as the guest DMA timer might be delayed by host
               scheduling as well as sped up afterwards because of TM catch-up. */
            uint32_t const cFramesMax = PDMAudioPropsMilliToFrames(&pCfg->Props, 200);
            pCfg->Backend.cFramesPreBuffering = pCfg->Backend.cFramesBufferSize / 2;
            pCfg->Backend.cFramesPreBuffering = RT_MIN(pCfg->Backend.cFramesPreBuffering, cFramesMax);
            pszWhat = "default";
        }
    }

    if (pCfg->Backend.cFramesPreBuffering >= pCfg->Backend.cFramesBufferSize)
    {
        LogRel(("Audio: Warning! Stream '%s': Pre-buffering (%RU64ms, %s) cannot equal or exceed the buffer size (%RU64ms)!\n",
                pszName,  PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesBufferSize), pszWhat,
                PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesPreBuffering) ));
        pCfg->Backend.cFramesPreBuffering = pCfg->Backend.cFramesBufferSize - 1;
    }

    LogRel2(("Audio: Using %s pre-buffering size %RU64 ms / %RU32 frames for stream '%s'\n",
             pszWhat, PDMAudioPropsFramesToMilli(&pCfg->Props, pCfg->Backend.cFramesPreBuffering),
             pCfg->Backend.cFramesPreBuffering, pszName));

    return VINF_SUCCESS;
}


/**
 * Worker thread function for drvAudioStreamConfigHint that's used when
 * PDMAUDIOBACKEND_F_ASYNC_HINT is in effect.
 */
static DECLCALLBACK(void) drvAudioStreamConfigHintWorker(PDRVAUDIO pThis, PPDMAUDIOSTREAMCFG pCfg)
{
    LogFlowFunc(("pThis=%p pCfg=%p\n", pThis, pCfg));
    AssertPtrReturnVoid(pCfg);
    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturnVoid(rc);

    PPDMIHOSTAUDIO const pHostDrvAudio = pThis->pHostDrvAudio;
    if (pHostDrvAudio)
    {
        AssertPtr(pHostDrvAudio->pfnStreamConfigHint);
        if (pHostDrvAudio->pfnStreamConfigHint)
            pHostDrvAudio->pfnStreamConfigHint(pHostDrvAudio, pCfg);
    }
    PDMAudioStrmCfgFree(pCfg);

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    LogFlowFunc(("returns\n"));
}


/**
 * Checks whether a given stream direction is enabled (permitted) or not.
 *
 * Currently there are only per-direction enabling/disabling of audio streams.
 * This lets a user disabling input so it an untrusted VM cannot listen in
 * without the user explicitly allowing it, or disable output so it won't
 * disturb your and cannot communicate with other VMs or machines
 *
 * See @bugref{9882}.
 *
 * @retval  true if the stream configuration is enabled/allowed.
 * @retval  false if not permitted.
 * @param   pThis   Pointer to the DrvAudio instance data.
 * @param   enmDir  The stream direction to check.
 */
DECLINLINE(bool) drvAudioStreamIsDirectionEnabled(PDRVAUDIO pThis, PDMAUDIODIR enmDir)
{
    switch (enmDir)
    {
        case PDMAUDIODIR_IN:
            return pThis->In.fEnabled;
        case PDMAUDIODIR_OUT:
            return pThis->Out.fEnabled;
        case PDMAUDIODIR_DUPLEX:
            return pThis->Out.fEnabled && pThis->In.fEnabled;
        default:
            AssertFailedReturn(false);
    }
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamConfigHint}
 */
static DECLCALLBACK(void) drvAudioStreamConfigHint(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAMCFG pCfg)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertReturnVoid(pCfg->enmDir == PDMAUDIODIR_IN || pCfg->enmDir == PDMAUDIODIR_OUT);

    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturnVoid(rc);

    /*
     * Don't do anything unless the backend has a pfnStreamConfigHint method
     * and the direction is currently enabled.
     */
    if (   pThis->pHostDrvAudio
        && pThis->pHostDrvAudio->pfnStreamConfigHint)
    {
        if (drvAudioStreamIsDirectionEnabled(pThis, pCfg->enmDir))
        {
            /*
             * Adjust the configuration (applying out settings) then call the backend driver.
             */
            rc = drvAudioStreamAdjustConfig(pThis, pCfg, pCfg->szName);
            AssertLogRelRC(rc);
            if (RT_SUCCESS(rc))
            {
                rc = VERR_CALLBACK_RETURN;
                if (pThis->BackendCfg.fFlags & PDMAUDIOBACKEND_F_ASYNC_HINT)
                {
                    PPDMAUDIOSTREAMCFG pDupCfg = PDMAudioStrmCfgDup(pCfg);
                    if (pDupCfg)
                    {
                        rc = RTReqPoolCallVoidNoWait(pThis->hReqPool, (PFNRT)drvAudioStreamConfigHintWorker, 2, pThis, pDupCfg);
                        if (RT_SUCCESS(rc))
                            LogFlowFunc(("Asynchronous call running on worker thread.\n"));
                        else
                            PDMAudioStrmCfgFree(pDupCfg);
                    }
                }
                if (RT_FAILURE_NP(rc))
                {
                    LogFlowFunc(("Doing synchronous call...\n"));
                    pThis->pHostDrvAudio->pfnStreamConfigHint(pThis->pHostDrvAudio, pCfg);
                }
            }
        }
        else
            LogFunc(("Ignoring hint because direction is not currently enabled\n"));
    }
    else
        LogFlowFunc(("Ignoring hint because backend has no pfnStreamConfigHint method.\n"));

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
}


/**
 * Common worker for synchronizing the ENABLED and PAUSED status bits with the
 * backend after it becomes ready.
 *
 * Used by async init and re-init.
 *
 * @note Is sometimes called w/o having entered DRVAUDIO::CritSectHotPlug.
 *       Caller must however own the stream critsect.
 */
static int drvAudioStreamUpdateBackendOnStatus(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, const char *pszWhen)
{
    int rc = VINF_SUCCESS;
    if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
    {
        rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
        if (RT_SUCCESS(rc))
        {
            if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PAUSED)
            {
                rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
                if (RT_FAILURE(rc))
                    LogRelMax(64, ("Audio: Failed to pause stream '%s' after %s: %Rrc\n", pStreamEx->Core.Cfg.szName, pszWhen, rc));
            }
        }
        else
            LogRelMax(64, ("Audio: Failed to enable stream '%s' after %s: %Rrc\n", pStreamEx->Core.Cfg.szName, pszWhen, rc));
    }
    return rc;
}


/**
 * For performing PDMIHOSTAUDIO::pfnStreamInitAsync on a worker thread.
 *
 * @param   pThis       Pointer to the DrvAudio instance data.
 * @param   pStreamEx   The stream.  One reference for us to release.
 */
static DECLCALLBACK(void) drvAudioStreamInitAsync(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    LogFlow(("pThis=%p pStreamEx=%p (%s)\n", pThis, pStreamEx, pStreamEx->Core.Cfg.szName));

    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturnVoid(rc);

    /*
     * Do the init job.
     */
    bool           fDestroyed;
    PPDMIHOSTAUDIO pIHostDrvAudio = pThis->pHostDrvAudio;
    AssertPtr(pIHostDrvAudio);
    if (pIHostDrvAudio && pIHostDrvAudio->pfnStreamInitAsync)
    {
        fDestroyed = pStreamEx->cRefs <= 1;
        rc = pIHostDrvAudio->pfnStreamInitAsync(pIHostDrvAudio, pStreamEx->pBackend, fDestroyed);
        LogFlow(("pfnStreamInitAsync returns %Rrc (on %p, fDestroyed=%d)\n", rc, pStreamEx, fDestroyed));
    }
    else
    {
        fDestroyed = true;
        rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
    }

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    RTCritSectEnter(&pStreamEx->Core.CritSect);

    /*
     * On success, update the backend on the stream status and mark it ready for business.
     */
    if (RT_SUCCESS(rc) && !fDestroyed)
    {
        RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

        /*
         * Update the backend state.
         */
        pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY; /* before the backend control call! */

        rc = drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "asynchronous initialization completed");

        /*
         * Modify the play state if output stream.
         */
        if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
        {
            DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
            switch (enmPlayState)
            {
                case DRVAUDIOPLAYSTATE_PREBUF:
                case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
                    break;
                case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
                    pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
                    break;
                case DRVAUDIOPLAYSTATE_NOPLAY:
                    pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
                    break;
                case DRVAUDIOPLAYSTATE_PLAY:
                case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
                    break; /* possible race here, so don't assert. */
                case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
                    AssertFailedBreak();
                /* no default */
                case DRVAUDIOPLAYSTATE_END:
                case DRVAUDIOPLAYSTATE_INVALID:
                    break;
            }
            LogFunc(("enmPlayState: %s -> %s\n", drvAudioPlayStateName(enmPlayState),
                     drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
        }

        /*
         * Update the last backend state.
         */
        pStreamEx->enmLastBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);

        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    }
    /*
     * Don't quite know what to do on failure...
     */
    else if (!fDestroyed)
    {
        LogRelMax(64, ("Audio: Failed to initialize stream '%s': %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
    }

    /*
     * Release the request handle, must be done while inside the critical section.
     */
    if (pStreamEx->hReqInitAsync != NIL_RTREQ)
    {
        LogFlowFunc(("Releasing hReqInitAsync=%p\n", pStreamEx->hReqInitAsync));
        RTReqRelease(pStreamEx->hReqInitAsync);
        pStreamEx->hReqInitAsync = NIL_RTREQ;
    }

    RTCritSectLeave(&pStreamEx->Core.CritSect);

    /*
     * Release our stream reference.
     */
    uint32_t cRefs = drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
    LogFlowFunc(("returns (fDestroyed=%d, cRefs=%u)\n", fDestroyed, cRefs)); RT_NOREF(cRefs);
}


/**
 * Worker for drvAudioStreamInitInternal and drvAudioStreamReInitInternal that
 * creates the backend (host driver) side of an audio stream.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to driver instance.
 * @param   pStreamEx   Stream to create backend for.  The Core.Cfg field
 *                      contains the requested configuration when we're called
 *                      and the actual configuration when successfully
 *                      returning.
 *
 * @note    Configuration precedence for requested audio stream configuration (first has highest priority, if set):
 *          - per global extra-data
 *          - per-VM extra-data
 *          - requested configuration (by pCfgReq)
 *          - default value
 */
static int drvAudioStreamCreateInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    AssertMsg((pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED) == 0,
              ("Stream '%s' already initialized in backend\n", pStreamEx->Core.Cfg.szName));

#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
    /*
     * Check if the stream direction is enabled (permitted).
     */
    if (!drvAudioStreamIsDirectionEnabled(pThis, pStreamEx->Core.Cfg.enmDir))
    {
        LogFunc(("Stream direction is disbled, returning w/o doing anything\n"));
        return VINF_SUCCESS;
    }
#endif

    /*
     * Adjust the stream config, applying defaults and any overriding settings.
     */
    int rc = drvAudioStreamAdjustConfig(pThis, &pStreamEx->Core.Cfg, pStreamEx->Core.Cfg.szName);
    if (RT_FAILURE(rc))
        return rc;
    PDMAUDIOSTREAMCFG const CfgReq = pStreamEx->Core.Cfg;

    /*
     * Call the host driver to create the stream.
     */
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    AssertLogRelMsgStmt(RT_VALID_PTR(pThis->pHostDrvAudio),
                        ("Audio: %p\n", pThis->pHostDrvAudio), rc = VERR_PDM_NO_ATTACHED_DRIVER);
    if (RT_SUCCESS(rc))
        AssertLogRelMsgStmt(pStreamEx->Core.cbBackend == pThis->BackendCfg.cbStream,
                            ("Audio: Backend changed? cbBackend changed from %#x to %#x\n",
                             pStreamEx->Core.cbBackend, pThis->BackendCfg.cbStream),
                            rc = VERR_STATE_CHANGED);
    if (RT_SUCCESS(rc))
        rc = pThis->pHostDrvAudio->pfnStreamCreate(pThis->pHostDrvAudio, pStreamEx->pBackend, &CfgReq, &pStreamEx->Core.Cfg);
    if (RT_SUCCESS(rc))
    {
        pStreamEx->enmLastBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);

        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);

        AssertLogRelReturn(pStreamEx->pBackend->uMagic  == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INTERNAL_ERROR_3);
        AssertLogRelReturn(pStreamEx->pBackend->pStream == &pStreamEx->Core, VERR_INTERNAL_ERROR_3);

        /* Must set the backend-initialized flag now or the backend won't be
           destroyed (this used to be done at the end of this function, with
           several possible early return paths before it). */
        pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_CREATED;
    }
    else
    {
        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
        if (rc == VERR_NOT_SUPPORTED)
            LogRel2(("Audio: Creating stream '%s' in backend not supported\n", pStreamEx->Core.Cfg.szName));
        else if (rc == VERR_AUDIO_STREAM_COULD_NOT_CREATE)
            LogRel2(("Audio: Stream '%s' could not be created in backend because of missing hardware / drivers\n",
                     pStreamEx->Core.Cfg.szName));
        else
            LogRel(("Audio: Creating stream '%s' in backend failed with %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
        return rc;
    }

    /* Remember if we need to call pfnStreamInitAsync. */
    pStreamEx->fNeedAsyncInit = rc == VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED;
    AssertStmt(rc != VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED || pThis->pHostDrvAudio->pfnStreamInitAsync != NULL,
               pStreamEx->fNeedAsyncInit = false);
    AssertMsg(   rc != VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED
              || pStreamEx->enmLastBackendState == PDMHOSTAUDIOSTREAMSTATE_INITIALIZING,
             ("rc=%Rrc %s\n", rc, PDMHostAudioStreamStateGetName(pStreamEx->enmLastBackendState)));

    PPDMAUDIOSTREAMCFG const pCfgAcq = &pStreamEx->Core.Cfg;

    /*
     * Validate acquired configuration.
     */
    char szTmp[PDMAUDIOPROPSTOSTRING_MAX];
    LogFunc(("Backend returned: %s\n", PDMAudioStrmCfgToString(pCfgAcq, szTmp, sizeof(szTmp)) ));
    AssertLogRelMsgReturn(AudioHlpStreamCfgIsValid(pCfgAcq),
                          ("Audio: Creating stream '%s' returned an invalid backend configuration (%s), skipping\n",
                           pCfgAcq->szName, PDMAudioPropsToString(&pCfgAcq->Props, szTmp, sizeof(szTmp))),
                          VERR_INVALID_PARAMETER);

    /* Let the user know that the backend changed one of the values requested above. */
    if (pCfgAcq->Backend.cFramesBufferSize != CfgReq.Backend.cFramesBufferSize)
        LogRel2(("Audio: Backend changed buffer size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
                 PDMAudioPropsFramesToMilli(&CfgReq.Props, CfgReq.Backend.cFramesBufferSize), CfgReq.Backend.cFramesBufferSize,
                 PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesBufferSize), pCfgAcq->Backend.cFramesBufferSize));

    if (pCfgAcq->Backend.cFramesPeriod != CfgReq.Backend.cFramesPeriod)
        LogRel2(("Audio: Backend changed period size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
                 PDMAudioPropsFramesToMilli(&CfgReq.Props, CfgReq.Backend.cFramesPeriod), CfgReq.Backend.cFramesPeriod,
                 PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPeriod), pCfgAcq->Backend.cFramesPeriod));

    /* Was pre-buffering requested, but the acquired configuration from the backend told us something else? */
    if (CfgReq.Backend.cFramesPreBuffering)
    {
        if (pCfgAcq->Backend.cFramesPreBuffering != CfgReq.Backend.cFramesPreBuffering)
            LogRel2(("Audio: Backend changed pre-buffering size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
                     PDMAudioPropsFramesToMilli(&CfgReq.Props, CfgReq.Backend.cFramesPreBuffering), CfgReq.Backend.cFramesPreBuffering,
                     PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPreBuffering), pCfgAcq->Backend.cFramesPreBuffering));

        if (pCfgAcq->Backend.cFramesPreBuffering > pCfgAcq->Backend.cFramesBufferSize)
        {
            pCfgAcq->Backend.cFramesPreBuffering = pCfgAcq->Backend.cFramesBufferSize;
            LogRel2(("Audio: Pre-buffering size bigger than buffer size for stream '%s', adjusting to %RU64ms (%RU32 frames)\n", pCfgAcq->szName,
                     PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPreBuffering), pCfgAcq->Backend.cFramesPreBuffering));
        }
    }
    else if (CfgReq.Backend.cFramesPreBuffering == 0) /* Was the pre-buffering requested as being disabeld? Tell the users. */
    {
        LogRel2(("Audio: Pre-buffering is disabled for stream '%s'\n", pCfgAcq->szName));
        pCfgAcq->Backend.cFramesPreBuffering = 0;
    }

    /*
     * Check if the backend did return sane values and correct if necessary.
     */
    uint32_t const cFramesPreBufferingMax = pCfgAcq->Backend.cFramesBufferSize - RT_MIN(16, pCfgAcq->Backend.cFramesBufferSize);
    if (pCfgAcq->Backend.cFramesPreBuffering > cFramesPreBufferingMax)
    {
        LogRel2(("Audio: Warning! Pre-buffering size of %RU32 frames for stream '%s' is too close to or larger than the %RU32 frames buffer size, reducing it to %RU32 frames!\n",
                 pCfgAcq->Backend.cFramesPreBuffering, pCfgAcq->szName, pCfgAcq->Backend.cFramesBufferSize, cFramesPreBufferingMax));
        AssertMsgFailed(("cFramesPreBuffering=%#x vs cFramesPreBufferingMax=%#x\n", pCfgAcq->Backend.cFramesPreBuffering, cFramesPreBufferingMax));
        pCfgAcq->Backend.cFramesPreBuffering = cFramesPreBufferingMax;
    }

    if (pCfgAcq->Backend.cFramesPeriod > pCfgAcq->Backend.cFramesBufferSize)
    {
        LogRel2(("Audio: Warning! Period size of %RU32 frames for stream '%s' is larger than the %RU32 frames buffer size, reducing it to %RU32 frames!\n",
                 pCfgAcq->Backend.cFramesPeriod, pCfgAcq->szName, pCfgAcq->Backend.cFramesBufferSize, pCfgAcq->Backend.cFramesBufferSize / 2));
        AssertMsgFailed(("cFramesPeriod=%#x vs cFramesBufferSize=%#x\n", pCfgAcq->Backend.cFramesPeriod, pCfgAcq->Backend.cFramesBufferSize));
        pCfgAcq->Backend.cFramesPeriod = pCfgAcq->Backend.cFramesBufferSize / 2;
    }

    LogRel2(("Audio: Buffer size for stream '%s' is %RU64 ms / %RU32 frames\n", pCfgAcq->szName,
             PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesBufferSize), pCfgAcq->Backend.cFramesBufferSize));
    LogRel2(("Audio: Pre-buffering size for stream '%s' is %RU64 ms / %RU32 frames\n", pCfgAcq->szName,
             PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPreBuffering), pCfgAcq->Backend.cFramesPreBuffering));
    LogRel2(("Audio: Scheduling hint for stream '%s' is %RU32ms / %RU32 frames\n", pCfgAcq->szName,
             pCfgAcq->Device.cMsSchedulingHint, PDMAudioPropsMilliToFrames(&pCfgAcq->Props, pCfgAcq->Device.cMsSchedulingHint)));

    /* Make sure the configured buffer size by the backend at least can hold the configured latency. */
    uint32_t const cMsPeriod = PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPeriod);
    LogRel2(("Audio: Period size of stream '%s' is %RU64 ms / %RU32 frames\n",
             pCfgAcq->szName, cMsPeriod, pCfgAcq->Backend.cFramesPeriod));
    /** @todo r=bird: This is probably a misleading/harmless warning as we'd just
     *        have to transfer more each time we move data.  The period is generally
     *        pure irrelevant fiction anyway.  A more relevant comparison would
     *        be to half the buffer size, i.e. making sure we get scheduled often
     *        enough to keep the buffer at least half full (probably more
     *        sensible if the buffer size was more than 2x scheduling periods). */
    if (   CfgReq.Device.cMsSchedulingHint              /* Any scheduling hint set? */
        && CfgReq.Device.cMsSchedulingHint > cMsPeriod) /* This might lead to buffer underflows. */
        LogRel(("Audio: Warning: Scheduling hint of stream '%s' is bigger (%RU64ms) than used period size (%RU64ms)\n",
                pCfgAcq->szName, CfgReq.Device.cMsSchedulingHint, cMsPeriod));

    /*
     * Done, just log the result:
     */
    LogFunc(("Acquired stream config: %s\n", PDMAudioStrmCfgToString(&pStreamEx->Core.Cfg, szTmp, sizeof(szTmp)) ));
    LogRel2(("Audio: Acquired stream config: %s\n", PDMAudioStrmCfgToString(&pStreamEx->Core.Cfg, szTmp, sizeof(szTmp)) ));

    return VINF_SUCCESS;
}


/**
 * Worker for drvAudioStreamCreate that initializes the audio stream.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to driver instance.
 * @param   pStreamEx   Stream to initialize.  Caller already set a few fields.
 *                      The Core.Cfg field contains the requested configuration
 *                      when we're called and the actual configuration when
 *                      successfully returning.
 */
static int drvAudioStreamInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    /*
     * Init host stream.
     */
    pStreamEx->Core.uMagic = PDMAUDIOSTREAM_MAGIC;

    char szTmp[PDMAUDIOSTRMCFGTOSTRING_MAX];
    LogFunc(("Requested stream config: %s\n", PDMAudioStrmCfgToString(&pStreamEx->Core.Cfg, szTmp, sizeof(szTmp)) ));
    LogRel2(("Audio: Creating stream: %s\n", PDMAudioStrmCfgToString(&pStreamEx->Core.Cfg, szTmp, sizeof(szTmp)) ));

    int rc = drvAudioStreamCreateInternalBackend(pThis, pStreamEx);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Configure host buffers.
     */
    Assert(pStreamEx->cbPreBufThreshold == 0);
    if (pStreamEx->Core.Cfg.Backend.cFramesPreBuffering != 0)
        pStreamEx->cbPreBufThreshold = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Cfg.Props,
                                                                  pStreamEx->Core.Cfg.Backend.cFramesPreBuffering);

    /* Allocate space for pre-buffering of output stream w/o mixing buffers. */
    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
    {
        Assert(pStreamEx->Out.cbPreBufAlloc == 0);
        Assert(pStreamEx->Out.cbPreBuffered == 0);
        Assert(pStreamEx->Out.offPreBuf == 0);
        if (pStreamEx->Core.Cfg.Backend.cFramesPreBuffering != 0)
        {
            uint32_t cbPreBufAlloc = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Cfg.Props,
                                                                pStreamEx->Core.Cfg.Backend.cFramesBufferSize);
            cbPreBufAlloc = RT_MIN(RT_ALIGN_32(pStreamEx->cbPreBufThreshold + _8K, _4K), cbPreBufAlloc);
            cbPreBufAlloc = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Cfg.Props, cbPreBufAlloc);
            pStreamEx->Out.cbPreBufAlloc     = cbPreBufAlloc;
            pStreamEx->Out.pbPreBuf          = (uint8_t *)RTMemAllocZ(cbPreBufAlloc);
            AssertReturn(pStreamEx->Out.pbPreBuf, VERR_NO_MEMORY);
        }
        pStreamEx->Out.enmPlayState          = DRVAUDIOPLAYSTATE_NOPLAY; /* Changed upon enable. */
    }

    /*
     * Register statistics.
     */
    PPDMDRVINS const pDrvIns = pThis->pDrvIns;
    /** @todo expose config and more. */
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Core.Cfg.Backend.cFramesBufferSize, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                           "The size of the backend buffer (in frames)",     "%s/0-HostBackendBufSize", pStreamEx->Core.Cfg.szName);
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Core.Cfg.Backend.cFramesPeriod, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                           "The size of the backend period (in frames)",     "%s/0-HostBackendPeriodSize", pStreamEx->Core.Cfg.szName);
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Core.Cfg.Backend.cFramesPreBuffering, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                           "Pre-buffer size (in frames)",                    "%s/0-HostBackendPreBufferSize", pStreamEx->Core.Cfg.szName);
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Core.Cfg.Device.cMsSchedulingHint, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                           "Device DMA scheduling hint (in milliseconds)",   "%s/0-DeviceSchedulingHint", pStreamEx->Core.Cfg.szName);
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Core.Cfg.Props.uHz, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_HZ,
                           "Backend stream frequency",                       "%s/Hz", pStreamEx->Core.Cfg.szName);
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Core.Cfg.Props.cbFrame, STAMTYPE_U8, STAMVISIBILITY_USED, STAMUNIT_BYTES,
                           "Backend frame size",                             "%s/Framesize", pStreamEx->Core.Cfg.szName);
    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_IN)
    {
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.cbBackendReadableBefore, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                               "Free space in backend buffer before play",   "%s/0-HostBackendBufReadableBefore", pStreamEx->Core.Cfg.szName);
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.cbBackendReadableAfter, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                               "Free space in backend buffer after play",    "%s/0-HostBackendBufReadableAfter", pStreamEx->Core.Cfg.szName);
#ifdef VBOX_WITH_STATISTICS
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.ProfCapture, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
                               "Profiling time spent in StreamCapture",      "%s/ProfStreamCapture", pStreamEx->Core.Cfg.szName);
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.ProfGetReadable, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
                               "Profiling time spent in StreamGetReadable",  "%s/ProfStreamGetReadable", pStreamEx->Core.Cfg.szName);
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.ProfGetReadableBytes, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_BYTES,
                               "Readable byte stats",                        "%s/ProfStreamGetReadableBytes", pStreamEx->Core.Cfg.szName);
#endif
    }
    else
    {
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.cbBackendWritableBefore, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                               "Free space in backend buffer before play",   "%s/0-HostBackendBufWritableBefore", pStreamEx->Core.Cfg.szName);
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.cbBackendWritableAfter, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
                               "Free space in backend buffer after play",    "%s/0-HostBackendBufWritableAfter", pStreamEx->Core.Cfg.szName);
#ifdef VBOX_WITH_STATISTICS
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.ProfPlay, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
                               "Profiling time spent in StreamPlay",         "%s/ProfStreamPlay", pStreamEx->Core.Cfg.szName);
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.ProfGetWritable, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
                               "Profiling time spent in StreamGetWritable",  "%s/ProfStreamGetWritable", pStreamEx->Core.Cfg.szName);
        PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.ProfGetWritableBytes, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_BYTES,
                               "Writeable byte stats",                       "%s/ProfStreamGetWritableBytes", pStreamEx->Core.Cfg.szName);
#endif
    }
#ifdef VBOX_WITH_STATISTICS
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->StatProfGetState, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
                           "Profiling time spent in StreamGetState",         "%s/ProfStreamGetState", pStreamEx->Core.Cfg.szName);
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->StatXfer, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_BYTES,
                           "Byte transfer stats (excluding pre-buffering)",  "%s/Transfers", pStreamEx->Core.Cfg.szName);
#endif
    PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->offInternal, STAMTYPE_U64, STAMVISIBILITY_USED, STAMUNIT_NONE,
                           "Internal stream offset",                         "%s/offInternal", pStreamEx->Core.Cfg.szName);

    LogFlowFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCreate}
 */
static DECLCALLBACK(int) drvAudioStreamCreate(PPDMIAUDIOCONNECTOR pInterface, uint32_t fFlags, PCPDMAUDIOSTREAMCFG pCfgReq,
                                              PPDMAUDIOSTREAM *ppStream)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);

    /*
     * Assert sanity.
     */
    AssertReturn(!(fFlags & ~PDMAUDIOSTREAM_CREATE_F_NO_MIXBUF), VERR_INVALID_FLAGS);
    AssertPtrReturn(pCfgReq, VERR_INVALID_POINTER);
    AssertPtrReturn(ppStream, VERR_INVALID_POINTER);
    *ppStream = NULL;
    LogFlowFunc(("pCfgReq=%s\n", pCfgReq->szName));
#ifdef LOG_ENABLED
    PDMAudioStrmCfgLog(pCfgReq);
#endif
    AssertReturn(AudioHlpStreamCfgIsValid(pCfgReq), VERR_INVALID_PARAMETER);
    AssertReturn(pCfgReq->enmDir == PDMAUDIODIR_IN || pCfgReq->enmDir == PDMAUDIODIR_OUT, VERR_NOT_SUPPORTED);

    /*
     * Grab a free stream count now.
     */
    int rc = RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
    AssertRCReturn(rc, rc);

    uint32_t * const pcFreeStreams = pCfgReq->enmDir == PDMAUDIODIR_IN ? &pThis->In.cStreamsFree : &pThis->Out.cStreamsFree;
    if (*pcFreeStreams > 0)
        *pcFreeStreams -= 1;
    else
    {
        RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
        LogFlowFunc(("Maximum number of host %s streams reached\n", PDMAudioDirGetName(pCfgReq->enmDir) ));
        return pCfgReq->enmDir == PDMAUDIODIR_IN ? VERR_AUDIO_NO_FREE_INPUT_STREAMS : VERR_AUDIO_NO_FREE_OUTPUT_STREAMS;
    }

    RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);

    /*
     * Get and check the backend size.
     *
     * Since we'll have to leave the hot-plug lock before we call the backend,
     * we'll have revalidate the size at that time.
     */
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    size_t const cbHstStrm = pThis->BackendCfg.cbStream;
    AssertStmt(cbHstStrm >= sizeof(PDMAUDIOBACKENDSTREAM), rc = VERR_OUT_OF_RANGE);
    AssertStmt(cbHstStrm < _16M, rc = VERR_OUT_OF_RANGE);

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    if (RT_SUCCESS(rc))
    {
        /*
         * Allocate and initialize common state.
         */
        PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)RTMemAllocZ(sizeof(DRVAUDIOSTREAM) + RT_ALIGN_Z(cbHstStrm, 64));
        if (pStreamEx)
        {
            rc = RTCritSectInit(&pStreamEx->Core.CritSect); /* (drvAudioStreamFree assumes it's initailized) */
            if (RT_SUCCESS(rc))
            {
                PPDMAUDIOBACKENDSTREAM pBackend = (PPDMAUDIOBACKENDSTREAM)(pStreamEx + 1);
                pBackend->uMagic                = PDMAUDIOBACKENDSTREAM_MAGIC;
                pBackend->pStream               = &pStreamEx->Core;

                pStreamEx->pBackend             = pBackend;
                pStreamEx->Core.Cfg             = *pCfgReq;
                pStreamEx->Core.cbBackend       = (uint32_t)cbHstStrm;
                pStreamEx->fDestroyImmediate    = true;
                pStreamEx->hReqInitAsync        = NIL_RTREQ;
                pStreamEx->uMagic               = DRVAUDIOSTREAM_MAGIC;

                /* Make a unqiue stream name including the host (backend) driver name. */
                AssertPtr(pThis->pHostDrvAudio);
                size_t cchName = RTStrPrintf(pStreamEx->Core.Cfg.szName, RT_ELEMENTS(pStreamEx->Core.Cfg.szName), "[%s] %s:0",
                                             pThis->BackendCfg.szName, pCfgReq->szName[0] != '\0' ? pCfgReq->szName : "<NoName>");
                if (cchName < sizeof(pStreamEx->Core.Cfg.szName))
                {
                    RTCritSectRwEnterShared(&pThis->CritSectGlobals);
                    for (uint32_t i = 0; i < 256; i++)
                    {
                        bool fDone = true;
                        PDRVAUDIOSTREAM pIt;
                        RTListForEach(&pThis->LstStreams, pIt, DRVAUDIOSTREAM, ListEntry)
                        {
                            if (strcmp(pIt->Core.Cfg.szName, pStreamEx->Core.Cfg.szName) == 0)
                            {
                                RTStrPrintf(pStreamEx->Core.Cfg.szName, RT_ELEMENTS(pStreamEx->Core.Cfg.szName), "[%s] %s:%u",
                                            pThis->BackendCfg.szName, pCfgReq->szName[0] != '\0' ? pCfgReq->szName : "<NoName>",
                                            i);
                                fDone = false;
                                break;
                            }
                        }
                        if (fDone)
                            break;
                    }
                    RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
                }

                /*
                 * Try to init the rest.
                 */
                rc = drvAudioStreamInitInternal(pThis, pStreamEx);
                if (RT_SUCCESS(rc))
                {
                    /* Set initial reference counts. */
                    pStreamEx->cRefs = pStreamEx->fNeedAsyncInit ? 2 : 1;

                    /* Add it to the list. */
                    RTCritSectRwEnterExcl(&pThis->CritSectGlobals);

                    RTListAppend(&pThis->LstStreams, &pStreamEx->ListEntry);
                    pThis->cStreams++;
                    STAM_REL_COUNTER_INC(&pThis->StatTotalStreamsCreated);

                    RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);

                    /*
                     * Init debug stuff if enabled (ignore failures).
                     */
                    if (pCfgReq->enmDir == PDMAUDIODIR_IN)
                    {
                        if (pThis->CfgIn.Dbg.fEnabled)
                            AudioHlpFileCreateAndOpen(&pStreamEx->In.Dbg.pFileCapture, pThis->CfgIn.Dbg.szPathOut,
                                                      "DrvAudioCapture", pThis->pDrvIns->iInstance, &pStreamEx->Core.Cfg.Props);
                    }
                    else /* Out */
                    {
                        if (pThis->CfgOut.Dbg.fEnabled)
                            AudioHlpFileCreateAndOpen(&pStreamEx->Out.Dbg.pFilePlay, pThis->CfgOut.Dbg.szPathOut,
                                                      "DrvAudioPlay", pThis->pDrvIns->iInstance, &pStreamEx->Core.Cfg.Props);
                    }

                    /*
                     * Kick off the asynchronous init.
                     */
                    if (!pStreamEx->fNeedAsyncInit)
                    {
#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
                        /* drvAudioStreamInitInternal returns success for disable stream directions w/o actually
                           creating a backend, so we need to check that before marking the backend ready.. */
                        if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
#endif
                            pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY;
                        PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                    }
                    else
                    {
                        int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, &pStreamEx->hReqInitAsync,
                                                  RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
                                                  (PFNRT)drvAudioStreamInitAsync, 2, pThis, pStreamEx);
                        LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
                        AssertRCStmt(rc2, drvAudioStreamInitAsync(pThis, pStreamEx));
                    }

#ifdef VBOX_STRICT
                    /*
                     * Assert lock order to make sure the lock validator picks up on it.
                     */
                    RTCritSectRwEnterShared(&pThis->CritSectGlobals);
                    RTCritSectEnter(&pStreamEx->Core.CritSect);
                    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
                    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
                    RTCritSectLeave(&pStreamEx->Core.CritSect);
                    RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
#endif

                    *ppStream = &pStreamEx->Core;
                    LogFlowFunc(("returns VINF_SUCCESS (pStreamEx=%p)\n", pStreamEx));
                    return VINF_SUCCESS;
                }

                LogFunc(("drvAudioStreamInitInternal failed: %Rrc\n", rc));
                int rc2 = drvAudioStreamUninitInternal(pThis, pStreamEx);
                AssertRC(rc2);
                drvAudioStreamFree(pStreamEx);
            }
            else
                RTMemFree(pStreamEx);
        }
        else
            rc = VERR_NO_MEMORY;
    }

    /*
     * Give back the stream count, we couldn't use it after all.
     */
    RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
    *pcFreeStreams += 1;
    RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);

    LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * Calls the backend to give it the chance to destroy its part of the audio stream.
 *
 * Called from drvAudioPowerOff, drvAudioStreamUninitInternal and
 * drvAudioStreamReInitInternal.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to driver instance.
 * @param   pStreamEx   Audio stream destruct backend for.
 */
static int drvAudioStreamDestroyInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    AssertPtr(pThis);
    AssertPtr(pStreamEx);

    int rc = VINF_SUCCESS;

#ifdef LOG_ENABLED
    char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
#endif
    LogFunc(("[%s] fStatus=%s\n", pStreamEx->Core.Cfg.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));

    if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
    {
        AssertPtr(pStreamEx->pBackend);

        /* Check if the pointer to  the host audio driver is still valid.
         * It can be NULL if we were called in drvAudioDestruct, for example. */
        RTCritSectRwEnterShared(&pThis->CritSectHotPlug); /** @todo needed? */
        if (pThis->pHostDrvAudio)
            rc = pThis->pHostDrvAudio->pfnStreamDestroy(pThis->pHostDrvAudio, pStreamEx->pBackend, pStreamEx->fDestroyImmediate);
        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);

        pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY);
        PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
    }

    LogFlowFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
    return rc;
}


/**
 * Uninitializes an audio stream - worker for drvAudioStreamDestroy,
 * drvAudioDestruct and drvAudioStreamCreate.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to driver instance.
 * @param   pStreamEx   Pointer to audio stream to uninitialize.
 */
static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    AssertPtrReturn(pThis,   VERR_INVALID_POINTER);
    AssertMsgReturn(pStreamEx->cRefs <= 1,
                    ("Stream '%s' still has %RU32 references held when uninitializing\n", pStreamEx->Core.Cfg.szName, pStreamEx->cRefs),
                    VERR_WRONG_ORDER);
    LogFlowFunc(("[%s] cRefs=%RU32\n", pStreamEx->Core.Cfg.szName, pStreamEx->cRefs));

    RTCritSectEnter(&pStreamEx->Core.CritSect);

    /*
     * ...
     */
    if (pStreamEx->fDestroyImmediate)
        drvAudioStreamControlInternal(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
    int rc = drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);

    /* Free pre-buffer space. */
    if (   pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT
        && pStreamEx->Out.pbPreBuf)
    {
        RTMemFree(pStreamEx->Out.pbPreBuf);
        pStreamEx->Out.pbPreBuf      = NULL;
        pStreamEx->Out.cbPreBufAlloc = 0;
        pStreamEx->Out.cbPreBuffered = 0;
        pStreamEx->Out.offPreBuf     = 0;
    }

    if (RT_SUCCESS(rc))
    {
#ifdef LOG_ENABLED
        if (pStreamEx->fStatus != PDMAUDIOSTREAM_STS_NONE)
        {
            char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
            LogFunc(("[%s] Warning: Still has %s set when uninitializing\n",
                     pStreamEx->Core.Cfg.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
        }
#endif
        pStreamEx->fStatus = PDMAUDIOSTREAM_STS_NONE;
    }

    PPDMDRVINS const pDrvIns = pThis->pDrvIns;
    PDMDrvHlpSTAMDeregisterByPrefix(pDrvIns, pStreamEx->Core.Cfg.szName);

    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_IN)
    {
        if (pThis->CfgIn.Dbg.fEnabled)
        {
            AudioHlpFileDestroy(pStreamEx->In.Dbg.pFileCapture);
            pStreamEx->In.Dbg.pFileCapture = NULL;
        }
    }
    else
    {
        Assert(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT);
        if (pThis->CfgOut.Dbg.fEnabled)
        {
            AudioHlpFileDestroy(pStreamEx->Out.Dbg.pFilePlay);
            pStreamEx->Out.Dbg.pFilePlay = NULL;
        }
    }

    RTCritSectLeave(&pStreamEx->Core.CritSect);
    LogFlowFunc(("Returning %Rrc\n", rc));
    return rc;
}


/**
 * Internal release function.
 *
 * @returns New reference count, UINT32_MAX if bad stream.
 * @param   pThis           Pointer to the DrvAudio instance data.
 * @param   pStreamEx       The stream to reference.
 * @param   fMayDestroy     Whether the caller is allowed to implicitly destroy
 *                          the stream or not.
 */
static uint32_t drvAudioStreamReleaseInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fMayDestroy)
{
    AssertPtrReturn(pStreamEx, UINT32_MAX);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, UINT32_MAX);
    AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, UINT32_MAX);
    Assert(!RTCritSectIsOwner(&pStreamEx->Core.CritSect));

    uint32_t cRefs = ASMAtomicDecU32(&pStreamEx->cRefs);
    if (cRefs != 0)
        Assert(cRefs < _1K);
    else if (fMayDestroy)
    {
/** @todo r=bird: Caching one stream in each direction for some time,
 * depending on the time it took to create it.  drvAudioStreamCreate can use it
 * if the configuration matches, otherwise it'll throw it away.  This will
 * provide a general speedup independ of device (HDA used to do this, but
 * doesn't) and backend implementation.  Ofc, the backend probably needs an
 * opt-out here. */
        int rc = drvAudioStreamUninitInternal(pThis, pStreamEx);
        if (RT_SUCCESS(rc))
        {
            RTCritSectRwEnterExcl(&pThis->CritSectGlobals);

            if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_IN)
                pThis->In.cStreamsFree++;
            else /* Out */
                pThis->Out.cStreamsFree++;
            pThis->cStreams--;

            RTListNodeRemove(&pStreamEx->ListEntry);

            RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);

            drvAudioStreamFree(pStreamEx);
        }
        else
        {
            LogRel(("Audio: Uninitializing stream '%s' failed with %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
            /** @todo r=bird: What's the plan now? */
        }
    }
    else
    {
        cRefs = ASMAtomicIncU32(&pStreamEx->cRefs);
        AssertFailed();
    }

    Log12Func(("returns %u (%s)\n", cRefs, cRefs > 0 ? pStreamEx->Core.Cfg.szName : "destroyed"));
    return cRefs;
}


/**
 * Asynchronous worker for drvAudioStreamDestroy.
 *
 * Does DISABLE and releases reference, possibly destroying the stream.
 *
 * @param   pThis       Pointer to the DrvAudio instance data.
 * @param   pStreamEx   The stream.  One reference for us to release.
 * @param   fImmediate  How to treat draining streams.
 */
static DECLCALLBACK(void) drvAudioStreamDestroyAsync(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fImmediate)
{
    LogFlowFunc(("pThis=%p pStreamEx=%p (%s) fImmediate=%RTbool\n", pThis, pStreamEx, pStreamEx->Core.Cfg.szName, fImmediate));
#ifdef LOG_ENABLED
    uint64_t const nsStart = RTTimeNanoTS();
#endif
    RTCritSectEnter(&pStreamEx->Core.CritSect);

    pStreamEx->fDestroyImmediate = fImmediate; /* Do NOT adjust for draining status, just pass it as-is. CoreAudio needs this. */

    if (!fImmediate && (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
        LogFlowFunc(("No DISABLE\n"));
    else
    {
        int rc2 = drvAudioStreamControlInternal(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
        LogFlowFunc(("DISABLE done: %Rrc\n", rc2));
        AssertRC(rc2);
    }

    RTCritSectLeave(&pStreamEx->Core.CritSect);

    drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);

    LogFlowFunc(("returning (after %'RU64 ns)\n", RTTimeNanoTS() - nsStart));
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamDestroy}
 */
static DECLCALLBACK(int) drvAudioStreamDestroy(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream, bool fImmediate)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);

    /* Ignore NULL streams. */
    if (!pStream)
        return VINF_SUCCESS;

    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;   /* Note! Do not touch pStream after this! */
    AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
    LogFlowFunc(("ENTER - %p (%s) fImmediate=%RTbool\n", pStreamEx, pStreamEx->Core.Cfg.szName, fImmediate));
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->pBackend && pStreamEx->pBackend->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INVALID_MAGIC);

    /*
     * The main difference from a regular release is that this will disable
     * (or drain if we could) the stream and we can cancel any pending
     * pfnStreamInitAsync call.
     */
    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, rc);

    if (pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC)
    {
        if (pStreamEx->cRefs > 0 && pStreamEx->cRefs < UINT32_MAX / 4)
        {
            char szStatus[DRVAUDIO_STATUS_STR_MAX];
            LogRel2(("Audio: Destroying stream '%s': cRefs=%u; status: %s; backend: %s; hReqInitAsync=%p\n",
                     pStreamEx->Core.Cfg.szName, pStreamEx->cRefs, drvAudioStreamStatusToStr(szStatus, pStreamEx->fStatus),
                     PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)),
                     pStreamEx->hReqInitAsync));

            /* Try cancel pending async init request and release the it. */
            if (pStreamEx->hReqInitAsync != NIL_RTREQ)
            {
                Assert(pStreamEx->cRefs >= 2);
                int rc2 = RTReqCancel(pStreamEx->hReqInitAsync);

                RTReqRelease(pStreamEx->hReqInitAsync);
                pStreamEx->hReqInitAsync = NIL_RTREQ;

                RTCritSectLeave(&pStreamEx->Core.CritSect); /* (exit before releasing the stream to avoid assertion) */

                if (RT_SUCCESS(rc2))
                {
                    LogFlowFunc(("Successfully cancelled pending pfnStreamInitAsync call (hReqInitAsync=%p).\n",
                                 pStreamEx->hReqInitAsync));
                    drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
                }
                else
                {
                    LogFlowFunc(("Failed to cancel pending pfnStreamInitAsync call (hReqInitAsync=%p): %Rrc\n",
                                 pStreamEx->hReqInitAsync, rc2));
                    Assert(rc2 == VERR_RT_REQUEST_STATE);
                }
            }
            else
                RTCritSectLeave(&pStreamEx->Core.CritSect);

            /*
             * Now, if the backend requests asynchronous disabling and destruction
             * push the disabling and destroying over to a worker thread.
             *
             * This is a general offloading feature that all backends should make use of,
             * however it's rather precarious on macs where stopping an already draining
             * stream may take 8-10ms which naturally isn't something we should be doing
             * on an EMT.
             */
            if (!(pThis->BackendCfg.fFlags & PDMAUDIOBACKEND_F_ASYNC_STREAM_DESTROY))
                drvAudioStreamDestroyAsync(pThis, pStreamEx, fImmediate);
            else
            {
                int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL /*phReq*/,
                                          RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
                                          (PFNRT)drvAudioStreamDestroyAsync, 3, pThis, pStreamEx, fImmediate);
                LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
                AssertRCStmt(rc2, drvAudioStreamDestroyAsync(pThis, pStreamEx, fImmediate));
            }
        }
        else
        {
            AssertLogRelMsgFailedStmt(("%p cRefs=%#x\n", pStreamEx, pStreamEx->cRefs), rc = VERR_CALLER_NO_REFERENCE);
            RTCritSectLeave(&pStreamEx->Core.CritSect); /*??*/
        }
    }
    else
    {
        AssertLogRelMsgFailedStmt(("%p uMagic=%#x\n", pStreamEx, pStreamEx->uMagic), rc = VERR_INVALID_MAGIC);
        RTCritSectLeave(&pStreamEx->Core.CritSect); /*??*/
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * Drops all audio data (and associated state) of a stream.
 *
 * Used by drvAudioStreamIterateInternal(), drvAudioStreamResetOnDisable(), and
 * drvAudioStreamReInitInternal().
 *
 * @param   pStreamEx   Stream to drop data for.
 */
static void drvAudioStreamResetInternal(PDRVAUDIOSTREAM pStreamEx)
{
    LogFunc(("[%s]\n", pStreamEx->Core.Cfg.szName));
    Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));

    pStreamEx->nsLastIterated       = 0;
    pStreamEx->nsLastPlayedCaptured = 0;
    pStreamEx->nsLastReadWritten    = 0;
    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
    {
        pStreamEx->Out.cbPreBuffered = 0;
        pStreamEx->Out.offPreBuf     = 0;
        pStreamEx->Out.enmPlayState  = pStreamEx->cbPreBufThreshold > 0
                                     ? DRVAUDIOPLAYSTATE_PREBUF : DRVAUDIOPLAYSTATE_PLAY;
    }
    else
        pStreamEx->In.enmCaptureState = pStreamEx->cbPreBufThreshold > 0
                                      ? DRVAUDIOCAPTURESTATE_PREBUF : DRVAUDIOCAPTURESTATE_CAPTURING;
}


/**
 * Re-initializes an audio stream with its existing host and guest stream
 * configuration.
 *
 * This might be the case if the backend told us we need to re-initialize
 * because something on the host side has changed.
 *
 * @note    Does not touch the stream's status flags.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to driver instance.
 * @param   pStreamEx   Stream to re-initialize.
 */
static int drvAudioStreamReInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    char szTmp[RT_MAX(PDMAUDIOSTRMCFGTOSTRING_MAX, DRVAUDIO_STATUS_STR_MAX)];
    LogFlowFunc(("[%s] status: %s\n", pStreamEx->Core.Cfg.szName, drvAudioStreamStatusToStr(szTmp, pStreamEx->fStatus) ));
    Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    /*
     * Destroy and re-create stream on backend side.
     */
    if (   (pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY))
        ==                       (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY))
        drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);

    if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
        drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);

    int rc = VERR_AUDIO_STREAM_NOT_READY;
    if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED))
    {
        drvAudioStreamResetInternal(pStreamEx);

        RT_BZERO(pStreamEx->pBackend + 1, pStreamEx->Core.cbBackend - sizeof(*pStreamEx->pBackend));

        rc = drvAudioStreamCreateInternalBackend(pThis, pStreamEx);
        if (RT_SUCCESS(rc))
        {
            LogFunc(("Acquired host config: %s\n", PDMAudioStrmCfgToString(&pStreamEx->Core.Cfg, szTmp, sizeof(szTmp)) ));
            /** @todo Validate (re-)acquired configuration with pStreamEx->Core.Core.Cfg?
             * drvAudioStreamInitInternal() does some setup and a bunch of
             * validations + adjustments of the stream config, so this surely is quite
             * optimistic. */
            if (true)
            {
                /*
                 * Kick off the asynchronous init.
                 */
                if (!pStreamEx->fNeedAsyncInit)
                {
                    pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY;
                    PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                }
                else
                {
                    drvAudioStreamRetainInternal(pStreamEx);
                    int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, &pStreamEx->hReqInitAsync,
                                              RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
                                              (PFNRT)drvAudioStreamInitAsync, 2, pThis, pStreamEx);
                    LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
                    AssertRCStmt(rc2, drvAudioStreamInitAsync(pThis, pStreamEx));
                }

                /*
                 * Update the backend on the stream state if it's ready, otherwise
                 * let the worker thread do it after the async init has completed.
                 */
                if (   (pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_BACKEND_READY | PDMAUDIOSTREAM_STS_BACKEND_CREATED))
                    ==                       (PDMAUDIOSTREAM_STS_BACKEND_READY | PDMAUDIOSTREAM_STS_BACKEND_CREATED))
                {
                    rc = drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "re-initializing");
                    /** @todo not sure if we really need to care about this status code...   */
                }
                else if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
                {
                    Assert(pStreamEx->hReqInitAsync != NIL_RTREQ);
                    LogFunc(("Asynchronous stream init (%p) ...\n", pStreamEx->hReqInitAsync));
                }
                else
                {
                    LogRel(("Audio: Re-initializing stream '%s' somehow failed, status: %s\n", pStreamEx->Core.Cfg.szName,
                            drvAudioStreamStatusToStr(szTmp, pStreamEx->fStatus) ));
                    AssertFailed();
                    rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
                }
            }
        }
        else
            LogRel(("Audio: Re-initializing stream '%s' failed with %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
    }
    else
    {
        LogRel(("Audio: Re-initializing stream '%s' failed to destroy previous backend.\n", pStreamEx->Core.Cfg.szName));
        AssertFailed();
    }

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    LogFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamReInit}
 */
static DECLCALLBACK(int) drvAudioStreamReInit(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT, VERR_INVALID_STATE);
    LogFlowFunc(("\n"));

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, rc);

    if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT)
    {
        const unsigned cMaxTries = 5;
        const uint64_t nsNow   = RTTimeNanoTS();

        /* Throttle re-initializing streams on failure. */
        if (   pStreamEx->cTriesReInit < cMaxTries
            && pStreamEx->hReqInitAsync == NIL_RTREQ
            && (   pStreamEx->nsLastReInit == 0
                || nsNow - pStreamEx->nsLastReInit >= RT_NS_1SEC * pStreamEx->cTriesReInit))
        {
            rc = drvAudioStreamReInitInternal(pThis, pStreamEx);
            if (RT_SUCCESS(rc))
            {
                /* Remove the pending re-init flag on success. */
                pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_NEED_REINIT;
                PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
            }
            else
            {
                pStreamEx->nsLastReInit = nsNow;
                pStreamEx->cTriesReInit++;

                /* Did we exceed our tries re-initializing the stream?
                 * Then this one is dead-in-the-water, so disable it for further use. */
                if (pStreamEx->cTriesReInit >= cMaxTries)
                {
                    LogRel(("Audio: Re-initializing stream '%s' exceeded maximum retries (%u), leaving as disabled\n",
                            pStreamEx->Core.Cfg.szName, cMaxTries));

                    /* Don't try to re-initialize anymore and mark as disabled. */
                    /** @todo should mark it as not-initialized too, shouldn't we?   */
                    pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_NEED_REINIT | PDMAUDIOSTREAM_STS_ENABLED);
                    PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);

                    /* Note: Further writes to this stream go to / will be read from the bit bucket (/dev/null) from now on. */
                }
            }
        }
        else
            Log8Func(("cTriesReInit=%d hReqInitAsync=%p nsLast=%RU64 nsNow=%RU64 nsDelta=%RU64\n", pStreamEx->cTriesReInit,
                      pStreamEx->hReqInitAsync, pStreamEx->nsLastReInit, nsNow, nsNow - pStreamEx->nsLastReInit));

#ifdef LOG_ENABLED
        char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
#endif
        Log3Func(("[%s] fStatus=%s\n", pStreamEx->Core.Cfg.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
    }
    else
    {
        AssertFailed();
        rc = VERR_INVALID_STATE;
    }

    RTCritSectLeave(&pStreamEx->Core.CritSect);

    LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * Internal retain function.
 *
 * @returns New reference count, UINT32_MAX if bad stream.
 * @param   pStreamEx           The stream to reference.
 */
static uint32_t drvAudioStreamRetainInternal(PDRVAUDIOSTREAM pStreamEx)
{
    AssertPtrReturn(pStreamEx, UINT32_MAX);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, UINT32_MAX);
    AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, UINT32_MAX);

    uint32_t const cRefs = ASMAtomicIncU32(&pStreamEx->cRefs);
    Assert(cRefs > 1);
    Assert(cRefs < _1K);

    Log12Func(("returns %u (%s)\n", cRefs, pStreamEx->Core.Cfg.szName));
    return cRefs;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRetain}
 */
static DECLCALLBACK(uint32_t) drvAudioStreamRetain(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    RT_NOREF(pInterface);
    return drvAudioStreamRetainInternal((PDRVAUDIOSTREAM)pStream);
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRelease}
 */
static DECLCALLBACK(uint32_t) drvAudioStreamRelease(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    return drvAudioStreamReleaseInternal(RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector),
                                         (PDRVAUDIOSTREAM)pStream,
                                         false /*fMayDestroy*/);
}


/**
 * Controls a stream's backend.
 *
 * @returns VBox status code.
 * @param   pThis           Pointer to driver instance.
 * @param   pStreamEx       Stream to control.
 * @param   enmStreamCmd    Control command.
 *
 * @note    Caller has entered the critical section of the stream.
 * @note    Can be called w/o having entered DRVAUDIO::CritSectHotPlug.
 */
static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd)
{
    AssertPtr(pThis);
    AssertPtr(pStreamEx);
    Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));

    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturn(rc, rc);

    /*
     * Whether to propagate commands down to the backend.
     *
     *      1. If the stream direction is disabled on the driver level, we should
     *         obviously not call the backend.  Our stream status will reflect the
     *         actual state so drvAudioEnable() can tell the backend if the user
     *         re-enables the stream direction.
     *
     *      2. If the backend hasn't finished initializing yet, don't try call
     *         it to start/stop/pause/whatever the stream.  (Better to do it here
     *         than to replicate this in the relevant backends.)  When the backend
     *         finish initializing the stream, we'll update it about the stream state.
     */
    bool const                     fDirEnabled     = drvAudioStreamIsDirectionEnabled(pThis, pStreamEx->Core.Cfg.enmDir);
    PDMHOSTAUDIOSTREAMSTATE const  enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
                                                     /* ^^^ (checks pThis->pHostDrvAudio != NULL too) */

    char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
    LogRel2(("Audio: %s stream '%s' backend (%s is %s; status: %s; backend-status: %s)\n",
             PDMAudioStrmCmdGetName(enmStreamCmd), pStreamEx->Core.Cfg.szName, PDMAudioDirGetName(pStreamEx->Core.Cfg.enmDir),
             fDirEnabled ? "enabled" : "disabled",  drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus),
             PDMHostAudioStreamStateGetName(enmBackendState) ));

    if (fDirEnabled)
    {
        if (   (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY /* don't really need this check, do we? */)
            && (   enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
                || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING) )
        {
            switch (enmStreamCmd)
            {
                case PDMAUDIOSTREAMCMD_ENABLE:
                    rc = pThis->pHostDrvAudio->pfnStreamEnable(pThis->pHostDrvAudio, pStreamEx->pBackend);
                    break;

                case PDMAUDIOSTREAMCMD_DISABLE:
                    rc = pThis->pHostDrvAudio->pfnStreamDisable(pThis->pHostDrvAudio, pStreamEx->pBackend);
                    break;

                case PDMAUDIOSTREAMCMD_PAUSE:
                    rc = pThis->pHostDrvAudio->pfnStreamPause(pThis->pHostDrvAudio, pStreamEx->pBackend);
                    break;

                case PDMAUDIOSTREAMCMD_RESUME:
                    rc = pThis->pHostDrvAudio->pfnStreamResume(pThis->pHostDrvAudio, pStreamEx->pBackend);
                    break;

                case PDMAUDIOSTREAMCMD_DRAIN:
                    if (pThis->pHostDrvAudio->pfnStreamDrain)
                        rc = pThis->pHostDrvAudio->pfnStreamDrain(pThis->pHostDrvAudio, pStreamEx->pBackend);
                    else
                        rc = VERR_NOT_SUPPORTED;
                    break;

                default:
                    AssertMsgFailedBreakStmt(("Command %RU32 not implemented\n", enmStreamCmd), rc = VERR_INTERNAL_ERROR_2);
            }
            if (RT_SUCCESS(rc))
                Log2Func(("[%s] %s succeeded (%Rrc)\n", pStreamEx->Core.Cfg.szName, PDMAudioStrmCmdGetName(enmStreamCmd), rc));
            else
            {
                LogFunc(("[%s] %s failed with %Rrc\n", pStreamEx->Core.Cfg.szName, PDMAudioStrmCmdGetName(enmStreamCmd), rc));
                if (   rc != VERR_NOT_IMPLEMENTED
                    && rc != VERR_NOT_SUPPORTED
                    && rc != VERR_AUDIO_STREAM_NOT_READY)
                    LogRel(("Audio: %s stream '%s' failed with %Rrc\n", PDMAudioStrmCmdGetName(enmStreamCmd), pStreamEx->Core.Cfg.szName, rc));
            }
        }
        else
            LogFlowFunc(("enmBackendStat(=%s) != OKAY || !(fStatus(=%#x) & BACKEND_READY)\n",
                         PDMHostAudioStreamStateGetName(enmBackendState), pStreamEx->fStatus));
    }
    else
        LogFlowFunc(("fDirEnabled=false\n"));

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    return rc;
}


/**
 * Resets the given audio stream.
 *
 * @param   pStreamEx   Stream to reset.
 */
static void drvAudioStreamResetOnDisable(PDRVAUDIOSTREAM pStreamEx)
{
    drvAudioStreamResetInternal(pStreamEx);

    LogFunc(("[%s]\n", pStreamEx->Core.Cfg.szName));

    pStreamEx->fStatus            &= PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY;
    pStreamEx->Core.fWarningsShown = PDMAUDIOSTREAM_WARN_FLAGS_NONE;

#ifdef VBOX_WITH_STATISTICS
    /*
     * Reset statistics.
     */
    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_IN)
    {
    }
    else if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
    {
    }
    else
        AssertFailed();
#endif
}


/**
 * Controls an audio stream.
 *
 * @returns VBox status code.
 * @param   pThis           Pointer to driver instance.
 * @param   pStreamEx       Stream to control.
 * @param   enmStreamCmd    Control command.
 */
static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd)
{
    AssertPtr(pThis);
    AssertPtr(pStreamEx);
    Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));

#ifdef LOG_ENABLED
    char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
#endif
    LogFunc(("[%s] enmStreamCmd=%s fStatus=%s\n", pStreamEx->Core.Cfg.szName, PDMAudioStrmCmdGetName(enmStreamCmd),
             drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));

    int rc = VINF_SUCCESS;

    switch (enmStreamCmd)
    {
        case PDMAUDIOSTREAMCMD_ENABLE:
#ifdef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
            if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED))
            {
                rc = drvAudioStreamReInitInternal(pThis, pStreamEx);
                if (RT_FAILURE(rc))
                    break;
            }
#endif /* DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION */
            if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED))
            {
                /* Are we still draining this stream? Then we must disable it first. */
                if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
                {
                    LogFunc(("Stream '%s' is still draining - disabling...\n", pStreamEx->Core.Cfg.szName));
                    rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
                    AssertRC(rc);
                    if (drvAudioStreamGetBackendState(pThis, pStreamEx) != PDMHOSTAUDIOSTREAMSTATE_DRAINING)
                    {
                        pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PENDING_DISABLE);
                        drvAudioStreamResetInternal(pStreamEx);
                        rc = VINF_SUCCESS;
                    }
                }

                if (RT_SUCCESS(rc))
                {
                    /* Reset the state before we try to start. */
                    PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
                    pStreamEx->enmLastBackendState = enmBackendState;
                    pStreamEx->offInternal         = 0;

                    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
                    {
                        pStreamEx->Out.cbPreBuffered = 0;
                        pStreamEx->Out.offPreBuf     = 0;
                        pStreamEx->Out.enmPlayState  = DRVAUDIOPLAYSTATE_NOPLAY;
                        switch (enmBackendState)
                        {
                            case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
                                if (pStreamEx->cbPreBufThreshold > 0)
                                    pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
                                break;
                            case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
                                AssertFailed();
                                RT_FALL_THROUGH();
                            case PDMHOSTAUDIOSTREAMSTATE_OKAY:
                                pStreamEx->Out.enmPlayState = pStreamEx->cbPreBufThreshold > 0
                                                            ? DRVAUDIOPLAYSTATE_PREBUF : DRVAUDIOPLAYSTATE_PLAY;
                                break;
                            case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
                            case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
                                break;
                            /* no default */
                            case PDMHOSTAUDIOSTREAMSTATE_INVALID:
                            case PDMHOSTAUDIOSTREAMSTATE_END:
                            case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
                                break;
                        }
                        LogFunc(("ENABLE: enmBackendState=%s enmPlayState=%s\n", PDMHostAudioStreamStateGetName(enmBackendState),
                                 drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
                    }
                    else
                    {
                        pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_NO_CAPTURE;
                        switch (enmBackendState)
                        {
                            case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
                                pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_PREBUF;
                                break;
                            case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
                                AssertFailed();
                                RT_FALL_THROUGH();
                            case PDMHOSTAUDIOSTREAMSTATE_OKAY:
                                pStreamEx->In.enmCaptureState = pStreamEx->cbPreBufThreshold > 0
                                                              ? DRVAUDIOCAPTURESTATE_PREBUF : DRVAUDIOCAPTURESTATE_CAPTURING;
                                break;
                            case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
                            case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
                                break;
                            /* no default */
                            case PDMHOSTAUDIOSTREAMSTATE_INVALID:
                            case PDMHOSTAUDIOSTREAMSTATE_END:
                            case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
                                break;
                        }
                        LogFunc(("ENABLE: enmBackendState=%s enmCaptureState=%s\n", PDMHostAudioStreamStateGetName(enmBackendState),
                                 drvAudioCaptureStateName(pStreamEx->In.enmCaptureState)));
                    }

                    rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
                    if (RT_SUCCESS(rc))
                    {
                        pStreamEx->nsStarted = RTTimeNanoTS();
                        pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_ENABLED;
                        PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                    }
                }
            }
            break;

        case PDMAUDIOSTREAMCMD_DISABLE:
#ifndef DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION
            if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
            {
                rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
                LogFunc(("DISABLE '%s': Backend DISABLE -> %Rrc\n", pStreamEx->Core.Cfg.szName, rc));
                if (RT_SUCCESS(rc)) /** @todo ignore this and reset it anyway? */
                    drvAudioStreamResetOnDisable(pStreamEx);
            }
#else
            if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
                rc = drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);
#endif /* DRVAUDIO_WITH_STREAM_DESTRUCTION_IN_DISABLED_DIRECTION */
            break;

        case PDMAUDIOSTREAMCMD_PAUSE:
            if ((pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PAUSED)) == PDMAUDIOSTREAM_STS_ENABLED)
            {
                rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
                if (RT_SUCCESS(rc))
                {
                    pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PAUSED;
                    PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                }
            }
            break;

        case PDMAUDIOSTREAMCMD_RESUME:
            if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PAUSED)
            {
                Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED);
                rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_RESUME);
                if (RT_SUCCESS(rc))
                {
                    pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_PAUSED;
                    PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                }
            }
            break;

        case PDMAUDIOSTREAMCMD_DRAIN:
            /*
             * Only for output streams and we don't want this command more than once.
             */
            AssertReturn(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT, VERR_INVALID_FUNCTION);
            AssertBreak(!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE));
            if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
            {
                rc = VERR_INTERNAL_ERROR_2;
                switch (pStreamEx->Out.enmPlayState)
                {
                    case DRVAUDIOPLAYSTATE_PREBUF:
                        if (pStreamEx->Out.cbPreBuffered > 0)
                        {
                            LogFunc(("DRAIN '%s': Initiating draining of pre-buffered data...\n", pStreamEx->Core.Cfg.szName));
                            pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
                            pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
                            PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                            rc = VINF_SUCCESS;
                            break;
                        }
                        RT_FALL_THROUGH();
                    case DRVAUDIOPLAYSTATE_NOPLAY:
                    case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
                    case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
                        LogFunc(("DRAIN '%s': Nothing to drain (enmPlayState=%s)\n",
                                 pStreamEx->Core.Cfg.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
                        rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
                        AssertRC(rc);
                        drvAudioStreamResetOnDisable(pStreamEx);
                        break;

                    case DRVAUDIOPLAYSTATE_PLAY:
                    case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
                        LogFunc(("DRAIN '%s': Initiating backend draining (enmPlayState=%s -> NOPLAY) ...\n",
                                 pStreamEx->Core.Cfg.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
                        pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
                        rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DRAIN);
                        if (RT_SUCCESS(rc))
                        {
                            pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
                            PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                        }
                        else
                        {
                            LogFunc(("DRAIN '%s': Backend DRAIN failed with %Rrc, disabling the stream instead...\n",
                                     pStreamEx->Core.Cfg.szName, rc));
                            rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
                            AssertRC(rc);
                            drvAudioStreamResetOnDisable(pStreamEx);
                        }
                        break;

                    case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
                        LogFunc(("DRAIN '%s': Initiating draining of pre-buffered data (already committing)...\n",
                                 pStreamEx->Core.Cfg.szName));
                        pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
                        PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
                        rc = VINF_SUCCESS;
                        break;

                    /* no default */
                    case DRVAUDIOPLAYSTATE_INVALID:
                    case DRVAUDIOPLAYSTATE_END:
                        AssertFailedBreak();
                }
            }
            break;

        default:
            rc = VERR_NOT_IMPLEMENTED;
            break;
    }

    if (RT_FAILURE(rc))
        LogFunc(("[%s] Failed with %Rrc\n", pStreamEx->Core.Cfg.szName, rc));

    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamControl}
 */
static DECLCALLBACK(int) drvAudioStreamControl(PPDMIAUDIOCONNECTOR pInterface,
                                               PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);

    /** @todo r=bird: why?  It's not documented to ignore NULL streams.   */
    if (!pStream)
        return VINF_SUCCESS;
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, rc);

    LogFlowFunc(("[%s] enmStreamCmd=%s\n", pStreamEx->Core.Cfg.szName, PDMAudioStrmCmdGetName(enmStreamCmd)));

    rc = drvAudioStreamControlInternal(pThis, pStreamEx, enmStreamCmd);

    RTCritSectLeave(&pStreamEx->Core.CritSect);
    return rc;
}


/**
 * Copy data to the pre-buffer, ring-buffer style.
 *
 * The @a cbMax parameter is almost always set to the threshold size, the
 * exception is when commiting the buffer and we want to top it off to reduce
 * the number of transfers to the backend (the first transfer may start
 * playback, so more data is better).
 */
static int drvAudioStreamPreBuffer(PDRVAUDIOSTREAM pStreamEx, const uint8_t *pbBuf, uint32_t cbBuf, uint32_t cbMax)
{
    uint32_t const cbAlloc = pStreamEx->Out.cbPreBufAlloc;
    AssertReturn(cbAlloc >= cbMax, VERR_INTERNAL_ERROR_3);
    AssertReturn(cbAlloc >= 8, VERR_INTERNAL_ERROR_4);
    AssertReturn(cbMax >= 8, VERR_INTERNAL_ERROR_5);

    uint32_t offRead = pStreamEx->Out.offPreBuf;
    uint32_t cbCur   = pStreamEx->Out.cbPreBuffered;
    AssertStmt(offRead < cbAlloc, offRead %= cbAlloc);
    AssertStmt(cbCur <= cbMax, offRead = (offRead + cbCur - cbMax) % cbAlloc; cbCur = cbMax);

    /*
     * First chunk.
     */
    uint32_t offWrite = (offRead + cbCur) % cbAlloc;
    uint32_t cbToCopy = RT_MIN(cbAlloc - offWrite, cbBuf);
    memcpy(&pStreamEx->Out.pbPreBuf[offWrite], pbBuf, cbToCopy);

    /* Advance. */
    offWrite = (offWrite + cbToCopy) % cbAlloc;
    for (;;)
    {
        pbBuf    += cbToCopy;
        cbCur    += cbToCopy;
        if (cbCur > cbMax)
            offRead = (offRead + cbCur - cbMax) % cbAlloc;
        cbBuf    -= cbToCopy;
        if (!cbBuf)
            break;

        /*
         * Second+ chunk, from the start of the buffer.
         *
         * Note! It is assumed very unlikely that we will ever see a cbBuf larger than
         *       cbMax, so we don't waste space on clipping cbBuf here (can happen with
         *       custom pre-buffer sizes).
         */
        Assert(offWrite == 0);
        cbToCopy = RT_MIN(cbAlloc, cbBuf);
        memcpy(pStreamEx->Out.pbPreBuf, pbBuf, cbToCopy);
    }

    /*
     * Update the pre-buffering size and position.
     */
    pStreamEx->Out.cbPreBuffered = RT_MIN(cbCur, cbMax);
    pStreamEx->Out.offPreBuf     = offRead;
    return VINF_SUCCESS;
}


/**
 * Worker for drvAudioStreamPlay() and drvAudioStreamPreBufComitting().
 *
 * Caller owns the lock.
 */
static int drvAudioStreamPlayLocked(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
                                    const uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbWritten)
{
    Log3Func(("%s: @%#RX64: cbBuf=%#x\n", pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbBuf));

    uint32_t      cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
    pStreamEx->Out.Stats.cbBackendWritableBefore = cbWritable;

    uint32_t      cbWritten  = 0;
    int           rc         = VINF_SUCCESS;
    uint8_t const cbFrame    = PDMAudioPropsFrameSize(&pStreamEx->Core.Cfg.Props);
    while (cbBuf >= cbFrame && cbWritable >= cbFrame)
    {
        uint32_t const cbToWrite    = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Cfg.Props, RT_MIN(cbBuf, cbWritable));
        uint32_t       cbWrittenNow = 0;
        rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, pbBuf, cbToWrite, &cbWrittenNow);
        if (RT_SUCCESS(rc))
        {
            if (cbWrittenNow != cbToWrite)
                Log3Func(("%s: @%#RX64: Wrote fewer bytes than requested: %#x, requested %#x\n",
                          pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbWrittenNow, cbToWrite));
#ifdef DEBUG_bird
            Assert(cbWrittenNow == cbToWrite);
#endif
            AssertStmt(cbWrittenNow <= cbToWrite, cbWrittenNow = cbToWrite);
            cbWritten              += cbWrittenNow;
            cbBuf                  -= cbWrittenNow;
            pbBuf                  += cbWrittenNow;
            pStreamEx->offInternal += cbWrittenNow;
        }
        else
        {
            *pcbWritten = cbWritten;
            LogFunc(("%s: @%#RX64: pfnStreamPlay failed writing %#x bytes (%#x previous written, %#x writable): %Rrc\n",
                     pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbToWrite, cbWritten, cbWritable, rc));
            return cbWritten ? VINF_SUCCESS : rc;
        }

        cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
    }

    STAM_PROFILE_ADD_PERIOD(&pStreamEx->StatXfer, cbWritten);
    *pcbWritten = cbWritten;
    pStreamEx->Out.Stats.cbBackendWritableAfter = cbWritable;
    if (cbWritten)
        pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();

    Log3Func(("%s: @%#RX64: Wrote %#x bytes (%#x bytes left)\n", pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbWritten, cbBuf));
    return rc;
}


/**
 * Worker for drvAudioStreamPlay() and drvAudioStreamPreBufComitting().
 */
static int drvAudioStreamPlayToPreBuffer(PDRVAUDIOSTREAM pStreamEx, const void *pvBuf, uint32_t cbBuf, uint32_t cbMax,
                                         uint32_t *pcbWritten)
{
    int rc = drvAudioStreamPreBuffer(pStreamEx, (uint8_t const *)pvBuf, cbBuf, cbMax);
    if (RT_SUCCESS(rc))
    {
        *pcbWritten = cbBuf;
        pStreamEx->offInternal += cbBuf;
        Log3Func(("[%s] Pre-buffering (%s): wrote %#x bytes => %#x bytes / %u%%\n",
                  pStreamEx->Core.Cfg.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState), cbBuf, pStreamEx->Out.cbPreBuffered,
                  pStreamEx->Out.cbPreBuffered * 100 / RT_MAX(pStreamEx->cbPreBufThreshold, 1)));

    }
    else
        *pcbWritten = 0;
    return rc;
}


/**
 * Used when we're committing (transfering) the pre-buffered bytes to the
 * device.
 *
 * This is called both from drvAudioStreamPlay() and
 * drvAudioStreamIterateInternal().
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to the DrvAudio instance data.
 * @param   pStreamEx   The stream to commit the pre-buffering for.
 * @param   pbBuf       Buffer with new bytes to write.  Can be NULL when called
 *                      in the PENDING_DISABLE state from
 *                      drvAudioStreamIterateInternal().
 * @param   cbBuf       Number of new bytes.  Can be zero.
 * @param   pcbWritten  Where to return the number of bytes written.
 *
 * @note    Locking: Stream critsect and hot-plug in shared mode.
 */
static int drvAudioStreamPreBufComitting(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
                                         const uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbWritten)
{
    /*
     * First, top up the buffer with new data from pbBuf.
     */
    *pcbWritten = 0;
    if (cbBuf > 0)
    {
        uint32_t const cbToCopy = RT_MIN(pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered, cbBuf);
        if (cbToCopy > 0)
        {
            int rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pbBuf, cbBuf, pStreamEx->Out.cbPreBufAlloc, pcbWritten);
            AssertRCReturn(rc, rc);
            pbBuf += cbToCopy;
            cbBuf -= cbToCopy;
        }
    }

    AssertReturn(pThis->pHostDrvAudio, VERR_AUDIO_BACKEND_NOT_ATTACHED);

    /*
     * Write the pre-buffered chunk.
     */
    int             rc      = VINF_SUCCESS;
    uint32_t const  cbAlloc = pStreamEx->Out.cbPreBufAlloc;
    AssertReturn(cbAlloc > 0, VERR_INTERNAL_ERROR_2);
    uint32_t        off     = pStreamEx->Out.offPreBuf;
    AssertStmt(off < pStreamEx->Out.cbPreBufAlloc, off %= cbAlloc);
    uint32_t        cbLeft  = pStreamEx->Out.cbPreBuffered;
    while (cbLeft > 0)
    {
        uint32_t const cbToWrite = RT_MIN(cbAlloc - off, cbLeft);
        Assert(cbToWrite > 0);

        uint32_t cbPreBufWritten = 0;
        rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, &pStreamEx->Out.pbPreBuf[off],
                                                 cbToWrite, &cbPreBufWritten);
        AssertRCBreak(rc);
        if (!cbPreBufWritten)
            break;
        AssertStmt(cbPreBufWritten <= cbToWrite, cbPreBufWritten = cbToWrite);
        off     = (off + cbPreBufWritten) % cbAlloc;
        cbLeft -= cbPreBufWritten;
    }

    if (cbLeft == 0)
    {
        LogFunc(("@%#RX64: Wrote all %#x bytes of pre-buffered audio data. %s -> PLAY\n", pStreamEx->offInternal,
                 pStreamEx->Out.cbPreBuffered, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
        pStreamEx->Out.cbPreBuffered = 0;
        pStreamEx->Out.offPreBuf     = 0;
        pStreamEx->Out.enmPlayState  = DRVAUDIOPLAYSTATE_PLAY;

        if (cbBuf > 0)
        {
            uint32_t cbWritten2 = 0;
            rc = drvAudioStreamPlayLocked(pThis, pStreamEx, pbBuf, cbBuf, &cbWritten2);
            if (RT_SUCCESS(rc))
                *pcbWritten += cbWritten2;
        }
        else
            pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
    }
    else
    {
        if (cbLeft != pStreamEx->Out.cbPreBuffered)
            pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();

        LogRel2(("Audio: @%#RX64: Stream '%s' pre-buffering commit problem: wrote %#x out of %#x + %#x - rc=%Rrc *pcbWritten=%#x %s -> PREBUF_COMMITTING\n",
                 pStreamEx->offInternal, pStreamEx->Core.Cfg.szName, pStreamEx->Out.cbPreBuffered - cbLeft,
                 pStreamEx->Out.cbPreBuffered, cbBuf, rc, *pcbWritten, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
        AssertMsg(   pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF_COMMITTING
                  || pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF
                  || RT_FAILURE(rc),
                  ("Buggy host driver buffer reporting? cbLeft=%#x cbPreBuffered=%#x enmPlayState=%s\n",
                   cbLeft, pStreamEx->Out.cbPreBuffered, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));

        pStreamEx->Out.cbPreBuffered = cbLeft;
        pStreamEx->Out.offPreBuf     = off;
        pStreamEx->Out.enmPlayState  = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
    }

    return *pcbWritten ? VINF_SUCCESS : rc;
}


/**
 * Does one iteration of an audio stream.
 *
 * This function gives the backend the chance of iterating / altering data and
 * does the actual mixing between the guest <-> host mixing buffers.
 *
 * @returns VBox status code.
 * @param   pThis       Pointer to driver instance.
 * @param   pStreamEx   Stream to iterate.
 */
static int drvAudioStreamIterateInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
{
    AssertPtrReturn(pThis, VERR_INVALID_POINTER);

#ifdef LOG_ENABLED
    char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
#endif
    Log3Func(("[%s] fStatus=%s\n", pStreamEx->Core.Cfg.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));

    /* Not enabled or paused? Skip iteration. */
    if ((pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PAUSED)) != PDMAUDIOSTREAM_STS_ENABLED)
        return VINF_SUCCESS;

    /*
     * Pending disable is really what we're here for.
     *
     * This only happens to output streams.  We ASSUME the caller (MixerBuffer)
     * implements a timeout on the draining, so we skip that here.
     */
    if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
    { /* likely until we get to the end of the stream at least. */ }
    else
    {
        AssertReturn(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT, VINF_SUCCESS);
        RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

        /*
         * Move pre-buffered samples to the backend.
         */
        if (pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF_COMMITTING)
        {
            if (pStreamEx->Out.cbPreBuffered > 0)
            {
                uint32_t cbIgnored = 0;
                drvAudioStreamPreBufComitting(pThis, pStreamEx, NULL, 0, &cbIgnored);
                Log3Func(("Stream '%s': Transferred %#x bytes\n", pStreamEx->Core.Cfg.szName, cbIgnored));
            }
            if (pStreamEx->Out.cbPreBuffered == 0)
            {
                Log3Func(("Stream '%s': No more pre-buffered data -> NOPLAY + backend DRAIN\n", pStreamEx->Core.Cfg.szName));
                pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;

                int rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DRAIN);
                if (RT_FAILURE(rc))
                {
                    LogFunc(("Stream '%s': Backend DRAIN failed with %Rrc, disabling the stream instead...\n",
                             pStreamEx->Core.Cfg.szName, rc));
                    rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
                    AssertRC(rc);
                    drvAudioStreamResetOnDisable(pStreamEx);
                }
            }
        }
        else
            Assert(pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_NOPLAY);

        /*
         * Check the backend status to see if it's still draining and to
         * update our status when it stops doing so.
         */
        PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
        if (enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING)
        {
            uint32_t cbIgnored = 0;
            pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, NULL, 0, &cbIgnored);
        }
        else
        {
            LogFunc(("Stream '%s': Backend finished draining.\n", pStreamEx->Core.Cfg.szName));
            drvAudioStreamResetOnDisable(pStreamEx);
        }

        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    }

    /* Update timestamps. */
    pStreamEx->nsLastIterated = RTTimeNanoTS();

    return VINF_SUCCESS; /** @todo r=bird: What can the caller do with an error status here? */
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamIterate}
 */
static DECLCALLBACK(int) drvAudioStreamIterate(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, rc);

    rc = drvAudioStreamIterateInternal(pThis, pStreamEx);

    RTCritSectLeave(&pStreamEx->Core.CritSect);

    if (RT_FAILURE(rc))
        LogFlowFuncLeaveRC(rc);
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetState}
 */
static DECLCALLBACK(PDMAUDIOSTREAMSTATE) drvAudioStreamGetState(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    PDRVAUDIO       pThis     = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, PDMAUDIOSTREAMSTATE_INVALID);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, PDMAUDIOSTREAMSTATE_INVALID);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, PDMAUDIOSTREAMSTATE_INVALID);
    STAM_PROFILE_START(&pStreamEx->StatProfGetState, a);

    /*
     * Get the status mask.
     */
    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, PDMAUDIOSTREAMSTATE_INVALID);
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
    uint32_t const                fStrmStatus     = pStreamEx->fStatus;
    PDMAUDIODIR const             enmDir          = pStreamEx->Core.Cfg.enmDir;
    Assert(enmDir == PDMAUDIODIR_IN || enmDir == PDMAUDIODIR_OUT);

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    RTCritSectLeave(&pStreamEx->Core.CritSect);

    /*
     * Translate it to state enum value.
     */
    PDMAUDIOSTREAMSTATE enmState;
    if (!(fStrmStatus & PDMAUDIOSTREAM_STS_NEED_REINIT))
    {
        if (fStrmStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
        {
            if (   (fStrmStatus & PDMAUDIOSTREAM_STS_ENABLED)
                && drvAudioStreamIsDirectionEnabled(pThis, pStreamEx->Core.Cfg.enmDir)
                && (   enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
                    || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING
                    || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_INITIALIZING ))
                enmState = enmDir == PDMAUDIODIR_IN ? PDMAUDIOSTREAMSTATE_ENABLED_READABLE : PDMAUDIOSTREAMSTATE_ENABLED_WRITABLE;
            else
                enmState = PDMAUDIOSTREAMSTATE_INACTIVE;
        }
        else
            enmState = PDMAUDIOSTREAMSTATE_NOT_WORKING;
    }
    else
        enmState = PDMAUDIOSTREAMSTATE_NEED_REINIT;

    STAM_PROFILE_STOP(&pStreamEx->StatProfGetState, a);
#ifdef LOG_ENABLED
    char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
#endif
    Log3Func(("[%s] returns %s (status: %s)\n", pStreamEx->Core.Cfg.szName, PDMAudioStreamStateGetName(enmState),
              drvAudioStreamStatusToStr(szStreamSts, fStrmStatus)));
    return enmState;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetWritable}
 */
static DECLCALLBACK(uint32_t) drvAudioStreamGetWritable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, 0);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, 0);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, 0);
    AssertMsgReturn(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT, ("Can't write to a non-output stream\n"), 0);
    STAM_PROFILE_START(&pStreamEx->Out.Stats.ProfGetWritable, a);

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, 0);
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    /*
     * Use the playback and backend states to determin how much can be written, if anything.
     */
    uint32_t cbWritable = 0;
    DRVAUDIOPLAYSTATE const       enmPlayMode     = pStreamEx->Out.enmPlayState;
    PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
    if (   PDMAudioStrmStatusCanWrite(pStreamEx->fStatus)
        && pThis->pHostDrvAudio != NULL
        && enmBackendState != PDMHOSTAUDIOSTREAMSTATE_DRAINING)
    {
        switch (enmPlayMode)
        {
            /*
             * Whatever the backend can hold.
             */
            case DRVAUDIOPLAYSTATE_PLAY:
            case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
                Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
                cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
                break;

            /*
             * Whatever we've got of available space in the pre-buffer.
             * Note! For the last round when we pass the pre-buffering threshold, we may
             *       report fewer bytes than what a DMA timer period for the guest device
             *       typically produces, however that should be transfered in the following
             *       round that goes directly to the backend buffer.
             */
            case DRVAUDIOPLAYSTATE_PREBUF:
                cbWritable = pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered;
                if (!cbWritable)
                    cbWritable = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Cfg.Props, 2);
                break;

            /*
             * These are slightly more problematic and can go wrong if the pre-buffer is
             * manually configured to be smaller than the output of a typeical DMA timer
             * period for the guest device.  So, to overcompensate, we just report back
             * the backend buffer size (the pre-buffer is circular, so no overflow issue).
             */
            case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
            case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
                cbWritable = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Cfg.Props,
                                                        RT_MAX(pStreamEx->Core.Cfg.Backend.cFramesBufferSize,
                                                               pStreamEx->Core.Cfg.Backend.cFramesPreBuffering));
                break;

            case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
            {
                /* Buggy backend: We weren't able to copy all the pre-buffered data to it
                   when reaching the threshold.  Try escape this situation, or at least
                   keep the extra buffering to a minimum.  We must try write something
                   as long as there is space for it, as we need the pfnStreamWrite call
                   to move the data. */
                Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
                uint32_t const cbMin = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Cfg.Props, 8);
                cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
                if (cbWritable >= pStreamEx->Out.cbPreBuffered + cbMin)
                    cbWritable -= pStreamEx->Out.cbPreBuffered + cbMin / 2;
                else
                    cbWritable = RT_MIN(cbMin, pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered);
                AssertLogRel(cbWritable);
                break;
            }

            case DRVAUDIOPLAYSTATE_NOPLAY:
                break;
            case DRVAUDIOPLAYSTATE_INVALID:
            case DRVAUDIOPLAYSTATE_END:
                AssertFailed();
                break;
        }

        /* Make sure to align the writable size to the host's frame size. */
        cbWritable = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Cfg.Props, cbWritable);
    }

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    STAM_PROFILE_ADD_PERIOD(&pStreamEx->Out.Stats.ProfGetWritableBytes, cbWritable);
    STAM_PROFILE_STOP(&pStreamEx->Out.Stats.ProfGetWritable, a);
    RTCritSectLeave(&pStreamEx->Core.CritSect);
    Log3Func(("[%s] cbWritable=%#RX32 (%RU64ms) enmPlayMode=%s enmBackendState=%s\n",
              pStreamEx->Core.Cfg.szName, cbWritable, PDMAudioPropsBytesToMilli(&pStreamEx->Core.Cfg.Props, cbWritable),
              drvAudioPlayStateName(enmPlayMode), PDMHostAudioStreamStateGetName(enmBackendState) ));
    return cbWritable;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamPlay}
 */
static DECLCALLBACK(int) drvAudioStreamPlay(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
                                            const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);

    /*
     * Check input and sanity.
     */
    AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
    AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
    AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
    uint32_t uTmp;
    if (pcbWritten)
        AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
    else
        pcbWritten = &uTmp;

    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertMsgReturn(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT,
                    ("Stream '%s' is not an output stream and therefore cannot be written to (direction is '%s')\n",
                     pStreamEx->Core.Cfg.szName, PDMAudioDirGetName(pStreamEx->Core.Cfg.enmDir)), VERR_ACCESS_DENIED);

    AssertMsg(PDMAudioPropsIsSizeAligned(&pStreamEx->Core.Cfg.Props, cbBuf),
              ("Stream '%s' got a non-frame-aligned write (%#RX32 bytes)\n", pStreamEx->Core.Cfg.szName, cbBuf));
    STAM_PROFILE_START(&pStreamEx->Out.Stats.ProfPlay, a);

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, rc);

    /*
     * First check that we can write to the stream, and if not,
     * whether to just drop the input into the bit bucket.
     */
    if (PDMAudioStrmStatusIsReady(pStreamEx->fStatus))
    {
        RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
        if (   pThis->Out.fEnabled /* (see @bugref{9882}) */
            && pThis->pHostDrvAudio != NULL)
        {
            /*
             * Get the backend state and process changes to it since last time we checked.
             */
            PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);

            /*
             * Do the transfering.
             */
            switch (pStreamEx->Out.enmPlayState)
            {
                case DRVAUDIOPLAYSTATE_PLAY:
                    Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                    Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
                    rc = drvAudioStreamPlayLocked(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
                    break;

                case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
                    Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                    Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
                    rc = drvAudioStreamPlayLocked(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
                    drvAudioStreamPreBuffer(pStreamEx, (uint8_t const *)pvBuf, *pcbWritten, pStreamEx->cbPreBufThreshold);
                    break;

                case DRVAUDIOPLAYSTATE_PREBUF:
                    if (cbBuf + pStreamEx->Out.cbPreBuffered < pStreamEx->cbPreBufThreshold)
                        rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
                    else if (   enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
                             && (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY))
                    {
                        Log3Func(("[%s] Pre-buffering completing: cbBuf=%#x cbPreBuffered=%#x => %#x vs cbPreBufThreshold=%#x\n",
                                  pStreamEx->Core.Cfg.szName, cbBuf, pStreamEx->Out.cbPreBuffered,
                                  cbBuf + pStreamEx->Out.cbPreBuffered, pStreamEx->cbPreBufThreshold));
                        rc = drvAudioStreamPreBufComitting(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
                    }
                    else
                    {
                        Log3Func(("[%s] Pre-buffering completing but device not ready: cbBuf=%#x cbPreBuffered=%#x => %#x vs cbPreBufThreshold=%#x; PREBUF -> PREBUF_OVERDUE\n",
                                  pStreamEx->Core.Cfg.szName, cbBuf, pStreamEx->Out.cbPreBuffered,
                                  cbBuf + pStreamEx->Out.cbPreBuffered, pStreamEx->cbPreBufThreshold));
                        pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_OVERDUE;
                        rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
                    }
                    break;

                case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
                    Assert(   !(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY)
                           || enmBackendState != PDMHOSTAUDIOSTREAMSTATE_OKAY);
                    RT_FALL_THRU();
                case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
                    rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
                    break;

                case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
                    Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                    Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
                    rc = drvAudioStreamPreBufComitting(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
                    break;

                case DRVAUDIOPLAYSTATE_NOPLAY:
                    *pcbWritten = cbBuf;
                    pStreamEx->offInternal += cbBuf;
                    Log3Func(("[%s] Discarding the data, backend state: %s\n", pStreamEx->Core.Cfg.szName,
                              PDMHostAudioStreamStateGetName(enmBackendState) ));
                    break;

                default:
                    *pcbWritten = cbBuf;
                    AssertMsgFailedBreak(("%d; cbBuf=%#x\n", pStreamEx->Out.enmPlayState, cbBuf));
            }

            if (!pStreamEx->Out.Dbg.pFilePlay || RT_FAILURE(rc))
            { /* likely */ }
            else
                AudioHlpFileWrite(pStreamEx->Out.Dbg.pFilePlay, pvBuf, *pcbWritten);
        }
        else
        {
            *pcbWritten = cbBuf;
            pStreamEx->offInternal += cbBuf;
            Log3Func(("[%s] Backend stream %s, discarding the data\n", pStreamEx->Core.Cfg.szName,
                      !pThis->Out.fEnabled ? "disabled" : !pThis->pHostDrvAudio ? "not attached" : "not ready yet"));
        }
        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    }
    else
        rc = VERR_AUDIO_STREAM_NOT_READY;

    STAM_PROFILE_STOP(&pStreamEx->Out.Stats.ProfPlay, a);
    RTCritSectLeave(&pStreamEx->Core.CritSect);
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetReadable}
 */
static DECLCALLBACK(uint32_t) drvAudioStreamGetReadable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, 0);
    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, 0);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, 0);
    AssertMsg(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_IN, ("Can't read from a non-input stream\n"));
    STAM_PROFILE_START(&pStreamEx->In.Stats.ProfGetReadable, a);

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, 0);
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

    /*
     * Use the capture state to determin how much can be written, if anything.
     */
    uint32_t cbReadable = 0;
    DRVAUDIOCAPTURESTATE const    enmCaptureState = pStreamEx->In.enmCaptureState;
    PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx); RT_NOREF(enmBackendState);
    if (   PDMAudioStrmStatusCanRead(pStreamEx->fStatus)
        && pThis->pHostDrvAudio != NULL)
    {
        switch (enmCaptureState)
        {
            /*
             * Whatever the backend has to offer when in capture mode.
             */
            case DRVAUDIOCAPTURESTATE_CAPTURING:
                Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
                cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
                break;

            /*
             * Same calculation as in drvAudioStreamCaptureSilence, only we cap it
             * at the pre-buffering threshold so we don't get into trouble when we
             * switch to capture mode between now and pfnStreamCapture.
             */
            case DRVAUDIOCAPTURESTATE_PREBUF:
            {
                uint64_t const cNsStream = RTTimeNanoTS() - pStreamEx->nsStarted;
                uint64_t const offCur    = PDMAudioPropsNanoToBytes64(&pStreamEx->Core.Cfg.Props, cNsStream);
                if (offCur > pStreamEx->offInternal)
                {
                    uint64_t const cbUnread = offCur - pStreamEx->offInternal;
                    cbReadable = (uint32_t)RT_MIN(pStreamEx->cbPreBufThreshold, cbUnread);
                }
                break;
            }

            case DRVAUDIOCAPTURESTATE_NO_CAPTURE:
                break;

            case DRVAUDIOCAPTURESTATE_INVALID:
            case DRVAUDIOCAPTURESTATE_END:
                AssertFailed();
                break;
        }

        /* Make sure to align the readable size to the host's frame size. */
        cbReadable = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Cfg.Props, cbReadable);
    }

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    STAM_PROFILE_ADD_PERIOD(&pStreamEx->In.Stats.ProfGetReadableBytes, cbReadable);
    STAM_PROFILE_STOP(&pStreamEx->In.Stats.ProfGetReadable, a);
    RTCritSectLeave(&pStreamEx->Core.CritSect);
    Log3Func(("[%s] cbReadable=%#RX32 (%RU64ms) enmCaptureMode=%s enmBackendState=%s\n",
              pStreamEx->Core.Cfg.szName, cbReadable, PDMAudioPropsBytesToMilli(&pStreamEx->Core.Cfg.Props, cbReadable),
              drvAudioCaptureStateName(enmCaptureState), PDMHostAudioStreamStateGetName(enmBackendState) ));
    return cbReadable;
}


/**
 * Worker for drvAudioStreamCapture that returns silence.
 *
 * The amount of silence returned is a function of how long the stream has been
 * enabled.
 *
 * @returns VINF_SUCCESS
 * @param   pStreamEx   The stream to commit the pre-buffering for.
 * @param   pbBuf       The output buffer.
 * @param   cbBuf       The size of the output buffer.
 * @param   pcbRead     Where to return the number of bytes actually read.
 */
static int drvAudioStreamCaptureSilence(PDRVAUDIOSTREAM pStreamEx, uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbRead)
{
    /** @todo  Does not take paused time into account...  */
    uint64_t const cNsStream = RTTimeNanoTS() - pStreamEx->nsStarted;
    uint64_t const offCur    = PDMAudioPropsNanoToBytes64(&pStreamEx->Core.Cfg.Props, cNsStream);
    if (offCur > pStreamEx->offInternal)
    {
        uint64_t const cbUnread  = offCur - pStreamEx->offInternal;
        uint32_t const cbToClear = (uint32_t)RT_MIN(cbBuf, cbUnread);
        *pcbRead                 = cbToClear;
        pStreamEx->offInternal  += cbToClear;
        cbBuf                   -= cbToClear;
        PDMAudioPropsClearBuffer(&pStreamEx->Core.Cfg.Props, pbBuf, cbToClear,
                                 PDMAudioPropsBytesToFrames(&pStreamEx->Core.Cfg.Props, cbToClear));
    }
    else
        *pcbRead = 0;
    Log4Func(("%s: @%#RX64: Read %#x bytes of silence (%#x bytes left)\n",
              pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, *pcbRead, cbBuf));
    return VINF_SUCCESS;
}


/**
 * Worker for drvAudioStreamCapture.
 */
static int drvAudioStreamCaptureLocked(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
                                       uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbRead)
{
    Log4Func(("%s: @%#RX64: cbBuf=%#x\n", pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbBuf));

    uint32_t      cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
    pStreamEx->In.Stats.cbBackendReadableBefore = cbReadable;

    uint32_t      cbRead     = 0;
    int           rc         = VINF_SUCCESS;
    uint8_t const cbFrame    = PDMAudioPropsFrameSize(&pStreamEx->Core.Cfg.Props);
    while (cbBuf >= cbFrame && cbReadable >= cbFrame)
    {
        uint32_t const cbToRead  = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Cfg.Props, RT_MIN(cbBuf, cbReadable));
        uint32_t       cbReadNow = 0;
        rc = pThis->pHostDrvAudio->pfnStreamCapture(pThis->pHostDrvAudio, pStreamEx->pBackend, pbBuf, cbToRead, &cbReadNow);
        if (RT_SUCCESS(rc))
        {
            if (cbReadNow != cbToRead)
                Log4Func(("%s: @%#RX64: Read fewer bytes than requested: %#x, requested %#x\n",
                          pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbReadNow, cbToRead));
#ifdef DEBUG_bird
            Assert(cbReadNow == cbToRead);
#endif
            AssertStmt(cbReadNow <= cbToRead, cbReadNow = cbToRead);
            cbRead                 += cbReadNow;
            cbBuf                  -= cbReadNow;
            pbBuf                  += cbReadNow;
            pStreamEx->offInternal += cbReadNow;
        }
        else
        {
            *pcbRead = cbRead;
            LogFunc(("%s: @%#RX64: pfnStreamCapture failed read %#x bytes (%#x previous read, %#x readable): %Rrc\n",
                     pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbToRead, cbRead, cbReadable, rc));
            return cbRead ? VINF_SUCCESS : rc;
        }

        cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
    }

    STAM_PROFILE_ADD_PERIOD(&pStreamEx->StatXfer, cbRead);
    *pcbRead = cbRead;
    pStreamEx->In.Stats.cbBackendReadableAfter = cbReadable;
    if (cbRead)
        pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();

    Log4Func(("%s: @%#RX64: Read %#x bytes (%#x bytes left)\n", pStreamEx->Core.Cfg.szName, pStreamEx->offInternal, cbRead, cbBuf));
    return rc;
}


/**
 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCapture}
 */
static DECLCALLBACK(int) drvAudioStreamCapture(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
                                               void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
    AssertPtr(pThis);

    /*
     * Check input and sanity.
     */
    AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
    AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
    AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
    AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
    uint32_t uTmp;
    if (pcbRead)
        AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
    else
        pcbRead = &uTmp;

    AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertReturn(pStreamEx->uMagic      == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    AssertMsgReturn(pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_IN,
                    ("Stream '%s' is not an input stream and therefore cannot be read from (direction is '%s')\n",
                     pStreamEx->Core.Cfg.szName, PDMAudioDirGetName(pStreamEx->Core.Cfg.enmDir)), VERR_ACCESS_DENIED);

    AssertMsg(PDMAudioPropsIsSizeAligned(&pStreamEx->Core.Cfg.Props, cbBuf),
              ("Stream '%s' got a non-frame-aligned write (%#RX32 bytes)\n", pStreamEx->Core.Cfg.szName, cbBuf));
    STAM_PROFILE_START(&pStreamEx->In.Stats.ProfCapture, a);

    int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertRCReturn(rc, rc);

    /*
     * First check that we can read from the stream, and if not,
     * whether to just drop the input into the bit bucket.
     */
    if (PDMAudioStrmStatusIsReady(pStreamEx->fStatus))
    {
        RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
        if (   pThis->In.fEnabled /* (see @bugref{9882}) */
            && pThis->pHostDrvAudio != NULL)
        {
            /*
             * Get the backend state and process changes to it since last time we checked.
             */
            PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);

            /*
             * Do the transfering.
             */
            switch (pStreamEx->In.enmCaptureState)
            {
                case DRVAUDIOCAPTURESTATE_CAPTURING:
                    Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
                    Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
                    rc = drvAudioStreamCaptureLocked(pThis, pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
                    break;

                case DRVAUDIOCAPTURESTATE_PREBUF:
                    if (enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY)
                    {
                        uint32_t const cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio,
                                                                                               pStreamEx->pBackend);
                        if (cbReadable >= pStreamEx->cbPreBufThreshold)
                        {
                            Log4Func(("[%s] Pre-buffering completed: cbReadable=%#x vs cbPreBufThreshold=%#x (cbBuf=%#x)\n",
                                      pStreamEx->Core.Cfg.szName, cbReadable, pStreamEx->cbPreBufThreshold, cbBuf));
                            pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_CAPTURING;
                            rc = drvAudioStreamCaptureLocked(pThis, pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
                            break;
                        }
                        pStreamEx->In.Stats.cbBackendReadableBefore = cbReadable;
                        pStreamEx->In.Stats.cbBackendReadableAfter  = cbReadable;
                        Log4Func(("[%s] Pre-buffering: Got %#x out of %#x\n",
                                  pStreamEx->Core.Cfg.szName, cbReadable, pStreamEx->cbPreBufThreshold));
                    }
                    else
                        Log4Func(("[%s] Pre-buffering: Backend status %s\n",
                                  pStreamEx->Core.Cfg.szName, PDMHostAudioStreamStateGetName(enmBackendState) ));
                    drvAudioStreamCaptureSilence(pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
                    break;

                case DRVAUDIOCAPTURESTATE_NO_CAPTURE:
                    *pcbRead = 0;
                    Log4Func(("[%s] Not capturing - backend state: %s\n",
                              pStreamEx->Core.Cfg.szName, PDMHostAudioStreamStateGetName(enmBackendState) ));
                    break;

                default:
                    *pcbRead = 0;
                    AssertMsgFailedBreak(("%d; cbBuf=%#x\n", pStreamEx->In.enmCaptureState, cbBuf));
            }

            if (!pStreamEx->In.Dbg.pFileCapture || RT_FAILURE(rc))
            { /* likely */ }
            else
                AudioHlpFileWrite(pStreamEx->In.Dbg.pFileCapture, pvBuf, *pcbRead);
        }
        else
        {
            *pcbRead = 0;
            Log4Func(("[%s] Backend stream %s, returning no data\n", pStreamEx->Core.Cfg.szName,
                      !pThis->Out.fEnabled ? "disabled" : !pThis->pHostDrvAudio ? "not attached" : "not ready yet"));
        }
        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    }
    else
        rc = VERR_AUDIO_STREAM_NOT_READY;

    STAM_PROFILE_STOP(&pStreamEx->In.Stats.ProfCapture, a);
    RTCritSectLeave(&pStreamEx->Core.CritSect);
    return rc;
}


/*********************************************************************************************************************************
*   PDMIHOSTAUDIOPORT interface implementation.                                                                                  *
*********************************************************************************************************************************/

/**
 * Worker for drvAudioHostPort_DoOnWorkerThread with stream argument, called on
 * worker thread.
 */
static DECLCALLBACK(void) drvAudioHostPort_DoOnWorkerThreadStreamWorker(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
                                                                        uintptr_t uUser, void *pvUser)
{
    LogFlowFunc(("pThis=%p uUser=%#zx pvUser=%p\n", pThis, uUser, pvUser));
    AssertPtrReturnVoid(pThis);
    AssertPtrReturnVoid(pStreamEx);
    AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);

    /*
     * The CritSectHotPlug lock should not be needed here as detach will destroy
     * the thread pool.  So, we'll leave taking the stream lock to the worker we're
     * calling as there are no lock order concerns.
     */
    PPDMIHOSTAUDIO const pIHostDrvAudio = pThis->pHostDrvAudio;
    AssertPtrReturnVoid(pIHostDrvAudio);
    AssertPtrReturnVoid(pIHostDrvAudio->pfnDoOnWorkerThread);
    pIHostDrvAudio->pfnDoOnWorkerThread(pIHostDrvAudio, pStreamEx->pBackend, uUser, pvUser);

    drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
    LogFlowFunc(("returns\n"));
}


/**
 * Worker for drvAudioHostPort_DoOnWorkerThread without stream argument, called
 * on worker thread.
 *
 * This wrapper isn't technically required, but it helps with logging and a few
 * extra sanity checks.
 */
static DECLCALLBACK(void) drvAudioHostPort_DoOnWorkerThreadWorker(PDRVAUDIO pThis, uintptr_t uUser, void *pvUser)
{
    LogFlowFunc(("pThis=%p uUser=%#zx pvUser=%p\n", pThis, uUser, pvUser));
    AssertPtrReturnVoid(pThis);

    /*
     * The CritSectHotPlug lock should not be needed here as detach will destroy
     * the thread pool.
     */
    PPDMIHOSTAUDIO const pIHostDrvAudio = pThis->pHostDrvAudio;
    AssertPtrReturnVoid(pIHostDrvAudio);
    AssertPtrReturnVoid(pIHostDrvAudio->pfnDoOnWorkerThread);

    pIHostDrvAudio->pfnDoOnWorkerThread(pIHostDrvAudio, NULL, uUser, pvUser);

    LogFlowFunc(("returns\n"));
}


/**
 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnDoOnWorkerThread}
 */
static DECLCALLBACK(int) drvAudioHostPort_DoOnWorkerThread(PPDMIHOSTAUDIOPORT pInterface, PPDMAUDIOBACKENDSTREAM pStream,
                                                           uintptr_t uUser, void *pvUser)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
    LogFlowFunc(("pStream=%p uUser=%#zx pvUser=%p\n", pStream, uUser, pvUser));

    /*
     * Assert some sanity.
     */
    PDRVAUDIOSTREAM pStreamEx;
    if (!pStream)
        pStreamEx = NULL;
    else
    {
        AssertPtrReturn(pStream, VERR_INVALID_POINTER);
        AssertReturn(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INVALID_MAGIC);
        pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
        AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
        AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
        AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
    }

    int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    AssertRCReturn(rc, rc);

    Assert(pThis->hReqPool != NIL_RTREQPOOL);
    AssertPtr(pThis->pHostDrvAudio);
    if (   pThis->hReqPool != NIL_RTREQPOOL
        && pThis->pHostDrvAudio != NULL)
    {
        AssertPtr(pThis->pHostDrvAudio->pfnDoOnWorkerThread);
        if (pThis->pHostDrvAudio->pfnDoOnWorkerThread)
        {
            /*
             * Try do the work.
             */
            if (!pStreamEx)
            {
                rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL /*phReq*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
                                     (PFNRT)drvAudioHostPort_DoOnWorkerThreadWorker, 3, pThis, uUser, pvUser);
                AssertRC(rc);
            }
            else
            {
                uint32_t cRefs = drvAudioStreamRetainInternal(pStreamEx);
                if (cRefs != UINT32_MAX)
                {
                    rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
                                         (PFNRT)drvAudioHostPort_DoOnWorkerThreadStreamWorker,
                                         4, pThis, pStreamEx, uUser, pvUser);
                    AssertRC(rc);
                    if (RT_FAILURE(rc))
                    {
                        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
                        drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
                        RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
                    }
                }
                else
                    rc = VERR_INVALID_PARAMETER;
            }
        }
        else
            rc = VERR_INVALID_FUNCTION;
    }
    else
        rc = VERR_INVALID_STATE;

    RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
    LogFlowFunc(("returns %Rrc\n", rc));
    return rc;
}


/**
 * Marks a stream for re-init.
 */
static void drvAudioStreamMarkNeedReInit(PDRVAUDIOSTREAM pStreamEx, const char *pszCaller)
{
    LogFlow((LOG_FN_FMT ": Flagging %s for re-init.\n", pszCaller, pStreamEx->Core.Cfg.szName)); RT_NOREF(pszCaller);
    Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));

    pStreamEx->fStatus      |= PDMAUDIOSTREAM_STS_NEED_REINIT;
    PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
    pStreamEx->cTriesReInit  = 0;
    pStreamEx->nsLastReInit  = 0;
}


/**
 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnNotifyDeviceChanged}
 */
static DECLCALLBACK(void) drvAudioHostPort_NotifyDeviceChanged(PPDMIHOSTAUDIOPORT pInterface, PDMAUDIODIR enmDir, void *pvUser)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
    AssertReturnVoid(enmDir == PDMAUDIODIR_IN || enmDir == PDMAUDIODIR_OUT);
    LogRel(("Audio: The %s device for %s is changing.\n", PDMAudioDirGetName(enmDir), pThis->BackendCfg.szName));

    /*
     * Grab the list lock in shared mode and do the work.
     */
    int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
    AssertRCReturnVoid(rc);

    PDRVAUDIOSTREAM pStreamEx;
    RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
    {
        if (pStreamEx->Core.Cfg.enmDir == enmDir)
        {
            RTCritSectEnter(&pStreamEx->Core.CritSect);
            RTCritSectRwEnterShared(&pThis->CritSectHotPlug);

            if (pThis->pHostDrvAudio->pfnStreamNotifyDeviceChanged)
            {
                LogFlowFunc(("Calling pfnStreamNotifyDeviceChanged on %s, old backend state: %s...\n", pStreamEx->Core.Cfg.szName,
                             PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)) ));
                pThis->pHostDrvAudio->pfnStreamNotifyDeviceChanged(pThis->pHostDrvAudio, pStreamEx->pBackend, pvUser);
                LogFlowFunc(("New stream backend state: %s\n",
                             PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)) ));
            }
            else
                drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);

            RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
            RTCritSectLeave(&pStreamEx->Core.CritSect);
        }
    }

    RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
}


/**
 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnStreamNotifyPreparingDeviceSwitch}
 */
static DECLCALLBACK(void) drvAudioHostPort_StreamNotifyPreparingDeviceSwitch(PPDMIHOSTAUDIOPORT pInterface,
                                                                             PPDMAUDIOBACKENDSTREAM pStream)
{
    RT_NOREF(pInterface);

    /*
     * Backend stream to validated DrvAudio stream:
     */
    AssertPtrReturnVoid(pStream);
    AssertReturnVoid(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
    AssertPtrReturnVoid(pStreamEx);
    AssertReturnVoid(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
    AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
    LogFlowFunc(("pStreamEx=%p '%s'\n", pStreamEx, pStreamEx->Core.Cfg.szName));

    /*
     * Grab the lock and do switch the state (only needed for output streams for now).
     */
    RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertReturnVoidStmt(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, RTCritSectLeave(&pStreamEx->Core.CritSect)); /* paranoia */

    if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
    {
        if (pStreamEx->cbPreBufThreshold > 0)
        {
            DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
            switch (enmPlayState)
            {
                case DRVAUDIOPLAYSTATE_PREBUF:
                case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
                case DRVAUDIOPLAYSTATE_NOPLAY:
                case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING: /* simpler */
                    pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_SWITCHING;
                    break;
                case DRVAUDIOPLAYSTATE_PLAY:
                    pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PLAY_PREBUF;
                    break;
                case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
                case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
                    break;
                /* no default */
                case DRVAUDIOPLAYSTATE_END:
                case DRVAUDIOPLAYSTATE_INVALID:
                    break;
            }
            LogFunc(("%s -> %s\n", drvAudioPlayStateName(enmPlayState), drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
        }
        else
            LogFunc(("No pre-buffering configured.\n"));
    }
    else
        LogFunc(("input stream, nothing to do.\n"));

    RTCritSectLeave(&pStreamEx->Core.CritSect);
}


/**
 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnStreamNotifyDeviceChanged}
 */
static DECLCALLBACK(void) drvAudioHostPort_StreamNotifyDeviceChanged(PPDMIHOSTAUDIOPORT pInterface,
                                                                     PPDMAUDIOBACKENDSTREAM pStream, bool fReInit)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);

    /*
     * Backend stream to validated DrvAudio stream:
     */
    AssertPtrReturnVoid(pStream);
    AssertReturnVoid(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC);
    PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
    AssertPtrReturnVoid(pStreamEx);
    AssertReturnVoid(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
    AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);

    /*
     * Grab the lock and do the requested work.
     */
    RTCritSectEnter(&pStreamEx->Core.CritSect);
    AssertReturnVoidStmt(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, RTCritSectLeave(&pStreamEx->Core.CritSect)); /* paranoia */

    if (fReInit)
        drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
    else
    {
        /*
         * Adjust the stream state now that the device has (perhaps finally) been switched.
         *
         * For enabled output streams, we must update the play state.  We could try commit
         * pre-buffered data here, but it's really not worth the hazzle and risk (don't
         * know which thread we're on, do we now).
         */
        AssertStmt(!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT),
                   pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_NEED_REINIT);


        if (pStreamEx->Core.Cfg.enmDir == PDMAUDIODIR_OUT)
        {
            DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
            pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
            LogFunc(("%s: %s -> %s\n", pStreamEx->Core.Cfg.szName, drvAudioPlayStateName(enmPlayState),
                     drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
            RT_NOREF(enmPlayState);
        }

        /* Disable and then fully resync. */
        /** @todo This doesn't work quite reliably if we're in draining mode
         * (PENDING_DISABLE, so the backend needs to take care of that prior to calling
         * us.  Sigh.  The idea was to avoid extra state mess in the backend... */
        drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
        drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "device changed");
    }

    RTCritSectLeave(&pStreamEx->Core.CritSect);
}


#ifdef VBOX_WITH_AUDIO_ENUM
/**
 * @callback_method_impl{FNTMTIMERDRV, Re-enumerate backend devices.}
 *
 * Used to do/trigger re-enumeration of backend devices with a delay after we
 * got notification as there can be further notifications following shortly
 * after the first one.  Also good to get it of random COM/whatever threads.
 */
static DECLCALLBACK(void) drvAudioEnumerateTimer(PPDMDRVINS pDrvIns, TMTIMERHANDLE hTimer, void *pvUser)
{
    PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
    RT_NOREF(hTimer, pvUser);

    /* Try push the work over to the thread-pool if we've got one. */
    RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
    if (pThis->hReqPool != NIL_RTREQPOOL)
    {
        int rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
                                 (PFNRT)drvAudioDevicesEnumerateInternal,
                                 3, pThis, true /*fLog*/, (PPDMAUDIOHOSTENUM)NULL /*pDevEnum*/);
        LogFunc(("RTReqPoolCallEx: %Rrc\n", rc));
        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
        if (RT_SUCCESS(rc))
            return;
    }
    else
        RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);

    LogFunc(("Calling drvAudioDevicesEnumerateInternal...\n"));
    drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
}
#endif /* VBOX_WITH_AUDIO_ENUM */


/**
 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnNotifyDevicesChanged}
 */
static DECLCALLBACK(void) drvAudioHostPort_NotifyDevicesChanged(PPDMIHOSTAUDIOPORT pInterface)
{
    PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
    LogRel(("Audio: Device configuration of driver '%s' has changed\n", pThis->BackendCfg.szName));

#ifdef RT_OS_DARWIN /** @todo Remove legacy behaviour: */
    /* Mark all host streams to re-initialize. */
    int rc2 = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
    AssertRCReturnVoid(rc2);
    PDRVAUDIOSTREAM pStreamEx;
    RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
    {
        RTCritSectEnter(&pStreamEx->Core.CritSect);
        drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
        RTCritSectLeave(&pStreamEx->Core.CritSect);
    }
    RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
#endif

#ifdef VBOX_WITH_AUDIO_ENUM
    /*
     * Re-enumerate all host devices with a tiny delay to avoid re-doing this
     * when a bunch of changes happens at once (they typically do on windows).
     * We'll keep postponing it till it quiesces for a fraction of a second.
     */
    int rc = PDMDrvHlpTimerSetMillies(pThis->pDrvIns, pThis->hEnumTimer, RT_MS_1SEC / 3);
    AssertRC(rc);
#endif
}


/*********************************************************************************************************************************
*   PDMIBASE interface implementation.                                                                                           *
*********************************************************************************************************************************/

/**
 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
 */
static DECLCALLBACK(void *) drvAudioQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
    LogFlowFunc(("pInterface=%p, pszIID=%s\n", pInterface, pszIID));

    PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
    PDRVAUDIO  pThis   = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);

    PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
    PDMIBASE_RETURN_INTERFACE(pszIID, PDMIAUDIOCONNECTOR, &pThis->IAudioConnector);
    PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIOPORT, &pThis->IHostAudioPort);

    return NULL;
}


/*********************************************************************************************************************************
*   PDMDRVREG interface implementation.                                                                                          *
*********************************************************************************************************************************/

/**
 * Power Off notification.
 *
 * @param   pDrvIns     The driver instance data.
 */
static DECLCALLBACK(void) drvAudioPowerOff(PPDMDRVINS pDrvIns)
{
    PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);

    LogFlowFuncEnter();

    /** @todo locking?   */
    if (pThis->pHostDrvAudio) /* If not lower driver is configured, bail out. */
    {
        /*
         * Just destroy the host stream on the backend side.
         * The rest will either be destructed by the device emulation or
         * in drvAudioDestruct().
         */
        int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
        AssertRCReturnVoid(rc);

        PDRVAUDIOSTREAM pStreamEx;
        RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
        {
            RTCritSectEnter(&pStreamEx->Core.CritSect);
            drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
            RTCritSectLeave(&pStreamEx->Core.CritSect);
        }

        RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
    }

    LogFlowFuncLeave();
}


/**
 * Detach notification.
 *
 * @param   pDrvIns     The driver instance data.
 * @param   fFlags      Detach flags.
 */
static DECLCALLBACK(void) drvAudioDetach(PPDMDRVINS pDrvIns, uint32_t fFlags)
{
    PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
    PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
    RT_NOREF(fFlags);

    int rc = RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
    AssertLogRelRCReturnVoid(rc);

    LogFunc(("%s (detached %p, hReqPool=%p)\n", pThis->BackendCfg.szName, pThis->pHostDrvAudio, pThis->hReqPool));

    /*
     * Must first destroy the thread pool first so we are certain no threads
     * are still using the instance being detached.  Release lock while doing
     * this as the thread functions may need to take it to complete.
     */
    if (pThis->pHostDrvAudio && pThis->hReqPool != NIL_RTREQPOOL)
    {
        RTREQPOOL hReqPool = pThis->hReqPool;
        pThis->hReqPool = NIL_RTREQPOOL;

        RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);

        RTReqPoolRelease(hReqPool);

        RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
    }

    /*
     * Now we can safely set pHostDrvAudio to NULL.
     */
    pThis->pHostDrvAudio = NULL;

    RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
}


/**
 * Initializes the host backend and queries its initial configuration.
 *
 * @returns VBox status code.
 * @param   pThis               Driver instance to be called.
 */
static int drvAudioHostInit(PDRVAUDIO pThis)
{
    LogFlowFuncEnter();

    /*
     * Check the function pointers, make sure the ones we define as
     * mandatory are present.
     */
    PPDMIHOSTAUDIO pIHostDrvAudio = pThis->pHostDrvAudio;
    AssertPtrReturn(pIHostDrvAudio, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnGetConfig, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnGetDevices, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnSetDevice, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnGetStatus, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnDoOnWorkerThread, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnStreamConfigHint, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamCreate, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnStreamInitAsync, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamDestroy, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnStreamNotifyDeviceChanged, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamEnable, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamDisable, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamPause, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamResume, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnStreamDrain, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamGetReadable, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamGetWritable, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pIHostDrvAudio->pfnStreamGetPending, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamGetState, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamPlay, VERR_INVALID_POINTER);
    AssertPtrReturn(pIHostDrvAudio->pfnStreamCapture, VERR_INVALID_POINTER);

    /*
     * Get the backend configuration.
     *
     * Note! Limit the number of streams to max 128 in each direction to
     *       prevent wasting resources.
     * Note! Take care not to wipe the DriverName config value on failure.
     */
    PDMAUDIOBACKENDCFG BackendCfg;
    RT_ZERO(BackendCfg);
    int rc = pIHostDrvAudio->pfnGetConfig(pIHostDrvAudio, &BackendCfg);
    if (RT_SUCCESS(rc))
    {
        if (LogIsEnabled() && strcmp(BackendCfg.szName, pThis->BackendCfg.szName) != 0)
            LogFunc(("BackendCfg.szName: '%s' -> '%s'\n", pThis->BackendCfg.szName, BackendCfg.szName));
        pThis->BackendCfg       = BackendCfg;
        pThis->In.cStreamsFree  = RT_MIN(BackendCfg.cMaxStreamsIn,  128);
        pThis->Out.cStreamsFree = RT_MIN(BackendCfg.cMaxStreamsOut, 128);

        LogFlowFunc(("cStreamsFreeIn=%RU8, cStreamsFreeOut=%RU8\n", pThis->In.cStreamsFree, pThis->Out.cStreamsFree));
    }
    else
    {
        LogRel(("Audio: Getting configuration for driver '%s' failed with %Rrc\n", pThis->BackendCfg.szName, rc));
        return VERR_AUDIO_BACKEND_INIT_FAILED;
    }

    LogRel2(("Audio: Host driver '%s' supports %RU32 input streams and %RU32 output streams at once.\n",
             pThis->BackendCfg.szName, pThis->In.cStreamsFree, pThis->Out.cStreamsFree));

#ifdef VBOX_WITH_AUDIO_ENUM
    int rc2 = drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
    if (rc2 != VERR_NOT_SUPPORTED) /* Some backends don't implement device enumeration. */
        AssertRC(rc2);
    /* Ignore rc2. */
#endif

    /*
     * Create a thread pool if stream creation can be asynchronous.
     *
     * The pool employs no pushback as the caller is typically EMT and
     * shouldn't be delayed.
     *
     * The number of threads limits and the device implementations use
     * of pfnStreamDestroy limits the number of streams pending async
     * init.  We use RTReqCancel in drvAudioStreamDestroy to allow us
     * to release extra reference held by the pfnStreamInitAsync call
     * if successful.  Cancellation will only be possible if the call
     * hasn't been picked up by a worker thread yet, so the max number
     * of threads in the pool defines how many destroyed streams that
     * can be lingering.  (We must keep this under control, otherwise
     * an evil guest could just rapidly trigger stream creation and
     * destruction to consume host heap and hog CPU resources for
     * configuring audio backends.)
     */
    if (   pThis->hReqPool == NIL_RTREQPOOL
        && (   pIHostDrvAudio->pfnStreamInitAsync
            || pIHostDrvAudio->pfnDoOnWorkerThread
            || (pThis->BackendCfg.fFlags & (PDMAUDIOBACKEND_F_ASYNC_HINT | PDMAUDIOBACKEND_F_ASYNC_STREAM_DESTROY)) ))
    {
        char szName[16];
        RTStrPrintf(szName, sizeof(szName), "Aud%uWr", pThis->pDrvIns->iInstance);
        RTREQPOOL hReqPool = NIL_RTREQPOOL;
        rc = RTReqPoolCreate(3 /*cMaxThreads*/, RT_MS_30SEC /*cMsMinIdle*/, UINT32_MAX /*cThreadsPushBackThreshold*/,
                             1 /*cMsMaxPushBack*/, szName, &hReqPool);
        LogFlowFunc(("Creating thread pool '%s': %Rrc, hReqPool=%p\n", szName, rc, hReqPool));
        AssertRCReturn(rc, rc);

        rc = RTReqPoolSetCfgVar(hReqPool, RTREQPOOLCFGVAR_THREAD_FLAGS, RTTHREADFLAGS_COM_MTA);
        AssertRCReturnStmt(rc, RTReqPoolRelease(hReqPool), rc);

        rc = RTReqPoolSetCfgVar(hReqPool, RTREQPOOLCFGVAR_MIN_THREADS, 1);
        AssertRC(rc); /* harmless */

        pThis->hReqPool = hReqPool;
    }
    else
        LogFlowFunc(("No thread pool.\n"));

    LogFlowFuncLeave();
    return VINF_SUCCESS;
}


/**
 * Does the actual backend driver attaching and queries the backend's interface.
 *
 * This is a worker for both drvAudioAttach and drvAudioConstruct.
 *
 * @returns VBox status code.
 * @param   pDrvIns     The driver instance.
 * @param   pThis       Pointer to driver instance.
 * @param   fFlags      Attach flags; see PDMDrvHlpAttach().
 */
static int drvAudioDoAttachInternal(PPDMDRVINS pDrvIns, PDRVAUDIO pThis, uint32_t fFlags)
{
    Assert(pThis->pHostDrvAudio == NULL); /* No nested attaching. */

    /*
     * Attach driver below and query its connector interface.
     */
    PPDMIBASE pDownBase;
    int rc = PDMDrvHlpAttach(pDrvIns, fFlags, &pDownBase);
    if (RT_SUCCESS(rc))
    {
        pThis->pHostDrvAudio = PDMIBASE_QUERY_INTERFACE(pDownBase, PDMIHOSTAUDIO);
        if (pThis->pHostDrvAudio)
        {
            /*
             * If everything went well, initialize the lower driver.
             */
            rc = drvAudioHostInit(pThis);
            if (RT_FAILURE(rc))
                pThis->pHostDrvAudio = NULL;
        }
        else
        {
            LogRel(("Audio: Failed to query interface for underlying host driver '%s'\n", pThis->BackendCfg.szName));
            rc = PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_MISSING_INTERFACE_BELOW,
                                  N_("The host audio driver does not implement PDMIHOSTAUDIO!"));
        }
    }
    /*
     * If the host driver below us failed to construct for some beningn reason,
     * we'll report it as a runtime error and replace it with the Null driver.
     *
     * Note! We do NOT change anything in PDM (or CFGM), so pDrvIns->pDownBase
     *       will remain NULL in this case.
     */
    else if (   rc == VERR_AUDIO_BACKEND_INIT_FAILED
             || rc == VERR_MODULE_NOT_FOUND
             || rc == VERR_SYMBOL_NOT_FOUND
             || rc == VERR_FILE_NOT_FOUND
             || rc == VERR_PATH_NOT_FOUND)
    {
        /* Complain: */
        LogRel(("DrvAudio: Host audio driver '%s' init failed with %Rrc. Switching to the NULL driver for now.\n",
                pThis->BackendCfg.szName, rc));
        PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "HostAudioNotResponding",
                                   N_("Host audio backend (%s) initialization has failed. Selecting the NULL audio backend with the consequence that no sound is audible"),
                                   pThis->BackendCfg.szName);

        /* Replace with null audio: */
        pThis->pHostDrvAudio = (PPDMIHOSTAUDIO)&g_DrvHostAudioNull;
        RTStrCopy(pThis->BackendCfg.szName, sizeof(pThis->BackendCfg.szName), "NULL");
        rc = drvAudioHostInit(pThis);
        AssertRC(rc);
    }

    LogFunc(("[%s] rc=%Rrc\n", pThis->BackendCfg.szName, rc));
    return rc;
}


/**
 * Attach notification.
 *
 * @param   pDrvIns     The driver instance data.
 * @param   fFlags      Attach flags.
 */
static DECLCALLBACK(int) drvAudioAttach(PPDMDRVINS pDrvIns, uint32_t fFlags)
{
    PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
    PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
    LogFunc(("%s\n", pThis->BackendCfg.szName));

    int rc = RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
    AssertRCReturn(rc, rc);

    rc = drvAudioDoAttachInternal(pDrvIns, pThis, fFlags);

    RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
    return rc;
}


/**
 * Handles state changes for all audio streams.
 *
 * @param   pDrvIns             Pointer to driver instance.
 * @param   enmCmd              Stream command to set for all streams.
 */
static void drvAudioStateHandler(PPDMDRVINS pDrvIns, PDMAUDIOSTREAMCMD enmCmd)
{
    PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
    PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
    LogFlowFunc(("enmCmd=%s\n", PDMAudioStrmCmdGetName(enmCmd)));

    int rc2 = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
    AssertRCReturnVoid(rc2);

    PDRVAUDIOSTREAM pStreamEx;
    RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
    {
        RTCritSectEnter(&pStreamEx->Core.CritSect);
        drvAudioStreamControlInternal(pThis, pStreamEx, enmCmd);
        RTCritSectLeave(&pStreamEx->Core.CritSect);
    }

    RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
}


/**
 * Resume notification.
 *
 * @param   pDrvIns     The driver instance data.
 */
static DECLCALLBACK(void) drvAudioResume(PPDMDRVINS pDrvIns)
{
    drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_RESUME);
}


/**
 * Suspend notification.
 *
 * @param   pDrvIns     The driver instance data.
 */
static DECLCALLBACK(void) drvAudioSuspend(PPDMDRVINS pDrvIns)
{
    drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_PAUSE);
}


/**
 * Destructs an audio driver instance.
 *
 * @copydoc FNPDMDRVDESTRUCT
 */
static DECLCALLBACK(void) drvAudioDestruct(PPDMDRVINS pDrvIns)
{
    PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
    PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);

    LogFlowFuncEnter();

    /*
     * We must start by setting pHostDrvAudio to NULL here as the anything below
     * us has already been destroyed at this point.
     */
    if (RTCritSectRwIsInitialized(&pThis->CritSectHotPlug))
    {
        RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
        pThis->pHostDrvAudio = NULL;
        RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
    }
    else
    {
        Assert(pThis->pHostDrvAudio == NULL);
        pThis->pHostDrvAudio = NULL;
    }

    /*
     * Make sure the thread pool is out of the picture before we terminate all the streams.
     */
    if (pThis->hReqPool != NIL_RTREQPOOL)
    {
        uint32_t cRefs = RTReqPoolRelease(pThis->hReqPool);
        Assert(cRefs == 0); RT_NOREF(cRefs);
        pThis->hReqPool = NIL_RTREQPOOL;
    }

    /*
     * Destroy all streams.
     */
    if (RTCritSectRwIsInitialized(&pThis->CritSectGlobals))
    {
        RTCritSectRwEnterExcl(&pThis->CritSectGlobals);

        PDRVAUDIOSTREAM pStreamEx, pStreamExNext;
        RTListForEachSafe(&pThis->LstStreams, pStreamEx, pStreamExNext, DRVAUDIOSTREAM, ListEntry)
        {
            int rc = drvAudioStreamUninitInternal(pThis, pStreamEx);
            if (RT_SUCCESS(rc))
            {
                RTListNodeRemove(&pStreamEx->ListEntry);
                drvAudioStreamFree(pStreamEx);
            }
        }

        RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
        RTCritSectRwDelete(&pThis->CritSectGlobals);
    }


    /* Sanity. */
    Assert(RTListIsEmpty(&pThis->LstStreams));

    if (RTCritSectRwIsInitialized(&pThis->CritSectHotPlug))
        RTCritSectRwDelete(&pThis->CritSectHotPlug);

    PDMDrvHlpSTAMDeregisterByPrefix(pDrvIns, "");

    LogFlowFuncLeave();
}


/**
 * Constructs an audio driver instance.
 *
 * @copydoc FNPDMDRVCONSTRUCT
 */
static DECLCALLBACK(int) drvAudioConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
{
    PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
    PDRVAUDIO       pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
    PCPDMDRVHLPR3   pHlp  = pDrvIns->pHlpR3;
    LogFlowFunc(("pDrvIns=%#p, pCfgHandle=%#p, fFlags=%x\n", pDrvIns, pCfg, fFlags));

    /*
     * Basic instance init.
     */
    RTListInit(&pThis->LstStreams);
    pThis->hReqPool = NIL_RTREQPOOL;

    /*
     * Read configuration.
     */
    PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
                                  "DriverName|"
                                  "InputEnabled|"
                                  "OutputEnabled|"
                                  "DebugEnabled|"
                                  "DebugPathOut|"
                                  /* Deprecated: */
                                  "PCMSampleBitIn|"
                                  "PCMSampleBitOut|"
                                  "PCMSampleHzIn|"
                                  "PCMSampleHzOut|"
                                  "PCMSampleSignedIn|"
                                  "PCMSampleSignedOut|"
                                  "PCMSampleSwapEndianIn|"
                                  "PCMSampleSwapEndianOut|"
                                  "PCMSampleChannelsIn|"
                                  "PCMSampleChannelsOut|"
                                  "PeriodSizeMsIn|"
                                  "PeriodSizeMsOut|"
                                  "BufferSizeMsIn|"
                                  "BufferSizeMsOut|"
                                  "PreBufferSizeMsIn|"
                                  "PreBufferSizeMsOut",
                                  "In|Out");

    int rc = pHlp->pfnCFGMQueryStringDef(pCfg, "DriverName", pThis->BackendCfg.szName, sizeof(pThis->BackendCfg.szName), "Untitled");
    AssertLogRelRCReturn(rc, rc);

    /* Neither input nor output by default for security reasons. */
    rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "InputEnabled",  &pThis->In.fEnabled, false);
    AssertLogRelRCReturn(rc, rc);

    rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "OutputEnabled", &pThis->Out.fEnabled, false);
    AssertLogRelRCReturn(rc, rc);

    /* Debug stuff (same for both directions). */
    rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "DebugEnabled", &pThis->CfgIn.Dbg.fEnabled, false);
    AssertLogRelRCReturn(rc, rc);

    rc = pHlp->pfnCFGMQueryStringDef(pCfg, "DebugPathOut", pThis->CfgIn.Dbg.szPathOut, sizeof(pThis->CfgIn.Dbg.szPathOut), "");
    AssertLogRelRCReturn(rc, rc);
    if (pThis->CfgIn.Dbg.szPathOut[0] == '\0')
    {
        rc = RTPathTemp(pThis->CfgIn.Dbg.szPathOut, sizeof(pThis->CfgIn.Dbg.szPathOut));
        if (RT_FAILURE(rc))
        {
            LogRel(("Audio: Warning! Failed to retrieve temporary directory: %Rrc - disabling debugging.\n", rc));
            pThis->CfgIn.Dbg.szPathOut[0] = '\0';
            pThis->CfgIn.Dbg.fEnabled = false;
        }
    }
    if (pThis->CfgIn.Dbg.fEnabled)
        LogRel(("Audio: Debugging for driver '%s' enabled (audio data written to '%s')\n",
                pThis->BackendCfg.szName, pThis->CfgIn.Dbg.szPathOut));

    /* Copy debug setup to the output direction. */
    pThis->CfgOut.Dbg = pThis->CfgIn.Dbg;

    LogRel2(("Audio: Verbose logging for driver '%s' is probably enabled too.\n", pThis->BackendCfg.szName));
    /* This ^^^^^^^ is the *WRONG* place for that kind of statement. Verbose logging might only be enabled for DrvAudio. */
    LogRel2(("Audio: Initial status for driver '%s' is: input is %s, output is %s\n",
             pThis->BackendCfg.szName, pThis->In.fEnabled ? "enabled" : "disabled", pThis->Out.fEnabled ? "enabled" : "disabled"));

    /*
     * Per direction configuration.  A bit complicated as
     * these wasn't originally in sub-nodes.
     */
    for (unsigned iDir = 0; iDir < 2; iDir++)
    {
        char         szNm[48];
        PDRVAUDIOCFG pAudioCfg = iDir == 0 ? &pThis->CfgIn : &pThis->CfgOut;
        const char  *pszDir    = iDir == 0 ? "In"           : "Out";

#define QUERY_VAL_RET(a_Width, a_szName, a_pValue, a_uDefault, a_ExprValid, a_szValidRange) \
            do { \
                rc = RT_CONCAT(pHlp->pfnCFGMQueryU,a_Width)(pDirNode, strcpy(szNm, a_szName), a_pValue); \
                if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT) \
                { \
                    rc = RT_CONCAT(pHlp->pfnCFGMQueryU,a_Width)(pCfg, strcat(szNm, pszDir), a_pValue); \
                    if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT) \
                    { \
                        *(a_pValue) = a_uDefault; \
                        rc = VINF_SUCCESS; \
                    } \
                    else \
                        LogRel(("DrvAudio: Warning! Please use '%s/" a_szName "' instead of '%s' for your VBoxInternal hacks\n", pszDir, szNm)); \
                } \
                AssertRCReturn(rc, PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, \
                                                       N_("Configuration error: Failed to read %s config value '%s'"), pszDir, szNm)); \
                if (!(a_ExprValid)) \
                    return PDMDrvHlpVMSetError(pDrvIns, VERR_OUT_OF_RANGE, RT_SRC_POS, \
                                               N_("Configuration error: Unsupported %s value %u. " a_szValidRange), szNm, *(a_pValue)); \
            } while (0)

        PCFGMNODE const pDirNode = pHlp->pfnCFGMGetChild(pCfg, pszDir);
        rc = pHlp->pfnCFGMValidateConfig(pDirNode, iDir == 0 ? "In/" : "Out/",
                                         "PCMSampleBit|"
                                         "PCMSampleHz|"
                                         "PCMSampleSigned|"
                                         "PCMSampleSwapEndian|"
                                         "PCMSampleChannels|"
                                         "PeriodSizeMs|"
                                         "BufferSizeMs|"
                                         "PreBufferSizeMs",
                                         "", pDrvIns->pReg->szName, pDrvIns->iInstance);
        AssertRCReturn(rc, rc);

        uint8_t cSampleBits = 0;
        QUERY_VAL_RET(8,  "PCMSampleBit",        &cSampleBits,                  0,
                         cSampleBits == 0
                      || cSampleBits == 8
                      || cSampleBits == 16
                      || cSampleBits == 32
                      || cSampleBits == 64,
                      "Must be either 0, 8, 16, 32 or 64");
        if (cSampleBits)
            PDMAudioPropsSetSampleSize(&pAudioCfg->Props, cSampleBits / 8);

        uint8_t cChannels;
        QUERY_VAL_RET(8,  "PCMSampleChannels",   &cChannels,                    0, cChannels <= 16, "Max 16");
        if (cChannels)
            PDMAudioPropsSetChannels(&pAudioCfg->Props, cChannels);

        QUERY_VAL_RET(32, "PCMSampleHz",         &pAudioCfg->Props.uHz,         0,
                      pAudioCfg->Props.uHz == 0 || (pAudioCfg->Props.uHz >= 6000 && pAudioCfg->Props.uHz <= 768000),
                      "In the range 6000 thru 768000, or 0");

        QUERY_VAL_RET(8,  "PCMSampleSigned",     &pAudioCfg->uSigned,           UINT8_MAX,
                      pAudioCfg->uSigned == 0 || pAudioCfg->uSigned == 1 || pAudioCfg->uSigned == UINT8_MAX,
                      "Must be either 0, 1, or 255");

        QUERY_VAL_RET(8,  "PCMSampleSwapEndian", &pAudioCfg->uSwapEndian,       UINT8_MAX,
                      pAudioCfg->uSwapEndian == 0 || pAudioCfg->uSwapEndian == 1 || pAudioCfg->uSwapEndian == UINT8_MAX,
                      "Must be either 0, 1, or 255");

        QUERY_VAL_RET(32, "PeriodSizeMs",        &pAudioCfg->uPeriodSizeMs,     0,
                      pAudioCfg->uPeriodSizeMs <= RT_MS_1SEC, "Max 1000");

        QUERY_VAL_RET(32, "BufferSizeMs",        &pAudioCfg->uBufferSizeMs,     0,
                      pAudioCfg->uBufferSizeMs <= RT_MS_5SEC, "Max 5000");

        QUERY_VAL_RET(32, "PreBufferSizeMs",     &pAudioCfg->uPreBufSizeMs,     UINT32_MAX,
                      pAudioCfg->uPreBufSizeMs <= RT_MS_1SEC || pAudioCfg->uPreBufSizeMs == UINT32_MAX,
                      "Max 1000, or 0xffffffff");
#undef QUERY_VAL_RET
    }

    /*
     * Init the rest of the driver instance data.
     */
    rc = RTCritSectRwInit(&pThis->CritSectHotPlug);
    AssertRCReturn(rc, rc);
    rc = RTCritSectRwInit(&pThis->CritSectGlobals);
    AssertRCReturn(rc, rc);
#ifdef VBOX_STRICT
    /* Define locking order: */
    RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
    RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
    RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
    RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
#endif

    pThis->pDrvIns                              = pDrvIns;
    /* IBase. */
    pDrvIns->IBase.pfnQueryInterface            = drvAudioQueryInterface;
    /* IAudioConnector. */
    pThis->IAudioConnector.pfnEnable            = drvAudioEnable;
    pThis->IAudioConnector.pfnIsEnabled         = drvAudioIsEnabled;
    pThis->IAudioConnector.pfnGetConfig         = drvAudioGetConfig;
    pThis->IAudioConnector.pfnGetStatus         = drvAudioGetStatus;
    pThis->IAudioConnector.pfnStreamConfigHint  = drvAudioStreamConfigHint;
    pThis->IAudioConnector.pfnStreamCreate      = drvAudioStreamCreate;
    pThis->IAudioConnector.pfnStreamDestroy     = drvAudioStreamDestroy;
    pThis->IAudioConnector.pfnStreamReInit      = drvAudioStreamReInit;
    pThis->IAudioConnector.pfnStreamRetain      = drvAudioStreamRetain;
    pThis->IAudioConnector.pfnStreamRelease     = drvAudioStreamRelease;
    pThis->IAudioConnector.pfnStreamControl     = drvAudioStreamControl;
    pThis->IAudioConnector.pfnStreamIterate     = drvAudioStreamIterate;
    pThis->IAudioConnector.pfnStreamGetState    = drvAudioStreamGetState;
    pThis->IAudioConnector.pfnStreamGetWritable = drvAudioStreamGetWritable;
    pThis->IAudioConnector.pfnStreamPlay        = drvAudioStreamPlay;
    pThis->IAudioConnector.pfnStreamGetReadable = drvAudioStreamGetReadable;
    pThis->IAudioConnector.pfnStreamCapture     = drvAudioStreamCapture;
    /* IHostAudioPort */
    pThis->IHostAudioPort.pfnDoOnWorkerThread                   = drvAudioHostPort_DoOnWorkerThread;
    pThis->IHostAudioPort.pfnNotifyDeviceChanged                = drvAudioHostPort_NotifyDeviceChanged;
    pThis->IHostAudioPort.pfnStreamNotifyPreparingDeviceSwitch  = drvAudioHostPort_StreamNotifyPreparingDeviceSwitch;
    pThis->IHostAudioPort.pfnStreamNotifyDeviceChanged          = drvAudioHostPort_StreamNotifyDeviceChanged;
    pThis->IHostAudioPort.pfnNotifyDevicesChanged               = drvAudioHostPort_NotifyDevicesChanged;

#ifdef VBOX_WITH_AUDIO_ENUM
    /*
     * Create a timer to trigger delayed device enumeration on device changes.
     */
    RTStrPrintf(pThis->szEnumTimerName, sizeof(pThis->szEnumTimerName), "AudioEnum-%u", pDrvIns->iInstance);
    rc = PDMDrvHlpTMTimerCreate(pDrvIns, TMCLOCK_REAL, drvAudioEnumerateTimer, NULL /*pvUser*/,
                                0 /*fFlags*/, pThis->szEnumTimerName, &pThis->hEnumTimer);
    AssertRCReturn(rc, rc);
#endif

    /*
     * Attach the host driver, if present.
     */
    rc = drvAudioDoAttachInternal(pDrvIns, pThis, fFlags);
    if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
        rc = VINF_SUCCESS;

    /*
     * Statistics (afte driver attach for name).
     */
    PDMDrvHlpSTAMRegister(pDrvIns, &pThis->BackendCfg.fFlags,   STAMTYPE_U32,  "BackendFlags",     STAMUNIT_COUNT, pThis->BackendCfg.szName); /* Mainly for the name. */
    PDMDrvHlpSTAMRegister(pDrvIns, &pThis->cStreams,            STAMTYPE_U32,  "Streams",          STAMUNIT_COUNT, "Current streams count.");
    PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatTotalStreamsCreated,          "TotalStreamsCreated", "Number of stream ever created.");
    PDMDrvHlpSTAMRegister(pDrvIns, &pThis->In.fEnabled,         STAMTYPE_BOOL, "InputEnabled",     STAMUNIT_NONE, "Whether input is enabled or not.");
    PDMDrvHlpSTAMRegister(pDrvIns, &pThis->In.cStreamsFree,     STAMTYPE_U32,  "InputStreamFree",  STAMUNIT_COUNT, "Number of free input stream slots");
    PDMDrvHlpSTAMRegister(pDrvIns, &pThis->Out.fEnabled,        STAMTYPE_BOOL, "OutputEnabled",    STAMUNIT_NONE, "Whether output is enabled or not.");
    PDMDrvHlpSTAMRegister(pDrvIns, &pThis->Out.cStreamsFree,    STAMTYPE_U32,  "OutputStreamFree", STAMUNIT_COUNT, "Number of free output stream slots");

    LogFlowFuncLeaveRC(rc);
    return rc;
}

/**
 * Audio driver registration record.
 */
const PDMDRVREG g_DrvAUDIO =
{
    /* u32Version */
    PDM_DRVREG_VERSION,
    /* szName */
    "AUDIO",
    /* szRCMod */
    "",
    /* szR0Mod */
    "",
    /* pszDescription */
    "Audio connector driver",
    /* fFlags */
    PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
    /* fClass */
    PDM_DRVREG_CLASS_AUDIO,
    /* cMaxInstances */
    UINT32_MAX,
    /* cbInstance */
    sizeof(DRVAUDIO),
    /* pfnConstruct */
    drvAudioConstruct,
    /* pfnDestruct */
    drvAudioDestruct,
    /* pfnRelocate */
    NULL,
    /* pfnIOCtl */
    NULL,
    /* pfnPowerOn */
    NULL,
    /* pfnReset */
    NULL,
    /* pfnSuspend */
    drvAudioSuspend,
    /* pfnResume */
    drvAudioResume,
    /* pfnAttach */
    drvAudioAttach,
    /* pfnDetach */
    drvAudioDetach,
    /* pfnPowerOff */
    drvAudioPowerOff,
    /* pfnSoftReset */
    NULL,
    /* u32EndVersion */
    PDM_DRVREG_VERSION
};