summaryrefslogtreecommitdiffstats
path: root/src/VBox/Devices/Audio/AudioMixBuffer.cpp
blob: 7ce89088c6144c8c57b8330eb03712c0447fac88 (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
/* $Id: AudioMixBuffer.cpp $ */
/** @file
 * Audio mixing buffer for converting reading/writing audio data.
 */

/*
 * Copyright (C) 2014-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
 */

/** @page pg_audio_mixing_buffers   Audio Mixer Buffer
 *
 * @section sec_audio_mixing_buffers_volume     Soft Volume Control
 *
 * The external code supplies an 8-bit volume (attenuation) value in the
 * 0 .. 255 range. This represents 0 to -96dB attenuation where an input
 * value of 0 corresponds to -96dB and 255 corresponds to 0dB (unchanged).
 *
 * Each step thus corresponds to 96 / 256 or 0.375dB. Every 6dB (16 steps)
 * represents doubling the sample value.
 *
 * For internal use, the volume control needs to be converted to a 16-bit
 * (sort of) exponential value between 1 and 65536. This is used with fixed
 * point arithmetic such that 65536 means 1.0 and 1 means 1/65536.
 *
 * For actual volume calculation, 33.31 fixed point is used. Maximum (or
 * unattenuated) volume is represented as 0x40000000; conveniently, this
 * value fits into a uint32_t.
 *
 * To enable fast processing, the maximum volume must be a power of two
 * and must not have a sign when converted to int32_t. While 0x80000000
 * violates these constraints, 0x40000000 does not.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_AUDIO_MIXER_BUFFER
#if defined(VBOX_AUDIO_MIX_BUFFER_TESTCASE) && !defined(RT_STRICT)
# define RT_STRICT /* Run the testcase with assertions because the main functions doesn't return on invalid input. */
#endif
#include <VBox/log.h>

#if 0
/*
 * AUDIOMIXBUF_DEBUG_DUMP_PCM_DATA enables dumping the raw PCM data
 * to a file on the host. Be sure to adjust AUDIOMIXBUF_DEBUG_DUMP_PCM_DATA_PATH
 * to your needs before using this!
 */
# define AUDIOMIXBUF_DEBUG_DUMP_PCM_DATA
# ifdef RT_OS_WINDOWS
#  define AUDIOMIXBUF_DEBUG_DUMP_PCM_DATA_PATH "c:\\temp\\"
# else
#  define AUDIOMIXBUF_DEBUG_DUMP_PCM_DATA_PATH "/tmp/"
# endif
/* Warning: Enabling this will generate *huge* logs! */
//# define AUDIOMIXBUF_DEBUG_MACROS
#endif

#include <iprt/asm-math.h>
#include <iprt/assert.h>
#ifdef AUDIOMIXBUF_DEBUG_DUMP_PCM_DATA
# include <iprt/file.h>
#endif
#include <iprt/mem.h>
#include <iprt/string.h> /* For RT_BZERO. */

#ifdef VBOX_AUDIO_TESTCASE
# define LOG_ENABLED
# include <iprt/stream.h>
#endif
#include <iprt/errcore.h>
#include <VBox/vmm/pdmaudioinline.h>

#include "AudioMixBuffer.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
#ifndef VBOX_AUDIO_TESTCASE
# ifdef DEBUG
#  define AUDMIXBUF_LOG(x) LogFlowFunc(x)
#  define AUDMIXBUF_LOG_ENABLED
# else
#  define AUDMIXBUF_LOG(x) do {} while (0)
# endif
#else /* VBOX_AUDIO_TESTCASE */
# define AUDMIXBUF_LOG(x) RTPrintf x
# define AUDMIXBUF_LOG_ENABLED
#endif


/** Bit shift for fixed point conversion.
 * @sa @ref sec_audio_mixing_buffers_volume */
#define AUDIOMIXBUF_VOL_SHIFT       30

/** Internal representation of 0dB volume (1.0 in fixed point).
 * @sa @ref sec_audio_mixing_buffers_volume */
#define AUDIOMIXBUF_VOL_0DB         (1 << AUDIOMIXBUF_VOL_SHIFT)
AssertCompile(AUDIOMIXBUF_VOL_0DB <= 0x40000000);   /* Must always hold. */
AssertCompile(AUDIOMIXBUF_VOL_0DB == 0x40000000);   /* For now -- when only attenuation is used. */


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** Logarithmic/exponential volume conversion table.
 * @sa @ref sec_audio_mixing_buffers_volume
 */
static uint32_t const s_aVolumeConv[256] =
{
        1,     1,     1,     1,     1,     1,     1,     1, /*   7 */
        1,     2,     2,     2,     2,     2,     2,     2, /*  15 */
        2,     2,     2,     2,     2,     3,     3,     3, /*  23 */
        3,     3,     3,     3,     4,     4,     4,     4, /*  31 */
        4,     4,     5,     5,     5,     5,     5,     6, /*  39 */
        6,     6,     6,     7,     7,     7,     8,     8, /*  47 */
        8,     9,     9,    10,    10,    10,    11,    11, /*  55 */
       12,    12,    13,    13,    14,    15,    15,    16, /*  63 */
       17,    17,    18,    19,    20,    21,    22,    23, /*  71 */
       24,    25,    26,    27,    28,    29,    31,    32, /*  79 */
       33,    35,    36,    38,    40,    41,    43,    45, /*  87 */
       47,    49,    52,    54,    56,    59,    61,    64, /*  95 */
       67,    70,    73,    76,    79,    83,    87,    91, /* 103 */
       95,    99,   103,   108,   112,   117,   123,   128, /* 111 */
      134,   140,   146,   152,   159,   166,   173,   181, /* 119 */
      189,   197,   206,   215,   225,   235,   245,   256, /* 127 */
      267,   279,   292,   304,   318,   332,   347,   362, /* 135 */
      378,   395,   412,   431,   450,   470,   490,   512, /* 143 */
      535,   558,   583,   609,   636,   664,   693,   724, /* 151 */
      756,   790,   825,   861,   899,   939,   981,  1024, /* 159 */
     1069,  1117,  1166,  1218,  1272,  1328,  1387,  1448, /* 167 */
     1512,  1579,  1649,  1722,  1798,  1878,  1961,  2048, /* 175 */
     2139,  2233,  2332,  2435,  2543,  2656,  2774,  2896, /* 183 */
     3025,  3158,  3298,  3444,  3597,  3756,  3922,  4096, /* 191 */
     4277,  4467,  4664,  4871,  5087,  5312,  5547,  5793, /* 199 */
     6049,  6317,  6597,  6889,  7194,  7512,  7845,  8192, /* 207 */
     8555,  8933,  9329,  9742, 10173, 10624, 11094, 11585, /* 215 */
    12098, 12634, 13193, 13777, 14387, 15024, 15689, 16384, /* 223 */
    17109, 17867, 18658, 19484, 20347, 21247, 22188, 23170, /* 231 */
    24196, 25268, 26386, 27554, 28774, 30048, 31379, 32768, /* 239 */
    34219, 35734, 37316, 38968, 40693, 42495, 44376, 46341, /* 247 */
    48393, 50535, 52773, 55109, 57549, 60097, 62757, 65536, /* 255 */
};



#ifdef VBOX_STRICT
# ifdef UNUSED

/**
 * Prints a single mixing buffer.
 * Internal helper function for debugging. Do not use directly.
 *
 * @returns VBox status code.
 * @param   pMixBuf                 Mixing buffer to print.
 * @param   pszFunc                 Function name to log this for.
 * @param   uIdtLvl                 Indention level to use.
 */
static void audioMixBufDbgPrintSingle(PAUDIOMIXBUF pMixBuf, const char *pszFunc, uint16_t uIdtLvl)
{
    Log(("%s: %*s %s: offRead=%RU32, offWrite=%RU32 -> %RU32/%RU32\n",
         pszFunc, uIdtLvl * 4, "",
         pMixBuf->pszName, pMixBuf->offRead, pMixBuf->offWrite, pMixBuf->cUsed, pMixBuf->cFrames));
}

static void audioMixBufDbgPrintInternal(PAUDIOMIXBUF pMixBuf, const char *pszFunc)
{
    audioMixBufDbgPrintSingle(pMixBuf, pszFunc, 0 /* iIdtLevel */);
}

/**
 * Validates a single mixing buffer.
 *
 * @return  @true if the buffer state is valid or @false if not.
 * @param   pMixBuf                 Mixing buffer to validate.
 */
static bool audioMixBufDbgValidate(PAUDIOMIXBUF pMixBuf)
{
    //const uint32_t offReadEnd  = (pMixBuf->offRead + pMixBuf->cUsed) % pMixBuf->cFrames;
    //const uint32_t offWriteEnd = (pMixBuf->offWrite + (pMixBuf->cFrames - pMixBuf->cUsed)) % pMixBuf->cFrames;

    bool fValid = true;

    AssertStmt(pMixBuf->offRead  <= pMixBuf->cFrames, fValid = false);
    AssertStmt(pMixBuf->offWrite <= pMixBuf->cFrames, fValid = false);
    AssertStmt(pMixBuf->cUsed    <= pMixBuf->cFrames, fValid = false);

    if (pMixBuf->offWrite > pMixBuf->offRead)
    {
        if (pMixBuf->offWrite - pMixBuf->offRead != pMixBuf->cUsed)
            fValid = false;
    }
    else if (pMixBuf->offWrite < pMixBuf->offRead)
    {
        if (pMixBuf->offWrite + pMixBuf->cFrames - pMixBuf->offRead != pMixBuf->cUsed)
            fValid = false;
    }

    if (!fValid)
    {
        audioMixBufDbgPrintInternal(pMixBuf, __FUNCTION__);
        AssertFailed();
    }

    return fValid;
}

# endif /* UNUSED */
#endif /* VBOX_STRICT */


/**
 * Merges @a i32Src into the value stored at @a pi32Dst.
 *
 * @param   pi32Dst     The value to merge @a i32Src into.
 * @param   i32Src      The new value to add.
 */
DECL_FORCE_INLINE(void) audioMixBufBlendSample(int32_t *pi32Dst, int32_t i32Src)
{
    if (i32Src)
    {
        int64_t const i32Dst = *pi32Dst;
        if (!i32Dst)
            *pi32Dst = i32Src;
        else
            *pi32Dst = (int32_t)(((int64_t)i32Dst + i32Src) / 2);
    }
}


/**
 * Variant of audioMixBufBlendSample that returns the result rather than storing it.
 *
 * This is used for stereo -> mono.
 */
DECL_FORCE_INLINE(int32_t) audioMixBufBlendSampleRet(int32_t i32Sample1, int32_t i32Sample2)
{
    if (!i32Sample1)
        return i32Sample2;
    if (!i32Sample2)
        return i32Sample1;
    return (int32_t)(((int64_t)i32Sample1 + i32Sample2) / 2);
}


/**
 * Blends (merges) the source buffer into the destination buffer.
 *
 * We're taking a very simple approach here, working sample by sample:
 *  - if one is silent, use the other one.
 *  - otherwise sum and divide by two.
 *
 * @param   pi32Dst     The destination stream buffer (input and output).
 * @param   pi32Src     The source stream buffer.
 * @param   cFrames     Number of frames to process.
 * @param   cChannels   Number of channels.
 */
static void audioMixBufBlendBuffer(int32_t *pi32Dst, int32_t const *pi32Src, uint32_t cFrames, uint8_t cChannels)
{
    switch (cChannels)
    {
        case 2:
            while (cFrames-- > 0)
            {
                audioMixBufBlendSample(&pi32Dst[0], pi32Src[0]);
                audioMixBufBlendSample(&pi32Dst[1], pi32Src[1]);
                pi32Dst += 2;
                pi32Src += 2;
            }
            break;

        default:
            cFrames *= cChannels;
            RT_FALL_THROUGH();
        case 1:
            while (cFrames-- > 0)
            {
                audioMixBufBlendSample(pi32Dst, pi32Src[0]);
                pi32Dst++;
                pi32Src++;
            }
            break;
    }
}


#ifdef AUDIOMIXBUF_DEBUG_MACROS
# define AUDMIXBUF_MACRO_LOG(x) AUDMIXBUF_LOG(x)
#elif defined(VBOX_AUDIO_TESTCASE_VERBOSE) /* Warning: VBOX_AUDIO_TESTCASE_VERBOSE will generate huge logs! */
# define AUDMIXBUF_MACRO_LOG(x) RTPrintf x
#else
# define AUDMIXBUF_MACRO_LOG(x) do {} while (0)
#endif

/*
 * Instantiate format conversion (in and out of the mixer buffer.)
 */
/** @todo Currently does not handle any endianness conversion yet! */

/* audioMixBufConvXXXS8: 8-bit, signed. */
#define a_Name      S8
#define a_Type      int8_t
#define a_Min       INT8_MIN
#define a_Max       INT8_MAX
#define a_fSigned   1
#define a_cShift    8
#include "AudioMixBuffer-Convert.cpp.h"

/* audioMixBufConvXXXU8: 8-bit, unsigned. */
#define a_Name      U8
#define a_Type      uint8_t
#define a_Min       0
#define a_Max       UINT8_MAX
#define a_fSigned   0
#define a_cShift    8
#include "AudioMixBuffer-Convert.cpp.h"

/* audioMixBufConvXXXS16: 16-bit, signed. */
#define a_Name      S16
#define a_Type      int16_t
#define a_Min       INT16_MIN
#define a_Max       INT16_MAX
#define a_fSigned   1
#define a_cShift    16
#include "AudioMixBuffer-Convert.cpp.h"

/* audioMixBufConvXXXU16: 16-bit, unsigned. */
#define a_Name      U16
#define a_Type      uint16_t
#define a_Min       0
#define a_Max       UINT16_MAX
#define a_fSigned   0
#define a_cShift    16
#include "AudioMixBuffer-Convert.cpp.h"

/* audioMixBufConvXXXS32: 32-bit, signed. */
#define a_Name      S32
#define a_Type      int32_t
#define a_Min       INT32_MIN
#define a_Max       INT32_MAX
#define a_fSigned   1
#define a_cShift    32
#include "AudioMixBuffer-Convert.cpp.h"

/* audioMixBufConvXXXU32: 32-bit, unsigned. */
#define a_Name      U32
#define a_Type      uint32_t
#define a_Min       0
#define a_Max       UINT32_MAX
#define a_fSigned   0
#define a_cShift    32
#include "AudioMixBuffer-Convert.cpp.h"

/* audioMixBufConvXXXRaw: 32-bit stored as 64-bit, signed. */
#define a_Name      Raw
#define a_Type      int64_t
#define a_Min       INT64_MIN
#define a_Max       INT64_MAX
#define a_fSigned   1
#define a_cShift    32 /* Yes, 32! */
#include "AudioMixBuffer-Convert.cpp.h"

#undef AUDMIXBUF_CONVERT
#undef AUDMIXBUF_MACRO_LOG


/*
 * Resampling core.
 */
/** @todo Separate down- and up-sampling, borrow filter code from RDP. */
#define COPY_LAST_FRAME_1CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
    } while (0)
#define COPY_LAST_FRAME_2CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
    } while (0)
#define COPY_LAST_FRAME_3CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
    } while (0)
#define COPY_LAST_FRAME_4CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
    } while (0)
#define COPY_LAST_FRAME_5CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
    } while (0)
#define COPY_LAST_FRAME_6CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
    } while (0)
#define COPY_LAST_FRAME_7CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
        (a_pi32Dst)[6] = (a_pi32Src)[6]; \
    } while (0)
#define COPY_LAST_FRAME_8CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
        (a_pi32Dst)[6] = (a_pi32Src)[6]; \
        (a_pi32Dst)[7] = (a_pi32Src)[7]; \
    } while (0)
#define COPY_LAST_FRAME_9CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
        (a_pi32Dst)[6] = (a_pi32Src)[6]; \
        (a_pi32Dst)[7] = (a_pi32Src)[7]; \
        (a_pi32Dst)[8] = (a_pi32Src)[8]; \
    } while (0)
#define COPY_LAST_FRAME_10CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
        (a_pi32Dst)[6] = (a_pi32Src)[6]; \
        (a_pi32Dst)[7] = (a_pi32Src)[7]; \
        (a_pi32Dst)[8] = (a_pi32Src)[8]; \
        (a_pi32Dst)[9] = (a_pi32Src)[9]; \
    } while (0)
#define COPY_LAST_FRAME_11CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
        (a_pi32Dst)[6] = (a_pi32Src)[6]; \
        (a_pi32Dst)[7] = (a_pi32Src)[7]; \
        (a_pi32Dst)[8] = (a_pi32Src)[8]; \
        (a_pi32Dst)[9] = (a_pi32Src)[9]; \
        (a_pi32Dst)[10] = (a_pi32Src)[10]; \
    } while (0)
#define COPY_LAST_FRAME_12CH(a_pi32Dst, a_pi32Src, a_cChannels) do { \
        (a_pi32Dst)[0] = (a_pi32Src)[0]; \
        (a_pi32Dst)[1] = (a_pi32Src)[1]; \
        (a_pi32Dst)[2] = (a_pi32Src)[2]; \
        (a_pi32Dst)[3] = (a_pi32Src)[3]; \
        (a_pi32Dst)[4] = (a_pi32Src)[4]; \
        (a_pi32Dst)[5] = (a_pi32Src)[5]; \
        (a_pi32Dst)[6] = (a_pi32Src)[6]; \
        (a_pi32Dst)[7] = (a_pi32Src)[7]; \
        (a_pi32Dst)[8] = (a_pi32Src)[8]; \
        (a_pi32Dst)[9] = (a_pi32Src)[9]; \
        (a_pi32Dst)[10] = (a_pi32Src)[10]; \
        (a_pi32Dst)[11] = (a_pi32Src)[11]; \
    } while (0)

#define INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_iCh) \
        (a_pi32Dst)[a_iCh] = ((a_pi32Last)[a_iCh] * a_i64FactorLast + (a_pi32Src)[a_iCh] * a_i64FactorCur) >> 32
#define INTERPOLATE_1CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
    } while (0)
#define INTERPOLATE_2CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
    } while (0)
#define INTERPOLATE_3CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
    } while (0)
#define INTERPOLATE_4CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
    } while (0)
#define INTERPOLATE_5CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
    } while (0)
#define INTERPOLATE_6CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
    } while (0)
#define INTERPOLATE_7CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 6); \
    } while (0)
#define INTERPOLATE_8CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 6); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 7); \
    } while (0)
#define INTERPOLATE_9CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 6); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 7); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 8); \
    } while (0)
#define INTERPOLATE_10CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 6); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 7); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 8); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 9); \
    } while (0)
#define INTERPOLATE_11CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 6); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 7); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 8); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 9); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 10); \
    } while (0)
#define INTERPOLATE_12CH(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, a_cChannels) do { \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 0); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 1); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 2); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 3); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 4); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 5); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 6); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 7); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 8); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 9); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 10); \
        INTERPOLATE_ONE(a_pi32Dst, a_pi32Src, a_pi32Last, a_i64FactorCur, a_i64FactorLast, 11); \
    } while (0)

#define AUDIOMIXBUF_RESAMPLE(a_cChannels, a_Suffix) \
    /** @returns Number of destination frames written. */ \
    static DECLCALLBACK(uint32_t) \
    audioMixBufResample##a_cChannels##Ch##a_Suffix(int32_t *pi32Dst, uint32_t cDstFrames, \
                                                   int32_t const *pi32Src, uint32_t cSrcFrames, uint32_t *pcSrcFramesRead, \
                                                   PAUDIOSTREAMRATE pRate) \
    { \
        Log5(("Src: %RU32 L %RU32;  Dst: %RU32 L%RU32; uDstInc=%#RX64\n", \
              pRate->offSrc, cSrcFrames, RT_HI_U32(pRate->offDst), cDstFrames, pRate->uDstInc)); \
        int32_t * const       pi32DstStart = pi32Dst; \
        int32_t const * const pi32SrcStart = pi32Src; \
        \
        int32_t ai32LastFrame[a_cChannels]; \
        COPY_LAST_FRAME_##a_cChannels##CH(ai32LastFrame, pRate->SrcLast.ai32Samples, a_cChannels); \
        \
        while (cDstFrames > 0 && cSrcFrames > 0) \
        { \
            int32_t const cSrcNeeded = RT_HI_U32(pRate->offDst) - pRate->offSrc + 1; \
            if (cSrcNeeded > 0) \
            { \
                if ((uint32_t)cSrcNeeded + 1 < cSrcFrames) \
                { \
                    pRate->offSrc += (uint32_t)cSrcNeeded; \
                    cSrcFrames    -= (uint32_t)cSrcNeeded; \
                    pi32Src       += (uint32_t)cSrcNeeded * a_cChannels; \
                    COPY_LAST_FRAME_##a_cChannels##CH(ai32LastFrame, &pi32Src[-a_cChannels], a_cChannels); \
                } \
                else \
                { \
                    pi32Src       += cSrcFrames * a_cChannels; \
                    pRate->offSrc += cSrcFrames; \
                    COPY_LAST_FRAME_##a_cChannels##CH(pRate->SrcLast.ai32Samples, &pi32Src[-a_cChannels], a_cChannels); \
                    *pcSrcFramesRead = (pi32Src - pi32SrcStart) / a_cChannels; \
                    return (pi32Dst - pi32DstStart) / a_cChannels; \
                } \
            } \
            \
            /* Interpolate. */ \
            int64_t const offFactorCur  = pRate->offDst & UINT32_MAX; \
            int64_t const offFactorLast = (int64_t)_4G - offFactorCur; \
            INTERPOLATE_##a_cChannels##CH(pi32Dst, pi32Src, ai32LastFrame, offFactorCur, offFactorLast, a_cChannels); \
            \
            /* Advance. */ \
            pRate->offDst += pRate->uDstInc; \
            pi32Dst       += a_cChannels; \
            cDstFrames    -= 1; \
        } \
        \
        COPY_LAST_FRAME_##a_cChannels##CH(pRate->SrcLast.ai32Samples, ai32LastFrame, a_cChannels); \
        *pcSrcFramesRead = (pi32Src - pi32SrcStart) / a_cChannels; \
        return (pi32Dst - pi32DstStart) / a_cChannels; \
    }

AUDIOMIXBUF_RESAMPLE(1,Generic)
AUDIOMIXBUF_RESAMPLE(2,Generic)
AUDIOMIXBUF_RESAMPLE(3,Generic)
AUDIOMIXBUF_RESAMPLE(4,Generic)
AUDIOMIXBUF_RESAMPLE(5,Generic)
AUDIOMIXBUF_RESAMPLE(6,Generic)
AUDIOMIXBUF_RESAMPLE(7,Generic)
AUDIOMIXBUF_RESAMPLE(8,Generic)
AUDIOMIXBUF_RESAMPLE(9,Generic)
AUDIOMIXBUF_RESAMPLE(10,Generic)
AUDIOMIXBUF_RESAMPLE(11,Generic)
AUDIOMIXBUF_RESAMPLE(12,Generic)


/**
 * Resets the resampling state unconditionally.
 *
 * @param   pRate   The state to reset.
 */
static void audioMixBufRateResetAlways(PAUDIOSTREAMRATE pRate)
{
    pRate->offDst = 0;
    pRate->offSrc = 0;
    for (uintptr_t i = 0; i < RT_ELEMENTS(pRate->SrcLast.ai32Samples); i++)
        pRate->SrcLast.ai32Samples[0] = 0;
}


/**
 * Resets the resampling state.
 *
 * @param   pRate   The state to reset.
 */
DECLINLINE(void) audioMixBufRateReset(PAUDIOSTREAMRATE pRate)
{
    if (pRate->offDst == 0)
    { /* likely */ }
    else
    {
        Assert(!pRate->fNoConversionNeeded);
        audioMixBufRateResetAlways(pRate);
    }
}


/**
 * Initializes the frame rate converter state.
 *
 * @returns VBox status code.
 * @param   pRate       The state to initialize.
 * @param   uSrcHz      The source frame rate.
 * @param   uDstHz      The destination frame rate.
 * @param   cChannels   The number of channels in a frame.
 */
DECLINLINE(int) audioMixBufRateInit(PAUDIOSTREAMRATE pRate, uint32_t uSrcHz, uint32_t uDstHz, uint8_t cChannels)
{
    /*
     * Do we need to set up frequency conversion?
     *
     * Some examples to get an idea of what uDstInc holds:
     *   44100 to 44100 -> (44100<<32) / 44100 = 0x01'00000000 (4294967296)
     *   22050 to 44100 -> (22050<<32) / 44100 = 0x00'80000000 (2147483648)
     *   44100 to 22050 -> (44100<<32) / 22050 = 0x02'00000000 (8589934592)
     *   44100 to 48000 -> (44100<<32) / 48000 = 0x00'EB333333 (3946001203.2)
     *   48000 to 44100 -> (48000<<32) / 44100 = 0x01'16A3B35F (4674794335.7823129251700680272109)
     */
    audioMixBufRateResetAlways(pRate);
    if (uSrcHz == uDstHz)
    {
        pRate->fNoConversionNeeded = true;
        pRate->uDstInc             = RT_BIT_64(32);
        pRate->pfnResample         = NULL;
    }
    else
    {
        pRate->fNoConversionNeeded = false;
        pRate->uDstInc             = ((uint64_t)uSrcHz << 32) / uDstHz;
        AssertReturn(uSrcHz != 0, VERR_INVALID_PARAMETER);
        switch (cChannels)
        {
            case  1: pRate->pfnResample = audioMixBufResample1ChGeneric; break;
            case  2: pRate->pfnResample = audioMixBufResample2ChGeneric; break;
            case  3: pRate->pfnResample = audioMixBufResample3ChGeneric; break;
            case  4: pRate->pfnResample = audioMixBufResample4ChGeneric; break;
            case  5: pRate->pfnResample = audioMixBufResample5ChGeneric; break;
            case  6: pRate->pfnResample = audioMixBufResample6ChGeneric; break;
            case  7: pRate->pfnResample = audioMixBufResample7ChGeneric; break;
            case  8: pRate->pfnResample = audioMixBufResample8ChGeneric; break;
            case  9: pRate->pfnResample = audioMixBufResample9ChGeneric; break;
            case 10: pRate->pfnResample = audioMixBufResample10ChGeneric; break;
            case 11: pRate->pfnResample = audioMixBufResample11ChGeneric; break;
            case 12: pRate->pfnResample = audioMixBufResample12ChGeneric; break;
            default:
                AssertMsgFailedReturn(("resampling %u changes is not implemented yet\n", cChannels), VERR_OUT_OF_RANGE);
        }
    }
    return VINF_SUCCESS;
}


/**
 * Initializes a mixing buffer.
 *
 * @returns VBox status code.
 * @param   pMixBuf                 Mixing buffer to initialize.
 * @param   pszName                 Name of mixing buffer for easier identification. Optional.
 * @param   pProps                  PCM audio properties to use for the mixing buffer.
 * @param   cFrames                 Maximum number of audio frames the mixing buffer can hold.
 */
int AudioMixBufInit(PAUDIOMIXBUF pMixBuf, const char *pszName, PCPDMAUDIOPCMPROPS pProps, uint32_t cFrames)
{
    AssertPtrReturn(pMixBuf, VERR_INVALID_POINTER);
    AssertPtrReturn(pszName, VERR_INVALID_POINTER);
    AssertPtrReturn(pProps,  VERR_INVALID_POINTER);
    Assert(PDMAudioPropsAreValid(pProps));

    /*
     * Initialize all members, setting the volume to max (0dB).
     */
    pMixBuf->cFrames        = 0;
    pMixBuf->pi32Samples    = NULL;
    pMixBuf->cChannels      = 0;
    pMixBuf->cbFrame        = 0;
    pMixBuf->offRead        = 0;
    pMixBuf->offWrite       = 0;
    pMixBuf->cUsed          = 0;
    pMixBuf->Props          = *pProps;
    pMixBuf->Volume.fMuted  = false;
    pMixBuf->Volume.fAllMax = true;
    for (uintptr_t i = 0; i < RT_ELEMENTS(pMixBuf->Volume.auChannels); i++)
        pMixBuf->Volume.auChannels[i] = AUDIOMIXBUF_VOL_0DB;

    int rc;
    uint8_t const cChannels = PDMAudioPropsChannels(pProps);
    if (cChannels >= 1 && cChannels <= PDMAUDIO_MAX_CHANNELS)
    {
        pMixBuf->pszName = RTStrDup(pszName);
        if (pMixBuf->pszName)
        {
            pMixBuf->pi32Samples = (int32_t *)RTMemAllocZ(cFrames * cChannels * sizeof(pMixBuf->pi32Samples[0]));
            if (pMixBuf->pi32Samples)
            {
                pMixBuf->cFrames    = cFrames;
                pMixBuf->cChannels  = cChannels;
                pMixBuf->cbFrame    = cChannels * sizeof(pMixBuf->pi32Samples[0]);
                pMixBuf->uMagic     = AUDIOMIXBUF_MAGIC;
#ifdef AUDMIXBUF_LOG_ENABLED
                char szTmp[PDMAUDIOPROPSTOSTRING_MAX];
                AUDMIXBUF_LOG(("%s: %s - cFrames=%#x (%d)\n",
                               pMixBuf->pszName, PDMAudioPropsToString(pProps, szTmp, sizeof(szTmp)), cFrames, cFrames));
#endif
                return VINF_SUCCESS;
            }
            RTStrFree(pMixBuf->pszName);
            pMixBuf->pszName = NULL;
            rc = VERR_NO_MEMORY;
        }
        else
            rc = VERR_NO_STR_MEMORY;
    }
    else
    {
        LogRelMaxFunc(64, ("cChannels=%d pszName=%s\n", cChannels, pszName));
        rc = VERR_OUT_OF_RANGE;
    }
    pMixBuf->uMagic = AUDIOMIXBUF_MAGIC_DEAD;
    return rc;
}

/**
 * Terminates (uninitializes) a mixing buffer.
 *
 * @param   pMixBuf     The mixing buffer.  Uninitialized mixer buffers will be
 *                      quietly ignored.  As will NULL.
 */
void AudioMixBufTerm(PAUDIOMIXBUF pMixBuf)
{
    if (!pMixBuf)
        return;

    /* Ignore calls for an uninitialized (zeroed) or already destroyed instance.  Happens a lot. */
    if (   pMixBuf->uMagic == 0
        || pMixBuf->uMagic == AUDIOMIXBUF_MAGIC_DEAD)
    {
        Assert(!pMixBuf->pszName);
        Assert(!pMixBuf->pi32Samples);
        Assert(!pMixBuf->cFrames);
        return;
    }

    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    pMixBuf->uMagic = ~AUDIOMIXBUF_MAGIC;

    if (pMixBuf->pszName)
    {
        AUDMIXBUF_LOG(("%s\n", pMixBuf->pszName));

        RTStrFree(pMixBuf->pszName);
        pMixBuf->pszName = NULL;
    }

    if (pMixBuf->pi32Samples)
    {
        Assert(pMixBuf->cFrames);
        RTMemFree(pMixBuf->pi32Samples);
        pMixBuf->pi32Samples = NULL;
    }

    pMixBuf->cFrames   = 0;
    pMixBuf->cChannels = 0;
}


/**
 * Drops all the frames in the given mixing buffer
 *
 * This will reset the read and write offsets to zero.
 *
 * @param   pMixBuf     The mixing buffer.  Uninitialized mixer buffers will be
 *                      quietly ignored.
 */
void AudioMixBufDrop(PAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturnVoid(pMixBuf);

    /* Ignore uninitialized (zeroed) mixer sink buffers (happens with AC'97 during VM construction). */
    if (   pMixBuf->uMagic == 0
        || pMixBuf->uMagic == AUDIOMIXBUF_MAGIC_DEAD)
        return;

    AUDMIXBUF_LOG(("%s\n", pMixBuf->pszName));

    pMixBuf->offRead  = 0;
    pMixBuf->offWrite = 0;
    pMixBuf->cUsed    = 0;
}


/**
 * Gets the maximum number of audio frames this buffer can hold.
 *
 * @returns Number of frames.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufSize(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return pMixBuf->cFrames;
}


/**
 * Gets the maximum number of bytes this buffer can hold.
 *
 * @returns Number of bytes.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufSizeBytes(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    AssertReturn(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC, 0);
    return AUDIOMIXBUF_F2B(pMixBuf, pMixBuf->cFrames);
}


/**
 * Worker for AudioMixBufUsed and AudioMixBufUsedBytes.
 */
DECLINLINE(uint32_t) audioMixBufUsedInternal(PCAUDIOMIXBUF pMixBuf)
{
    uint32_t const cFrames = pMixBuf->cFrames;
    uint32_t       cUsed   = pMixBuf->cUsed;
    AssertStmt(cUsed <= cFrames, cUsed = cFrames);
    return cUsed;
}


/**
 * Get the number of used (readable) frames in the buffer.
 *
 * @returns Number of frames.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufUsed(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return audioMixBufUsedInternal(pMixBuf);
}


/**
 * Get the number of (readable) bytes in the buffer.
 *
 * @returns Number of bytes.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufUsedBytes(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return AUDIOMIXBUF_F2B(pMixBuf, audioMixBufUsedInternal(pMixBuf));
}


/**
 * Worker for AudioMixBufFree and AudioMixBufFreeBytes.
 */
DECLINLINE(uint32_t) audioMixBufFreeInternal(PCAUDIOMIXBUF pMixBuf)
{
    uint32_t const cFrames = pMixBuf->cFrames;
    uint32_t       cUsed   = pMixBuf->cUsed;
    AssertStmt(cUsed <= cFrames, cUsed = cFrames);
    uint32_t const cFramesFree = cFrames - cUsed;

    AUDMIXBUF_LOG(("%s: %RU32 of %RU32\n", pMixBuf->pszName, cFramesFree, cFrames));
    return cFramesFree;
}


/**
 * Gets the free buffer space in frames.
 *
 * @return  Number of frames.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufFree(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return audioMixBufFreeInternal(pMixBuf);
}


/**
 * Gets the free buffer space in bytes.
 *
 * @return  Number of bytes.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufFreeBytes(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return AUDIOMIXBUF_F2B(pMixBuf, audioMixBufFreeInternal(pMixBuf));
}


/**
 * Checks if the buffer is empty.
 *
 * @retval  true if empty buffer.
 * @retval  false if not empty and there are frames to be processed.
 * @param   pMixBuf     The mixing buffer.
 */
bool AudioMixBufIsEmpty(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, true);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return pMixBuf->cUsed == 0;
}


/**
 * Get the current read position.
 *
 * This is for the testcase.
 *
 * @returns Frame number.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufReadPos(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return pMixBuf->offRead;
}


/**
 * Gets the current write position.
 *
 * This is for the testcase.
 *
 * @returns Frame number.
 * @param   pMixBuf     The mixing buffer.
 */
uint32_t AudioMixBufWritePos(PCAUDIOMIXBUF pMixBuf)
{
    AssertPtrReturn(pMixBuf, 0);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    return pMixBuf->offWrite;
}


/**
 * Creates a mapping between desination channels and source source channels.
 *
 * @param   paidxChannelMap     Where to store the mapping.  Indexed by
 *                              destination channel.  Entry is either source
 *                              channel index or -1 for zero and -2 for silence.
 * @param   pSrcProps           The source properties.
 * @param   pDstProps           The desination properties.
 */
static void audioMixBufInitChannelMap(int8_t paidxChannelMap[PDMAUDIO_MAX_CHANNELS],
                                      PCPDMAUDIOPCMPROPS pSrcProps, PCPDMAUDIOPCMPROPS pDstProps)
{
    uintptr_t const cDstChannels = PDMAudioPropsChannels(pDstProps);
    uintptr_t const cSrcChannels = PDMAudioPropsChannels(pSrcProps);
    uintptr_t       idxDst;
    for (idxDst = 0; idxDst < cDstChannels; idxDst++)
    {
        uint8_t const idDstCh = pDstProps->aidChannels[idxDst];
        if (idDstCh >= PDMAUDIOCHANNELID_FRONT_LEFT && idDstCh < PDMAUDIOCHANNELID_END)
        {
            uintptr_t idxSrc;
            for (idxSrc = 0; idxSrc < cSrcChannels; idxSrc++)
                if (idDstCh == pSrcProps->aidChannels[idxSrc])
                {
                    paidxChannelMap[idxDst] = idxSrc;
                    break;
                }
            if (idxSrc >= cSrcChannels)
            {
                /** @todo deal with mono. */
                paidxChannelMap[idxDst] = -2;
            }
        }
        else if (idDstCh == PDMAUDIOCHANNELID_UNKNOWN)
        {
            /** @todo What to do here?  Pick unused source channels in order? */
            paidxChannelMap[idxDst] = -2;
        }
        else
        {
            AssertMsg(idDstCh == PDMAUDIOCHANNELID_UNUSED_SILENCE || idDstCh == PDMAUDIOCHANNELID_UNUSED_ZERO,
                      ("idxDst=%u idDstCh=%u\n", idxDst, idDstCh));
            paidxChannelMap[idxDst] = idDstCh == PDMAUDIOCHANNELID_UNUSED_SILENCE ? -2 : -1;
        }
    }

    /* Set the remainder to -1 just to be sure their are safe. */
    for (; idxDst < PDMAUDIO_MAX_CHANNELS; idxDst++)
        paidxChannelMap[idxDst] = -1;
}


/**
 * Initializes the peek state, setting up encoder and (if necessary) resampling.
 *
 * @returns VBox status code.
 */
int AudioMixBufInitPeekState(PCAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFPEEKSTATE pState, PCPDMAUDIOPCMPROPS pProps)
{
    AssertPtr(pMixBuf);
    AssertPtr(pState);
    AssertPtr(pProps);

    /*
     * Pick the encoding function first.
     */
    uint8_t const cbSample = PDMAudioPropsSampleSize(pProps);
    uint8_t const cSrcCh   = PDMAudioPropsChannels(&pMixBuf->Props);
    uint8_t const cDstCh   = PDMAudioPropsChannels(pProps);
    pState->cSrcChannels   = cSrcCh;
    pState->cDstChannels   = cDstCh;
    pState->cbDstFrame     = PDMAudioPropsFrameSize(pProps);
    audioMixBufInitChannelMap(pState->aidxChannelMap, &pMixBuf->Props, pProps);
    AssertReturn(cDstCh > 0 && cDstCh <= PDMAUDIO_MAX_CHANNELS, VERR_OUT_OF_RANGE);
    AssertReturn(cSrcCh > 0 && cSrcCh <= PDMAUDIO_MAX_CHANNELS, VERR_OUT_OF_RANGE);

    if (PDMAudioPropsIsSigned(pProps))
    {
        /* Assign generic encoder first. */
        switch (cbSample)
        {
            case 1: pState->pfnEncode = audioMixBufEncodeGenericS8; break;
            case 2: pState->pfnEncode = audioMixBufEncodeGenericS16; break;
            case 4: pState->pfnEncode = audioMixBufEncodeGenericS32; break;
            case 8:
                AssertReturn(pProps->fRaw, VERR_DISK_INVALID_FORMAT);
                pState->pfnEncode = audioMixBufEncodeGenericRaw;
                break;
            default:
                AssertMsgFailedReturn(("%u bytes\n", cbSample), VERR_OUT_OF_RANGE);
        }

        /* Any specializations available? */
        switch (cDstCh)
        {
            case 1:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode1ChTo1ChS8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode1ChTo1ChS16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode1ChTo1ChS32; break;
                        case 8: pState->pfnEncode = audioMixBufEncode1ChTo1ChRaw; break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode2ChTo1ChS8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode2ChTo1ChS16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode2ChTo1ChS32; break;
                        case 8: pState->pfnEncode = audioMixBufEncode2ChTo1ChRaw; break;
                    }
                break;

            case 2:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode1ChTo2ChS8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode1ChTo2ChS16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode1ChTo2ChS32; break;
                        case 8: pState->pfnEncode = audioMixBufEncode1ChTo2ChRaw; break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode2ChTo2ChS8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode2ChTo2ChS16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode2ChTo2ChS32; break;
                        case 8: pState->pfnEncode = audioMixBufEncode2ChTo2ChRaw; break;
                    }
                break;
        }
    }
    else
    {
        /* Assign generic encoder first. */
        switch (cbSample)
        {
            case 1: pState->pfnEncode = audioMixBufEncodeGenericU8; break;
            case 2: pState->pfnEncode = audioMixBufEncodeGenericU16; break;
            case 4: pState->pfnEncode = audioMixBufEncodeGenericU32; break;
            default:
                AssertMsgFailedReturn(("%u bytes\n", cbSample), VERR_OUT_OF_RANGE);
        }

        /* Any specializations available? */
        switch (cDstCh)
        {
            case 1:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode1ChTo1ChU8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode1ChTo1ChU16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode1ChTo1ChU32; break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode2ChTo1ChU8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode2ChTo1ChU16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode2ChTo1ChU32; break;
                    }
                break;

            case 2:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode1ChTo2ChU8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode1ChTo2ChU16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode1ChTo2ChU32; break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1: pState->pfnEncode = audioMixBufEncode2ChTo2ChU8; break;
                        case 2: pState->pfnEncode = audioMixBufEncode2ChTo2ChU16; break;
                        case 4: pState->pfnEncode = audioMixBufEncode2ChTo2ChU32; break;
                    }
                break;
        }
    }

    int rc = audioMixBufRateInit(&pState->Rate, PDMAudioPropsHz(&pMixBuf->Props), PDMAudioPropsHz(pProps), cSrcCh);
    AUDMIXBUF_LOG(("%s: %RU32 Hz to %RU32 Hz => uDstInc=0x%'RX64\n", pMixBuf->pszName, PDMAudioPropsHz(&pMixBuf->Props),
                   PDMAudioPropsHz(pProps), pState->Rate.uDstInc));
    return rc;
}


/**
 * Initializes the write/blend state, setting up decoders and (if necessary)
 * resampling.
 *
 * @returns VBox status code.
 */
int AudioMixBufInitWriteState(PCAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, PCPDMAUDIOPCMPROPS pProps)
{
    AssertPtr(pMixBuf);
    AssertPtr(pState);
    AssertPtr(pProps);

    /*
     * Pick the encoding function first.
     */
    uint8_t const cbSample = PDMAudioPropsSampleSize(pProps);
    uint8_t const cSrcCh   = PDMAudioPropsChannels(pProps);
    uint8_t const cDstCh   = PDMAudioPropsChannels(&pMixBuf->Props);
    pState->cSrcChannels   = cSrcCh;
    pState->cDstChannels   = cDstCh;
    pState->cbSrcFrame     = PDMAudioPropsFrameSize(pProps);
    audioMixBufInitChannelMap(pState->aidxChannelMap, pProps, &pMixBuf->Props);

    if (PDMAudioPropsIsSigned(pProps))
    {
        /* Assign generic decoders first. */
        switch (cbSample)
        {
            case 1:
                pState->pfnDecode      = audioMixBufDecodeGenericS8;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericS8Blend;
                break;
            case 2:
                pState->pfnDecode      = audioMixBufDecodeGenericS16;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericS16Blend;
                break;
            case 4:
                pState->pfnDecode      = audioMixBufDecodeGenericS32;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericS32Blend;
                break;
            case 8:
                AssertReturn(pProps->fRaw, VERR_DISK_INVALID_FORMAT);
                pState->pfnDecode      = audioMixBufDecodeGenericRaw;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericRawBlend;
                break;
            default:
                AssertMsgFailedReturn(("%u bytes\n", cbSample), VERR_OUT_OF_RANGE);
        }

        /* Any specializations available? */
        switch (cDstCh)
        {
            case 1:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChS8;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChS8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChS16;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChS16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChS32;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChS32Blend;
                            break;
                        case 8:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChRaw;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChRawBlend;
                            break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChS8;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChS8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChS16;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChS16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChS32;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChS32Blend;
                            break;
                        case 8:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChRaw;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChRawBlend;
                            break;
                    }
                break;

            case 2:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChS8;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChS8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChS16;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChS16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChS32;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChS32Blend;
                            break;
                        case 8:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChRaw;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChRawBlend;
                            break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChS8;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChS8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChS16;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChS16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChS32;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChS32Blend;
                            break;
                        case 8:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChRaw;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChRawBlend;
                            break;
                    }
                break;
        }
    }
    else
    {
        /* Assign generic decoders first. */
        switch (cbSample)
        {
            case 1:
                pState->pfnDecode      = audioMixBufDecodeGenericU8;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericU8Blend;
                break;
            case 2:
                pState->pfnDecode      = audioMixBufDecodeGenericU16;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericU16Blend;
                break;
            case 4:
                pState->pfnDecode      = audioMixBufDecodeGenericU32;
                pState->pfnDecodeBlend = audioMixBufDecodeGenericU32Blend;
                break;
            default:
                AssertMsgFailedReturn(("%u bytes\n", cbSample), VERR_OUT_OF_RANGE);
        }

        /* Any specializations available? */
        switch (cDstCh)
        {
            case 1:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChU8;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChU8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChU16;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChU16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode1ChTo1ChU32;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo1ChU32Blend;
                            break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChU8;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChU8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChU16;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChU16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode2ChTo1ChU32;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo1ChU32Blend;
                            break;
                    }
                break;

            case 2:
                if (cSrcCh == 1)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChU8;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChU8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChU16;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChU16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode1ChTo2ChU32;
                            pState->pfnDecodeBlend = audioMixBufDecode1ChTo2ChU32Blend;
                            break;
                    }
                else if (cSrcCh == 2)
                    switch (cbSample)
                    {
                        case 1:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChU8;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChU8Blend;
                            break;
                        case 2:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChU16;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChU16Blend;
                            break;
                        case 4:
                            pState->pfnDecode      = audioMixBufDecode2ChTo2ChU32;
                            pState->pfnDecodeBlend = audioMixBufDecode2ChTo2ChU32Blend;
                            break;
                    }
                break;
        }
    }

    int rc = audioMixBufRateInit(&pState->Rate, PDMAudioPropsHz(pProps), PDMAudioPropsHz(&pMixBuf->Props), cDstCh);
    AUDMIXBUF_LOG(("%s: %RU32 Hz to %RU32 Hz => uDstInc=0x%'RX64\n", pMixBuf->pszName, PDMAudioPropsHz(pProps),
                   PDMAudioPropsHz(&pMixBuf->Props), pState->Rate.uDstInc));
    return rc;
}


/**
 * Worker for AudioMixBufPeek that handles the rate conversion case.
 */
DECL_NO_INLINE(static, void)
audioMixBufPeekResampling(PCAUDIOMIXBUF pMixBuf, uint32_t offSrcFrame, uint32_t cMaxSrcFrames, uint32_t *pcSrcFramesPeeked,
                          PAUDIOMIXBUFPEEKSTATE pState, void *pvDst, uint32_t cbDst, uint32_t *pcbDstPeeked)
{
    *pcSrcFramesPeeked = 0;
    *pcbDstPeeked      = 0;
    while (cMaxSrcFrames > 0 && cbDst >= pState->cbDstFrame)
    {
        /* Rate conversion into temporary buffer. */
        int32_t  ai32DstRate[1024];
        uint32_t cSrcFrames    = RT_MIN(pMixBuf->cFrames - offSrcFrame, cMaxSrcFrames);
        uint32_t cDstMaxFrames = RT_MIN(RT_ELEMENTS(ai32DstRate) / pState->cSrcChannels, cbDst / pState->cbDstFrame);
        uint32_t const cDstFrames = pState->Rate.pfnResample(ai32DstRate, cDstMaxFrames,
                                                             &pMixBuf->pi32Samples[offSrcFrame * pMixBuf->cChannels],
                                                             cSrcFrames, &cSrcFrames, &pState->Rate);
        *pcSrcFramesPeeked += cSrcFrames;
        cMaxSrcFrames      -= cSrcFrames;
        offSrcFrame         = (offSrcFrame + cSrcFrames) % pMixBuf->cFrames;

        /* Encode the converted frames. */
        uint32_t const cbDstEncoded = cDstFrames * pState->cbDstFrame;
        pState->pfnEncode(pvDst, ai32DstRate, cDstFrames, pState);
        *pcbDstPeeked      += cbDstEncoded;
        cbDst              -= cbDstEncoded;
        pvDst               = (uint8_t *)pvDst + cbDstEncoded;
    }
}


/**
 * Copies data out of the mixing buffer, converting it if needed, but leaves the
 * read offset untouched.
 *
 * @param   pMixBuf             The mixing buffer.
 * @param   offSrcFrame         The offset to start reading at relative to
 *                              current read position (offRead).  The caller has
 *                              made sure there is at least this number of
 *                              frames available in the buffer before calling.
 * @param   cMaxSrcFrames       Maximum number of frames to read.
 * @param   pcSrcFramesPeeked   Where to return the actual number of frames read
 *                              from the mixing buffer.
 * @param   pState              Output configuration & conversion state.
 * @param   pvDst               The destination buffer.
 * @param   cbDst               The size of the destination buffer in bytes.
 * @param   pcbDstPeeked        Where to put the actual number of bytes
 *                              returned.
 */
void AudioMixBufPeek(PCAUDIOMIXBUF pMixBuf, uint32_t offSrcFrame, uint32_t cMaxSrcFrames, uint32_t *pcSrcFramesPeeked,
                     PAUDIOMIXBUFPEEKSTATE pState, void *pvDst, uint32_t cbDst, uint32_t *pcbDstPeeked)
{
    /*
     * Check inputs.
     */
    AssertPtr(pMixBuf);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    AssertPtr(pState);
    AssertPtr(pState->pfnEncode);
    Assert(pState->cSrcChannels == PDMAudioPropsChannels(&pMixBuf->Props));
    Assert(cMaxSrcFrames > 0);
    Assert(cMaxSrcFrames <= pMixBuf->cFrames);
    Assert(offSrcFrame <= pMixBuf->cFrames);
    Assert(offSrcFrame + cMaxSrcFrames <= pMixBuf->cUsed);
    AssertPtr(pcSrcFramesPeeked);
    AssertPtr(pvDst);
    Assert(cbDst >= pState->cbDstFrame);
    AssertPtr(pcbDstPeeked);

    /*
     * Make start frame absolute.
     */
    offSrcFrame = (pMixBuf->offRead + offSrcFrame) % pMixBuf->cFrames;

    /*
     * Hopefully no sample rate conversion is necessary...
     */
    if (pState->Rate.fNoConversionNeeded)
    {
        /* Figure out how much we should convert. */
        cMaxSrcFrames      = RT_MIN(cMaxSrcFrames, cbDst / pState->cbDstFrame);
        *pcSrcFramesPeeked = cMaxSrcFrames;
        *pcbDstPeeked      = cMaxSrcFrames * pState->cbDstFrame;

        /* First chunk. */
        uint32_t const cSrcFrames1 = RT_MIN(pMixBuf->cFrames - offSrcFrame, cMaxSrcFrames);
        pState->pfnEncode(pvDst, &pMixBuf->pi32Samples[offSrcFrame * pMixBuf->cChannels], cSrcFrames1, pState);

        /* Another chunk from the start of the mixing buffer? */
        if (cMaxSrcFrames > cSrcFrames1)
            pState->pfnEncode((uint8_t *)pvDst + cSrcFrames1 * pState->cbDstFrame,
                              &pMixBuf->pi32Samples[0], cMaxSrcFrames - cSrcFrames1, pState);

        //Log9Func(("*pcbDstPeeked=%#x\n%32.*Rhxd\n", *pcbDstPeeked, *pcbDstPeeked, pvDst));
    }
    else
        audioMixBufPeekResampling(pMixBuf, offSrcFrame, cMaxSrcFrames, pcSrcFramesPeeked, pState, pvDst, cbDst, pcbDstPeeked);
}


/**
 * Worker for AudioMixBufWrite that handles the rate conversion case.
 */
DECL_NO_INLINE(static, void)
audioMixBufWriteResampling(PAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, const void *pvSrcBuf, uint32_t cbSrcBuf,
                           uint32_t offDstFrame, uint32_t cDstMaxFrames, uint32_t *pcDstFramesWritten)
{
    *pcDstFramesWritten = 0;
    while (cDstMaxFrames > 0 && cbSrcBuf >= pState->cbSrcFrame)
    {
        /* Decode into temporary buffer. */
        int32_t  ai32Decoded[1024];
        uint32_t cFramesDecoded = RT_MIN(RT_ELEMENTS(ai32Decoded) / pState->cDstChannels, cbSrcBuf / pState->cbSrcFrame);
        pState->pfnDecode(ai32Decoded, pvSrcBuf, cFramesDecoded, pState);
        cbSrcBuf -= cFramesDecoded * pState->cbSrcFrame;
        pvSrcBuf  = (uint8_t const *)pvSrcBuf + cFramesDecoded * pState->cbSrcFrame;

        /* Rate convert that into the mixer. */
        uint32_t iFrameDecoded = 0;
        while (iFrameDecoded < cFramesDecoded)
        {
            uint32_t cDstMaxFramesNow = RT_MIN(pMixBuf->cFrames - offDstFrame, cDstMaxFrames);
            uint32_t cSrcFrames       = cFramesDecoded - iFrameDecoded;
            uint32_t const cDstFrames = pState->Rate.pfnResample(&pMixBuf->pi32Samples[offDstFrame * pMixBuf->cChannels],
                                                                 cDstMaxFramesNow,
                                                                 &ai32Decoded[iFrameDecoded * pState->cDstChannels],
                                                                 cSrcFrames, &cSrcFrames, &pState->Rate);

            iFrameDecoded       += cSrcFrames;
            *pcDstFramesWritten += cDstFrames;
            offDstFrame          = (offDstFrame + cDstFrames) % pMixBuf->cFrames;
        }
    }

    /** @todo How to squeeze odd frames out of 22050 => 44100 conversion?   */
}


/**
 * Writes @a cbSrcBuf bytes to the mixer buffer starting at @a offDstFrame,
 * converting it as needed, leaving the write offset untouched.
 *
 * @param   pMixBuf             The mixing buffer.
 * @param   pState              Source configuration & conversion state.
 * @param   pvSrcBuf            The source frames.
 * @param   cbSrcBuf            Number of bytes of source frames.  This will be
 *                              convered in full.
 * @param   offDstFrame         Mixing buffer offset relative to the write
 *                              position.
 * @param   cDstMaxFrames       Max number of frames to write.
 * @param   pcDstFramesWritten  Where to return the number of frames actually
 *                              written.
 *
 * @note    Does not advance the write position, please call AudioMixBufCommit()
 *          to do that.
 */
void AudioMixBufWrite(PAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, const void *pvSrcBuf, uint32_t cbSrcBuf,
                      uint32_t offDstFrame, uint32_t cDstMaxFrames, uint32_t *pcDstFramesWritten)
{
    /*
     * Check inputs.
     */
    AssertPtr(pMixBuf);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    AssertPtr(pState);
    AssertPtr(pState->pfnDecode);
    AssertPtr(pState->pfnDecodeBlend);
    Assert(pState->cDstChannels == PDMAudioPropsChannels(&pMixBuf->Props));
    Assert(cDstMaxFrames > 0);
    Assert(cDstMaxFrames <= pMixBuf->cFrames - pMixBuf->cUsed);
    Assert(offDstFrame <= pMixBuf->cFrames);
    AssertPtr(pvSrcBuf);
    Assert(!(cbSrcBuf % pState->cbSrcFrame));
    AssertPtr(pcDstFramesWritten);

    /*
     * Make start frame absolute.
     */
    offDstFrame = (pMixBuf->offWrite + offDstFrame) % pMixBuf->cFrames;

    /*
     * Hopefully no sample rate conversion is necessary...
     */
    if (pState->Rate.fNoConversionNeeded)
    {
        /* Figure out how much we should convert. */
        Assert(cDstMaxFrames >= cbSrcBuf / pState->cbSrcFrame);
        cDstMaxFrames       = RT_MIN(cDstMaxFrames, cbSrcBuf / pState->cbSrcFrame);
        *pcDstFramesWritten = cDstMaxFrames;

        //Log10Func(("cbSrc=%#x\n%32.*Rhxd\n", pState->cbSrcFrame * cDstMaxFrames, pState->cbSrcFrame * cDstMaxFrames, pvSrcBuf));

        /* First chunk. */
        uint32_t const cDstFrames1 = RT_MIN(pMixBuf->cFrames - offDstFrame, cDstMaxFrames);
        pState->pfnDecode(&pMixBuf->pi32Samples[offDstFrame * pMixBuf->cChannels], pvSrcBuf, cDstFrames1, pState);
        //Log8Func(("offDstFrame=%#x cDstFrames1=%#x\n%32.*Rhxd\n", offDstFrame, cDstFrames1,
        //          cDstFrames1 * pMixBuf->cbFrame, &pMixBuf->pi32Samples[offDstFrame * pMixBuf->cChannels]));

        /* Another chunk from the start of the mixing buffer? */
        if (cDstMaxFrames > cDstFrames1)
        {
            pState->pfnDecode(&pMixBuf->pi32Samples[0], (uint8_t *)pvSrcBuf + cDstFrames1 * pState->cbSrcFrame,
                              cDstMaxFrames - cDstFrames1, pState);
            //Log8Func(("cDstFrames2=%#x\n%32.*Rhxd\n", cDstMaxFrames - cDstFrames1,
            //          (cDstMaxFrames - cDstFrames1) * pMixBuf->cbFrame, &pMixBuf->pi32Samples[0]));
        }
    }
    else
        audioMixBufWriteResampling(pMixBuf, pState, pvSrcBuf, cbSrcBuf, offDstFrame, cDstMaxFrames, pcDstFramesWritten);
}


/**
 * Worker for AudioMixBufBlend that handles the rate conversion case.
 */
DECL_NO_INLINE(static, void)
audioMixBufBlendResampling(PAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, const void *pvSrcBuf, uint32_t cbSrcBuf,
                           uint32_t offDstFrame, uint32_t cDstMaxFrames, uint32_t *pcDstFramesBlended)
{
    *pcDstFramesBlended = 0;
    while (cDstMaxFrames > 0 && cbSrcBuf >= pState->cbSrcFrame)
    {
        /* Decode into temporary buffer.  This then has the destination channel count. */
        int32_t  ai32Decoded[1024];
        uint32_t cFramesDecoded = RT_MIN(RT_ELEMENTS(ai32Decoded) / pState->cDstChannels, cbSrcBuf / pState->cbSrcFrame);
        pState->pfnDecode(ai32Decoded, pvSrcBuf, cFramesDecoded, pState);
        cbSrcBuf -= cFramesDecoded * pState->cbSrcFrame;
        pvSrcBuf  = (uint8_t const *)pvSrcBuf + cFramesDecoded * pState->cbSrcFrame;

        /* Rate convert that into another temporary buffer and then blend that into the mixer. */
        uint32_t iFrameDecoded = 0;
        while (iFrameDecoded < cFramesDecoded)
        {
            int32_t  ai32Rate[1024];
            uint32_t cDstMaxFramesNow = RT_MIN(RT_ELEMENTS(ai32Rate) / pState->cDstChannels, cDstMaxFrames);
            uint32_t cSrcFrames       = cFramesDecoded - iFrameDecoded;
            uint32_t const cDstFrames = pState->Rate.pfnResample(&ai32Rate[0], cDstMaxFramesNow,
                                                                 &ai32Decoded[iFrameDecoded * pState->cDstChannels],
                                                                 cSrcFrames, &cSrcFrames, &pState->Rate);

            /* First chunk.*/
            uint32_t const cDstFrames1 = RT_MIN(pMixBuf->cFrames - offDstFrame, cDstFrames);
            audioMixBufBlendBuffer(&pMixBuf->pi32Samples[offDstFrame * pMixBuf->cChannels],
                                   ai32Rate, cDstFrames1, pState->cDstChannels);

            /* Another chunk from the start of the mixing buffer? */
            if (cDstFrames > cDstFrames1)
                audioMixBufBlendBuffer(&pMixBuf->pi32Samples[0], &ai32Rate[cDstFrames1 * pState->cDstChannels],
                                       cDstFrames - cDstFrames1, pState->cDstChannels);

            /* Advance */
            iFrameDecoded       += cSrcFrames;
            *pcDstFramesBlended += cDstFrames;
            offDstFrame          = (offDstFrame + cDstFrames) % pMixBuf->cFrames;
        }
    }

    /** @todo How to squeeze odd frames out of 22050 => 44100 conversion?   */
}


/**
 * @todo not sure if 'blend' is the appropriate term here, but you know what
 *       we mean.
 */
void AudioMixBufBlend(PAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, const void *pvSrcBuf, uint32_t cbSrcBuf,
                      uint32_t offDstFrame, uint32_t cDstMaxFrames, uint32_t *pcDstFramesBlended)
{
    /*
     * Check inputs.
     */
    AssertPtr(pMixBuf);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    AssertPtr(pState);
    AssertPtr(pState->pfnDecode);
    AssertPtr(pState->pfnDecodeBlend);
    Assert(pState->cDstChannels == PDMAudioPropsChannels(&pMixBuf->Props));
    Assert(cDstMaxFrames > 0);
    Assert(cDstMaxFrames <= pMixBuf->cFrames - pMixBuf->cUsed);
    Assert(offDstFrame <= pMixBuf->cFrames);
    AssertPtr(pvSrcBuf);
    Assert(!(cbSrcBuf % pState->cbSrcFrame));
    AssertPtr(pcDstFramesBlended);

    /*
     * Make start frame absolute.
     */
    offDstFrame = (pMixBuf->offWrite + offDstFrame) % pMixBuf->cFrames;

    /*
     * Hopefully no sample rate conversion is necessary...
     */
    if (pState->Rate.fNoConversionNeeded)
    {
        /* Figure out how much we should convert. */
        Assert(cDstMaxFrames >= cbSrcBuf / pState->cbSrcFrame);
        cDstMaxFrames       = RT_MIN(cDstMaxFrames, cbSrcBuf / pState->cbSrcFrame);
        *pcDstFramesBlended = cDstMaxFrames;

        /* First chunk. */
        uint32_t const cDstFrames1 = RT_MIN(pMixBuf->cFrames - offDstFrame, cDstMaxFrames);
        pState->pfnDecodeBlend(&pMixBuf->pi32Samples[offDstFrame * pMixBuf->cChannels], pvSrcBuf, cDstFrames1, pState);

        /* Another chunk from the start of the mixing buffer? */
        if (cDstMaxFrames > cDstFrames1)
            pState->pfnDecodeBlend(&pMixBuf->pi32Samples[0], (uint8_t *)pvSrcBuf + cDstFrames1 * pState->cbSrcFrame,
                                   cDstMaxFrames - cDstFrames1, pState);
    }
    else
        audioMixBufBlendResampling(pMixBuf, pState, pvSrcBuf, cbSrcBuf, offDstFrame, cDstMaxFrames, pcDstFramesBlended);
}


/**
 * Writes @a cFrames of silence at @a offFrame relative to current write pos.
 *
 * This will also adjust the resampling state.
 *
 * @param   pMixBuf     The mixing buffer.
 * @param   pState      The write state.
 * @param   offFrame    Where to start writing silence relative to the current
 *                      write position.
 * @param   cFrames     Number of frames of silence.
 * @sa      AudioMixBufWrite
 *
 * @note    Does not advance the write position, please call AudioMixBufCommit()
 *          to do that.
 */
void AudioMixBufSilence(PAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, uint32_t offFrame, uint32_t cFrames)
{
    /*
     * Check inputs.
     */
    AssertPtr(pMixBuf);
    Assert(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);
    AssertPtr(pState);
    AssertPtr(pState->pfnDecode);
    AssertPtr(pState->pfnDecodeBlend);
    Assert(pState->cDstChannels == PDMAudioPropsChannels(&pMixBuf->Props));
    Assert(cFrames > 0);
#ifdef VBOX_STRICT
    uint32_t const cMixBufFree = pMixBuf->cFrames - pMixBuf->cUsed;
#endif
    Assert(cFrames <= cMixBufFree);
    Assert(offFrame < cMixBufFree);
    Assert(offFrame + cFrames <= cMixBufFree);

    /*
     * Make start frame absolute.
     */
    offFrame = (pMixBuf->offWrite + offFrame) % pMixBuf->cFrames;

    /*
     * First chunk.
     */
    uint32_t const cFramesChunk1 = RT_MIN(pMixBuf->cFrames - offFrame, cFrames);
    RT_BZERO(&pMixBuf->pi32Samples[offFrame * pMixBuf->cChannels], cFramesChunk1 * pMixBuf->cbFrame);

    /*
     * Second chunk, if needed.
     */
    if (cFrames > cFramesChunk1)
    {
        cFrames -= cFramesChunk1;
        AssertStmt(cFrames <= pMixBuf->cFrames, cFrames = pMixBuf->cFrames);
        RT_BZERO(&pMixBuf->pi32Samples[0], cFrames * pMixBuf->cbFrame);
    }

    /*
     * Reset the resampling state.
     */
    audioMixBufRateReset(&pState->Rate);
}


/**
 * Records a blending gap (silence) of @a cFrames.
 *
 * This is used to adjust or reset the resampling state so we start from a
 * silence state the next time we need to blend or write using @a pState.
 *
 * @param   pMixBuf     The mixing buffer.
 * @param   pState      The write state.
 * @param   cFrames     Number of frames of silence.
 * @sa      AudioMixBufSilence
 */
void AudioMixBufBlendGap(PAUDIOMIXBUF pMixBuf, PAUDIOMIXBUFWRITESTATE pState, uint32_t cFrames)
{
    /*
     * For now we'll just reset the resampling state regardless of how many
     * frames of silence there is.
     */
    audioMixBufRateReset(&pState->Rate);
    RT_NOREF(pMixBuf, cFrames);
}


/**
 * Advances the read position of the buffer.
 *
 * For use after done peeking with AudioMixBufPeek().
 *
 * @param   pMixBuf     The mixing buffer.
 * @param   cFrames     Number of frames to advance.
 * @sa      AudioMixBufCommit
 */
void AudioMixBufAdvance(PAUDIOMIXBUF pMixBuf, uint32_t cFrames)
{
    AssertPtrReturnVoid(pMixBuf);
    AssertReturnVoid(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);

    AssertStmt(cFrames <= pMixBuf->cUsed, cFrames = pMixBuf->cUsed);
    pMixBuf->cUsed   -= cFrames;
    pMixBuf->offRead  = (pMixBuf->offRead + cFrames) % pMixBuf->cFrames;
    LogFlowFunc(("%s: Advanced %u frames: offRead=%u cUsed=%u\n", pMixBuf->pszName, cFrames, pMixBuf->offRead, pMixBuf->cUsed));
}


/**
 * Worker for audioMixAdjustVolume that adjust one contiguous chunk.
 */
static void audioMixAdjustVolumeWorker(PAUDIOMIXBUF pMixBuf, uint32_t off, uint32_t cFrames)
{
    int32_t       *pi32Samples = &pMixBuf->pi32Samples[off * pMixBuf->cChannels];
    switch (pMixBuf->cChannels)
    {
        case 1:
        {
            uint32_t const uFactorCh0 = pMixBuf->Volume.auChannels[0];
            while (cFrames-- > 0)
            {
                *pi32Samples = (int32_t)(ASMMult2xS32RetS64(*pi32Samples, uFactorCh0) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples++;
            }
            break;
        }

        case 2:
        {
            uint32_t const uFactorCh0 = pMixBuf->Volume.auChannels[0];
            uint32_t const uFactorCh1 = pMixBuf->Volume.auChannels[1];
            while (cFrames-- > 0)
            {
                pi32Samples[0] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[0], uFactorCh0) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[1] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[1], uFactorCh1) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples += 2;
            }
            break;
        }

        case 3:
        {
            uint32_t const uFactorCh0 = pMixBuf->Volume.auChannels[0];
            uint32_t const uFactorCh1 = pMixBuf->Volume.auChannels[1];
            uint32_t const uFactorCh2 = pMixBuf->Volume.auChannels[2];
            while (cFrames-- > 0)
            {
                pi32Samples[0] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[0], uFactorCh0) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[1] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[1], uFactorCh1) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[2] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[2], uFactorCh2) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples += 3;
            }
            break;
        }

        case 4:
        {
            uint32_t const uFactorCh0 = pMixBuf->Volume.auChannels[0];
            uint32_t const uFactorCh1 = pMixBuf->Volume.auChannels[1];
            uint32_t const uFactorCh2 = pMixBuf->Volume.auChannels[2];
            uint32_t const uFactorCh3 = pMixBuf->Volume.auChannels[3];
            while (cFrames-- > 0)
            {
                pi32Samples[0] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[0], uFactorCh0) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[1] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[1], uFactorCh1) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[2] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[2], uFactorCh2) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[3] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[3], uFactorCh3) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples += 4;
            }
            break;
        }

        case 5:
        {
            uint32_t const uFactorCh0 = pMixBuf->Volume.auChannels[0];
            uint32_t const uFactorCh1 = pMixBuf->Volume.auChannels[1];
            uint32_t const uFactorCh2 = pMixBuf->Volume.auChannels[2];
            uint32_t const uFactorCh3 = pMixBuf->Volume.auChannels[3];
            uint32_t const uFactorCh4 = pMixBuf->Volume.auChannels[4];
            while (cFrames-- > 0)
            {
                pi32Samples[0] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[0], uFactorCh0) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[1] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[1], uFactorCh1) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[2] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[2], uFactorCh2) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[3] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[3], uFactorCh3) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[4] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[4], uFactorCh4) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples += 5;
            }
            break;
        }

        case 6:
        {
            uint32_t const uFactorCh0 = pMixBuf->Volume.auChannels[0];
            uint32_t const uFactorCh1 = pMixBuf->Volume.auChannels[1];
            uint32_t const uFactorCh2 = pMixBuf->Volume.auChannels[2];
            uint32_t const uFactorCh3 = pMixBuf->Volume.auChannels[3];
            uint32_t const uFactorCh4 = pMixBuf->Volume.auChannels[4];
            uint32_t const uFactorCh5 = pMixBuf->Volume.auChannels[5];
            while (cFrames-- > 0)
            {
                pi32Samples[0] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[0], uFactorCh0) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[1] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[1], uFactorCh1) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[2] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[2], uFactorCh2) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[3] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[3], uFactorCh3) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[4] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[4], uFactorCh4) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples[5] = (int32_t)(ASMMult2xS32RetS64(pi32Samples[5], uFactorCh5) >> AUDIOMIXBUF_VOL_SHIFT);
                pi32Samples += 6;
            }
            break;
        }

        default:
            while (cFrames-- > 0)
                for (uint32_t iCh = 0; iCh < pMixBuf->cChannels; iCh++, pi32Samples++)
                    *pi32Samples = ASMMult2xS32RetS64(*pi32Samples, pMixBuf->Volume.auChannels[iCh]) >> AUDIOMIXBUF_VOL_SHIFT;
            break;
    }
}


/**
 * Does volume adjustments for the given stretch of the buffer.
 *
 * @param   pMixBuf     The mixing buffer.
 * @param   offFirst    Where to start (validated).
 * @param   cFrames     How many frames (validated).
 */
static void audioMixAdjustVolume(PAUDIOMIXBUF pMixBuf, uint32_t offFirst, uint32_t cFrames)
{
    /* Caller has already validated these, so we don't need to repeat that in non-strict builds. */
    Assert(offFirst < pMixBuf->cFrames);
    Assert(cFrames <= pMixBuf->cFrames);

    /*
     * Muted?
     */
    if (pMixBuf->Volume.fMuted)
    {
        /* first chunk */
        uint32_t const cFramesChunk1 = RT_MIN(pMixBuf->cFrames - offFirst, cFrames);
        RT_BZERO(&pMixBuf->pi32Samples[offFirst * pMixBuf->cChannels], pMixBuf->cbFrame * cFramesChunk1);

        /* second chunk */
        if (cFramesChunk1 < cFrames)
            RT_BZERO(&pMixBuf->pi32Samples[0], pMixBuf->cbFrame * (cFrames - cFramesChunk1));
    }
    /*
     * Less than max volume?
     */
    else if (!pMixBuf->Volume.fAllMax)
    {
        /* first chunk */
        uint32_t const cFramesChunk1 = RT_MIN(pMixBuf->cFrames - offFirst, cFrames);
        audioMixAdjustVolumeWorker(pMixBuf, offFirst, cFramesChunk1);

        /* second chunk */
        if (cFramesChunk1 < cFrames)
            audioMixAdjustVolumeWorker(pMixBuf, 0, cFrames - cFramesChunk1);
    }
}


/**
 * Adjust for volume settings and advances the write position of the buffer.
 *
 * For use after done peeking with AudioMixBufWrite(), AudioMixBufSilence(),
 * AudioMixBufBlend() and AudioMixBufBlendGap().
 *
 * @param   pMixBuf     The mixing buffer.
 * @param   cFrames     Number of frames to advance.
 * @sa      AudioMixBufAdvance, AudioMixBufSetVolume
 */
void AudioMixBufCommit(PAUDIOMIXBUF pMixBuf, uint32_t cFrames)
{
    AssertPtrReturnVoid(pMixBuf);
    AssertReturnVoid(pMixBuf->uMagic == AUDIOMIXBUF_MAGIC);

    AssertStmt(cFrames <= pMixBuf->cFrames - pMixBuf->cUsed, cFrames = pMixBuf->cFrames - pMixBuf->cUsed);

    audioMixAdjustVolume(pMixBuf, pMixBuf->offWrite, cFrames);

    pMixBuf->cUsed   += cFrames;
    pMixBuf->offWrite = (pMixBuf->offWrite + cFrames) % pMixBuf->cFrames;
    LogFlowFunc(("%s: Advanced %u frames: offWrite=%u cUsed=%u\n", pMixBuf->pszName, cFrames, pMixBuf->offWrite, pMixBuf->cUsed));
}


/**
 * Sets the volume.
 *
 * The volume adjustments are applied by AudioMixBufCommit().
 *
 * @param   pMixBuf     Mixing buffer to set volume for.
 * @param   pVol        Pointer to volume structure to set.
 */
void AudioMixBufSetVolume(PAUDIOMIXBUF pMixBuf, PCPDMAUDIOVOLUME pVol)
{
    AssertPtrReturnVoid(pMixBuf);
    AssertPtrReturnVoid(pVol);

    LogFlowFunc(("%s: fMuted=%RTbool auChannels=%.*Rhxs\n",
                 pMixBuf->pszName, pVol->fMuted, sizeof(pVol->auChannels), pVol->auChannels));

    /*
     * Convert PDM audio volume to the internal format.
     */
    if (!pVol->fMuted)
    {
        pMixBuf->Volume.fMuted  = false;

        AssertCompileSize(pVol->auChannels[0], sizeof(uint8_t));
        for (uintptr_t i = 0; i < pMixBuf->cChannels; i++)
            pMixBuf->Volume.auChannels[i] = s_aVolumeConv[pVol->auChannels[i]] * (AUDIOMIXBUF_VOL_0DB >> 16);

        pMixBuf->Volume.fAllMax = true;
        for (uintptr_t i = 0; i < pMixBuf->cChannels; i++)
            if (pMixBuf->Volume.auChannels[i] != AUDIOMIXBUF_VOL_0DB)
            {
                pMixBuf->Volume.fAllMax = false;
                break;
            }
    }
    else
    {
        pMixBuf->Volume.fMuted  = true;
        pMixBuf->Volume.fAllMax = false;
        for (uintptr_t i = 0; i < RT_ELEMENTS(pMixBuf->Volume.auChannels); i++)
            pMixBuf->Volume.auChannels[i] = 0;
    }
}