oxideav-ac4 0.0.7

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

use crate::acpl::{sb_to_pb, AcplHuffParam, AcplQuantMode};
use crate::qmf::NUM_QMF_SUBBANDS;

// =====================================================================
// §5.7.7.7 Tables 203 / 204 / 205 / 206 — ALPHA / BETA dequantisation
// =====================================================================

/// `alpha_dq[alpha_q]` for fine quantisation per Table 203.
/// Length 33 (`alpha_q ∈ 0..=32`).
#[rustfmt::skip]
pub const ALPHA_DQ_FINE: [f32; 33] = [
    -2.000000, -1.809375, -1.637500, -1.484375, -1.350000, -1.234375,
    -1.137500, -1.059375, -1.000000, -0.940625, -0.862500, -0.765625,
    -0.650000, -0.515625, -0.362500, -0.190625,  0.000000,  0.190625,
     0.362500,  0.515625,  0.650000,  0.765625,  0.862500,  0.940625,
     1.000000,  1.059375,  1.137500,  1.234375,  1.350000,  1.484375,
     1.637500,  1.809375,  2.000000,
];

/// `ibeta[alpha_q]` for fine quantisation per Table 203 (column 2).
/// Used to pick a column out of `BETA_DQ_FINE` for the matching beta
/// dequant.
#[rustfmt::skip]
pub const IBETA_FINE: [u8; 33] = [
    0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5,
    6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0,
];

/// `alpha_dq[alpha_q]` for coarse quantisation per Table 205. Length 17.
#[rustfmt::skip]
pub const ALPHA_DQ_COARSE: [f32; 17] = [
    -2.000000, -1.637500, -1.350000, -1.137500, -1.000000, -0.862500,
    -0.650000, -0.362500,  0.000000,  0.362500,  0.650000,  0.862500,
     1.000000,  1.137500,  1.350000,  1.637500,  2.000000,
];

/// `ibeta[alpha_q]` for coarse quantisation per Table 205 (column 2).
#[rustfmt::skip]
pub const IBETA_COARSE: [u8; 17] = [
    0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0,
];

/// `beta_dq[beta_q][ibeta]` for fine quantisation per Table 204.
/// Indexed by `[beta_q][ibeta]` with `beta_q ∈ 0..=8`, `ibeta ∈ 0..=8`.
/// The spec table is signed via the `beta_q` ↔ huffman delta convention
/// (positive index = positive coefficient); here the table only carries
/// the magnitude — the caller flips the sign when `beta_q < 0`.
#[rustfmt::skip]
pub const BETA_DQ_FINE: [[f32; 9]; 9] = [
    // beta_q = 0
    [0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000],
    // beta_q = 1
    [0.2375000, 0.2035449, 0.1729297, 0.1456543, 0.1217188, 0.1011230, 0.0838672, 0.0699512, 0.0593750],
    // beta_q = 2
    [0.5500000, 0.4713672, 0.4004688, 0.3373047, 0.2818750, 0.2341797, 0.1942188, 0.1619922, 0.1375000],
    // beta_q = 3
    [0.9375000, 0.8034668, 0.6826172, 0.5749512, 0.4804688, 0.3991699, 0.3310547, 0.2761230, 0.2343750],
    // beta_q = 4
    [1.4000000, 1.1998440, 1.0193750, 0.8585938, 0.7175000, 0.5960938, 0.4943750, 0.4123438, 0.3500000],
    // beta_q = 5
    [1.9375000, 1.6604980, 1.4107420, 1.1882319, 0.9929688, 0.8249512, 0.6841797, 0.5706543, 0.4843750],
    // beta_q = 6
    [2.5500000, 2.1854300, 1.8567190, 1.5638670, 1.3068750, 1.0857420, 0.9004688, 0.7510547, 0.6375000],
    // beta_q = 7
    [3.2375000, 2.7746389, 2.3573050, 1.9854980, 1.6592190, 1.3784670, 1.1432420, 0.9535449, 0.8093750],
    // beta_q = 8
    [4.0000000, 3.4281249, 2.9124999, 2.4531250, 2.0500000, 1.7031250, 1.4125000, 1.1781250, 1.0000000],
];

/// `beta_dq[beta_q][ibeta]` for coarse quantisation per Table 206.
/// Indexed by `[beta_q][ibeta]` with `beta_q ∈ 0..=4`, `ibeta ∈ 0..=4`.
#[rustfmt::skip]
pub const BETA_DQ_COARSE: [[f32; 5]; 5] = [
    // beta_q = 0
    [0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000],
    // beta_q = 1
    [0.5500000, 0.4004688, 0.2818750, 0.1942188, 0.1375000],
    // beta_q = 2
    [1.4000000, 1.0193750, 0.7175000, 0.4943750, 0.3500000],
    // beta_q = 3
    [2.5500000, 1.8567190, 1.3068750, 0.9004688, 0.6375000],
    // beta_q = 4
    [4.0000000, 2.9124999, 2.0500000, 1.4125000, 1.0000000],
];

/// `beta3` dequantisation delta per Table 207. Multiply the recovered
/// `beta3_q` value by this delta to get `acpl_beta_3_dq`.
pub fn beta3_delta(qm: AcplQuantMode) -> f32 {
    match qm {
        AcplQuantMode::Fine => 0.125,
        AcplQuantMode::Coarse => 0.25,
    }
}

/// `gamma` dequantisation delta per Table 208 (`g1..g6`). Both modes
/// expressed as the spec's exact `n / 16384` ratios.
pub fn gamma_delta(qm: AcplQuantMode) -> f32 {
    match qm {
        AcplQuantMode::Fine => 1638.0 / 16384.0,
        AcplQuantMode::Coarse => 3276.0 / 16384.0,
    }
}

/// Look up `(alpha_dq, ibeta)` from a recovered alpha quantised index
/// per Table 203 (Fine) or Table 205 (Coarse).
///
/// The huffman pipeline already produces a *signed* `alpha_q` in the
/// range `-N/2 ..= +N/2` (where `N = ALPHA_DQ_*.len() - 1`) thanks to
/// the F0/DF/DT codebooks' `cb_off`. The dequant tables are addressed
/// by the *unsigned* lane index `alpha_q + cb_off`, where `cb_off =
/// N/2`. We re-add it here.
pub fn dequantize_alpha_index(qm: AcplQuantMode, alpha_q: i32) -> (f32, u8) {
    match qm {
        AcplQuantMode::Fine => {
            let lane = (alpha_q + 16).clamp(0, 32) as usize;
            (ALPHA_DQ_FINE[lane], IBETA_FINE[lane])
        }
        AcplQuantMode::Coarse => {
            let lane = (alpha_q + 8).clamp(0, 16) as usize;
            (ALPHA_DQ_COARSE[lane], IBETA_COARSE[lane])
        }
    }
}

/// Look up the dequantised beta from `beta_q` and the matching
/// `ibeta` produced by [`dequantize_alpha_index`].
///
/// Per Table 204 / 206, beta values are unsigned magnitudes — the
/// recovered `beta_q` carries the sign, so we flip the lookup once at
/// the end.
pub fn dequantize_beta_index(qm: AcplQuantMode, beta_q: i32, ibeta: u8) -> f32 {
    let mag = beta_q.unsigned_abs() as usize;
    let val = match qm {
        AcplQuantMode::Fine => {
            let row = mag.min(8);
            let col = (ibeta as usize).min(8);
            BETA_DQ_FINE[row][col]
        }
        AcplQuantMode::Coarse => {
            let row = mag.min(4);
            let col = (ibeta as usize).min(4);
            BETA_DQ_COARSE[row][col]
        }
    };
    if beta_q < 0 {
        -val
    } else {
        val
    }
}

// =====================================================================
// §5.7.7.7 Pseudocode 121 — differential decoding
// =====================================================================

/// Differential decoding state per parameter-set type
/// (`acpl_<SET>_q_prev`).
///
/// The spec mandates an initial all-zero `q_prev` for the first AC-4
/// frame, and carries the last `q[ps]` row forward across frames to
/// seed the next `DIFF_TIME` decode.
#[derive(Debug, Clone)]
pub struct AcplDiffState {
    /// Carries `acpl_<SET>_q[num_pset-1]` across calls. Length =
    /// `acpl_num_param_bands` once primed; the first call sees an
    /// empty vector and fills it.
    pub q_prev: Vec<i32>,
}

impl AcplDiffState {
    pub fn new() -> Self {
        Self { q_prev: Vec::new() }
    }

    /// Replace the running `q_prev` row.
    pub fn carry(&mut self, row: &[i32]) {
        self.q_prev.clear();
        self.q_prev.extend_from_slice(row);
    }
}

impl Default for AcplDiffState {
    fn default() -> Self {
        Self::new()
    }
}

/// Apply `Pseudocode 121` differential decoding to the per-parameter-set
/// huffman-decoded deltas to recover the absolute `acpl_<SET>_q` array.
///
/// `params[ps]` is one parameter set's worth of huffman output (with
/// either `DIFF_FREQ` or `DIFF_TIME` direction); `num_bands` is
/// `acpl_num_param_bands`. The returned matrix is `num_pset`
/// rows × `num_bands` columns. The state `q_prev` is updated to the
/// last decoded row for forward chaining.
pub fn differential_decode(
    params: &[AcplHuffParam],
    num_bands: u32,
    state: &mut AcplDiffState,
) -> Vec<Vec<i32>> {
    let nb = num_bands as usize;
    if state.q_prev.len() != nb {
        state.q_prev = vec![0; nb];
    }
    let mut out = Vec::with_capacity(params.len());
    for p in params {
        // Per the spec the huffman delta vector should be exactly
        // `num_bands` long (per `acpl_data_*` framing); be defensive
        // for unusual lengths by taking what we can and zero-padding.
        let mut row = vec![0i32; nb];
        if !p.direction_time {
            // DIFF_FREQ — first value is absolute, rest accumulate.
            if !p.values.is_empty() {
                row[0] = p.values[0];
                for i in 1..nb {
                    let d = p.values.get(i).copied().unwrap_or(0);
                    row[i] = row[i - 1] + d;
                }
            }
        } else {
            // DIFF_TIME — each band reuses q_prev[i] + delta.
            for i in 0..nb {
                let d = p.values.get(i).copied().unwrap_or(0);
                row[i] = state.q_prev[i] + d;
            }
        }
        state.q_prev = row.clone();
        out.push(row);
    }
    out
}

// =====================================================================
// §5.7.7.7 Helpers — turn `acpl_<SET>_q` into dequantised f32 arrays
// =====================================================================

/// Dequantise one (or two) parameter sets' worth of (alpha, beta)
/// indices into their floating-point counterparts. The returned matrix
/// shape mirrors the input: `pset × num_bands`.
///
/// The shared `ibeta` linkage between Tables 203/204 (Fine) and
/// Tables 205/206 (Coarse) is honoured per the spec — beta is looked up
/// with the alpha column's `ibeta`.
pub fn dequantize_alpha_beta(
    alpha_q: &[Vec<i32>],
    beta_q: &[Vec<i32>],
    qm: AcplQuantMode,
) -> (Vec<Vec<f32>>, Vec<Vec<f32>>) {
    debug_assert_eq!(alpha_q.len(), beta_q.len());
    let mut alpha_dq = Vec::with_capacity(alpha_q.len());
    let mut beta_dq = Vec::with_capacity(beta_q.len());
    for ps in 0..alpha_q.len() {
        let n = alpha_q[ps].len();
        let mut a_row = vec![0.0f32; n];
        let mut b_row = vec![0.0f32; n];
        for i in 0..n {
            let (a_val, ibeta) = dequantize_alpha_index(qm, alpha_q[ps][i]);
            a_row[i] = a_val;
            let bq = beta_q[ps].get(i).copied().unwrap_or(0);
            b_row[i] = dequantize_beta_index(qm, bq, ibeta);
        }
        alpha_dq.push(a_row);
        beta_dq.push(b_row);
    }
    (alpha_dq, beta_dq)
}

/// Dequantise `beta3_q` to `acpl_beta_3_dq` per Table 207.
pub fn dequantize_beta3(beta3_q: &[Vec<i32>], qm: AcplQuantMode) -> Vec<Vec<f32>> {
    let delta = beta3_delta(qm);
    beta3_q
        .iter()
        .map(|row| row.iter().map(|&q| (q as f32) * delta).collect())
        .collect()
}

/// Dequantise `gamma_q` to `g_dq` per Table 208.
pub fn dequantize_gamma(gamma_q: &[Vec<i32>], qm: AcplQuantMode) -> Vec<Vec<f32>> {
    let delta = gamma_delta(qm);
    gamma_q
        .iter()
        .map(|row| row.iter().map(|&q| (q as f32) * delta).collect())
        .collect()
}

// =====================================================================
// §5.7.7.3 Pseudocode 109 — interpolate()
// =====================================================================

/// One frame's worth of dequantised parameter values across (pset, sb).
///
/// Indexed `[ps][sb]` after the spec's `interpolate()` rewrite (which
/// folds the `sb_to_pb()` lookup into the storage). The previous
/// frame's last-row values are carried in `prev` (length
/// `num_qmf_subbands`).
#[derive(Debug, Clone)]
pub struct InterpInputs<'a> {
    /// `acpl_param_dq[ps][sb]` — already expanded over `sb_to_pb()`.
    /// Outer length = `num_pset`, inner = `num_qmf_subbands`.
    pub by_pset: &'a [Vec<f32>],
    /// `acpl_param_prev[sb]` from the previous frame's last set.
    pub prev: &'a [f32],
}

/// `interpolate(acpl_param, num_pset, sb, ts)` per §5.7.7.3
/// Pseudocode 109.
///
/// `num_ts` is `num_qmf_timeslots`. `interpolation_type == 0` means
/// smooth, `== 1` means steep (driven by `acpl_param_timeslot[]` —
/// `param_timeslots` here).
#[allow(clippy::too_many_arguments)]
pub fn interpolate(
    inputs: &InterpInputs<'_>,
    num_pset: u32,
    sb: u32,
    ts: u32,
    num_ts: u32,
    interp_steep: bool,
    param_timeslots: &[u8],
) -> f32 {
    let sb_idx = sb as usize;
    if !interp_steep {
        // Smooth interpolation
        if num_pset == 1 {
            let p = inputs.by_pset[0].get(sb_idx).copied().unwrap_or(0.0);
            let prev = inputs.prev.get(sb_idx).copied().unwrap_or(0.0);
            let delta = p - prev;
            prev + ((ts + 1) as f32) * delta / (num_ts as f32)
        } else {
            // 2 parameter sets
            let ts_2 = num_ts / 2;
            let p0 = inputs.by_pset[0].get(sb_idx).copied().unwrap_or(0.0);
            let p1 = inputs.by_pset[1].get(sb_idx).copied().unwrap_or(0.0);
            if ts < ts_2 {
                let prev = inputs.prev.get(sb_idx).copied().unwrap_or(0.0);
                let delta = p0 - prev;
                prev + ((ts + 1) as f32) * delta / (ts_2 as f32)
            } else {
                let delta = p1 - p0;
                p0 + ((ts - ts_2 + 1) as f32) * delta / ((num_ts - ts_2) as f32)
            }
        }
    } else {
        // Steep interpolation
        if num_pset == 1 {
            let bound = param_timeslots.first().copied().unwrap_or(0) as u32;
            if ts < bound {
                inputs.prev.get(sb_idx).copied().unwrap_or(0.0)
            } else {
                inputs.by_pset[0].get(sb_idx).copied().unwrap_or(0.0)
            }
        } else {
            let bound0 = param_timeslots.first().copied().unwrap_or(0) as u32;
            let bound1 = param_timeslots.get(1).copied().unwrap_or(0) as u32;
            if ts < bound0 {
                inputs.prev.get(sb_idx).copied().unwrap_or(0.0)
            } else if ts < bound1 {
                inputs.by_pset[0].get(sb_idx).copied().unwrap_or(0.0)
            } else {
                inputs.by_pset[1].get(sb_idx).copied().unwrap_or(0.0)
            }
        }
    }
}

/// Expand a per-parameter-band array `pb_vals[pset][pb]` to a per-QMF-
/// subband array `sb_vals[pset][sb]` via `sb_to_pb()` (§5.7.7.2 Table
/// 197). This is the standard input to [`interpolate`]'s `by_pset` field.
pub fn expand_pb_to_sb(pb_vals: &[Vec<f32>], num_param_bands: u32) -> Vec<Vec<f32>> {
    pb_vals
        .iter()
        .map(|row| {
            let mut out = vec![0.0f32; NUM_QMF_SUBBANDS];
            for sb in 0..NUM_QMF_SUBBANDS {
                let pb = sb_to_pb(sb as u32, num_param_bands) as usize;
                out[sb] = row.get(pb).copied().unwrap_or(0.0);
            }
            out
        })
        .collect()
}

/// Update the `prev[sb]` array per §5.7.7.3 Pseudocode 110, using the
/// last parameter set in the current frame.
pub fn update_param_prev(prev: &mut Vec<f32>, last_set_sb: &[f32]) {
    prev.clear();
    prev.extend_from_slice(last_set_sb);
    // Pad / truncate to NUM_QMF_SUBBANDS so the next frame sees a
    // canonically-shaped state.
    prev.resize(NUM_QMF_SUBBANDS, 0.0);
}

// =====================================================================
// §5.7.7.4.2 Decorrelator — Tables 198 / 199 / 200 / 201 + Pseudocode
// 111
// =====================================================================

/// Per-subband region delay (Table 198).
pub fn region_delay(sb: u32) -> usize {
    match sb {
        0..=6 => 7,
        7..=22 => 10,
        _ => 12,
    }
}

/// Per-subband filter length (Table 198).
pub fn region_filter_length(sb: u32) -> usize {
    match sb {
        0..=6 => 7,
        7..=22 => 4,
        _ => 2,
    }
}

/// Decorrelator selector for the three parallel modules.
#[derive(Debug, Clone, Copy)]
pub enum DecorrelatorId {
    D0,
    D1,
    D2,
}

/// Region k0 coefficients (Table 199), indexed `[D][i]` with i in
/// `0..=7`. `D0` = column 0, `D1` = column 1, `D2` = column 2.
#[rustfmt::skip]
pub const A_K0: [[f64; 8]; 3] = [
    // D0
    [1.0000, 0.5306, -0.4533, -0.6248,  0.0424,  0.4237,  0.4311,  0.1688],
    // D1
    [1.0000, -0.4178, 0.1082, -0.2368, -0.1014, -0.1052, -0.3528,  0.4665],
    // D2
    [1.0000, 0.4007,  0.4747,  0.2611, -0.1211, -0.4248, -0.2989, -0.1932],
];

/// Region k1 coefficients (Table 200), indexed `[D][i]` with i in
/// `0..=4`.
#[rustfmt::skip]
pub const A_K1: [[f64; 5]; 3] = [
    [1.0000,  0.5561, -0.3039, -0.5024, -0.1850],
    [1.0000,  0.0425,  0.3235, -0.1556,  0.4958],
    [1.0000, -0.4361,  0.0345,  0.5215, -0.4178],
];

/// Region k2 coefficients (Table 201), indexed `[D][i]` with i in
/// `0..=2`.
#[rustfmt::skip]
pub const A_K2: [[f64; 3]; 3] = [
    [1.0000,  0.5773,  0.3321],
    [1.0000,  0.2327, -0.3901],
    [1.0000, -0.6057,  0.3804],
];

/// Look up the `a[i]` coefficient vector for the requested decorrelator
/// `D` and subband region (k0 / k1 / k2). Returned slice length matches
/// `region_filter_length(sb) + 1`.
pub fn region_coeffs(d: DecorrelatorId, sb: u32) -> &'static [f64] {
    let col = match d {
        DecorrelatorId::D0 => 0,
        DecorrelatorId::D1 => 1,
        DecorrelatorId::D2 => 2,
    };
    match sb {
        0..=6 => &A_K0[col][..],
        7..=22 => &A_K1[col][..],
        _ => &A_K2[col][..],
    }
}

/// Per-channel + per-decorrelator running state for
/// [`InputSignalModifier`]. Carries the tail of `x[ts-i-delay][sb]`
/// (input history) and `y[ts-i][sb]` (output history) needed by
/// Pseudocode 111. Sized to the maximum delay+filterLength = 12 + 2 =
/// 14 in the worst region; we allocate 24 per subband for slack.
#[derive(Debug, Clone)]
pub struct InputSignalModifier {
    /// Decorrelator id (D0/D1/D2).
    pub which: DecorrelatorId,
    /// `x_hist[sb][k]` = previous input sample at offset `k` slots in
    /// the past for QMF subband `sb`. Complex (re, im) pair.
    pub x_hist: Vec<Vec<(f32, f32)>>,
    /// `y_hist[sb][k]` = previous output sample at offset `k` slots in
    /// the past.
    pub y_hist: Vec<Vec<(f32, f32)>>,
}

impl InputSignalModifier {
    pub fn new(which: DecorrelatorId) -> Self {
        let depth = 24usize;
        Self {
            which,
            x_hist: vec![vec![(0.0, 0.0); depth]; NUM_QMF_SUBBANDS],
            y_hist: vec![vec![(0.0, 0.0); depth]; NUM_QMF_SUBBANDS],
        }
    }

    /// Reset the running history (e.g. on substream restart).
    pub fn reset(&mut self) {
        for h in &mut self.x_hist {
            for v in h {
                *v = (0.0, 0.0);
            }
        }
        for h in &mut self.y_hist {
            for v in h {
                *v = (0.0, 0.0);
            }
        }
    }

    /// Process one (sb, ts) sample of the input matrix `x`. Returns the
    /// decorrelated output `y[ts][sb]`. The caller pushes the input
    /// (re, im) and receives the corresponding output.
    pub fn process_sample(&mut self, sb: u32, x_in: (f32, f32)) -> (f32, f32) {
        let sb_idx = sb as usize;
        let delay = region_delay(sb);
        let filter_length = region_filter_length(sb);
        let a = region_coeffs(self.which, sb);
        // Push x_in into x_hist (offset 0 = brand-new sample).
        let xh = &mut self.x_hist[sb_idx];
        xh.rotate_right(1);
        xh[0] = x_in;
        let yh = &mut self.y_hist[sb_idx];

        // b[0] = a[filterLength], y = b[0] * x[ts-delay] / a[0]
        let b0 = a[filter_length];
        let a0 = a[0];
        let xd = if delay < xh.len() {
            xh[delay]
        } else {
            (0.0, 0.0)
        };
        let mut y_re = (b0 / a0) * xd.0 as f64;
        let mut y_im = (b0 / a0) * xd.1 as f64;
        for i in 1..=filter_length {
            let bi = a[filter_length - i];
            let xi_idx = i + delay;
            let xi = if xi_idx < xh.len() {
                xh[xi_idx]
            } else {
                (0.0, 0.0)
            };
            // y_hist[i-1] is the output at ts-i (since after rotate_right
            // we'll push current y at offset 0).
            let yi = if i - 1 < yh.len() {
                yh[i - 1]
            } else {
                (0.0, 0.0)
            };
            let ai = a[i];
            y_re += (bi * xi.0 as f64 - ai * yi.0 as f64) / a0;
            y_im += (bi * xi.1 as f64 - ai * yi.1 as f64) / a0;
        }
        let y_out = (y_re as f32, y_im as f32);
        // Push y_out into y_hist (rotate_right shifts older outputs up).
        yh.rotate_right(1);
        yh[0] = y_out;
        y_out
    }
}

/// Triplet of decorrelator modules for the three `u_x` paths used by
/// the multichannel A-CPL configurations.
#[derive(Debug, Clone)]
pub struct Decorrelator {
    pub d0: InputSignalModifier,
    pub d1: InputSignalModifier,
    pub d2: InputSignalModifier,
}

impl Decorrelator {
    pub fn new() -> Self {
        Self {
            d0: InputSignalModifier::new(DecorrelatorId::D0),
            d1: InputSignalModifier::new(DecorrelatorId::D1),
            d2: InputSignalModifier::new(DecorrelatorId::D2),
        }
    }
}

impl Default for Decorrelator {
    fn default() -> Self {
        Self::new()
    }
}

// =====================================================================
// §5.7.7.4.3 Transient ducker — Pseudocodes 112 / 113 / 114
// =====================================================================

/// Spec constants from Pseudocode 112.
pub const DUCKER_ALPHA: f32 = 0.76592833836465;
pub const DUCKER_ALPHA_SMOOTH: f32 = 0.25;
pub const DUCKER_GAMMA: f32 = 1.5;
pub const DUCKER_EPSILON: f32 = 1.0e-9;

/// `acpl_max_num_param_bands = 15` per Pseudocode 112.
pub const ACPL_MAX_NUM_PARAM_BANDS: usize = 15;

/// Persistent transient-ducker state across AC-4 frames.
#[derive(Debug, Clone)]
pub struct TransientDucker {
    pub p_peak_decay_prev: [f32; ACPL_MAX_NUM_PARAM_BANDS],
    pub p_smooth_prev: [f32; ACPL_MAX_NUM_PARAM_BANDS],
    pub smooth_peak_diff_prev: [f32; ACPL_MAX_NUM_PARAM_BANDS],
}

impl TransientDucker {
    pub fn new() -> Self {
        Self {
            p_peak_decay_prev: [0.0; ACPL_MAX_NUM_PARAM_BANDS],
            p_smooth_prev: [0.0; ACPL_MAX_NUM_PARAM_BANDS],
            smooth_peak_diff_prev: [0.0; ACPL_MAX_NUM_PARAM_BANDS],
        }
    }

    /// Reset state (called when `acpl_param_prev` is reinitialised).
    pub fn reset(&mut self) {
        *self = Self::new();
    }

    /// Compute `duck_gain[pb]` from the per-pb energy array
    /// (Pseudocode 112). Updates the carrying state.
    pub fn update(
        &mut self,
        p_energy: &[f32; ACPL_MAX_NUM_PARAM_BANDS],
    ) -> [f32; ACPL_MAX_NUM_PARAM_BANDS] {
        let mut duck = [1.0f32; ACPL_MAX_NUM_PARAM_BANDS];
        for pb in 0..ACPL_MAX_NUM_PARAM_BANDS {
            let p_peak_decay = if DUCKER_ALPHA * self.p_peak_decay_prev[pb] < p_energy[pb] {
                p_energy[pb]
            } else {
                DUCKER_ALPHA * self.p_peak_decay_prev[pb]
            };
            let smooth = (1.0 - DUCKER_ALPHA_SMOOTH) * self.p_smooth_prev[pb]
                + DUCKER_ALPHA_SMOOTH * p_energy[pb];
            let smooth_peak_diff = (1.0 - DUCKER_ALPHA_SMOOTH) * self.smooth_peak_diff_prev[pb]
                + DUCKER_ALPHA_SMOOTH * (p_peak_decay - p_energy[pb]);
            let g = if DUCKER_GAMMA * smooth_peak_diff > smooth {
                smooth / (DUCKER_GAMMA * (smooth_peak_diff + DUCKER_EPSILON))
            } else {
                1.0
            };
            duck[pb] = g;
            self.p_peak_decay_prev[pb] = p_peak_decay;
            self.p_smooth_prev[pb] = smooth;
            self.smooth_peak_diff_prev[pb] = smooth_peak_diff;
        }
        duck
    }
}

impl Default for TransientDucker {
    fn default() -> Self {
        Self::new()
    }
}

/// Compute `p_energy[pb]` from one column of QMF subbands per
/// Pseudocode 113 (`pb` = parameter band, summed |x|² over the QMF
/// subbands mapping to that pb via Table 197).
pub fn compute_p_energy(
    x: &[(f32, f32); NUM_QMF_SUBBANDS],
    num_param_bands: u32,
) -> [f32; ACPL_MAX_NUM_PARAM_BANDS] {
    let mut e = [0.0f32; ACPL_MAX_NUM_PARAM_BANDS];
    for sb in 0..NUM_QMF_SUBBANDS as u32 {
        let pb = sb_to_pb(sb, num_param_bands) as usize;
        let (re, im) = x[sb as usize];
        e[pb] += re * re + im * im;
    }
    e
}

/// Apply the per-pb `duck_gain` to a single QMF column (Pseudocode 114).
pub fn apply_transient_ducker(
    x: &[(f32, f32); NUM_QMF_SUBBANDS],
    duck_gain: &[f32; ACPL_MAX_NUM_PARAM_BANDS],
    num_param_bands: u32,
) -> [(f32, f32); NUM_QMF_SUBBANDS] {
    let mut out = *x;
    for sb in 0..NUM_QMF_SUBBANDS as u32 {
        let pb = sb_to_pb(sb, num_param_bands) as usize;
        let g = duck_gain[pb];
        out[sb as usize].0 *= g;
        out[sb as usize].1 *= g;
    }
    out
}

// =====================================================================
// §5.7.7.5 Pseudocode 115 / 116 — channel-pair element synthesis
// =====================================================================

/// Persistent state for a single ACplModule (carries the previous
/// frame's `acpl_alpha_prev[sb]` / `acpl_beta_prev[sb]` and the
/// decorrelator + ducker scratch).
#[derive(Debug, Clone)]
pub struct AcplCpeState {
    pub alpha_prev_sb: Vec<f32>,
    pub beta_prev_sb: Vec<f32>,
    pub decorrelator: InputSignalModifier,
    pub ducker: TransientDucker,
}

impl AcplCpeState {
    pub fn new(which: DecorrelatorId) -> Self {
        Self {
            alpha_prev_sb: vec![0.0; NUM_QMF_SUBBANDS],
            beta_prev_sb: vec![0.0; NUM_QMF_SUBBANDS],
            decorrelator: InputSignalModifier::new(which),
            ducker: TransientDucker::new(),
        }
    }
}

/// Inputs to one full §5.7.7.5 channel-pair synthesis pass.
pub struct AcplCpeFrame<'a> {
    /// `x0[ts][sb]` — left / first-channel QMF input matrix
    /// (`num_qmf_timeslots` slots × 64 subbands). For ASPX_ACPL_2 the
    /// `x1` channel is absent (caller passes None).
    pub x0: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    /// `x1[ts][sb]` — right / second-channel QMF input matrix. Some()
    /// for ASPX_ACPL_1, None for ASPX_ACPL_2.
    pub x1: Option<&'a [[(f32, f32); NUM_QMF_SUBBANDS]]>,
    /// `acpl_alpha_dq[pset][pb]` recovered values.
    pub alpha_dq: &'a [Vec<f32>],
    /// `acpl_beta_dq[pset][pb]` recovered values.
    pub beta_dq: &'a [Vec<f32>],
    /// `acpl_num_param_bands`.
    pub num_param_bands: u32,
    /// `acpl_qmf_band` from Table 59 — first subband at which the
    /// mixed-with-decorrelator path takes over from the M/S split.
    /// (For multichannel paths the spec sets this to 0.)
    pub acpl_qmf_band: u32,
    /// Steep interpolation flag.
    pub steep: bool,
    /// `acpl_param_timeslot[pset]` for the steep mode.
    pub param_timeslots: &'a [u8],
}

/// Output matrices from [`acpl_module`] — `(z0, z1)` per Pseudocode 116.
pub struct AcplCpeOutput {
    pub z0: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>,
    pub z1: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>,
}

/// `Pseudocode 116 ACplModule(acpl_alpha, acpl_beta, num_pset, x0, x1, y)`
/// — the two-channel A-CPL synthesis.
///
/// `y[ts][sb]` is the post-ducker decorrelated output of `x0` (provided
/// by [`run_pseudocode_115_pair`] below); `x1` may be all-zero for the
/// `ASPX_ACPL_2` mode (single-channel input).
pub fn acpl_module(
    frame: &AcplCpeFrame<'_>,
    y: &[[(f32, f32); NUM_QMF_SUBBANDS]],
) -> AcplCpeOutput {
    let num_ts = frame.x0.len();
    debug_assert_eq!(y.len(), num_ts);
    let num_pset = frame.alpha_dq.len() as u32;
    let alpha_sb = expand_pb_to_sb(frame.alpha_dq, frame.num_param_bands);
    let beta_sb = expand_pb_to_sb(frame.beta_dq, frame.num_param_bands);
    // Default prev to zeros for the first frame.
    let prev_alpha = vec![0.0f32; NUM_QMF_SUBBANDS];
    let prev_beta = vec![0.0f32; NUM_QMF_SUBBANDS];
    let alpha_inp = InterpInputs {
        by_pset: &alpha_sb,
        prev: &prev_alpha,
    };
    let beta_inp = InterpInputs {
        by_pset: &beta_sb,
        prev: &prev_beta,
    };

    let zero_col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
    let mut z0_out = Vec::with_capacity(num_ts);
    let mut z1_out = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let x0_col = frame.x0[ts];
        let x1_col = match frame.x1 {
            Some(matrix) => matrix[ts],
            None => zero_col,
        };
        let y_col = y[ts];
        let mut z0_col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        let mut z1_col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            let interp_a = interpolate(
                &alpha_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                frame.steep,
                frame.param_timeslots,
            );
            let interp_b = interpolate(
                &beta_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                frame.steep,
                frame.param_timeslots,
            );
            let sb_i = sb as usize;
            if sb < frame.acpl_qmf_band {
                let (x0r, x0i) = x0_col[sb_i];
                let (x1r, x1i) = x1_col[sb_i];
                z0_col[sb_i] = (0.5 * (x0r + x1r), 0.5 * (x0i + x1i));
                z1_col[sb_i] = (0.5 * (x0r - x1r), 0.5 * (x0i - x1i));
            } else {
                let (x0r, x0i) = x0_col[sb_i];
                let (yr, yi) = y_col[sb_i];
                let plus_a = 1.0 + interp_a;
                let minus_a = 1.0 - interp_a;
                z0_col[sb_i] = (
                    0.5 * (x0r * plus_a + yr * interp_b),
                    0.5 * (x0i * plus_a + yi * interp_b),
                );
                z1_col[sb_i] = (
                    0.5 * (x0r * minus_a - yr * interp_b),
                    0.5 * (x0i * minus_a - yi * interp_b),
                );
            }
        }
        z0_out.push(z0_col);
        z1_out.push(z1_col);
    }
    AcplCpeOutput {
        z0: z0_out,
        z1: z1_out,
    }
}

/// Run the complete §5.7.7.5 channel-pair element pipeline
/// (Pseudocode 115): scale inputs by 2, run the decorrelator + ducker
/// to get `y0`, then call [`acpl_module`].
///
/// `state` carries the `D0` decorrelator + ducker between calls (so
/// the IIR delay-line state survives across frames).
pub fn run_pseudocode_115_pair(state: &mut AcplCpeState, frame: AcplCpeFrame<'_>) -> AcplCpeOutput {
    // x0in = 2 * x0
    let num_ts = frame.x0.len();
    let mut x0in = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let mut col = frame.x0[ts];
        for sb in 0..NUM_QMF_SUBBANDS {
            col[sb].0 *= 2.0;
            col[sb].1 *= 2.0;
        }
        x0in.push(col);
    }
    // u0 = inputSignalModification(x0in)  (D0)
    let mut u0 = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let mut col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            col[sb as usize] = state.decorrelator.process_sample(sb, x0in[ts][sb as usize]);
        }
        u0.push(col);
    }
    // y0 = applyTransientDucker(u0)
    let mut y0 = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let p_energy = compute_p_energy(&u0[ts], frame.num_param_bands);
        let duck = state.ducker.update(&p_energy);
        y0.push(apply_transient_ducker(
            &u0[ts],
            &duck,
            frame.num_param_bands,
        ));
    }
    // Call acpl_module with x0in (note the spec: ACplModule receives
    // x0in, not raw x0).
    let mut x1in_owned: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>;
    let inner_x1: Option<&[[(f32, f32); NUM_QMF_SUBBANDS]]> = if let Some(x1) = frame.x1 {
        x1in_owned = Vec::with_capacity(num_ts);
        for ts in 0..num_ts {
            let mut col = x1[ts];
            for sb in 0..NUM_QMF_SUBBANDS {
                col[sb].0 *= 2.0;
                col[sb].1 *= 2.0;
            }
            x1in_owned.push(col);
        }
        Some(x1in_owned.as_slice())
    } else {
        None
    };
    let inner_frame = AcplCpeFrame {
        x0: &x0in,
        x1: inner_x1,
        alpha_dq: frame.alpha_dq,
        beta_dq: frame.beta_dq,
        num_param_bands: frame.num_param_bands,
        acpl_qmf_band: frame.acpl_qmf_band,
        steep: frame.steep,
        param_timeslots: frame.param_timeslots,
    };
    let out = acpl_module(&inner_frame, &y0);
    // Update prev arrays per Pseudocode 110 (last param set's expanded
    // sb values).
    if !frame.alpha_dq.is_empty() {
        let last_idx = frame.alpha_dq.len() - 1;
        let alpha_sb = expand_pb_to_sb(frame.alpha_dq, frame.num_param_bands);
        let beta_sb = expand_pb_to_sb(frame.beta_dq, frame.num_param_bands);
        update_param_prev(&mut state.alpha_prev_sb, &alpha_sb[last_idx]);
        update_param_prev(&mut state.beta_prev_sb, &beta_sb[last_idx]);
    }
    out
}

// =====================================================================
// §5.7.7.6.2 Pseudocodes 118 / 119 — ASPX_ACPL_3 multichannel synthesis
// =====================================================================

/// Per-channel QMF matrix shape used throughout §5.7.7.6.2: a vector of
/// per-timeslot `[ (re, im); NUM_QMF_SUBBANDS ]` columns.
pub type AcplQmfMatrix = Vec<[(f32, f32); NUM_QMF_SUBBANDS]>;

/// `Transform(g1, g2, num_pset, x0, x1)` per §5.7.7.6.2 Pseudocode 119.
///
/// Linearly mixes the two A-CPL carrier channels (`x0`, `x1`) by the
/// interpolated gamma matrices `g1`, `g2`:
///
/// ```text
///   v[ts][sb] = x0[ts][sb] * interp_g1[ts][sb]
///             + x1[ts][sb] * interp_g2[ts][sb]
/// ```
///
/// `g1_pb` / `g2_pb` are per-`(pset, pb)` matrices; we fan them out to
/// per-subband via [`expand_pb_to_sb`] and then the §5.7.7.3 [`interpolate`]
/// call walks them across timeslots. `prev_g1` / `prev_g2` carry the
/// previous frame's last-set `[sb]` row (zero on the first frame, per the
/// spec).
///
/// The output is `[ts][sb]` shaped, matching the rest of the §5.7.7
/// per-slot interfaces.
#[allow(clippy::too_many_arguments)]
pub fn transform(
    x0: &[[(f32, f32); NUM_QMF_SUBBANDS]],
    x1: &[[(f32, f32); NUM_QMF_SUBBANDS]],
    g1_pb: &[Vec<f32>],
    g2_pb: &[Vec<f32>],
    num_param_bands: u32,
    prev_g1: &[f32],
    prev_g2: &[f32],
    steep: bool,
    param_timeslots: &[u8],
) -> Vec<[(f32, f32); NUM_QMF_SUBBANDS]> {
    let num_ts = x0.len();
    debug_assert_eq!(x1.len(), num_ts);
    let num_pset = g1_pb.len() as u32;
    let g1_sb = expand_pb_to_sb(g1_pb, num_param_bands);
    let g2_sb = expand_pb_to_sb(g2_pb, num_param_bands);
    let g1_inp = InterpInputs {
        by_pset: &g1_sb,
        prev: prev_g1,
    };
    let g2_inp = InterpInputs {
        by_pset: &g2_sb,
        prev: prev_g2,
    };
    let mut out = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let mut v_col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            let g1 = interpolate(
                &g1_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let g2 = interpolate(
                &g2_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let (x0r, x0i) = x0[ts][sb as usize];
            let (x1r, x1i) = x1[ts][sb as usize];
            v_col[sb as usize] = (x0r * g1 + x1r * g2, x0i * g1 + x1i * g2);
        }
        out.push(v_col);
    }
    out
}

/// `ACplModule2(g1, g2, a, b, num_pset, x0, x1, y)` per §5.7.7.6.2
/// Pseudocode 119.
///
/// Builds the (z0, z1) channel pair from the two A-CPL carrier inputs,
/// the gamma + alpha + beta parameter matrices, and the decorrelator
/// output `y`:
///
/// ```text
///   z0 = 0.5*(x0*(g1+g1*a) + x1*(g2+g2*a) + y*b)
///   z1 = 0.5*(x0*(g1-g1*a) + x1*(g2-g2*a) - y*b)
/// ```
///
/// The interpolations are taken on the full `g1`, `g2`, `g1*a`, `g2*a`
/// and `b` per-`pb` matrices (computed from the dequantised arrays
/// before the call). Per the spec the interpolations are computed on
/// the products `g*a` (not on `g` and `a` separately) because that's
/// the point at which time-interpolation must be evaluated.
///
/// `prev_*` are the previous-frame `[sb]` rows for each interpolated
/// matrix (zero on the first frame).
#[allow(clippy::too_many_arguments)]
pub fn acpl_module2(
    x0: &[[(f32, f32); NUM_QMF_SUBBANDS]],
    x1: &[[(f32, f32); NUM_QMF_SUBBANDS]],
    y: &[[(f32, f32); NUM_QMF_SUBBANDS]],
    g1_pb: &[Vec<f32>],
    g2_pb: &[Vec<f32>],
    g1a_pb: &[Vec<f32>],
    g2a_pb: &[Vec<f32>],
    b_pb: &[Vec<f32>],
    num_param_bands: u32,
    steep: bool,
    param_timeslots: &[u8],
) -> (AcplQmfMatrix, AcplQmfMatrix) {
    let num_ts = x0.len();
    debug_assert_eq!(x1.len(), num_ts);
    debug_assert_eq!(y.len(), num_ts);
    let num_pset = g1_pb.len() as u32;
    let g1_sb = expand_pb_to_sb(g1_pb, num_param_bands);
    let g2_sb = expand_pb_to_sb(g2_pb, num_param_bands);
    let g1a_sb = expand_pb_to_sb(g1a_pb, num_param_bands);
    let g2a_sb = expand_pb_to_sb(g2a_pb, num_param_bands);
    let b_sb = expand_pb_to_sb(b_pb, num_param_bands);
    let zero_prev = vec![0.0f32; NUM_QMF_SUBBANDS];
    let g1_inp = InterpInputs {
        by_pset: &g1_sb,
        prev: &zero_prev,
    };
    let g2_inp = InterpInputs {
        by_pset: &g2_sb,
        prev: &zero_prev,
    };
    let g1a_inp = InterpInputs {
        by_pset: &g1a_sb,
        prev: &zero_prev,
    };
    let g2a_inp = InterpInputs {
        by_pset: &g2a_sb,
        prev: &zero_prev,
    };
    let b_inp = InterpInputs {
        by_pset: &b_sb,
        prev: &zero_prev,
    };

    let mut z0_out = Vec::with_capacity(num_ts);
    let mut z1_out = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let mut z0_col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        let mut z1_col = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            let g1 = interpolate(
                &g1_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let g2 = interpolate(
                &g2_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let g1a = interpolate(
                &g1a_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let g2a = interpolate(
                &g2a_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let b = interpolate(
                &b_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let sb_i = sb as usize;
            let (x0r, x0i) = x0[ts][sb_i];
            let (x1r, x1i) = x1[ts][sb_i];
            let (yr, yi) = y[ts][sb_i];
            z0_col[sb_i] = (
                0.5 * (x0r * (g1 + g1a) + x1r * (g2 + g2a) + yr * b),
                0.5 * (x0i * (g1 + g1a) + x1i * (g2 + g2a) + yi * b),
            );
            z1_col[sb_i] = (
                0.5 * (x0r * (g1 - g1a) + x1r * (g2 - g2a) - yr * b),
                0.5 * (x0i * (g1 - g1a) + x1i * (g2 - g2a) - yi * b),
            );
        }
        z0_out.push(z0_col);
        z1_out.push(z1_col);
    }
    (z0_out, z1_out)
}

/// `ACplModule3(b3, a, num_pset, z0, z1, y2)` per §5.7.7.6.2
/// Pseudocode 119.
///
/// Adds a cross-residual decorrelator term to an existing `(z0, z1)`
/// pair using `beta3` and the alpha matrix:
///
/// ```text
///   z0 += 0.25 * y2 * (b3 + b3*a)
///   z1 += 0.25 * y2 * (b3 - b3*a)
/// ```
///
/// The dequantised `b3_pb` and `b3a_pb` per-`(pset, pb)` matrices are
/// fanned out to subbands via [`expand_pb_to_sb`] and run through
/// [`interpolate`] across timeslots. The `(z0, z1)` slices are mutated
/// in-place to match the spec's `z0[ts][sb] += ...` form.
#[allow(clippy::too_many_arguments)]
pub fn acpl_module3(
    z0: &mut [[(f32, f32); NUM_QMF_SUBBANDS]],
    z1: &mut [[(f32, f32); NUM_QMF_SUBBANDS]],
    y2: &[[(f32, f32); NUM_QMF_SUBBANDS]],
    b3_pb: &[Vec<f32>],
    b3a_pb: &[Vec<f32>],
    num_param_bands: u32,
    steep: bool,
    param_timeslots: &[u8],
) {
    let num_ts = z0.len();
    debug_assert_eq!(z1.len(), num_ts);
    debug_assert_eq!(y2.len(), num_ts);
    let num_pset = b3_pb.len() as u32;
    let b3_sb = expand_pb_to_sb(b3_pb, num_param_bands);
    let b3a_sb = expand_pb_to_sb(b3a_pb, num_param_bands);
    let zero_prev = vec![0.0f32; NUM_QMF_SUBBANDS];
    let b3_inp = InterpInputs {
        by_pset: &b3_sb,
        prev: &zero_prev,
    };
    let b3a_inp = InterpInputs {
        by_pset: &b3a_sb,
        prev: &zero_prev,
    };
    for ts in 0..num_ts {
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            let b3 = interpolate(
                &b3_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let b3a = interpolate(
                &b3a_inp,
                num_pset,
                sb,
                ts as u32,
                num_ts as u32,
                steep,
                param_timeslots,
            );
            let sb_i = sb as usize;
            let (yr, yi) = y2[ts][sb_i];
            z0[ts][sb_i].0 += 0.25 * yr * (b3 + b3a);
            z0[ts][sb_i].1 += 0.25 * yi * (b3 + b3a);
            z1[ts][sb_i].0 += 0.25 * yr * (b3 - b3a);
            z1[ts][sb_i].1 += 0.25 * yi * (b3 - b3a);
        }
    }
}

/// Helper: per-`(pset, pb)` element-wise multiply of two per-band
/// matrices. Returned matrix has the same shape as `a`. For mismatched
/// inner-row lengths the shorter wins.
fn pb_matrix_mul(a: &[Vec<f32>], b: &[Vec<f32>]) -> Vec<Vec<f32>> {
    debug_assert_eq!(a.len(), b.len());
    a.iter()
        .zip(b.iter())
        .map(|(ar, br)| {
            let n = ar.len().min(br.len());
            let mut row = Vec::with_capacity(n);
            for i in 0..n {
                row.push(ar[i] * br[i]);
            }
            row
        })
        .collect()
}

/// Helper: per-`(pset, pb)` element-wise sum of three per-band
/// matrices. Used to build `g1+g3+g5` and `g2+g4+g6` for the third
/// `Transform()` call in Pseudocode 118.
fn pb_matrix_sum3(a: &[Vec<f32>], b: &[Vec<f32>], c: &[Vec<f32>]) -> Vec<Vec<f32>> {
    debug_assert_eq!(a.len(), b.len());
    debug_assert_eq!(a.len(), c.len());
    a.iter()
        .zip(b.iter())
        .zip(c.iter())
        .map(|((ar, br), cr)| {
            let n = ar.len().min(br.len()).min(cr.len());
            let mut row = Vec::with_capacity(n);
            for i in 0..n {
                row.push(ar[i] + br[i] + cr[i]);
            }
            row
        })
        .collect()
}

/// Helper: scalar-multiply each element of a `(pset, pb)` matrix.
fn pb_matrix_scale(a: &[Vec<f32>], s: f32) -> Vec<Vec<f32>> {
    a.iter()
        .map(|row| row.iter().map(|&v| v * s).collect())
        .collect()
}

/// Persistent state for the §5.7.7.6.2 ASPX_ACPL_3 multichannel
/// pipeline: three parallel `D0`/`D1`/`D2` decorrelator + ducker pairs
/// (one per `Transform()` output) plus the running `prev` matrices for
/// the gamma interpolations.
#[derive(Debug, Clone)]
pub struct AcplMchState {
    pub d0: InputSignalModifier,
    pub d1: InputSignalModifier,
    pub d2: InputSignalModifier,
    pub ducker0: TransientDucker,
    pub ducker1: TransientDucker,
    pub ducker2: TransientDucker,
    /// `acpl_g1_prev[sb]` — last-frame's per-sb gamma1 row.
    pub g1_prev_sb: Vec<f32>,
    pub g2_prev_sb: Vec<f32>,
    pub g3_prev_sb: Vec<f32>,
    pub g4_prev_sb: Vec<f32>,
}

impl AcplMchState {
    pub fn new() -> Self {
        Self {
            d0: InputSignalModifier::new(DecorrelatorId::D0),
            d1: InputSignalModifier::new(DecorrelatorId::D1),
            d2: InputSignalModifier::new(DecorrelatorId::D2),
            ducker0: TransientDucker::new(),
            ducker1: TransientDucker::new(),
            ducker2: TransientDucker::new(),
            g1_prev_sb: vec![0.0; NUM_QMF_SUBBANDS],
            g2_prev_sb: vec![0.0; NUM_QMF_SUBBANDS],
            g3_prev_sb: vec![0.0; NUM_QMF_SUBBANDS],
            g4_prev_sb: vec![0.0; NUM_QMF_SUBBANDS],
        }
    }
}

impl Default for AcplMchState {
    fn default() -> Self {
        Self::new()
    }
}

/// Inputs to one full §5.7.7.6.2 ASPX_ACPL_3 multichannel synthesis pass.
///
/// All matrices are per-`(pset, pb)`. The dequantisation pipeline must
/// have already converted the Huffman-decoded indices via
/// [`dequantize_alpha_beta`] / [`dequantize_beta3`] / [`dequantize_gamma`].
pub struct AcplMchFrame<'a> {
    /// `x0[ts][sb]` — first A-CPL carrier (left/L for ASPX_ACPL_3).
    pub x0: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    /// `x1[ts][sb]` — second A-CPL carrier (right/R for ASPX_ACPL_3).
    pub x1: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    /// `x2[ts][sb]` — centre channel passthrough.
    pub x2: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    /// `acpl_alpha_1_dq[pset][pb]` (left side).
    pub alpha_1_dq: &'a [Vec<f32>],
    /// `acpl_alpha_2_dq[pset][pb]` (right side).
    pub alpha_2_dq: &'a [Vec<f32>],
    /// `acpl_beta_1_dq[pset][pb]`.
    pub beta_1_dq: &'a [Vec<f32>],
    /// `acpl_beta_2_dq[pset][pb]`.
    pub beta_2_dq: &'a [Vec<f32>],
    /// `acpl_beta_3_dq[pset][pb]` — the cross-residual term used by
    /// `ACplModule3`.
    pub beta_3_dq: &'a [Vec<f32>],
    /// `g1_dq[pset][pb]` .. `g6_dq[pset][pb]` per §5.7.7.7 Tables 207-208.
    pub g1_dq: &'a [Vec<f32>],
    pub g2_dq: &'a [Vec<f32>],
    pub g3_dq: &'a [Vec<f32>],
    pub g4_dq: &'a [Vec<f32>],
    pub g5_dq: &'a [Vec<f32>],
    pub g6_dq: &'a [Vec<f32>],
    pub num_param_bands: u32,
    pub steep: bool,
    pub param_timeslots: &'a [u8],
}

/// Output channels from [`run_pseudocode_118_5x`] — `(L, R, C, Ls, Rs)`
/// indexed as `(z0, z2, z4, z1, z3)` in the spec.
pub struct AcplMchOutput {
    pub z0: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // L
    pub z2: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // R
    pub z4: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // C
    pub z1: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // Ls
    pub z3: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // Rs
}

/// Run the full §5.7.7.6.2 Pseudocode 118 ASPX_ACPL_3 multichannel
/// pipeline. Produces the five output channels (L, Ls, R, Rs, C) from
/// the two A-CPL carriers, the centre channel and the gamma+alpha+beta
/// matrices.
///
/// Pipeline (verbatim from Pseudocode 118):
///
/// 1. `x0in = x0*(1+2*sqrt(0.5))`, `x1in = x1*(1+2*sqrt(0.5))`.
/// 2. `v1 = Transform(g1, g2, x0in, x1in)`,
///    `v2 = Transform(g3, g4, x0in, x1in)`,
///    `v3 = Transform(g1+g3+g5, g2+g4+g6, x0in, x1in)`.
/// 3. `u0 = D0(v1)`, `u1 = D1(v2)`, `u2 = D2(v3)`.
/// 4. `y0 = ducker(u0)`, `y1 = ducker(u1)`, `y2 = ducker(u2)`.
/// 5. `(z0, z1) = ACplModule2(g1, g2, alpha_1, beta_1, x0in, x1in, y0)`.
/// 6. `(z2, z3) = ACplModule2(g3, g4, alpha_2, beta_2, x0in, x1in, y1)`.
/// 7. `(z4, z5) = ACplModule2(g5, g6, 1, 0, x0in, x1in, 0)`.
/// 8. `(z0, z1) = ACplModule3(beta_3, alpha_1, z0, z1, y2)`.
/// 9. `(z2, z3) = ACplModule3(beta_3, alpha_2, z2, z3, y2)`.
/// 10. `(z4, z5) = ACplModule3(-beta_3, 1, z4, z5, y2)`.
/// 11. `z1 *= sqrt(2)`, `z3 *= sqrt(2)`, `z4 *= sqrt(2)`.
/// 12. `z4 = x2` (note: per the spec text, z4 is initialised from
///     `ACplModule2(g5, g6, ..)` and then has the ACplModule3 correction
///     and `*sqrt(2)` applied — but the surrounding text in §5.7.7.6.2
///     reads "z4 = x2" outside the pseudocode body. We follow the
///     pseudocode literally: the centre channel is the synthesised z4;
///     a caller wanting the spec's "z4 = x2" passthrough can override
///     [`AcplMchOutput::z4`] after the fact).
pub fn run_pseudocode_118_5x(state: &mut AcplMchState, frame: AcplMchFrame<'_>) -> AcplMchOutput {
    let num_ts = frame.x0.len();
    debug_assert_eq!(frame.x1.len(), num_ts);
    debug_assert_eq!(frame.x2.len(), num_ts);

    // Step 1: x0in = x0 * (1 + 2*sqrt(0.5)), x1in = x1 * (1 + 2*sqrt(0.5)).
    // 1 + 2*sqrt(0.5) = 1 + sqrt(2).
    let scale = 1.0 + 2.0 * (0.5f32).sqrt();
    let scale_x = |x: &[[(f32, f32); NUM_QMF_SUBBANDS]]| -> Vec<[(f32, f32); NUM_QMF_SUBBANDS]> {
        x.iter()
            .map(|col| {
                let mut out = *col;
                for sb in 0..NUM_QMF_SUBBANDS {
                    out[sb].0 *= scale;
                    out[sb].1 *= scale;
                }
                out
            })
            .collect()
    };
    let x0in = scale_x(frame.x0);
    let x1in = scale_x(frame.x1);

    // Step 2: build the three Transform() outputs.
    let g_sum_1 = pb_matrix_sum3(frame.g1_dq, frame.g3_dq, frame.g5_dq);
    let g_sum_2 = pb_matrix_sum3(frame.g2_dq, frame.g4_dq, frame.g6_dq);
    let v1 = transform(
        &x0in,
        &x1in,
        frame.g1_dq,
        frame.g2_dq,
        frame.num_param_bands,
        &state.g1_prev_sb,
        &state.g2_prev_sb,
        frame.steep,
        frame.param_timeslots,
    );
    let v2 = transform(
        &x0in,
        &x1in,
        frame.g3_dq,
        frame.g4_dq,
        frame.num_param_bands,
        &state.g3_prev_sb,
        &state.g4_prev_sb,
        frame.steep,
        frame.param_timeslots,
    );
    let v3 = transform(
        &x0in,
        &x1in,
        &g_sum_1,
        &g_sum_2,
        frame.num_param_bands,
        &vec![0.0; NUM_QMF_SUBBANDS],
        &vec![0.0; NUM_QMF_SUBBANDS],
        frame.steep,
        frame.param_timeslots,
    );

    // Step 3: u_x = decorrelator_x(v_x).
    let mut u0 = Vec::with_capacity(num_ts);
    let mut u1 = Vec::with_capacity(num_ts);
    let mut u2 = Vec::with_capacity(num_ts);
    for ts in 0..num_ts {
        let mut col0 = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        let mut col1 = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        let mut col2 = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            col0[sb as usize] = state.d0.process_sample(sb, v1[ts][sb as usize]);
            col1[sb as usize] = state.d1.process_sample(sb, v2[ts][sb as usize]);
            col2[sb as usize] = state.d2.process_sample(sb, v3[ts][sb as usize]);
        }
        u0.push(col0);
        u1.push(col1);
        u2.push(col2);
    }

    // Step 4: y_x = ducker(u_x).
    let apply_ducker = |u: &[[(f32, f32); NUM_QMF_SUBBANDS]],
                        ducker: &mut TransientDucker|
     -> Vec<[(f32, f32); NUM_QMF_SUBBANDS]> {
        u.iter()
            .map(|col| {
                let p_energy = compute_p_energy(col, frame.num_param_bands);
                let duck = ducker.update(&p_energy);
                apply_transient_ducker(col, &duck, frame.num_param_bands)
            })
            .collect()
    };
    let y0 = apply_ducker(&u0, &mut state.ducker0);
    let y1 = apply_ducker(&u1, &mut state.ducker1);
    let y2 = apply_ducker(&u2, &mut state.ducker2);

    // Step 5: (z0, z1) = ACplModule2(g1, g2, alpha_1, beta_1, x0in, x1in, y0).
    // Per Pseudocode 119 the (g1*a) / (g2*a) interpolations sample the
    // *product* matrices — we precompute them at parameter-band granularity.
    let g1_a1 = pb_matrix_mul(frame.g1_dq, frame.alpha_1_dq);
    let g2_a1 = pb_matrix_mul(frame.g2_dq, frame.alpha_1_dq);
    let (mut z0, mut z1) = acpl_module2(
        &x0in,
        &x1in,
        &y0,
        frame.g1_dq,
        frame.g2_dq,
        &g1_a1,
        &g2_a1,
        frame.beta_1_dq,
        frame.num_param_bands,
        frame.steep,
        frame.param_timeslots,
    );

    // Step 6: (z2, z3) = ACplModule2(g3, g4, alpha_2, beta_2, x0in, x1in, y1).
    let g3_a2 = pb_matrix_mul(frame.g3_dq, frame.alpha_2_dq);
    let g4_a2 = pb_matrix_mul(frame.g4_dq, frame.alpha_2_dq);
    let (mut z2, mut z3) = acpl_module2(
        &x0in,
        &x1in,
        &y1,
        frame.g3_dq,
        frame.g4_dq,
        &g3_a2,
        &g4_a2,
        frame.beta_2_dq,
        frame.num_param_bands,
        frame.steep,
        frame.param_timeslots,
    );

    // Step 7: (z4, z5) = ACplModule2(g5, g6, 1, 0, x0in, x1in, 0).
    // a == 1 → g*a == g; b == 0 → no decorrelator term; y == 0 too.
    let zero_y = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
    // β = 0 across all bands. The shape follows the gamma matrices.
    let zero_pb: Vec<Vec<f32>> = frame
        .g5_dq
        .iter()
        .map(|row| vec![0.0f32; row.len()])
        .collect();
    let (mut z4, _z5) = acpl_module2(
        &x0in,
        &x1in,
        &zero_y,
        frame.g5_dq,
        frame.g6_dq,
        frame.g5_dq, // g5 * 1
        frame.g6_dq, // g6 * 1
        &zero_pb,
        frame.num_param_bands,
        frame.steep,
        frame.param_timeslots,
    );
    // _z5 is a temporary per the spec note ("Note that z5 is used as a
    // temporary variable only and does not constitute an output channel.").

    // Step 8: (z0, z1) += ACplModule3(beta_3, alpha_1, z0, z1, y2).
    let b3_a1 = pb_matrix_mul(frame.beta_3_dq, frame.alpha_1_dq);
    acpl_module3(
        &mut z0,
        &mut z1,
        &y2,
        frame.beta_3_dq,
        &b3_a1,
        frame.num_param_bands,
        frame.steep,
        frame.param_timeslots,
    );

    // Step 9: (z2, z3) += ACplModule3(beta_3, alpha_2, z2, z3, y2).
    let b3_a2 = pb_matrix_mul(frame.beta_3_dq, frame.alpha_2_dq);
    acpl_module3(
        &mut z2,
        &mut z3,
        &y2,
        frame.beta_3_dq,
        &b3_a2,
        frame.num_param_bands,
        frame.steep,
        frame.param_timeslots,
    );

    // Step 10: (z4, z5) += ACplModule3(-beta_3, 1, z4, z5, y2). a == 1 →
    // beta3*a == beta3 (i.e. b3a == b3 with a sign flip on b3 — but the
    // spec writes -b3 for this row). So b3 is negated and b3a == -b3 too.
    let neg_b3 = pb_matrix_scale(frame.beta_3_dq, -1.0);
    let neg_b3_a = pb_matrix_scale(frame.beta_3_dq, -1.0); // a == 1 → -b3*1 = -b3.
    let mut z5_dummy = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
    acpl_module3(
        &mut z4,
        &mut z5_dummy,
        &y2,
        &neg_b3,
        &neg_b3_a,
        frame.num_param_bands,
        frame.steep,
        frame.param_timeslots,
    );

    // Step 11: z1 *= sqrt(2), z3 *= sqrt(2), z4 *= sqrt(2).
    let sq2 = (2.0f32).sqrt();
    let scale_inplace = |z: &mut [[(f32, f32); NUM_QMF_SUBBANDS]], s: f32| {
        for col in z.iter_mut() {
            for sb in 0..NUM_QMF_SUBBANDS {
                col[sb].0 *= s;
                col[sb].1 *= s;
            }
        }
    };
    scale_inplace(&mut z1, sq2);
    scale_inplace(&mut z3, sq2);
    scale_inplace(&mut z4, sq2);

    // Update state's prev arrays from the last param set's expanded
    // [sb] rows (gammas only — alpha/beta state lives elsewhere if a
    // caller wants to chain it).
    let update_prev = |prev: &mut Vec<f32>, src_pb: &[Vec<f32>]| {
        if !src_pb.is_empty() {
            let last = &src_pb[src_pb.len() - 1];
            let sb = expand_pb_to_sb(std::slice::from_ref(last), frame.num_param_bands);
            update_param_prev(prev, &sb[0]);
        }
    };
    update_prev(&mut state.g1_prev_sb, frame.g1_dq);
    update_prev(&mut state.g2_prev_sb, frame.g2_dq);
    update_prev(&mut state.g3_prev_sb, frame.g3_dq);
    update_prev(&mut state.g4_prev_sb, frame.g4_dq);

    AcplMchOutput { z0, z2, z4, z1, z3 }
}

// =====================================================================
// §5.7.7.6.1 Pseudocode 117 — ASPX_ACPL_1 / ASPX_ACPL_2 multichannel
// =====================================================================

/// Persistent state for the §5.7.7.6.1 ASPX_ACPL_1 / ASPX_ACPL_2
/// multichannel wrapper (Pseudocode 117): two parallel `ACplModule`s,
/// each with its own `AcplCpeState` (D0 for the L-side ACplModule,
/// D1 for the R-side). Carried across AC-4 frames by the decoder.
#[derive(Debug, Clone)]
pub struct Acpl5xPairState {
    /// State for the first ACplModule — drives the L / Ls output pair
    /// from the L (and optionally Ls) carrier. Decorrelator = D0.
    pub left_pair: AcplCpeState,
    /// State for the second ACplModule — drives the R / Rs output pair
    /// from the R (and optionally Rs) carrier. Decorrelator = D1.
    pub right_pair: AcplCpeState,
    /// Differential-decode state for the first `acpl_data_1ch()` set
    /// (alpha / beta on the L-side module).
    pub alpha1_diff: AcplDiffState,
    pub beta1_diff: AcplDiffState,
    /// Differential-decode state for the second `acpl_data_1ch()` set
    /// (alpha / beta on the R-side module).
    pub alpha2_diff: AcplDiffState,
    pub beta2_diff: AcplDiffState,
}

impl Acpl5xPairState {
    pub fn new() -> Self {
        Self {
            left_pair: AcplCpeState::new(DecorrelatorId::D0),
            right_pair: AcplCpeState::new(DecorrelatorId::D1),
            alpha1_diff: AcplDiffState::new(),
            beta1_diff: AcplDiffState::new(),
            alpha2_diff: AcplDiffState::new(),
            beta2_diff: AcplDiffState::new(),
        }
    }
}

impl Default for Acpl5xPairState {
    fn default() -> Self {
        Self::new()
    }
}

/// 5_X codec mode selector for [`run_pseudocode_117_5x`] — chooses
/// between the two-carrier `ASPX_ACPL_1` (`x3`/`x4` present) and the
/// one-carrier `ASPX_ACPL_2` (`x3`/`x4` are zero / absent).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Acpl5xPairMode {
    /// `5_X_codec_mode == ASPX_ACPL_1` — L/R carriers + Ls/Rs carriers
    /// (4 driving channels into the two parallel ACplModule's).
    AspxAcpl1,
    /// `5_X_codec_mode == ASPX_ACPL_2` — only L/R carriers; Ls/Rs come
    /// from each ACplModule's decorrelator-driven `y0`/`y1` term.
    AspxAcpl2,
}

/// Inputs to one §5.7.7.6.1 Pseudocode 117 wrapper pass.
///
/// Carrier channel ordering follows the spec:
///
/// * `x0` = Left, `x1` = Right (always present)
/// * `x2` = Centre (passthrough — copied straight to `z4`)
/// * `x3` = Left surround, `x4` = Right surround (only used when
///   `mode == AspxAcpl1`; `None` for `AspxAcpl2`).
///
/// Each ACplModule consumes its own `acpl_data_1ch()` set (the
/// dequantised `acpl_alpha_1_dq` / `acpl_beta_1_dq` for module #1, and
/// `acpl_alpha_2_dq` / `acpl_beta_2_dq` for module #2). `num_pset_1` /
/// `num_pset_2` and the two framing rows can differ between modules.
pub struct Acpl5xPairFrame<'a> {
    pub mode: Acpl5xPairMode,
    pub x0: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    pub x1: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    pub x2: &'a [[(f32, f32); NUM_QMF_SUBBANDS]],
    pub x3: Option<&'a [[(f32, f32); NUM_QMF_SUBBANDS]]>,
    pub x4: Option<&'a [[(f32, f32); NUM_QMF_SUBBANDS]]>,
    /// `acpl_alpha_1_dq[pset][pb]` / `acpl_beta_1_dq[pset][pb]` (module
    /// #1, drives L / Ls).
    pub alpha_1_dq: &'a [Vec<f32>],
    pub beta_1_dq: &'a [Vec<f32>],
    /// `acpl_alpha_2_dq[pset][pb]` / `acpl_beta_2_dq[pset][pb]` (module
    /// #2, drives R / Rs).
    pub alpha_2_dq: &'a [Vec<f32>],
    pub beta_2_dq: &'a [Vec<f32>],
    pub num_param_bands: u32,
    /// The multichannel paths set `acpl_qmf_band` to 0 (see
    /// §5.7.7.6.1) — the M/S split below `acpl_qmf_band` only applies
    /// to the channel-pair flow.
    pub acpl_qmf_band: u32,
    pub steep_1: bool,
    pub steep_2: bool,
    pub param_timeslots_1: &'a [u8],
    pub param_timeslots_2: &'a [u8],
}

/// Output channels from [`run_pseudocode_117_5x`] — the five 5.X output
/// QMF matrices in spec ordering (`z0`=L, `z1`=Ls, `z2`=R, `z3`=Rs,
/// `z4`=C).
pub struct Acpl5xPairOutput {
    pub z0: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // L
    pub z1: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // Ls
    pub z2: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // R
    pub z3: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // Rs
    pub z4: Vec<[(f32, f32); NUM_QMF_SUBBANDS]>, // C
}

/// Run the §5.7.7.6.1 Pseudocode 117 multichannel wrapper for
/// `5_X_codec_mode in { ASPX_ACPL_1, ASPX_ACPL_2 }`.
///
/// Verbatim from Pseudocode 117 (TS 103 190-1 §5.7.7.6.1):
///
/// ```text
///   x0in = 2*x0;
///   x1in = 2*x1;
///   u0 = inputSignalModification(x0in);   // D0
///   u1 = inputSignalModification(x1in);   // D1
///   y0 = applyTransientDucker(u0);
///   y1 = applyTransientDucker(u1);
///   if (5_X_codec_mode == ASPX_ACPL_1) {
///       x3in = 2*x3;
///       x4in = 2*x4;
///       (z0, z1) = ACplModule(alpha_1, beta_1, num_pset_1, x0in, x3in, y0);
///       (z2, z3) = ACplModule(alpha_2, beta_2, num_pset_2, x1in, x4in, y1);
///   }
///   else if (5_X_codec_mode == ASPX_ACPL_2) {
///       (z0, z1) = ACplModule(alpha_1, beta_1, num_pset_1, x0in, 0, y0);
///       (z2, z3) = ACplModule(alpha_2, beta_2, num_pset_2, x1in, 0, y1);
///   }
///   z1 *= sqrt(2);
///   z3 *= sqrt(2);
///   z4 = x2;
/// ```
///
/// Each `ACplModule` is invoked through [`run_pseudocode_115_pair`] so
/// the L-side and R-side decorrelator (D0/D1) + ducker state stays
/// chained across frames in `state.left_pair` / `state.right_pair`.
pub fn run_pseudocode_117_5x(
    state: &mut Acpl5xPairState,
    frame: Acpl5xPairFrame<'_>,
) -> Acpl5xPairOutput {
    let num_ts = frame.x0.len();
    debug_assert_eq!(frame.x1.len(), num_ts);
    debug_assert_eq!(frame.x2.len(), num_ts);

    // Module #1: L-side. ASPX_ACPL_1 -> x1 = x3 (Ls carrier).
    //                   ASPX_ACPL_2 -> x1 = None.
    let pair1_x1 = match frame.mode {
        Acpl5xPairMode::AspxAcpl1 => frame.x3,
        Acpl5xPairMode::AspxAcpl2 => None,
    };
    let pair1 = AcplCpeFrame {
        x0: frame.x0,
        x1: pair1_x1,
        alpha_dq: frame.alpha_1_dq,
        beta_dq: frame.beta_1_dq,
        num_param_bands: frame.num_param_bands,
        acpl_qmf_band: frame.acpl_qmf_band,
        steep: frame.steep_1,
        param_timeslots: frame.param_timeslots_1,
    };
    let out1 = run_pseudocode_115_pair(&mut state.left_pair, pair1);

    // Module #2: R-side. ASPX_ACPL_1 -> x1 = x4 (Rs carrier).
    //                   ASPX_ACPL_2 -> x1 = None.
    let pair2_x1 = match frame.mode {
        Acpl5xPairMode::AspxAcpl1 => frame.x4,
        Acpl5xPairMode::AspxAcpl2 => None,
    };
    let pair2 = AcplCpeFrame {
        x0: frame.x1,
        x1: pair2_x1,
        alpha_dq: frame.alpha_2_dq,
        beta_dq: frame.beta_2_dq,
        num_param_bands: frame.num_param_bands,
        acpl_qmf_band: frame.acpl_qmf_band,
        steep: frame.steep_2,
        param_timeslots: frame.param_timeslots_2,
    };
    let out2 = run_pseudocode_115_pair(&mut state.right_pair, pair2);

    // Step "z1 *= sqrt(2)", "z3 *= sqrt(2)" — the surround pair gets the
    // sqrt(2) scale per the spec.
    let sq2 = (2.0f32).sqrt();
    let scale_inplace = |z: &mut [[(f32, f32); NUM_QMF_SUBBANDS]], s: f32| {
        for col in z.iter_mut() {
            for sb in 0..NUM_QMF_SUBBANDS {
                col[sb].0 *= s;
                col[sb].1 *= s;
            }
        }
    };
    let mut z0 = out1.z0;
    let mut z1 = out1.z1;
    let mut z2 = out2.z0;
    let mut z3 = out2.z1;
    scale_inplace(&mut z1, sq2);
    scale_inplace(&mut z3, sq2);

    // Centre channel passthrough: z4 = x2 (no scale per the pseudocode).
    let z4: Vec<[(f32, f32); NUM_QMF_SUBBANDS]> = frame.x2.to_vec();

    // Borrow-checker quietener: z0/z2 are intentionally not re-scaled.
    let _ = (&mut z0, &mut z2);

    Acpl5xPairOutput { z0, z1, z2, z3, z4 }
}

// =====================================================================
// §5.7.7 — top-level helpers wired into Ac4Decoder
// =====================================================================

use crate::acpl::{AcplConfig1ch, AcplData1ch, AcplInterpolationType};
use crate::qmf::{QmfAnalysisBank, QmfSynthesisBank};

/// Per-substream A-CPL persistent state — diff state for ALPHA and BETA
/// plus the channel-pair `AcplCpeState` (decorrelator + ducker + prev
/// arrays). Carried across AC-4 frames by the decoder.
#[derive(Debug, Clone)]
pub struct AcplSubstreamState {
    pub alpha_diff: AcplDiffState,
    pub beta_diff: AcplDiffState,
    pub cpe: AcplCpeState,
}

impl AcplSubstreamState {
    pub fn new() -> Self {
        Self {
            alpha_diff: AcplDiffState::new(),
            beta_diff: AcplDiffState::new(),
            cpe: AcplCpeState::new(DecorrelatorId::D0),
        }
    }
}

impl Default for AcplSubstreamState {
    fn default() -> Self {
        Self::new()
    }
}

/// Run the §5.7.7 A-CPL channel-pair synthesis on a mono PCM input
/// (already ASPX-extended) and emit stereo PCM via QMF
/// analysis → A-CPL → QMF synthesis.
///
/// Spec wiring (ETSI TS 103 190-1):
///   * `pcm_in` — mono ASPX-extended PCM, length must be a multiple of
///     64 (one QMF slot = 64 samples).
///   * `cfg` — parsed `acpl_config_1ch()` (PARTIAL or FULL) for the
///     active substream (§4.2.13.1 Table 59).
///   * `data` — parsed `acpl_data_1ch()` (§4.2.13.3 Table 61).
///   * `state` — per-substream state carried across frames.
///
/// Returns `(left, right)` interleaved-friendly PCM buffers, each the
/// same length as `pcm_in`, or `None` if the input length isn't aligned
/// to a QMF slot boundary or the parameters are inconsistent.
pub fn run_acpl_1ch_pcm(
    pcm_in: &[f32],
    cfg: &AcplConfig1ch,
    data: &AcplData1ch,
    state: &mut AcplSubstreamState,
) -> Option<(Vec<f32>, Vec<f32>)> {
    if pcm_in.is_empty() || pcm_in.len() % NUM_QMF_SUBBANDS != 0 {
        return None;
    }
    let n_slots = pcm_in.len() / NUM_QMF_SUBBANDS;
    if n_slots == 0 {
        return None;
    }
    // Forward QMF analysis on the input PCM. `process_block` already
    // returns the per-slot `[(re, im); 64]` columns we need.
    let mut ana = QmfAnalysisBank::new();
    let x0 = ana.process_block(pcm_in);
    // Differential decode + dequantize ALPHA / BETA.
    let alpha_q = differential_decode(&data.alpha1, cfg.num_param_bands, &mut state.alpha_diff);
    let beta_q = differential_decode(&data.beta1, cfg.num_param_bands, &mut state.beta_diff);
    let (alpha_dq, beta_dq) = dequantize_alpha_beta(&alpha_q, &beta_q, cfg.quant_mode);
    if alpha_dq.is_empty() {
        return None;
    }
    // Run the §5.7.7.5 channel-pair element. ASPX_ACPL_2 has x1 == None
    // (single ASPX channel — the spec's "1-channel A-CPL").
    let frame = AcplCpeFrame {
        x0: &x0,
        x1: None,
        alpha_dq: &alpha_dq,
        beta_dq: &beta_dq,
        num_param_bands: cfg.num_param_bands,
        acpl_qmf_band: cfg.qmf_band as u32,
        steep: matches!(
            data.framing.interpolation_type,
            AcplInterpolationType::Steep
        ),
        param_timeslots: &data.framing.param_timeslots,
    };
    let out = run_pseudocode_115_pair(&mut state.cpe, frame);
    // Inverse QMF synthesis for both output channels.
    let mut syn0 = QmfSynthesisBank::new();
    let mut syn1 = QmfSynthesisBank::new();
    let mut left = Vec::with_capacity(pcm_in.len());
    let mut right = Vec::with_capacity(pcm_in.len());
    for ts in 0..n_slots {
        left.extend_from_slice(&syn0.process_slot(&out.z0[ts]));
        right.extend_from_slice(&syn1.process_slot(&out.z1[ts]));
    }
    Some((left, right))
}

/// Run the §5.7.7 A-CPL channel-pair synthesis on a stereo PCM input
/// (M / S channels from a joint-MDCT body, both already ASPX-extended on
/// the M side per `aspx_data_1ch()`) and emit stereo PCM via QMF
/// analysis → A-CPL → QMF synthesis.
///
/// Spec wiring (ETSI TS 103 190-1 §4.2.6.3 ASPX_ACPL_1):
///   * `pcm_m` / `pcm_s` — joint-MDCT M (mid) and S (side) PCM streams,
///     same length, multiple of 64 samples.
///   * `cfg` — parsed `acpl_config_1ch(PARTIAL)` for the active substream.
///   * `data` — parsed `acpl_data_1ch()` (§4.2.13.3 Table 61).
///   * `state` — per-substream state carried across frames.
///
/// In the spec's `acpl_module()` (Pseudocode 116) the low subbands below
/// `acpl_qmf_band` recover `(L, R)` via the inverse-M/S split
/// `z0 = 0.5*(x0+x1)`, `z1 = 0.5*(x0-x1)`; the upper subbands re-mix the
/// decorrelator output `y` (computed from `x0`) into the second channel
/// using the parametric `alpha`/`beta` coefficients. We feed `pcm_m` into
/// `x0` and `pcm_s` into `x1` here, matching the spec's M/S convention.
pub fn run_acpl_1ch_pcm_stereo(
    pcm_m: &[f32],
    pcm_s: &[f32],
    cfg: &AcplConfig1ch,
    data: &AcplData1ch,
    state: &mut AcplSubstreamState,
) -> Option<(Vec<f32>, Vec<f32>)> {
    if pcm_m.is_empty() || pcm_m.len() % NUM_QMF_SUBBANDS != 0 || pcm_m.len() != pcm_s.len() {
        return None;
    }
    let n_slots = pcm_m.len() / NUM_QMF_SUBBANDS;
    if n_slots == 0 {
        return None;
    }
    let mut ana_m = QmfAnalysisBank::new();
    let mut ana_s = QmfAnalysisBank::new();
    let x0 = ana_m.process_block(pcm_m);
    let x1 = ana_s.process_block(pcm_s);
    let alpha_q = differential_decode(&data.alpha1, cfg.num_param_bands, &mut state.alpha_diff);
    let beta_q = differential_decode(&data.beta1, cfg.num_param_bands, &mut state.beta_diff);
    let (alpha_dq, beta_dq) = dequantize_alpha_beta(&alpha_q, &beta_q, cfg.quant_mode);
    if alpha_dq.is_empty() {
        return None;
    }
    let frame = AcplCpeFrame {
        x0: &x0,
        x1: Some(&x1),
        alpha_dq: &alpha_dq,
        beta_dq: &beta_dq,
        num_param_bands: cfg.num_param_bands,
        acpl_qmf_band: cfg.qmf_band as u32,
        steep: matches!(
            data.framing.interpolation_type,
            AcplInterpolationType::Steep
        ),
        param_timeslots: &data.framing.param_timeslots,
    };
    let out = run_pseudocode_115_pair(&mut state.cpe, frame);
    let mut syn0 = QmfSynthesisBank::new();
    let mut syn1 = QmfSynthesisBank::new();
    let mut left = Vec::with_capacity(pcm_m.len());
    let mut right = Vec::with_capacity(pcm_m.len());
    for ts in 0..n_slots {
        left.extend_from_slice(&syn0.process_slot(&out.z0[ts]));
        right.extend_from_slice(&syn1.process_slot(&out.z1[ts]));
    }
    Some((left, right))
}

// =====================================================================
// §5.7.7.6 — top-level helpers wired into the 5_X channel-element
// =====================================================================

use crate::acpl::{AcplConfig2ch, AcplData1ch as AcplData1chTy, AcplData2ch};

/// Five-channel PCM output bundle from the 5_X A-CPL pipelines —
/// (L, R, C, Ls, Rs) in spec ordering.
#[derive(Debug, Clone)]
pub struct Acpl5xPcmOutput {
    pub left: Vec<f32>,
    pub right: Vec<f32>,
    pub centre: Vec<f32>,
    pub left_surround: Vec<f32>,
    pub right_surround: Vec<f32>,
}

/// Per-substream A-CPL state for the 5_X `ASPX_ACPL_1` /
/// `ASPX_ACPL_2` pair pipeline (Pseudocode 117). Composed of the
/// [`Acpl5xPairState`] plus the L/R QMF analysis + per-output QMF
/// synthesis banks needed to round-trip PCM end-to-end.
pub struct Acpl5xPairPcmState {
    pub pair: Acpl5xPairState,
    pub ana_l: QmfAnalysisBank,
    pub ana_r: QmfAnalysisBank,
    pub ana_c: QmfAnalysisBank,
    pub ana_ls: QmfAnalysisBank,
    pub ana_rs: QmfAnalysisBank,
    pub syn_l: QmfSynthesisBank,
    pub syn_r: QmfSynthesisBank,
    pub syn_c: QmfSynthesisBank,
    pub syn_ls: QmfSynthesisBank,
    pub syn_rs: QmfSynthesisBank,
}

impl Acpl5xPairPcmState {
    pub fn new() -> Self {
        Self {
            pair: Acpl5xPairState::new(),
            ana_l: QmfAnalysisBank::new(),
            ana_r: QmfAnalysisBank::new(),
            ana_c: QmfAnalysisBank::new(),
            ana_ls: QmfAnalysisBank::new(),
            ana_rs: QmfAnalysisBank::new(),
            syn_l: QmfSynthesisBank::new(),
            syn_r: QmfSynthesisBank::new(),
            syn_c: QmfSynthesisBank::new(),
            syn_ls: QmfSynthesisBank::new(),
            syn_rs: QmfSynthesisBank::new(),
        }
    }
}

impl Default for Acpl5xPairPcmState {
    fn default() -> Self {
        Self::new()
    }
}

/// Run the §5.7.7.6.1 Pseudocode 117 ASPX_ACPL_1 / ASPX_ACPL_2 5_X
/// pipeline end-to-end at PCM granularity.
///
/// Inputs (every PCM buffer must be the same length and a multiple of
/// 64 samples — one QMF slot per 64 samples):
///
/// * `pcm_l` / `pcm_r` — already-ASPX-extended carrier PCM for the
///   primary pair. Required.
/// * `pcm_c` — centre channel PCM (passthrough → `centre` output).
/// * `pcm_ls` / `pcm_rs` — surround carriers for ASPX_ACPL_1 (`mode ==
///   AspxAcpl1`); `None` for ASPX_ACPL_2.
/// * `cfg_1` / `data_1` — `acpl_config_1ch()` + `acpl_data_1ch()` for
///   the L-side ACplModule (alpha_1 / beta_1).
/// * `cfg_2` / `data_2` — same, for the R-side ACplModule (alpha_2 /
///   beta_2).
/// * `state` — per-substream state (carries decorrelator + ducker IIR
///   state and the ALPHA / BETA differential-decode rolling sums
///   across frames).
///
/// Returns the five-channel PCM bundle, or `None` if the input shape
/// is invalid (mismatched length / not a multiple of 64 / inconsistent
/// surround presence vs. mode).
#[allow(clippy::too_many_arguments)]
pub fn run_acpl_5x_pair_pcm(
    mode: Acpl5xPairMode,
    pcm_l: &[f32],
    pcm_r: &[f32],
    pcm_c: &[f32],
    pcm_ls: Option<&[f32]>,
    pcm_rs: Option<&[f32]>,
    cfg_1: &AcplConfig1ch,
    data_1: &AcplData1chTy,
    cfg_2: &AcplConfig1ch,
    data_2: &AcplData1chTy,
    state: &mut Acpl5xPairPcmState,
) -> Option<Acpl5xPcmOutput> {
    if pcm_l.is_empty() || pcm_l.len() % NUM_QMF_SUBBANDS != 0 {
        return None;
    }
    if pcm_l.len() != pcm_r.len() || pcm_l.len() != pcm_c.len() {
        return None;
    }
    let n_slots = pcm_l.len() / NUM_QMF_SUBBANDS;
    if n_slots == 0 {
        return None;
    }
    // Mode → surround carrier presence consistency check.
    match mode {
        Acpl5xPairMode::AspxAcpl1 => {
            let (ls, rs) = (pcm_ls?, pcm_rs?);
            if ls.len() != pcm_l.len() || rs.len() != pcm_l.len() {
                return None;
            }
        }
        Acpl5xPairMode::AspxAcpl2 => {
            // Surround carriers must be absent in ASPX_ACPL_2 mode.
            if pcm_ls.is_some() || pcm_rs.is_some() {
                return None;
            }
        }
    }
    // QMF analysis on every active input.
    let x0 = state.ana_l.process_block(pcm_l);
    let x1 = state.ana_r.process_block(pcm_r);
    let x2 = state.ana_c.process_block(pcm_c);
    let x3_owned = pcm_ls.map(|p| state.ana_ls.process_block(p));
    let x4_owned = pcm_rs.map(|p| state.ana_rs.process_block(p));

    // Differential-decode the two acpl_data_1ch parameter sets.
    let alpha1_q = differential_decode(
        &data_1.alpha1,
        cfg_1.num_param_bands,
        &mut state.pair.alpha1_diff,
    );
    let beta1_q = differential_decode(
        &data_1.beta1,
        cfg_1.num_param_bands,
        &mut state.pair.beta1_diff,
    );
    let (alpha1_dq, beta1_dq) = dequantize_alpha_beta(&alpha1_q, &beta1_q, cfg_1.quant_mode);
    let alpha2_q = differential_decode(
        &data_2.alpha1,
        cfg_2.num_param_bands,
        &mut state.pair.alpha2_diff,
    );
    let beta2_q = differential_decode(
        &data_2.beta1,
        cfg_2.num_param_bands,
        &mut state.pair.beta2_diff,
    );
    let (alpha2_dq, beta2_dq) = dequantize_alpha_beta(&alpha2_q, &beta2_q, cfg_2.quant_mode);
    if alpha1_dq.is_empty() || alpha2_dq.is_empty() {
        return None;
    }
    // Pseudocode 117 wrapper over Pseudocode 115 / 116.
    let frame = Acpl5xPairFrame {
        mode,
        x0: &x0,
        x1: &x1,
        x2: &x2,
        x3: x3_owned.as_deref(),
        x4: x4_owned.as_deref(),
        alpha_1_dq: &alpha1_dq,
        beta_1_dq: &beta1_dq,
        alpha_2_dq: &alpha2_dq,
        beta_2_dq: &beta2_dq,
        num_param_bands: cfg_1.num_param_bands,
        // 5.X multichannel paths set acpl_qmf_band = 0 per §5.7.7.6.1.
        acpl_qmf_band: 0,
        steep_1: matches!(
            data_1.framing.interpolation_type,
            AcplInterpolationType::Steep
        ),
        steep_2: matches!(
            data_2.framing.interpolation_type,
            AcplInterpolationType::Steep
        ),
        param_timeslots_1: &data_1.framing.param_timeslots,
        param_timeslots_2: &data_2.framing.param_timeslots,
    };
    let out = run_pseudocode_117_5x(&mut state.pair, frame);

    // QMF synthesis on each output channel.
    let mut left = Vec::with_capacity(pcm_l.len());
    let mut right = Vec::with_capacity(pcm_l.len());
    let mut centre = Vec::with_capacity(pcm_l.len());
    let mut left_surround = Vec::with_capacity(pcm_l.len());
    let mut right_surround = Vec::with_capacity(pcm_l.len());
    for ts in 0..n_slots {
        left.extend_from_slice(&state.syn_l.process_slot(&out.z0[ts]));
        right.extend_from_slice(&state.syn_r.process_slot(&out.z2[ts]));
        centre.extend_from_slice(&state.syn_c.process_slot(&out.z4[ts]));
        left_surround.extend_from_slice(&state.syn_ls.process_slot(&out.z1[ts]));
        right_surround.extend_from_slice(&state.syn_rs.process_slot(&out.z3[ts]));
    }
    Some(Acpl5xPcmOutput {
        left,
        right,
        centre,
        left_surround,
        right_surround,
    })
}

/// Per-substream A-CPL state for the 5_X `ASPX_ACPL_3` multichannel
/// pipeline (Pseudocode 118). Bundles the [`AcplMchState`] (D0/D1/D2 +
/// 3x ducker + per-pset prev gammas) with the L/R QMF analysis +
/// per-output QMF synthesis banks plus the alpha/beta/beta3/gamma
/// differential-decode rolling state.
pub struct Acpl5xMchPcmState {
    pub mch: AcplMchState,
    pub ana_l: QmfAnalysisBank,
    pub ana_r: QmfAnalysisBank,
    pub ana_c: QmfAnalysisBank,
    pub syn_l: QmfSynthesisBank,
    pub syn_r: QmfSynthesisBank,
    pub syn_c: QmfSynthesisBank,
    pub syn_ls: QmfSynthesisBank,
    pub syn_rs: QmfSynthesisBank,
    pub alpha1_diff: AcplDiffState,
    pub alpha2_diff: AcplDiffState,
    pub beta1_diff: AcplDiffState,
    pub beta2_diff: AcplDiffState,
    pub beta3_diff: AcplDiffState,
    pub gamma_diff: [AcplDiffState; 6],
}

impl Acpl5xMchPcmState {
    pub fn new() -> Self {
        Self {
            mch: AcplMchState::new(),
            ana_l: QmfAnalysisBank::new(),
            ana_r: QmfAnalysisBank::new(),
            ana_c: QmfAnalysisBank::new(),
            syn_l: QmfSynthesisBank::new(),
            syn_r: QmfSynthesisBank::new(),
            syn_c: QmfSynthesisBank::new(),
            syn_ls: QmfSynthesisBank::new(),
            syn_rs: QmfSynthesisBank::new(),
            alpha1_diff: AcplDiffState::new(),
            alpha2_diff: AcplDiffState::new(),
            beta1_diff: AcplDiffState::new(),
            beta2_diff: AcplDiffState::new(),
            beta3_diff: AcplDiffState::new(),
            gamma_diff: [
                AcplDiffState::new(),
                AcplDiffState::new(),
                AcplDiffState::new(),
                AcplDiffState::new(),
                AcplDiffState::new(),
                AcplDiffState::new(),
            ],
        }
    }
}

impl Default for Acpl5xMchPcmState {
    fn default() -> Self {
        Self::new()
    }
}

/// Run the §5.7.7.6.2 Pseudocode 118 ASPX_ACPL_3 5_X pipeline
/// end-to-end at PCM granularity.
///
/// `pcm_l` / `pcm_r` are the two A-CPL carrier streams (already
/// ASPX-extended); `pcm_c` is the centre channel passthrough. All
/// three buffers must share the same length, and that length must be a
/// multiple of 64 samples.
///
/// `cfg` is the parsed `acpl_config_2ch()` (§4.2.13.2 Table 60); `data`
/// is the parsed `acpl_data_2ch()` (§4.2.13.4 Table 62) which carries
/// (alpha1, alpha2, beta1, beta2, beta3, gamma1..gamma6) Huffman
/// parameter sets. `state` is the per-substream ACPL state (carries
/// the D0/D1/D2 + ducker state and the differential-decode rolling
/// sums across frames).
pub fn run_acpl_5x_mch_pcm(
    pcm_l: &[f32],
    pcm_r: &[f32],
    pcm_c: &[f32],
    cfg: &AcplConfig2ch,
    data: &AcplData2ch,
    state: &mut Acpl5xMchPcmState,
) -> Option<Acpl5xPcmOutput> {
    if pcm_l.is_empty() || pcm_l.len() % NUM_QMF_SUBBANDS != 0 {
        return None;
    }
    if pcm_l.len() != pcm_r.len() || pcm_l.len() != pcm_c.len() {
        return None;
    }
    let n_slots = pcm_l.len() / NUM_QMF_SUBBANDS;
    if n_slots == 0 {
        return None;
    }
    // QMF analysis on the two carriers + the centre passthrough.
    let x0 = state.ana_l.process_block(pcm_l);
    let x1 = state.ana_r.process_block(pcm_r);
    let x2 = state.ana_c.process_block(pcm_c);
    // Differential-decode all 11 parameter sets.
    let nb = cfg.num_param_bands;
    let alpha1_q = differential_decode(&data.alpha1, nb, &mut state.alpha1_diff);
    let alpha2_q = differential_decode(&data.alpha2, nb, &mut state.alpha2_diff);
    let beta1_q = differential_decode(&data.beta1, nb, &mut state.beta1_diff);
    let beta2_q = differential_decode(&data.beta2, nb, &mut state.beta2_diff);
    let beta3_q = differential_decode(&data.beta3, nb, &mut state.beta3_diff);
    let g1q = differential_decode(&data.gamma1, nb, &mut state.gamma_diff[0]);
    let g2q = differential_decode(&data.gamma2, nb, &mut state.gamma_diff[1]);
    let g3q = differential_decode(&data.gamma3, nb, &mut state.gamma_diff[2]);
    let g4q = differential_decode(&data.gamma4, nb, &mut state.gamma_diff[3]);
    let g5q = differential_decode(&data.gamma5, nb, &mut state.gamma_diff[4]);
    let g6q = differential_decode(&data.gamma6, nb, &mut state.gamma_diff[5]);
    let (alpha1_dq, beta1_dq) = dequantize_alpha_beta(&alpha1_q, &beta1_q, cfg.quant_mode_0);
    let (alpha2_dq, beta2_dq) = dequantize_alpha_beta(&alpha2_q, &beta2_q, cfg.quant_mode_0);
    let beta3_dq = dequantize_beta3(&beta3_q, cfg.quant_mode_0);
    let g1_dq = dequantize_gamma(&g1q, cfg.quant_mode_1);
    let g2_dq = dequantize_gamma(&g2q, cfg.quant_mode_1);
    let g3_dq = dequantize_gamma(&g3q, cfg.quant_mode_1);
    let g4_dq = dequantize_gamma(&g4q, cfg.quant_mode_1);
    let g5_dq = dequantize_gamma(&g5q, cfg.quant_mode_1);
    let g6_dq = dequantize_gamma(&g6q, cfg.quant_mode_1);
    if alpha1_dq.is_empty() {
        return None;
    }
    let frame = AcplMchFrame {
        x0: &x0,
        x1: &x1,
        x2: &x2,
        alpha_1_dq: &alpha1_dq,
        alpha_2_dq: &alpha2_dq,
        beta_1_dq: &beta1_dq,
        beta_2_dq: &beta2_dq,
        beta_3_dq: &beta3_dq,
        g1_dq: &g1_dq,
        g2_dq: &g2_dq,
        g3_dq: &g3_dq,
        g4_dq: &g4_dq,
        g5_dq: &g5_dq,
        g6_dq: &g6_dq,
        num_param_bands: nb,
        steep: matches!(
            data.framing.interpolation_type,
            AcplInterpolationType::Steep
        ),
        param_timeslots: &data.framing.param_timeslots,
    };
    let out = run_pseudocode_118_5x(&mut state.mch, frame);
    let mut left = Vec::with_capacity(pcm_l.len());
    let mut right = Vec::with_capacity(pcm_l.len());
    let mut centre = Vec::with_capacity(pcm_l.len());
    let mut left_surround = Vec::with_capacity(pcm_l.len());
    let mut right_surround = Vec::with_capacity(pcm_l.len());
    for ts in 0..n_slots {
        left.extend_from_slice(&state.syn_l.process_slot(&out.z0[ts]));
        right.extend_from_slice(&state.syn_r.process_slot(&out.z2[ts]));
        centre.extend_from_slice(&state.syn_c.process_slot(&out.z4[ts]));
        left_surround.extend_from_slice(&state.syn_ls.process_slot(&out.z1[ts]));
        right_surround.extend_from_slice(&state.syn_rs.process_slot(&out.z3[ts]));
    }
    Some(Acpl5xPcmOutput {
        left,
        right,
        centre,
        left_surround,
        right_surround,
    })
}

// =====================================================================
// Tests
// =====================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::acpl::AcplHuffParam;

    // ---------------- §5.7.7.7 dequantisation tables -----------------

    #[test]
    fn alpha_dq_fine_anchors_table_203() {
        // Table 203 anchors: index 0 = -2.0, index 16 = 0.0, index 32 = +2.0
        assert_eq!(ALPHA_DQ_FINE[0], -2.000000);
        assert_eq!(ALPHA_DQ_FINE[16], 0.000000);
        assert_eq!(ALPHA_DQ_FINE[32], 2.000000);
        // Anti-symmetry around the centre: alpha[16+k] = -alpha[16-k].
        for k in 1..=16 {
            let lo = ALPHA_DQ_FINE[16 - k];
            let hi = ALPHA_DQ_FINE[16 + k];
            assert!((lo + hi).abs() < 1e-6, "k={k} lo={lo} hi={hi}");
        }
    }

    #[test]
    fn alpha_dq_coarse_anchors_table_205() {
        assert_eq!(ALPHA_DQ_COARSE[0], -2.000000);
        assert_eq!(ALPHA_DQ_COARSE[8], 0.000000);
        assert_eq!(ALPHA_DQ_COARSE[16], 2.000000);
        for k in 1..=8 {
            let lo = ALPHA_DQ_COARSE[8 - k];
            let hi = ALPHA_DQ_COARSE[8 + k];
            assert!((lo + hi).abs() < 1e-6, "k={k} lo={lo} hi={hi}");
        }
    }

    #[test]
    fn ibeta_fine_table_203_column2() {
        assert_eq!(IBETA_FINE[0], 0);
        assert_eq!(IBETA_FINE[8], 8);
        assert_eq!(IBETA_FINE[16], 0);
        assert_eq!(IBETA_FINE[24], 8);
        assert_eq!(IBETA_FINE[32], 0);
    }

    #[test]
    fn ibeta_coarse_table_205_column2() {
        assert_eq!(IBETA_COARSE[0], 0);
        assert_eq!(IBETA_COARSE[4], 4);
        assert_eq!(IBETA_COARSE[8], 0);
        assert_eq!(IBETA_COARSE[12], 4);
        assert_eq!(IBETA_COARSE[16], 0);
    }

    #[test]
    fn beta_dq_fine_anchors_table_204() {
        // beta_q=0 row is all zeros.
        for col in 0..9 {
            assert_eq!(BETA_DQ_FINE[0][col], 0.0);
        }
        // Anchor: beta_q=8, ibeta=0 → 4.0; ibeta=8 → 1.0.
        assert_eq!(BETA_DQ_FINE[8][0], 4.0);
        assert_eq!(BETA_DQ_FINE[8][8], 1.0);
        // Strict monotone-decrease across ibeta for any non-zero beta_q.
        for q in 1..=8 {
            for c in 1..9 {
                assert!(
                    BETA_DQ_FINE[q][c] < BETA_DQ_FINE[q][c - 1],
                    "beta_q={q} col={c}"
                );
            }
        }
    }

    #[test]
    fn beta_dq_coarse_anchors_table_206() {
        assert_eq!(BETA_DQ_COARSE[0][0], 0.0);
        assert_eq!(BETA_DQ_COARSE[4][0], 4.0);
        assert_eq!(BETA_DQ_COARSE[4][4], 1.0);
        for q in 1..=4 {
            for c in 1..5 {
                assert!(
                    BETA_DQ_COARSE[q][c] < BETA_DQ_COARSE[q][c - 1],
                    "beta_q={q} col={c}"
                );
            }
        }
    }

    #[test]
    fn beta3_and_gamma_deltas_match_tables_207_208() {
        assert_eq!(beta3_delta(AcplQuantMode::Fine), 0.125);
        assert_eq!(beta3_delta(AcplQuantMode::Coarse), 0.25);
        assert!((gamma_delta(AcplQuantMode::Fine) - 1638.0 / 16384.0).abs() < 1e-9);
        assert!((gamma_delta(AcplQuantMode::Coarse) - 3276.0 / 16384.0).abs() < 1e-9);
    }

    #[test]
    fn dequantize_alpha_fine_round_trips_through_signed_index() {
        // alpha_q = 0 (Huffman F0 cb_off=16 → recovered i32=0) → lane
        // 16 → +0.0.
        let (a, ib) = dequantize_alpha_index(AcplQuantMode::Fine, 0);
        assert_eq!(a, 0.0);
        assert_eq!(ib, 0);
        // alpha_q = -16 (lane 0) → -2.0.
        let (a, ib) = dequantize_alpha_index(AcplQuantMode::Fine, -16);
        assert_eq!(a, -2.000000);
        assert_eq!(ib, 0);
        // alpha_q = +8 (lane 24) → +1.0.
        let (a, ib) = dequantize_alpha_index(AcplQuantMode::Fine, 8);
        assert_eq!(a, 1.000000);
        assert_eq!(ib, 8);
    }

    #[test]
    fn dequantize_beta_fine_uses_ibeta_column() {
        // beta_q=+1, ibeta=0 → +0.2375.
        let v = dequantize_beta_index(AcplQuantMode::Fine, 1, 0);
        assert!((v - 0.2375).abs() < 1e-6);
        // beta_q=-1, ibeta=0 → -0.2375.
        let v = dequantize_beta_index(AcplQuantMode::Fine, -1, 0);
        assert!((v + 0.2375).abs() < 1e-6);
        // beta_q=+8, ibeta=8 → +1.0.
        let v = dequantize_beta_index(AcplQuantMode::Fine, 8, 8);
        assert!((v - 1.0).abs() < 1e-6);
    }

    // ----------------- §5.7.7.7 differential decode ------------------

    #[test]
    fn differential_decode_freq_accumulates_from_seed() {
        // DIFF_FREQ: row[0]=values[0], row[i]=row[i-1]+values[i].
        let p = AcplHuffParam {
            values: vec![5, 1, -2, 3],
            direction_time: false,
        };
        let mut st = AcplDiffState::new();
        let out = differential_decode(&[p], 4, &mut st);
        assert_eq!(out, vec![vec![5, 6, 4, 7]]);
        assert_eq!(st.q_prev, vec![5, 6, 4, 7]);
    }

    #[test]
    fn differential_decode_time_uses_prev_then_carries() {
        // First set DIFF_FREQ → seed q_prev. Second set DIFF_TIME → adds
        // to q_prev band-by-band.
        let p1 = AcplHuffParam {
            values: vec![1, 2, 3],
            direction_time: false,
        };
        let p2 = AcplHuffParam {
            values: vec![10, -1, 0],
            direction_time: true,
        };
        let mut st = AcplDiffState::new();
        let out = differential_decode(&[p1, p2], 3, &mut st);
        // p1 → [1, 3, 6]
        // p2 (DIFF_TIME) → [1+10, 3-1, 6+0] = [11, 2, 6]
        assert_eq!(out, vec![vec![1, 3, 6], vec![11, 2, 6]]);
        assert_eq!(st.q_prev, vec![11, 2, 6]);
    }

    #[test]
    fn differential_decode_carries_across_frames() {
        // Frame 1 sets q_prev = [4, 5]. Frame 2 starts with DIFF_TIME
        // and should pick up q_prev from frame 1.
        let mut st = AcplDiffState::new();
        let p1 = AcplHuffParam {
            values: vec![4, 1],
            direction_time: false,
        };
        let _ = differential_decode(&[p1], 2, &mut st);
        assert_eq!(st.q_prev, vec![4, 5]);
        let p2 = AcplHuffParam {
            values: vec![1, -2],
            direction_time: true,
        };
        let out2 = differential_decode(&[p2], 2, &mut st);
        assert_eq!(out2, vec![vec![5, 3]]);
        assert_eq!(st.q_prev, vec![5, 3]);
    }

    // -------------- §5.7.7.7 dequantize_alpha_beta -------------------

    #[test]
    fn dequantize_alpha_beta_returns_two_synced_matrices() {
        // 1 param set, 2 bands. alpha_q = [0, 8] (fine, lanes 16+0=16
        // and 16+8=24 → 0.0 and 1.0; ibetas 0 and 8). beta_q = [+1, -1]
        // → +0.2375 (col 0), -0.0593750 (col 8).
        let alpha_q = vec![vec![0i32, 8]];
        let beta_q = vec![vec![1i32, -1]];
        let (a, b) = dequantize_alpha_beta(&alpha_q, &beta_q, AcplQuantMode::Fine);
        assert_eq!(a.len(), 1);
        assert_eq!(a[0].len(), 2);
        assert!((a[0][0] - 0.0).abs() < 1e-6);
        assert!((a[0][1] - 1.0).abs() < 1e-6);
        assert!((b[0][0] - 0.2375).abs() < 1e-6);
        assert!((b[0][1] + 0.0593750).abs() < 1e-6);
    }

    // ---------------- §5.7.7.3 interpolate ---------------------------

    #[test]
    fn interpolate_smooth_one_param_set_linear_ramp() {
        // 1 param set, prev=0.0, p=4.0, num_ts=4 → ts=0 → 1.0, ts=3 → 4.0
        let p_set = vec![vec![4.0f32; NUM_QMF_SUBBANDS]];
        let prev = vec![0.0f32; NUM_QMF_SUBBANDS];
        let inp = InterpInputs {
            by_pset: &p_set,
            prev: &prev,
        };
        for ts in 0..4u32 {
            let v = interpolate(&inp, 1, 0, ts, 4, false, &[]);
            let expected = (ts + 1) as f32;
            assert!(
                (v - expected).abs() < 1e-6,
                "ts={ts} v={v} expected={expected}"
            );
        }
    }

    #[test]
    fn interpolate_steep_falls_to_constants() {
        // 1 param set, steep, ts < timeslot[0] → prev, else current.
        let p_set = vec![vec![5.0f32; NUM_QMF_SUBBANDS]];
        let prev = vec![1.0f32; NUM_QMF_SUBBANDS];
        let inp = InterpInputs {
            by_pset: &p_set,
            prev: &prev,
        };
        // boundary at ts=2.
        assert_eq!(interpolate(&inp, 1, 0, 0, 4, true, &[2]), 1.0);
        assert_eq!(interpolate(&inp, 1, 0, 1, 4, true, &[2]), 1.0);
        assert_eq!(interpolate(&inp, 1, 0, 2, 4, true, &[2]), 5.0);
        assert_eq!(interpolate(&inp, 1, 0, 3, 4, true, &[2]), 5.0);
    }

    #[test]
    fn interpolate_smooth_two_sets_meets_at_midpoint() {
        // 2 sets: prev=0, p0=4, p1=8, num_ts=8 → ts_2=4.
        // ts in [0,4): linear 0→4 over ts_2=4 → ts=0 → 1, ts=3 → 4.
        // ts in [4,8): linear 4→8 over (8-4)=4 → ts=4 → 5, ts=7 → 8.
        let p_set = vec![
            vec![4.0f32; NUM_QMF_SUBBANDS],
            vec![8.0f32; NUM_QMF_SUBBANDS],
        ];
        let prev = vec![0.0f32; NUM_QMF_SUBBANDS];
        let inp = InterpInputs {
            by_pset: &p_set,
            prev: &prev,
        };
        for ts in 0..8u32 {
            let v = interpolate(&inp, 2, 0, ts, 8, false, &[]);
            let expected = (ts + 1) as f32;
            assert!(
                (v - expected).abs() < 1e-5,
                "ts={ts} v={v} expected={expected}"
            );
        }
    }

    // ---------------- expand_pb_to_sb -------------------------------

    #[test]
    fn expand_pb_to_sb_preserves_first_pb_for_low_subbands_15() {
        // Table 197 column 15: sb=0 → pb=0, sb=8 → pb=8, sb=63 → pb=14.
        let pb = vec![vec![
            0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0,
        ]];
        let sb = expand_pb_to_sb(&pb, 15);
        assert_eq!(sb[0][0], 0.0);
        assert_eq!(sb[0][8], 8.0);
        assert_eq!(sb[0][9], 9.0);
        assert_eq!(sb[0][14], 11.0); // sb=14 → pb=11 (rows 14-17 → 11)
        assert_eq!(sb[0][63], 14.0);
    }

    // ----------------- §5.7.7.4.2 Decorrelator -----------------------

    #[test]
    fn region_delay_filter_length_match_table_198() {
        assert_eq!(region_delay(0), 7);
        assert_eq!(region_filter_length(0), 7);
        assert_eq!(region_delay(6), 7);
        assert_eq!(region_filter_length(6), 7);
        assert_eq!(region_delay(7), 10);
        assert_eq!(region_filter_length(7), 4);
        assert_eq!(region_delay(22), 10);
        assert_eq!(region_filter_length(22), 4);
        assert_eq!(region_delay(23), 12);
        assert_eq!(region_filter_length(23), 2);
        assert_eq!(region_delay(63), 12);
        assert_eq!(region_filter_length(63), 2);
    }

    #[test]
    fn region_coeffs_match_tables_199_200_201_first_row() {
        assert_eq!(region_coeffs(DecorrelatorId::D0, 0)[0], 1.0);
        assert!((region_coeffs(DecorrelatorId::D0, 0)[1] - 0.5306).abs() < 1e-12);
        assert!((region_coeffs(DecorrelatorId::D1, 7)[1] - 0.0425).abs() < 1e-12);
        assert!((region_coeffs(DecorrelatorId::D2, 23)[1] + 0.6057).abs() < 1e-12);
    }

    #[test]
    fn input_signal_modifier_zero_input_zero_output() {
        let mut m = InputSignalModifier::new(DecorrelatorId::D0);
        for sb in 0..NUM_QMF_SUBBANDS as u32 {
            let y = m.process_sample(sb, (0.0, 0.0));
            assert_eq!(y, (0.0, 0.0));
        }
    }

    #[test]
    fn input_signal_modifier_impulse_eventually_yields_nonzero() {
        // Push an impulse at ts=0 into sb=0 and run for >7+7=14 slots.
        // The IIR response should produce non-zero output by ts ≥ delay.
        let mut m = InputSignalModifier::new(DecorrelatorId::D0);
        let mut energy = 0.0f64;
        for ts in 0..32 {
            let x = if ts == 0 { (1.0f32, 0.0) } else { (0.0, 0.0) };
            let y = m.process_sample(0, x);
            energy += (y.0 as f64).powi(2) + (y.1 as f64).powi(2);
        }
        assert!(energy > 0.0, "decorrelator should emit non-zero IIR tail");
    }

    // ----------------- §5.7.7.4.3 Transient ducker -------------------

    #[test]
    fn transient_ducker_passes_silence_unmodified() {
        let mut d = TransientDucker::new();
        let p_e = [0.0f32; ACPL_MAX_NUM_PARAM_BANDS];
        let g = d.update(&p_e);
        for v in g.iter() {
            assert_eq!(*v, 1.0, "silence should yield gain 1.0 (no transient)");
        }
    }

    #[test]
    fn transient_ducker_attenuates_after_peak() {
        // Push a unit-energy spike followed by zero — the smoothed
        // decay should trigger ducking on the second slot.
        let mut d = TransientDucker::new();
        let mut spike = [0.0f32; ACPL_MAX_NUM_PARAM_BANDS];
        spike[0] = 1.0;
        let _ = d.update(&spike);
        // Now silence — peak_decay tail still > smooth, gamma branch
        // should fire and pull duck_gain[0] below 1.0.
        let zeros = [0.0f32; ACPL_MAX_NUM_PARAM_BANDS];
        let g = d.update(&zeros);
        assert!(g[0] < 1.0, "ducker should attenuate the post-peak slot");
        assert!(g[0] > 0.0);
    }

    #[test]
    fn compute_p_energy_aggregates_per_param_band() {
        // Subband 0 → pb 0 in 15-band config. Magnitude 3 at sb 0 →
        // p_energy[0] = 9.
        let mut x = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        x[0] = (3.0, 0.0);
        x[1] = (0.0, 4.0);
        let e = compute_p_energy(&x, 15);
        assert_eq!(e[0], 9.0);
        assert_eq!(e[1], 16.0);
        for pb in 2..ACPL_MAX_NUM_PARAM_BANDS {
            assert_eq!(e[pb], 0.0);
        }
    }

    #[test]
    fn apply_transient_ducker_scales_per_pb() {
        let x = [(2.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        let mut g = [1.0f32; ACPL_MAX_NUM_PARAM_BANDS];
        g[0] = 0.5;
        let out = apply_transient_ducker(&x, &g, 15);
        // sb 0 maps to pb 0 (gain 0.5) → 1.0, sb 1 maps to pb 1 (gain
        // 1.0) → 2.0.
        assert_eq!(out[0].0, 1.0);
        assert_eq!(out[1].0, 2.0);
    }

    // ----------------- §5.7.7.5 acpl_module --------------------------

    /// Synthetic stereo A-CPL frame: small sine signal in x0, zero in x1
    /// (ASPX_ACPL_2 mode), modest alpha/beta values, single param set.
    /// After running the synthesis we expect:
    ///   1) The output to differ from the input (cross-channel mixing
    ///      happened above acpl_qmf_band).
    ///   2) Below acpl_qmf_band the output is the M/S split of x0/x1.
    ///   3) The output stays within reasonable bounds (no NaN / inf).
    #[test]
    fn acpl_module_mixes_channels_above_qmf_band_aspx_acpl_2() {
        let num_ts = 32usize;
        let num_pb = 15u32;
        // Build x0 with a tone in subband 12 and 30, x1 silent.
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let zero = [(0.0f32, 0.0f32); NUM_QMF_SUBBANDS];
        for ts in 0..num_ts {
            let phase = (ts as f32) * 0.5;
            x0[ts][12] = (phase.cos(), phase.sin());
            x0[ts][30] = (0.5 * phase.cos(), 0.5 * phase.sin());
        }
        // Synthetic decorrelator output y = x0 (just for the math test).
        let y: Vec<_> = x0.clone();
        // alpha = +0.5 across bands, beta = +0.5 across bands.
        let alpha_dq = vec![vec![0.5f32; num_pb as usize]];
        let beta_dq = vec![vec![0.5f32; num_pb as usize]];
        let frame = AcplCpeFrame {
            x0: &x0,
            x1: None,
            alpha_dq: &alpha_dq,
            beta_dq: &beta_dq,
            num_param_bands: num_pb,
            acpl_qmf_band: 8, // M/S below sb=8, mixed above
            steep: false,
            param_timeslots: &[],
        };
        let out = acpl_module(&frame, &y);
        assert_eq!(out.z0.len(), num_ts);
        assert_eq!(out.z1.len(), num_ts);
        // Above acpl_qmf_band, with x1=0 and y=x0, the formula is
        //   z0 = 0.5 * (x0 * (1+a) + x0 * b) = 0.5 * x0 * (1+a+b)
        // With smooth interp, num_pset=1, prev=0, p=0.5:
        //   interp(ts) = (ts+1)/num_ts * 0.5
        // At ts=0 → interp = 0.5/32 ≈ 0.0156, scale = 0.5*(1 + 2*0.0156)
        //          = 0.5156 → z0 = 0.5156 * x0 ≠ x0.
        // At ts=num_ts-1 → interp = 0.5, scale = 1.0 → z0 = x0 (boundary).
        let early = 0u32;
        let interp_early = 0.5_f32 * ((early + 1) as f32) / (num_ts as f32);
        let scale_early = 0.5_f32 * (1.0 + 2.0 * interp_early);
        let (z0r, z0i) = out.z0[early as usize][12];
        let (x0r, x0i) = x0[early as usize][12];
        let exp_re = scale_early * x0r;
        let exp_im = scale_early * x0i;
        assert!(
            (z0r - exp_re).abs() < 1e-5,
            "z0r {z0r} vs {exp_re} (scale {scale_early})"
        );
        assert!((z0i - exp_im).abs() < 1e-5, "z0i {z0i} vs {exp_im}");
        // Demonstrate divergence: at ts=0 z0 ≠ x0 because scale ≠ 1.0.
        assert!(
            (z0r - x0r).abs() > 1e-4 || (z0i - x0i).abs() > 1e-4,
            "z0[early][12] should differ from x0 (mixing scale != 1.0) — got z0=({z0r},{z0i}) x0=({x0r},{x0i}) scale={scale_early}"
        );
        // Below acpl_qmf_band (sb < 8): with x1 = 0, z0 = 0.5*x0,
        // z1 = 0.5*x0.
        for sb in 0..8 {
            for ts in 0..num_ts {
                let (z0r, z0i) = out.z0[ts][sb];
                let (z1r, z1i) = out.z1[ts][sb];
                assert!((z0r - 0.5 * x0[ts][sb].0).abs() < 1e-6);
                assert!((z0i - 0.5 * x0[ts][sb].1).abs() < 1e-6);
                assert!((z1r - 0.5 * x0[ts][sb].0).abs() < 1e-6);
                assert!((z1i - 0.5 * x0[ts][sb].1).abs() < 1e-6);
            }
        }
        // No NaN / Inf in output.
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                assert!(out.z0[ts][sb].0.is_finite());
                assert!(out.z0[ts][sb].1.is_finite());
                assert!(out.z1[ts][sb].0.is_finite());
                assert!(out.z1[ts][sb].1.is_finite());
            }
        }
        // Silence the unused y matrix to suppress warnings.
        let _ = zero;
    }

    /// ASPX_ACPL_1: x1 ≠ 0 — stereo input. Verify the M/S split below
    /// `acpl_qmf_band` correctly produces (x0+x1)/2 and (x0-x1)/2.
    #[test]
    fn acpl_module_below_qmf_band_is_mid_side_split() {
        let num_ts = 8usize;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            x0[ts][2] = (1.0, 0.0);
            x1[ts][2] = (0.0, 1.0);
        }
        let y = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let alpha_dq = vec![vec![0.0f32; 15]];
        let beta_dq = vec![vec![0.0f32; 15]];
        let frame = AcplCpeFrame {
            x0: &x0,
            x1: Some(&x1),
            alpha_dq: &alpha_dq,
            beta_dq: &beta_dq,
            num_param_bands: 15,
            acpl_qmf_band: 4,
            steep: false,
            param_timeslots: &[],
        };
        let out = acpl_module(&frame, &y);
        for ts in 0..num_ts {
            let z0 = out.z0[ts][2];
            let z1 = out.z1[ts][2];
            // (1+0j + 0+1j)/2 = (0.5, 0.5)
            assert!((z0.0 - 0.5).abs() < 1e-6);
            assert!((z0.1 - 0.5).abs() < 1e-6);
            // (1+0j - (0+1j))/2 = (0.5, -0.5)
            assert!((z1.0 - 0.5).abs() < 1e-6);
            assert!((z1.1 + 0.5).abs() < 1e-6);
        }
    }

    /// End-to-end check: run the full Pseudocode 115 pipeline (decorr
    /// + ducker + acpl_module) on a non-trivial frame. Verify nothing
    ///   blows up and the output differs from passthrough.
    #[test]
    fn run_pseudocode_115_pair_end_to_end() {
        let num_ts = 16usize;
        let num_pb = 9u32;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            let phase = (ts as f32) * 0.3;
            for sb in 0..32 {
                x0[ts][sb] = (
                    0.1 * (phase + sb as f32 * 0.1).cos(),
                    0.1 * (phase + sb as f32 * 0.1).sin(),
                );
            }
        }
        let alpha_dq = vec![vec![0.3f32; num_pb as usize]];
        let beta_dq = vec![vec![0.3f32; num_pb as usize]];
        let mut state = AcplCpeState::new(DecorrelatorId::D0);
        let frame = AcplCpeFrame {
            x0: &x0,
            x1: None,
            alpha_dq: &alpha_dq,
            beta_dq: &beta_dq,
            num_param_bands: num_pb,
            acpl_qmf_band: 4,
            steep: false,
            param_timeslots: &[],
        };
        let out = run_pseudocode_115_pair(&mut state, frame);
        assert_eq!(out.z0.len(), num_ts);
        assert_eq!(out.z1.len(), num_ts);
        // Output should differ from the passthrough below acpl_qmf_band
        // (we doubled x0 inside).
        let mut diff_energy = 0.0f64;
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                assert!(out.z0[ts][sb].0.is_finite());
                assert!(out.z0[ts][sb].1.is_finite());
                assert!(out.z1[ts][sb].0.is_finite());
                assert!(out.z1[ts][sb].1.is_finite());
                let dr = out.z0[ts][sb].0 - x0[ts][sb].0;
                let di = out.z0[ts][sb].1 - x0[ts][sb].1;
                diff_energy += (dr as f64).powi(2) + (di as f64).powi(2);
            }
        }
        assert!(diff_energy > 0.0, "output should diverge from x0");
        // After a frame, prev arrays should be populated.
        assert_eq!(state.alpha_prev_sb.len(), NUM_QMF_SUBBANDS);
        assert_eq!(state.beta_prev_sb.len(), NUM_QMF_SUBBANDS);
        // alpha_dq=0.3 across pb → expand_pb_to_sb fills sb with 0.3.
        for sb in 0..NUM_QMF_SUBBANDS {
            assert!((state.alpha_prev_sb[sb] - 0.3).abs() < 1e-6);
            assert!((state.beta_prev_sb[sb] - 0.3).abs() < 1e-6);
        }
    }

    /// End-to-end: alpha=0, beta=0 with x1 = x0 → above acpl_qmf_band
    /// the formula collapses to z0 = 0.5*x0in = x0 (since x0in = 2*x0).
    #[test]
    fn acpl_module_zero_params_passthrough_above_qmf_band() {
        let num_ts = 4usize;
        let mut x0in = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            x0in[ts][20] = (2.0, 1.0); // already-doubled x0
        }
        let y = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let alpha_dq = vec![vec![0.0f32; 15]];
        let beta_dq = vec![vec![0.0f32; 15]];
        let frame = AcplCpeFrame {
            x0: &x0in,
            x1: None,
            alpha_dq: &alpha_dq,
            beta_dq: &beta_dq,
            num_param_bands: 15,
            acpl_qmf_band: 8,
            steep: false,
            param_timeslots: &[],
        };
        let out = acpl_module(&frame, &y);
        // Above qmf_band (sb=20), a=b=0, y=0 → z0 = 0.5*x0*(1+0) = 0.5*x0in
        // = (1.0, 0.5)
        for ts in 0..num_ts {
            let z = out.z0[ts][20];
            assert!((z.0 - 1.0).abs() < 1e-6);
            assert!((z.1 - 0.5).abs() < 1e-6);
            // z1 = 0.5*x0*(1-0) = 0.5*x0 = (1.0, 0.5)
            let z1 = out.z1[ts][20];
            assert!((z1.0 - 1.0).abs() < 1e-6);
            assert!((z1.1 - 0.5).abs() < 1e-6);
        }
    }

    // ----------------- run_acpl_1ch_pcm — PCM end-to-end --------------

    #[test]
    fn run_acpl_1ch_pcm_emits_two_channel_pcm_with_energy() {
        // End-to-end smoke test: feed a synthetic mono sine into the
        // §5.7.7.5 channel-pair pipeline (QMF analysis → A-CPL → QMF
        // synthesis) and assert both output channels carry energy and
        // come out the right length.
        use crate::acpl::{
            Acpl1chMode, AcplConfig1ch, AcplData1ch, AcplFramingData, AcplHuffParam,
            AcplInterpolationType, AcplQuantMode,
        };
        let _ = Acpl1chMode::Full; // silence unused-import warning
        let n_slots = 32usize;
        let n = n_slots * NUM_QMF_SUBBANDS;
        let mut pcm = vec![0.0f32; n];
        let f = 440.0_f32 / 48_000.0_f32;
        for (i, s) in pcm.iter_mut().enumerate() {
            *s = (2.0 * std::f32::consts::PI * f * i as f32).sin();
        }
        let cfg = AcplConfig1ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode: AcplQuantMode::Fine,
            qmf_band: 0,
        };
        // Hand-built parsed acpl_data_1ch — single param set, alpha
        // and beta carrying the F0 anchor index (huffman F0 cb_off
        // gives signed 0 here).
        let alpha = AcplHuffParam {
            values: vec![4i32; cfg.num_param_bands as usize],
            direction_time: false,
        };
        let beta = AcplHuffParam {
            values: vec![2i32; cfg.num_param_bands as usize],
            direction_time: false,
        };
        let data = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![alpha],
            beta1: vec![beta],
        };
        let mut state = AcplSubstreamState::new();
        let (left, right) = run_acpl_1ch_pcm(&pcm, &cfg, &data, &mut state).expect("synth runs");
        assert_eq!(left.len(), pcm.len());
        assert_eq!(right.len(), pcm.len());
        // Both channels should carry energy in the steady-state tail.
        let start = 1024usize;
        let e_l: f64 = left[start..].iter().map(|&s| (s as f64).powi(2)).sum();
        let e_r: f64 = right[start..].iter().map(|&s| (s as f64).powi(2)).sum();
        assert!(e_l > 1e-6, "left channel silent (e={e_l})");
        assert!(e_r > 1e-6, "right channel silent (e={e_r})");
        // The two channels must differ — a non-zero alpha drives them
        // apart.
        let mut diffs = 0usize;
        for (l, r) in left[start..].iter().zip(right[start..].iter()) {
            if (l - r).abs() > 1e-6 {
                diffs += 1;
            }
        }
        assert!(
            diffs > (left.len() - start) / 4,
            "channels too similar (diffs={diffs})"
        );
    }

    #[test]
    fn run_acpl_1ch_pcm_stereo_emits_two_channels_distinct_from_l_r_passthrough() {
        // Stereo (M/S) input variant — same shape as ACPL_2 but with x1
        // populated. Verifies the spec's M/S split path runs end-to-end
        // and produces non-silent, distinct channels.
        use crate::acpl::{
            AcplConfig1ch, AcplData1ch, AcplFramingData, AcplHuffParam, AcplInterpolationType,
            AcplQuantMode,
        };
        let n_slots = 32usize;
        let n = n_slots * NUM_QMF_SUBBANDS;
        let mut pcm_m = vec![0.0f32; n];
        let mut pcm_s = vec![0.0f32; n];
        let f_m = 440.0_f32 / 48_000.0_f32;
        let f_s = 220.0_f32 / 48_000.0_f32;
        for i in 0..n {
            pcm_m[i] = (2.0 * std::f32::consts::PI * f_m * i as f32).sin();
            pcm_s[i] = 0.3 * (2.0 * std::f32::consts::PI * f_s * i as f32).sin();
        }
        let cfg = AcplConfig1ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode: AcplQuantMode::Fine,
            // PARTIAL mode: nonzero qmf_band so the M/S split path
            // engages on low subbands.
            qmf_band: 8,
        };
        let alpha = AcplHuffParam {
            values: vec![4i32; cfg.num_param_bands as usize],
            direction_time: false,
        };
        let beta = AcplHuffParam {
            values: vec![2i32; cfg.num_param_bands as usize],
            direction_time: false,
        };
        let data = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![alpha],
            beta1: vec![beta],
        };
        let mut state = AcplSubstreamState::new();
        let (left, right) = run_acpl_1ch_pcm_stereo(&pcm_m, &pcm_s, &cfg, &data, &mut state)
            .expect("stereo synth runs");
        assert_eq!(left.len(), pcm_m.len());
        assert_eq!(right.len(), pcm_m.len());
        let start = 1024usize;
        let e_l: f64 = left[start..].iter().map(|&s| (s as f64).powi(2)).sum();
        let e_r: f64 = right[start..].iter().map(|&s| (s as f64).powi(2)).sum();
        assert!(e_l > 1e-6, "left channel silent (e={e_l})");
        assert!(e_r > 1e-6, "right channel silent (e={e_r})");
        // The output must not be a literal pass-through of the input.
        let mut diff_from_input = 0usize;
        for i in start..left.len() {
            if (left[i] - pcm_m[i]).abs() > 1e-3 {
                diff_from_input += 1;
            }
        }
        assert!(
            diff_from_input > (left.len() - start) / 4,
            "left channel matches input PCM (diff_from_input={diff_from_input})"
        );
    }

    #[test]
    fn run_acpl_1ch_pcm_stereo_rejects_mismatched_lengths() {
        use crate::acpl::{
            AcplConfig1ch, AcplData1ch, AcplFramingData, AcplInterpolationType, AcplQuantMode,
        };
        let pcm_m = vec![0.0f32; 64];
        let pcm_s = vec![0.0f32; 128];
        let cfg = AcplConfig1ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode: AcplQuantMode::Fine,
            qmf_band: 0,
        };
        let data = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![],
            beta1: vec![],
        };
        let mut state = AcplSubstreamState::new();
        assert!(run_acpl_1ch_pcm_stereo(&pcm_m, &pcm_s, &cfg, &data, &mut state).is_none());
    }

    #[test]
    fn run_acpl_1ch_pcm_rejects_misaligned_pcm() {
        use crate::acpl::{
            AcplConfig1ch, AcplData1ch, AcplFramingData, AcplInterpolationType, AcplQuantMode,
        };
        let pcm = vec![0.0f32; 65]; // not a multiple of 64
        let cfg = AcplConfig1ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode: AcplQuantMode::Fine,
            qmf_band: 0,
        };
        let data = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![],
            beta1: vec![],
        };
        let mut state = AcplSubstreamState::new();
        assert!(run_acpl_1ch_pcm(&pcm, &cfg, &data, &mut state).is_none());
    }

    // =====================================================================
    // §5.7.7.6.2 — ASPX_ACPL_3 multichannel transform synthesis tests
    // (Pseudocodes 117 / 118 / 119 wiring + helpers)
    // =====================================================================

    /// `Transform()` with `g1 = 1, g2 = 0` should pass `x0` through and
    /// drop `x1`. `g1 = 0, g2 = 1` should pass `x1` through.
    #[test]
    fn transform_unit_gammas_select_carriers() {
        let num_ts = 8usize;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            x0[ts][10] = (1.0, 0.0);
            x1[ts][10] = (0.0, 1.0);
        }
        let g1 = vec![vec![1.0f32; 15]];
        let g2 = vec![vec![0.0f32; 15]];
        let prev = vec![1.0f32; NUM_QMF_SUBBANDS];
        let prev_zero = vec![0.0f32; NUM_QMF_SUBBANDS];
        // num_pset == 1, prev_g1 = 1.0 across sb -> interpolation stays
        // at 1.0 (start at prev=1.0, target=1.0, no ramp).
        let v = transform(&x0, &x1, &g1, &g2, 15, &prev, &prev_zero, false, &[]);
        for ts in 0..num_ts {
            // sb=10: v = x0 * 1 + x1 * 0 = x0.
            let (vr, vi) = v[ts][10];
            assert!((vr - 1.0).abs() < 1e-5, "ts={ts} vr={vr}, expected x0=1.0");
            assert!((vi - 0.0).abs() < 1e-5, "ts={ts} vi={vi}");
            // sb=20: both x0 and x1 are zero, result must be zero.
            assert_eq!(v[ts][20], (0.0, 0.0));
        }

        // Now flip: g1 = 0 → x1 carries through.
        let g1 = vec![vec![0.0f32; 15]];
        let g2 = vec![vec![1.0f32; 15]];
        let prev_g2 = vec![1.0f32; NUM_QMF_SUBBANDS];
        let v = transform(&x0, &x1, &g1, &g2, 15, &prev_zero, &prev_g2, false, &[]);
        for ts in 0..num_ts {
            let (vr, vi) = v[ts][10];
            assert!((vr - 0.0).abs() < 1e-5);
            assert!((vi - 1.0).abs() < 1e-5);
        }
    }

    /// `Transform()` with mixed gammas should produce the linear
    /// combination `x0*g1 + x1*g2` after the smooth-interpolation ramp.
    #[test]
    fn transform_mixes_two_carriers_with_gammas() {
        let num_ts = 4usize;
        let mut x0 = vec![[(2.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 3.0f32); NUM_QMF_SUBBANDS]; num_ts];
        // Make g1 = 0.5 across all bands, g2 = 0.25. With prev = same
        // values, smooth interpolation collapses to constant gammas.
        let g1 = vec![vec![0.5f32; 15]];
        let g2 = vec![vec![0.25f32; 15]];
        let prev_g1 = vec![0.5f32; NUM_QMF_SUBBANDS];
        let prev_g2 = vec![0.25f32; NUM_QMF_SUBBANDS];
        let v = transform(&x0, &x1, &g1, &g2, 15, &prev_g1, &prev_g2, false, &[]);
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                let (vr, vi) = v[ts][sb];
                // x0 contributes (2 * 0.5, 0). x1 contributes (0, 3 * 0.25).
                assert!((vr - 1.0).abs() < 1e-5, "ts={ts} sb={sb} vr={vr}");
                assert!((vi - 0.75).abs() < 1e-5, "ts={ts} sb={sb} vi={vi}");
            }
        }
        // Quiet unused-mut warnings.
        let _ = (&mut x0, &mut x1);
    }

    /// `acpl_module2()` with g1=g2=g1*a=g2*a=b=0 must yield silent z0,z1.
    #[test]
    fn acpl_module2_zero_gammas_is_silent() {
        let num_ts = 4usize;
        let x0 = vec![[(1.0f32, 0.5f32); NUM_QMF_SUBBANDS]; num_ts];
        let x1 = vec![[(0.5f32, 1.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let y = vec![[(2.0f32, 2.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let zero = vec![vec![0.0f32; 15]];
        let (z0, z1) = acpl_module2(
            &x0,
            &x1,
            &y,
            &zero,
            &zero,
            &zero,
            &zero,
            &zero,
            15,
            false,
            &[],
        );
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                assert_eq!(z0[ts][sb], (0.0, 0.0));
                assert_eq!(z1[ts][sb], (0.0, 0.0));
            }
        }
    }

    /// `acpl_module2()` with g1=1, g2=0, a=0, b=0 (so g1a = g2a = 0):
    ///   z0 = 0.5 * (x0 * (g1+g1a) + x1 * (g2+g2a) + y*b)
    ///       = 0.5 * x0 * 1
    ///   z1 = 0.5 * x0 * (1-0) = 0.5 * x0
    /// → both z0 and z1 collapse to 0.5*x0.
    #[test]
    fn acpl_module2_unit_g1_zero_alpha_beta_passes_half_x0_to_both() {
        let num_ts = 4usize;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let y = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            x0[ts][5] = (4.0, 2.0);
        }
        let g1 = vec![vec![1.0f32; 15]];
        let g2 = vec![vec![0.0f32; 15]];
        let g1a = vec![vec![0.0f32; 15]]; // a=0 → g1*a=0
        let g2a = vec![vec![0.0f32; 15]];
        let b = vec![vec![0.0f32; 15]];
        let (z0, z1) = acpl_module2(&x0, &x1, &y, &g1, &g2, &g1a, &g2a, &b, 15, false, &[]);
        // smooth interpolation with prev=0, target=1 → at ts=num_ts-1, g1
        // hits 1.0, but z formula has g1+g1a so 1+0=1; z = 0.5*x0*1 = 0.5*x0.
        // Just assert the last ts converges.
        let last = num_ts - 1;
        let (z0r, z0i) = z0[last][5];
        let (z1r, z1i) = z1[last][5];
        assert!((z0r - 2.0).abs() < 1e-5, "z0r={z0r} expected 2.0");
        assert!((z0i - 1.0).abs() < 1e-5, "z0i={z0i} expected 1.0");
        assert!((z1r - 2.0).abs() < 1e-5, "z1r={z1r}");
        assert!((z1i - 1.0).abs() < 1e-5, "z1i={z1i}");
    }

    /// `acpl_module3()` adds a beta3-driven decorrelator residual.
    /// With b3=1, b3a=0 (i.e. a=0): z0 += 0.25*y*1 = 0.25*y, z1 += same.
    #[test]
    fn acpl_module3_adds_decorrelator_residual() {
        let num_ts = 4usize;
        let mut z0 = vec![[(1.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut z1 = vec![[(0.0f32, 1.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let y2 = vec![[(4.0f32, 4.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let b3 = vec![vec![1.0f32; 15]];
        let b3a = vec![vec![0.0f32; 15]];
        acpl_module3(&mut z0, &mut z1, &y2, &b3, &b3a, 15, false, &[]);
        // After ramp completes (ts=num_ts-1) b3 = 1.0, b3a = 0:
        //   z0 += 0.25 * y2 * (1 + 0) = 0.25 * (4, 4) = (1, 1)
        //   z1 += 0.25 * y2 * (1 - 0) = (1, 1)
        let last = num_ts - 1;
        let (z0r, z0i) = z0[last][7];
        assert!((z0r - 2.0).abs() < 1e-5, "z0r={z0r}");
        assert!((z0i - 1.0).abs() < 1e-5, "z0i={z0i}");
        let (z1r, z1i) = z1[last][7];
        assert!((z1r - 1.0).abs() < 1e-5, "z1r={z1r}");
        assert!((z1i - 2.0).abs() < 1e-5, "z1i={z1i}");
    }

    /// `acpl_module3()` with all-zero beta3 is a no-op.
    #[test]
    fn acpl_module3_zero_beta3_is_noop() {
        let num_ts = 4usize;
        let mut z0 = vec![[(7.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut z1 = vec![[(0.0f32, 7.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let y2 = vec![[(99.0f32, -99.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let zero = vec![vec![0.0f32; 15]];
        acpl_module3(&mut z0, &mut z1, &y2, &zero, &zero, 15, false, &[]);
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                assert_eq!(z0[ts][sb], (7.0, 0.0));
                assert_eq!(z1[ts][sb], (0.0, 7.0));
            }
        }
    }

    /// Smoke test for the full §5.7.7.6.2 ASPX_ACPL_3 pipeline. Feed
    /// non-zero L/R/C carriers and verify all 5 outputs are populated and
    /// finite.
    #[test]
    fn run_pseudocode_118_5x_emits_five_finite_channels() {
        let num_ts = 16usize;
        let num_pb = 9u32;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x2 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            for sb in 0..32 {
                let p = (ts as f32) * 0.2 + sb as f32 * 0.05;
                x0[ts][sb] = (0.1 * p.cos(), 0.1 * p.sin());
                x1[ts][sb] = (0.05 * p.sin(), 0.05 * p.cos());
                x2[ts][sb] = (0.03 * (p * 1.3).cos(), 0.0);
            }
        }
        let alpha_1 = vec![vec![0.4f32; num_pb as usize]];
        let alpha_2 = vec![vec![-0.2f32; num_pb as usize]];
        let beta_1 = vec![vec![0.3f32; num_pb as usize]];
        let beta_2 = vec![vec![0.2f32; num_pb as usize]];
        let beta_3 = vec![vec![0.15f32; num_pb as usize]];
        let g1 = vec![vec![0.6f32; num_pb as usize]];
        let g2 = vec![vec![0.3f32; num_pb as usize]];
        let g3 = vec![vec![0.2f32; num_pb as usize]];
        let g4 = vec![vec![0.5f32; num_pb as usize]];
        let g5 = vec![vec![0.1f32; num_pb as usize]];
        let g6 = vec![vec![0.1f32; num_pb as usize]];
        let mut state = AcplMchState::new();
        let frame = AcplMchFrame {
            x0: &x0,
            x1: &x1,
            x2: &x2,
            alpha_1_dq: &alpha_1,
            alpha_2_dq: &alpha_2,
            beta_1_dq: &beta_1,
            beta_2_dq: &beta_2,
            beta_3_dq: &beta_3,
            g1_dq: &g1,
            g2_dq: &g2,
            g3_dq: &g3,
            g4_dq: &g4,
            g5_dq: &g5,
            g6_dq: &g6,
            num_param_bands: num_pb,
            steep: false,
            param_timeslots: &[],
        };
        let out = run_pseudocode_118_5x(&mut state, frame);
        assert_eq!(out.z0.len(), num_ts);
        assert_eq!(out.z1.len(), num_ts);
        assert_eq!(out.z2.len(), num_ts);
        assert_eq!(out.z3.len(), num_ts);
        assert_eq!(out.z4.len(), num_ts);
        // No NaN / Inf in any output channel.
        for z in [&out.z0, &out.z1, &out.z2, &out.z3, &out.z4] {
            for col in z.iter() {
                for sb in 0..NUM_QMF_SUBBANDS {
                    assert!(
                        col[sb].0.is_finite() && col[sb].1.is_finite(),
                        "non-finite output: {:?}",
                        col[sb]
                    );
                }
            }
        }
        // Carriers are non-zero; the synthesis must produce non-zero
        // energy on all five channels.
        for (name, z) in [
            ("z0=L", &out.z0),
            ("z1=Ls", &out.z1),
            ("z2=R", &out.z2),
            ("z3=Rs", &out.z3),
            ("z4=C", &out.z4),
        ] {
            let e: f64 = z
                .iter()
                .flat_map(|col| col.iter())
                .map(|s| (s.0 as f64).powi(2) + (s.1 as f64).powi(2))
                .sum();
            assert!(e > 0.0, "channel {name} silent (energy {e})");
        }
        // Gamma prev arrays should be populated after the call.
        assert_eq!(state.g1_prev_sb.len(), NUM_QMF_SUBBANDS);
        for sb in 0..NUM_QMF_SUBBANDS {
            assert!((state.g1_prev_sb[sb] - 0.6).abs() < 1e-6);
        }
    }

    /// All-zero alpha/beta/beta3 + matching gamma should still produce
    /// valid, finite output. This covers the "no decorrelator coupling"
    /// path through the 5_X synthesis.
    #[test]
    fn run_pseudocode_118_5x_zero_alpha_beta_remains_finite() {
        let num_ts = 8usize;
        let num_pb = 9u32;
        let x0 = vec![[(0.5f32, 0.5f32); NUM_QMF_SUBBANDS]; num_ts];
        let x1 = vec![[(0.5f32, -0.5f32); NUM_QMF_SUBBANDS]; num_ts];
        let x2 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let zero = vec![vec![0.0f32; num_pb as usize]];
        let g1 = vec![vec![1.0f32; num_pb as usize]]; // g1 != 0 so v1 isn't trivially silent
        let mut state = AcplMchState::new();
        let frame = AcplMchFrame {
            x0: &x0,
            x1: &x1,
            x2: &x2,
            alpha_1_dq: &zero,
            alpha_2_dq: &zero,
            beta_1_dq: &zero,
            beta_2_dq: &zero,
            beta_3_dq: &zero,
            g1_dq: &g1,
            g2_dq: &zero,
            g3_dq: &zero,
            g4_dq: &zero,
            g5_dq: &zero,
            g6_dq: &zero,
            num_param_bands: num_pb,
            steep: false,
            param_timeslots: &[],
        };
        let out = run_pseudocode_118_5x(&mut state, frame);
        for col in out.z0.iter() {
            for sb in 0..NUM_QMF_SUBBANDS {
                assert!(col[sb].0.is_finite());
                assert!(col[sb].1.is_finite());
            }
        }
    }

    /// Smoke test for `pb_matrix_*` helpers used inside Pseudocode 118.
    #[test]
    fn pb_matrix_helpers() {
        let a = vec![vec![1.0f32, 2.0, 3.0]];
        let b = vec![vec![10.0f32, 20.0, 30.0]];
        let c = vec![vec![100.0f32, 200.0, 300.0]];
        let prod = pb_matrix_mul(&a, &b);
        assert_eq!(prod, vec![vec![10.0, 40.0, 90.0]]);
        let sum = pb_matrix_sum3(&a, &b, &c);
        assert_eq!(sum, vec![vec![111.0, 222.0, 333.0]]);
        let scaled = pb_matrix_scale(&a, -2.0);
        assert_eq!(scaled, vec![vec![-2.0, -4.0, -6.0]]);
    }

    /// Spec consistency: the `(1 + 2*sqrt(0.5))` scaling factor applied
    /// to x0/x1 in Pseudocode 118 must equal `1 + sqrt(2)` ≈ 2.414...
    #[test]
    fn pseudocode_118_scaling_factor() {
        let s = 1.0f32 + 2.0 * (0.5f32).sqrt();
        let expected = 1.0f32 + (2.0f32).sqrt();
        assert!((s - expected).abs() < 1e-6);
    }

    /// `AcplMchState::new()` should initialise prev arrays to zero.
    #[test]
    fn acpl_mch_state_zero_init() {
        let s = AcplMchState::new();
        assert!(s.g1_prev_sb.iter().all(|&v| v == 0.0));
        assert!(s.g2_prev_sb.iter().all(|&v| v == 0.0));
        assert!(s.g3_prev_sb.iter().all(|&v| v == 0.0));
        assert!(s.g4_prev_sb.iter().all(|&v| v == 0.0));
        assert_eq!(s.g1_prev_sb.len(), NUM_QMF_SUBBANDS);
    }

    // =====================================================================
    // §5.7.7.6.1 — ASPX_ACPL_1 / ASPX_ACPL_2 multichannel wrapper tests
    // (Pseudocode 117)
    // =====================================================================

    /// `Acpl5xPairState::new()` should set up D0 on the L-side and D1 on
    /// the R-side, with zero prev arrays + diff state.
    #[test]
    fn acpl_5x_pair_state_initial_decorrelators() {
        let s = Acpl5xPairState::new();
        assert!(matches!(s.left_pair.decorrelator.which, DecorrelatorId::D0));
        assert!(matches!(
            s.right_pair.decorrelator.which,
            DecorrelatorId::D1
        ));
        assert!(s.left_pair.alpha_prev_sb.iter().all(|&v| v == 0.0));
        assert!(s.right_pair.alpha_prev_sb.iter().all(|&v| v == 0.0));
        assert!(s.alpha1_diff.q_prev.is_empty());
        assert!(s.alpha2_diff.q_prev.is_empty());
    }

    /// Build a small synthetic 5_X frame with x0/x1 carrying tones and
    /// the centre channel carrying a distinct tone. Run Pseudocode 117
    /// in `ASPX_ACPL_2` mode (no Ls/Rs carriers) and verify that:
    ///
    /// 1. Five output matrices are produced, all `num_ts × 64` shaped.
    /// 2. The centre output `z4` matches `x2` byte-for-byte (passthrough).
    /// 3. `z1` / `z3` are scaled by sqrt(2) (the M/S split below
    ///    `acpl_qmf_band` is `0.5*(x0±0)*sqrt(2)` for the surround pair).
    /// 4. No NaN / Inf in any output sample.
    #[test]
    fn run_pseudocode_117_5x_aspx_acpl_2_passthrough_centre_and_finite() {
        let num_ts = 16usize;
        let num_pb = 9u32;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x2 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            x0[ts][8] = (1.0, 0.0);
            x1[ts][12] = (0.0, 1.0);
            x2[ts][20] = (0.5, -0.5);
        }
        let alpha1 = vec![vec![0.3f32; num_pb as usize]];
        let beta1 = vec![vec![0.2f32; num_pb as usize]];
        let alpha2 = vec![vec![-0.4f32; num_pb as usize]];
        let beta2 = vec![vec![0.1f32; num_pb as usize]];
        let mut state = Acpl5xPairState::new();
        let frame = Acpl5xPairFrame {
            mode: Acpl5xPairMode::AspxAcpl2,
            x0: &x0,
            x1: &x1,
            x2: &x2,
            x3: None,
            x4: None,
            alpha_1_dq: &alpha1,
            beta_1_dq: &beta1,
            alpha_2_dq: &alpha2,
            beta_2_dq: &beta2,
            num_param_bands: num_pb,
            acpl_qmf_band: 0,
            steep_1: false,
            steep_2: false,
            param_timeslots_1: &[],
            param_timeslots_2: &[],
        };
        let out = run_pseudocode_117_5x(&mut state, frame);
        assert_eq!(out.z0.len(), num_ts);
        assert_eq!(out.z1.len(), num_ts);
        assert_eq!(out.z2.len(), num_ts);
        assert_eq!(out.z3.len(), num_ts);
        assert_eq!(out.z4.len(), num_ts);
        // Centre passthrough z4 == x2.
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                assert_eq!(out.z4[ts][sb], x2[ts][sb], "z4 != x2 at ts={ts} sb={sb}");
            }
        }
        // No NaN / Inf in any output sample.
        for ts in 0..num_ts {
            for sb in 0..NUM_QMF_SUBBANDS {
                for (re, im) in [
                    out.z0[ts][sb],
                    out.z1[ts][sb],
                    out.z2[ts][sb],
                    out.z3[ts][sb],
                    out.z4[ts][sb],
                ] {
                    assert!(re.is_finite(), "non-finite re at ts={ts} sb={sb}");
                    assert!(im.is_finite(), "non-finite im at ts={ts} sb={sb}");
                }
            }
        }
    }

    /// In ASPX_ACPL_1 mode, the Ls / Rs carriers (`x3` / `x4`) are
    /// expected to participate in the M/S split below `acpl_qmf_band`.
    /// With alpha=beta=0 and `acpl_qmf_band=64` (whole-band M/S), the
    /// pair output should reduce to `(0.5*(x0+x3)*2, 0.5*(x0-x3)*2) =
    /// (x0+x3, x0-x3)` — note the inner `x0in = 2*x0` doubles the
    /// inputs first. We then have `z1 *= sqrt(2)`, so the surround
    /// channel is `(x0-x3) * sqrt(2)`.
    #[test]
    fn run_pseudocode_117_5x_aspx_acpl_1_low_band_ms_split() {
        let num_ts = 4usize;
        let num_pb = 9u32;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let x2 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x3 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x4 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        // Pick distinct tones so z0 = (x0+x3) and z1 = (x0-x3)*sqrt(2).
        for ts in 0..num_ts {
            x0[ts][2] = (0.7, 0.0);
            x3[ts][2] = (0.3, 0.0);
            x1[ts][2] = (0.5, 0.5);
            x4[ts][2] = (0.1, -0.1);
        }
        let alpha1 = vec![vec![0.0f32; num_pb as usize]];
        let beta1 = vec![vec![0.0f32; num_pb as usize]];
        let alpha2 = vec![vec![0.0f32; num_pb as usize]];
        let beta2 = vec![vec![0.0f32; num_pb as usize]];
        let mut state = Acpl5xPairState::new();
        let frame = Acpl5xPairFrame {
            mode: Acpl5xPairMode::AspxAcpl1,
            x0: &x0,
            x1: &x1,
            x2: &x2,
            x3: Some(&x3),
            x4: Some(&x4),
            alpha_1_dq: &alpha1,
            beta_1_dq: &beta1,
            alpha_2_dq: &alpha2,
            beta_2_dq: &beta2,
            num_param_bands: num_pb,
            // Whole-band M/S split: every sb < 64 takes the (x0+x1)/2
            // and (x0-x1)/2 path inside acpl_module().
            acpl_qmf_band: NUM_QMF_SUBBANDS as u32,
            steep_1: false,
            steep_2: false,
            param_timeslots_1: &[],
            param_timeslots_2: &[],
        };
        let out = run_pseudocode_117_5x(&mut state, frame);
        let sq2 = (2.0f32).sqrt();
        for ts in 0..num_ts {
            // L-side: x0in = 2*x0, x3in = 2*x3 ->
            //   z0 = 0.5 * (x0in + x3in) = x0 + x3 = (1.0, 0.0)
            //   z1 = 0.5 * (x0in - x3in) = x0 - x3 = (0.4, 0.0); then *sqrt(2).
            let (z0r, z0i) = out.z0[ts][2];
            let (z1r, z1i) = out.z1[ts][2];
            assert!((z0r - 1.0).abs() < 1e-5, "ts={ts} z0r={z0r}");
            assert!((z0i - 0.0).abs() < 1e-5, "ts={ts} z0i={z0i}");
            assert!(
                (z1r - 0.4 * sq2).abs() < 1e-5,
                "ts={ts} z1r={z1r} expected={}",
                0.4 * sq2
            );
            assert!((z1i - 0.0).abs() < 1e-5, "ts={ts} z1i={z1i}");
            // R-side: x1in = 2*x1, x4in = 2*x4 ->
            //   z2 = 0.5 * (x1in + x4in) = x1 + x4 = (0.6, 0.4)
            //   z3 = 0.5 * (x1in - x4in) = x1 - x4 = (0.4, 0.6); then *sqrt(2).
            let (z2r, z2i) = out.z2[ts][2];
            let (z3r, z3i) = out.z3[ts][2];
            assert!((z2r - 0.6).abs() < 1e-5, "ts={ts} z2r={z2r}");
            assert!((z2i - 0.4).abs() < 1e-5, "ts={ts} z2i={z2i}");
            assert!(
                (z3r - 0.4 * sq2).abs() < 1e-5,
                "ts={ts} z3r={z3r} expected={}",
                0.4 * sq2
            );
            assert!(
                (z3i - 0.6 * sq2).abs() < 1e-5,
                "ts={ts} z3i={z3i} expected={}",
                0.6 * sq2
            );
        }
    }

    /// Both modes: Pseudocode 117 must propagate decorrelator + ducker
    /// state across calls. After a frame, the L-side / R-side prev
    /// arrays are populated by the inner `run_pseudocode_115_pair()` —
    /// this test runs two frames and checks the second frame sees the
    /// updated `alpha_prev` / `beta_prev` from the first.
    #[test]
    fn run_pseudocode_117_5x_state_carries_across_frames() {
        let num_ts = 8usize;
        let num_pb = 9u32;
        let x0 = vec![[(1.0f32, 0.5f32); NUM_QMF_SUBBANDS]; num_ts];
        let x1 = vec![[(0.5f32, 1.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let x2 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let alpha1 = vec![vec![0.42f32; num_pb as usize]];
        let beta1 = vec![vec![0.13f32; num_pb as usize]];
        let alpha2 = vec![vec![-0.11f32; num_pb as usize]];
        let beta2 = vec![vec![0.21f32; num_pb as usize]];
        let mut state = Acpl5xPairState::new();
        // Pre-state: prev arrays are zeros.
        assert!(state.left_pair.alpha_prev_sb.iter().all(|&v| v == 0.0));
        assert!(state.right_pair.alpha_prev_sb.iter().all(|&v| v == 0.0));
        let frame = Acpl5xPairFrame {
            mode: Acpl5xPairMode::AspxAcpl2,
            x0: &x0,
            x1: &x1,
            x2: &x2,
            x3: None,
            x4: None,
            alpha_1_dq: &alpha1,
            beta_1_dq: &beta1,
            alpha_2_dq: &alpha2,
            beta_2_dq: &beta2,
            num_param_bands: num_pb,
            acpl_qmf_band: 0,
            steep_1: false,
            steep_2: false,
            param_timeslots_1: &[],
            param_timeslots_2: &[],
        };
        let _out1 = run_pseudocode_117_5x(&mut state, frame);
        // Post-state: prev arrays carry the last param-set's expanded
        // sb rows. With a single param set of constant 0.42 / -0.11
        // across all bands, every sb entry must equal that constant.
        for sb in 0..NUM_QMF_SUBBANDS {
            assert!(
                (state.left_pair.alpha_prev_sb[sb] - 0.42).abs() < 1e-6,
                "left alpha_prev[{sb}] = {}",
                state.left_pair.alpha_prev_sb[sb]
            );
            assert!(
                (state.right_pair.alpha_prev_sb[sb] - (-0.11)).abs() < 1e-6,
                "right alpha_prev[{sb}] = {}",
                state.right_pair.alpha_prev_sb[sb]
            );
            assert!(
                (state.left_pair.beta_prev_sb[sb] - 0.13).abs() < 1e-6,
                "left beta_prev[{sb}] = {}",
                state.left_pair.beta_prev_sb[sb]
            );
            assert!(
                (state.right_pair.beta_prev_sb[sb] - 0.21).abs() < 1e-6,
                "right beta_prev[{sb}] = {}",
                state.right_pair.beta_prev_sb[sb]
            );
        }
    }

    /// ASPX_ACPL_2 (no surround carriers) should compute exactly the
    /// same per-side output as calling `run_pseudocode_115_pair()`
    /// twice with x1 = None — Pseudocode 117 is only adding the
    /// sqrt(2) post-scale + centre passthrough on top of two parallel
    /// channel-pair passes.
    #[test]
    fn run_pseudocode_117_5x_aspx_acpl_2_matches_two_115_passes() {
        let num_ts = 12usize;
        let num_pb = 9u32;
        let mut x0 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let mut x1 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        let x2 = vec![[(0.0f32, 0.0f32); NUM_QMF_SUBBANDS]; num_ts];
        for ts in 0..num_ts {
            for sb in 0..32 {
                let phase = (ts as f32 * 0.2) + (sb as f32 * 0.1);
                x0[ts][sb] = (0.1 * phase.cos(), 0.1 * phase.sin());
                x1[ts][sb] = (0.05 * phase.sin(), 0.05 * phase.cos());
            }
        }
        let alpha1 = vec![vec![0.3f32; num_pb as usize]];
        let beta1 = vec![vec![0.2f32; num_pb as usize]];
        let alpha2 = vec![vec![0.1f32; num_pb as usize]];
        let beta2 = vec![vec![0.4f32; num_pb as usize]];
        // Reference: run two independent channel-pair passes.
        let mut ref_state_l = AcplCpeState::new(DecorrelatorId::D0);
        let mut ref_state_r = AcplCpeState::new(DecorrelatorId::D1);
        let ref_l = run_pseudocode_115_pair(
            &mut ref_state_l,
            AcplCpeFrame {
                x0: &x0,
                x1: None,
                alpha_dq: &alpha1,
                beta_dq: &beta1,
                num_param_bands: num_pb,
                acpl_qmf_band: 0,
                steep: false,
                param_timeslots: &[],
            },
        );
        let ref_r = run_pseudocode_115_pair(
            &mut ref_state_r,
            AcplCpeFrame {
                x0: &x1,
                x1: None,
                alpha_dq: &alpha2,
                beta_dq: &beta2,
                num_param_bands: num_pb,
                acpl_qmf_band: 0,
                steep: false,
                param_timeslots: &[],
            },
        );
        // Run Pseudocode 117 — should match the references modulo the
        // sqrt(2) post-scale on the surround pair.
        let mut state = Acpl5xPairState::new();
        let frame = Acpl5xPairFrame {
            mode: Acpl5xPairMode::AspxAcpl2,
            x0: &x0,
            x1: &x1,
            x2: &x2,
            x3: None,
            x4: None,
            alpha_1_dq: &alpha1,
            beta_1_dq: &beta1,
            alpha_2_dq: &alpha2,
            beta_2_dq: &beta2,
            num_param_bands: num_pb,
            acpl_qmf_band: 0,
            steep_1: false,
            steep_2: false,
            param_timeslots_1: &[],
            param_timeslots_2: &[],
        };
        let out = run_pseudocode_117_5x(&mut state, frame);
        let sq2 = (2.0f32).sqrt();
        // Spot-check a few subbands across the time axis.
        for ts in 0..num_ts {
            for sb in [0usize, 5, 16, 31, 47, 63] {
                let (a_r, a_i) = out.z0[ts][sb];
                let (e_r, e_i) = ref_l.z0[ts][sb];
                assert!(
                    (a_r - e_r).abs() < 1e-5 && (a_i - e_i).abs() < 1e-5,
                    "z0 mismatch ts={ts} sb={sb} got ({a_r},{a_i}) want ({e_r},{e_i})"
                );
                let (a_r, a_i) = out.z2[ts][sb];
                let (e_r, e_i) = ref_r.z0[ts][sb];
                assert!(
                    (a_r - e_r).abs() < 1e-5 && (a_i - e_i).abs() < 1e-5,
                    "z2 mismatch ts={ts} sb={sb} got ({a_r},{a_i}) want ({e_r},{e_i})"
                );
                let (a_r, a_i) = out.z1[ts][sb];
                let (e_r, e_i) = (ref_l.z1[ts][sb].0 * sq2, ref_l.z1[ts][sb].1 * sq2);
                assert!(
                    (a_r - e_r).abs() < 1e-5 && (a_i - e_i).abs() < 1e-5,
                    "z1 mismatch ts={ts} sb={sb} got ({a_r},{a_i}) want ({e_r},{e_i})"
                );
                let (a_r, a_i) = out.z3[ts][sb];
                let (e_r, e_i) = (ref_r.z1[ts][sb].0 * sq2, ref_r.z1[ts][sb].1 * sq2);
                assert!(
                    (a_r - e_r).abs() < 1e-5 && (a_i - e_i).abs() < 1e-5,
                    "z3 mismatch ts={ts} sb={sb} got ({a_r},{a_i}) want ({e_r},{e_i})"
                );
            }
        }
    }

    // =====================================================================
    // §5.7.7.6 — 5_X-walker glue: PCM-level helpers for ASPX_ACPL_{1,2,3}
    // =====================================================================

    /// `run_acpl_5x_pair_pcm` should reject inputs whose lengths don't
    /// align (one PCM channel a multiple of 64, all channels same
    /// length, surround presence consistent with mode).
    #[test]
    fn run_acpl_5x_pair_pcm_rejects_misaligned_inputs() {
        use crate::acpl::{
            AcplConfig1ch, AcplData1ch, AcplFramingData, AcplHuffParam, AcplInterpolationType,
            AcplQuantMode,
        };
        let cfg = AcplConfig1ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode: AcplQuantMode::Fine,
            qmf_band: 0,
        };
        let data = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![AcplHuffParam {
                values: vec![4i32; cfg.num_param_bands as usize],
                direction_time: false,
            }],
            beta1: vec![AcplHuffParam {
                values: vec![2i32; cfg.num_param_bands as usize],
                direction_time: false,
            }],
        };
        let mut state = Acpl5xPairPcmState::new();
        // Length not a multiple of 64 → None.
        let pcm_short = vec![0.0f32; 65];
        assert!(run_acpl_5x_pair_pcm(
            Acpl5xPairMode::AspxAcpl2,
            &pcm_short,
            &pcm_short,
            &pcm_short,
            None,
            None,
            &cfg,
            &data,
            &cfg,
            &data,
            &mut state,
        )
        .is_none());
        // Surround present in ASPX_ACPL_2 mode → None.
        let pcm = vec![0.0f32; 64];
        assert!(run_acpl_5x_pair_pcm(
            Acpl5xPairMode::AspxAcpl2,
            &pcm,
            &pcm,
            &pcm,
            Some(&pcm),
            Some(&pcm),
            &cfg,
            &data,
            &cfg,
            &data,
            &mut state,
        )
        .is_none());
        // Surround missing in ASPX_ACPL_1 mode → None.
        assert!(run_acpl_5x_pair_pcm(
            Acpl5xPairMode::AspxAcpl1,
            &pcm,
            &pcm,
            &pcm,
            None,
            None,
            &cfg,
            &data,
            &cfg,
            &data,
            &mut state,
        )
        .is_none());
    }

    /// End-to-end: feed three sine carriers (L/R/C) into the
    /// `ASPX_ACPL_2` 5_X PCM pipeline. We expect five output channels
    /// of the right length with all carrying energy and no NaN/Inf.
    #[test]
    fn run_acpl_5x_pair_pcm_aspx_acpl_2_emits_five_channels() {
        use crate::acpl::{
            AcplConfig1ch, AcplData1ch, AcplFramingData, AcplHuffParam, AcplInterpolationType,
            AcplQuantMode,
        };
        let n_slots = 64usize;
        let n = n_slots * NUM_QMF_SUBBANDS;
        let mut pcm_l = vec![0.0f32; n];
        let mut pcm_r = vec![0.0f32; n];
        let mut pcm_c = vec![0.0f32; n];
        let f_l = 440.0f32 / 48_000.0;
        let f_r = 220.0f32 / 48_000.0;
        let f_c = 880.0f32 / 48_000.0;
        for i in 0..n {
            pcm_l[i] = (2.0 * std::f32::consts::PI * f_l * i as f32).sin();
            pcm_r[i] = 0.5 * (2.0 * std::f32::consts::PI * f_r * i as f32).sin();
            pcm_c[i] = 0.3 * (2.0 * std::f32::consts::PI * f_c * i as f32).sin();
        }
        let cfg = AcplConfig1ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode: AcplQuantMode::Fine,
            qmf_band: 0,
        };
        let data1 = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![AcplHuffParam {
                values: vec![4i32; cfg.num_param_bands as usize],
                direction_time: false,
            }],
            beta1: vec![AcplHuffParam {
                values: vec![2i32; cfg.num_param_bands as usize],
                direction_time: false,
            }],
        };
        let data2 = AcplData1ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![AcplHuffParam {
                values: vec![-3i32; cfg.num_param_bands as usize],
                direction_time: false,
            }],
            beta1: vec![AcplHuffParam {
                values: vec![1i32; cfg.num_param_bands as usize],
                direction_time: false,
            }],
        };
        let mut state = Acpl5xPairPcmState::new();
        let out = run_acpl_5x_pair_pcm(
            Acpl5xPairMode::AspxAcpl2,
            &pcm_l,
            &pcm_r,
            &pcm_c,
            None,
            None,
            &cfg,
            &data1,
            &cfg,
            &data2,
            &mut state,
        )
        .expect("synth runs");
        assert_eq!(out.left.len(), n);
        assert_eq!(out.right.len(), n);
        assert_eq!(out.centre.len(), n);
        assert_eq!(out.left_surround.len(), n);
        assert_eq!(out.right_surround.len(), n);
        let start = 2048usize;
        let energy =
            |b: &[f32]| -> f64 { b[start..].iter().map(|&s| (s as f64).powi(2)).sum::<f64>() };
        assert!(energy(&out.left) > 1e-6, "left silent");
        assert!(energy(&out.right) > 1e-6, "right silent");
        assert!(energy(&out.centre) > 1e-6, "centre silent");
        assert!(energy(&out.left_surround) > 1e-6, "Ls silent");
        assert!(energy(&out.right_surround) > 1e-6, "Rs silent");
        for b in [
            &out.left,
            &out.right,
            &out.centre,
            &out.left_surround,
            &out.right_surround,
        ] {
            for &s in b.iter() {
                assert!(s.is_finite(), "non-finite sample");
            }
        }
    }

    /// `run_acpl_5x_mch_pcm` should reject misaligned inputs and emit
    /// five distinct PCM streams when fed a real ASPX_ACPL_3 frame.
    #[test]
    fn run_acpl_5x_mch_pcm_aspx_acpl_3_emits_five_channels() {
        use crate::acpl::{
            AcplConfig2ch, AcplData2ch, AcplFramingData, AcplHuffParam, AcplInterpolationType,
            AcplQuantMode,
        };
        let n_slots = 64usize;
        let n = n_slots * NUM_QMF_SUBBANDS;
        let mut pcm_l = vec![0.0f32; n];
        let mut pcm_r = vec![0.0f32; n];
        let mut pcm_c = vec![0.0f32; n];
        let f_l = 440.0f32 / 48_000.0;
        let f_r = 220.0f32 / 48_000.0;
        let f_c = 660.0f32 / 48_000.0;
        for i in 0..n {
            pcm_l[i] = (2.0 * std::f32::consts::PI * f_l * i as f32).sin();
            pcm_r[i] = (2.0 * std::f32::consts::PI * f_r * i as f32).cos();
            pcm_c[i] = 0.3 * (2.0 * std::f32::consts::PI * f_c * i as f32).sin();
        }
        let cfg = AcplConfig2ch {
            num_param_bands_id: 0,
            num_param_bands: 15,
            quant_mode_0: AcplQuantMode::Fine,
            quant_mode_1: AcplQuantMode::Fine,
        };
        let mk_huff = |seed: i32| AcplHuffParam {
            values: vec![seed; cfg.num_param_bands as usize],
            direction_time: false,
        };
        let data = AcplData2ch {
            framing: AcplFramingData {
                interpolation_type: AcplInterpolationType::Smooth,
                num_param_sets_cod: 0,
                num_param_sets: 1,
                param_timeslots: vec![],
            },
            alpha1: vec![mk_huff(4)],
            alpha2: vec![mk_huff(-3)],
            beta1: vec![mk_huff(2)],
            beta2: vec![mk_huff(1)],
            beta3: vec![mk_huff(0)],
            gamma1: vec![mk_huff(2)],
            gamma2: vec![mk_huff(0)],
            gamma3: vec![mk_huff(0)],
            gamma4: vec![mk_huff(2)],
            gamma5: vec![mk_huff(1)],
            gamma6: vec![mk_huff(1)],
        };
        let mut state = Acpl5xMchPcmState::new();
        // Reject mismatched lengths.
        let pcm_bad = vec![0.0f32; 65];
        assert!(
            run_acpl_5x_mch_pcm(&pcm_bad, &pcm_bad, &pcm_bad, &cfg, &data, &mut state).is_none()
        );
        // Run end-to-end on the well-formed frame.
        let out = run_acpl_5x_mch_pcm(&pcm_l, &pcm_r, &pcm_c, &cfg, &data, &mut state)
            .expect("synth runs");
        assert_eq!(out.left.len(), n);
        assert_eq!(out.right.len(), n);
        assert_eq!(out.centre.len(), n);
        assert_eq!(out.left_surround.len(), n);
        assert_eq!(out.right_surround.len(), n);
        let start = 2048usize;
        let energy =
            |b: &[f32]| -> f64 { b[start..].iter().map(|&s| (s as f64).powi(2)).sum::<f64>() };
        for b in [
            &out.left,
            &out.right,
            &out.centre,
            &out.left_surround,
            &out.right_surround,
        ] {
            for &s in b.iter() {
                assert!(s.is_finite(), "non-finite sample");
            }
        }
        assert!(energy(&out.left) > 1e-6, "left silent");
        assert!(energy(&out.right) > 1e-6, "right silent");
        assert!(energy(&out.centre) > 1e-6, "centre silent");
    }
}