1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
//! AC-4 IMS (Immersive Multichannel Service) encoder scaffold.
//!
//! Round 46 — Auditor-mode scaffold for the IMS encoder per ETSI
//! TS 103 190-2 V1.2.1 §6.2 / §6.3.2.1 (`ac4_toc()`). Emits a
//! structurally-valid `raw_ac4_frame()` with an IMS-flavoured TOC
//! (`bitstream_version = 2` + `ac4_presentation_v1_info()` +
//! `ac4_substream_group_info()`); the substream body itself is
//! all-zero placeholder bits — the encoder side of the audio pipeline
//! (MDCT analysis, scalefactor selection, ASF/SSF entropy coding, A-SPX
//! envelope coding, A-CPL parameter extraction) is deferred. The
//! decoder-side counterpart is expected to re-tile zeros back to
//! silence PCM.
//!
//! Round 47 fixes the v2 TOC bit layout to match the literal §6.2.1.1
//! / §6.2.1.3 / §6.3.2.5 syntax boxes (the round-46 scaffold skipped
//! `b_hsf_ext` / `b_single_substream` in `ac4_substream_group_info()`
//! and emitted a stale `ac4_presentation_v1_info()` skeleton missing
//! `mdcompat`, `frame_rate_fractions_info()`, `emdf_info()`,
//! `b_presentation_filter`, and the trailing
//! `ac4_substream_info_chan()` body). The matching v2 dispatch in
//! [`crate::toc::parse_ac4_toc`] now walks the same syntax, so v2
//! `Ac4ImsEncoder::encode_frame()` → `parse_ac4_toc` round-trips the
//! same `(channels, samples, sample_rate, b_iframe_global)` tuple as
//! the v0 path.
//!
//! The Auditor-mode goal is to land the public type surface and the
//! TOC writer so downstream tooling (TS 103 190-2 conformance
//! checkers, MP4 packagers, demux smoke tests) can pull a real frame
//! through the round-trip. Production-grade IMS encoding is multiple
//! weeks of work.
//!
//! ## What this scaffold does
//!
//! * Emits an IMS `ac4_toc()` frame header per §6.2.1.1 syntax box:
//! `bitstream_version` (2 b) + `sequence_counter` (10 b) +
//! `b_wait_frames` (1 b) + `fs_index` (1 b) + `frame_rate_index`
//! (4 b) + `b_iframe_global` (1 b) + `b_single_presentation` (1 b) +
//! `b_payload_base` (1 b). For `bitstream_version == 2` the per-pres
//! loop calls `ac4_presentation_v1_info()` (§6.2.1.3) followed by
//! the `ac4_substream_group_info()` element (§6.3.2.5). The encoder
//! produces a single-presentation, single-substream-group frame —
//! the smallest IMS shape that round-trips through a demuxer.
//!
//! * Provides a TS 103 190-1 fallback ([`Ac4ImsEncoder::encode_frame_v0`])
//! that emits a `bitstream_version == 0` TOC. The decoder in this
//! crate (which currently parses the v0 syntax — the v1 / v2 variant
//! from TS 103 190-2 is an orthogonal future round) accepts this
//! path and yields a structurally-valid silent `AudioFrame` of the
//! declared duration. The IMS-flavoured `encode_frame` itself is
//! round-trip-validated against a forward `parse_ac4_toc` call to
//! confirm the header bytes describe the same `(channels, samples,
//! sample_rate, b_iframe_global)` tuple back to the caller — even
//! though the `bitstream_version == 2` branch of `parse_ac4_toc`
//! itself isn't yet implemented.
//!
//! ## What this scaffold does NOT do
//!
//! * No MDCT analysis. The audio body is emitted as zero bits so the
//! `audio_size_value` field is honest about an empty payload.
//! * No A-SPX envelope coding, no A-CPL parameter extraction, no
//! metadata (DRC / DE / EMDF) emission — those are all silent /
//! absent in the produced frame.
//! * No `ac4_substream_group_info()` body beyond the
//! `b_substreams_present == 1` + `n_lf_substreams == 2` skeleton.
//! The `sus_ver` bit + the per-substream `b_audio_ndot` /
//! `b_pres_ndot` / `b_oamd_ndot` flags are all zero.
//! * No bit-rate signalling beyond `br_code = 0`.
use oxideav_core::bits::BitWriter;
use crate::encoder_asf::{
average_per_sfb_correlation, build_5_0_simple_asf_body_from_pcm_spectra,
build_5_1_simple_asf_body_from_pcm_spectra, build_7_0_simple_asf_body_from_pcm_spectra,
build_7_1_simple_asf_body_from_pcm_spectra, build_mono_simple_asf_body_from_pcm_spectrum,
build_stereo_simple_asf_joint_body_from_pcm_spectra,
build_stereo_simple_asf_split_body_from_pcm_spectra,
};
use crate::encoder_mdct::EncoderMdctState;
/// Encoder-side builder for AC-4 IMS frames. One instance per audio
/// stream — carries the 10-bit `sequence_counter` rolling counter and
/// the canonical frame layout (sample rate, frame-rate index, channel
/// mode) so each `encode_frame()` call produces a structurally-valid
/// output frame ready to wrap in a sync-frame (`0xAC40` / `0xAC41`)
/// or hand to an MP4 muxer.
///
/// Round 46 lands the Auditor-mode bit layout per ETSI TS 103 190-2
/// §6.2.1.1 — the audio body itself is all-zero placeholder bits.
#[derive(Debug, Clone)]
pub struct Ac4ImsEncoder {
/// `bitstream_version` value to emit (TS 103 190-2 Table 74).
/// `0` selects the TS 103 190-1 v0 path (`ac4_presentation_info()`
/// per-pres); `2` selects the IMS path
/// (`ac4_presentation_v1_info()` + `ac4_substream_group_info()`).
pub bitstream_version: u8,
/// Rolling 10-bit `sequence_counter` field — wraps modulo 1024.
pub sequence_counter: u16,
/// `fs_index` (1 b): 0 → 44.1 kHz, 1 → 48 kHz.
pub fs_index: u8,
/// `frame_rate_index` (4 b) per Table 83 / 84.
pub frame_rate_index: u8,
/// `b_iframe_global` flag for this frame.
pub b_iframe_global: bool,
/// Channel mode prefix code per Table 85 (TS 103 190-1) / Table
/// 78 (TS 103 190-2): `0b0` → mono, `0b10` → stereo, etc.
/// Encoded as the literal prefix in the low-order bits of
/// `channel_mode_value` with the bit count in
/// `channel_mode_bits`.
pub channel_mode_value: u8,
/// Bit-width of `channel_mode_value` (1..=11).
pub channel_mode_bits: u8,
/// Forward-MDCT analysis state for `encode_frame_pcm()`. Carries
/// the previous frame's `N` PCM samples so the 50% TDAC overlap
/// runs correctly across frames. Lazy-initialised on first use.
pub mdct_state: Option<EncoderMdctState>,
/// Forward-MDCT analysis state for the secondary (right) channel of
/// `encode_frame_pcm_stereo()`. Identical role to `mdct_state` but
/// for the second channel — separate so 50% TDAC overlap is
/// per-channel.
pub mdct_state_r: Option<EncoderMdctState>,
/// Forward-MDCT analysis state for the multichannel encoder paths
/// (`encode_frame_pcm_5_0()` and any future N>2 variants). One
/// [`EncoderMdctState`] per output channel — separate so 50% TDAC
/// overlap continuity is preserved per channel across frames. Lazy-
/// initialised on first use; grown to the required channel count.
pub mdct_states_multi: Vec<EncoderMdctState>,
}
impl Ac4ImsEncoder {
/// New encoder defaulting to the smallest-valid IMS shape:
/// `bitstream_version = 2`, sequence_counter = 0, 48 kHz, 24 fps
/// (`frame_rate_index = 1`), b_iframe_global = 1, mono channel
/// mode (`0b0`, 1 b).
pub fn new() -> Self {
Self {
bitstream_version: 2,
sequence_counter: 0,
fs_index: 1,
frame_rate_index: 1,
b_iframe_global: true,
channel_mode_value: 0b0,
channel_mode_bits: 1,
mdct_state: None,
mdct_state_r: None,
mdct_states_multi: Vec::new(),
}
}
/// Switch to a TS 103 190-1 v0 frame layout. The decoder in this
/// crate parses v0 today; v2 is structurally emitted but not yet
/// re-parsed end-to-end.
pub fn with_v0(mut self) -> Self {
self.bitstream_version = 0;
self
}
/// Stereo channel mode (`0b10`, 2 b).
pub fn with_stereo(mut self) -> Self {
self.channel_mode_value = 0b10;
self.channel_mode_bits = 2;
self
}
/// 5.0 channel mode (`0b1101`, 4 b) per Table 85 — channel_mode 3 —
/// the 5.0 surround layout (`L, R, C, Ls, Rs`) without LFE. Drives the
/// decoder's `5_X_channel_element()` walker for `channels == 5` (no
/// `b_has_lfe` block) and the corresponding `dispatch_5x_cfg3_simple_aspx`
/// PCM output path.
pub fn with_5_0(mut self) -> Self {
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
self
}
/// 5.1 channel mode (`0b1110`, 4 b) per Table 85.
pub fn with_5_1(mut self) -> Self {
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
self
}
/// 7.0 (3/4/0) channel mode (`0b1111000`, 7 b) per ETSI TS 103 190-1
/// §4.3.3.7.1 Table 88 — channel_mode value `1111000` → ch_mode 5 → 7
/// channels with layout `L, C, R, Ls, Rs, Lb, Rb`. Drives the decoder's
/// `7_X_channel_element()` walker for `channels == 7` (no `b_has_lfe`
/// — that branch is gated on channel_mode 6 / 7.1) per §4.2.6.14
/// Table 33. The decoder's internal coding order for the inner
/// `five_channel_data()` is `[L, R, C, Ls, Rs]` per Table 180 (the
/// inner SCE order differs from the surface Table 88 listing's `L, C,
/// R` ordering — the decoder treats the inner five_channel_data slots
/// as L/R/C/Ls/Rs).
pub fn with_7_0(mut self) -> Self {
self.channel_mode_value = 0b1111000;
self.channel_mode_bits = 7;
self
}
/// 7.1 (3/4/0.1) channel mode (`0b1111001`, 7 b) per ETSI TS 103 190-1
/// §4.3.3.7.1 Table 88 — channel_mode value `1111001` → ch_mode 6 → 8
/// channels with layout `L, C, R, Ls, Rs, Lb, Rb, LFE`. Drives the
/// decoder's `7_X_channel_element()` walker for `channels == 8` (with
/// `b_has_lfe`) per §4.2.6.14 Table 33. The decoder's internal coding
/// order for the inner `five_channel_data()` is `[L, R, C, Ls, Rs]`
/// per Table 180 (the inner SCE order differs from the surface
/// Table 88 listing's `L, C, R` ordering — the decoder treats the
/// inner five_channel_data slots as L/R/C/Ls/Rs).
pub fn with_7_1(mut self) -> Self {
self.channel_mode_value = 0b1111001;
self.channel_mode_bits = 7;
self
}
/// Encode one Auditor-mode frame: emits a `raw_ac4_frame()`
/// payload (TOC + minimum-viable substream skeleton) and bumps
/// `sequence_counter`. Returns the produced bytes.
pub fn encode_frame(&mut self, body_padding_bytes: usize) -> Vec<u8> {
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut frame = bw.finish();
// Pad the substream body with zeros so downstream demuxers see
// a non-empty frame. `body_padding_bytes` lets callers tune
// the final frame size for size-table tests.
if body_padding_bytes > 0 {
frame.extend(vec![0u8; body_padding_bytes]);
}
// sequence_counter is 10 bits — wrap modulo 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
frame
}
/// Encode the same frame at `bitstream_version = 0` regardless of
/// the encoder's configured version — used by the round-trip test
/// to feed a TS 103 190-1-decodable frame back through
/// [`crate::toc::parse_ac4_toc`].
pub fn encode_frame_v0(&mut self, body_padding_bytes: usize) -> Vec<u8> {
let saved = self.bitstream_version;
self.bitstream_version = 0;
let f = self.encode_frame(body_padding_bytes);
self.bitstream_version = saved;
f
}
/// Emit the `ac4_toc()` element per ETSI TS 103 190-2 §6.2.1.1.
/// The leading shared-with-v0 prefix is identical
/// (bitstream_version + sequence_counter + b_wait_frames +
/// fs_index + frame_rate_index + b_iframe_global +
/// b_single_presentation + b_payload_base + per-presentation
/// loop). For `bitstream_version <= 1` the per-pres loop runs
/// `ac4_presentation_info()` (TS 103 190-1 Table 5); for
/// `bitstream_version >= 2` it runs `ac4_presentation_v1_info()`
/// (TS 103 190-2 §6.2.1.3) then the per-substream-group
/// `ac4_substream_group_info()` (§6.3.2.5).
fn write_toc(&self, bw: &mut BitWriter) {
// bitstream_version (2 b) — Table 74.
bw.write_u32(self.bitstream_version as u32, 2);
// sequence_counter (10 b).
bw.write_u32(self.sequence_counter as u32, 10);
// b_wait_frames = 0.
bw.write_u32(0, 1);
// fs_index (1 b), frame_rate_index (4 b).
bw.write_u32(self.fs_index as u32, 1);
bw.write_u32(self.frame_rate_index as u32, 4);
// b_iframe_global, b_single_presentation = 1.
bw.write_u32(if self.b_iframe_global { 1 } else { 0 }, 1);
bw.write_u32(1, 1);
// b_payload_base = 0.
bw.write_u32(0, 1);
if self.bitstream_version <= 1 {
self.write_presentation_v0(bw);
} else {
// TS 103 190-2 §6.2.1.1: for bitstream_version > 1 the TOC
// carries a single `b_program_id` flag (no short_program_id /
// program_uuid in this scaffold), then the per-pres
// `ac4_presentation_v1_info()` loop, then the per-group
// `ac4_substream_group_info()` loop. Round 47 emits a
// single-presentation, single-substream-group frame: the
// smallest IMS shape that round-trips through `parse_ac4_toc`.
bw.write_u32(0, 1); // b_program_id = 0 (no program identifier)
self.write_presentation_v1_info(bw);
self.write_substream_group_info(bw);
}
// substream_index_table(): n_substreams = 1, b_size_present = 0
// (single-substream layout).
bw.write_u32(1, 2);
bw.write_u32(0, 1);
}
/// `ac4_presentation_info()` per ETSI TS 103 190-1 §4.3.3.3
/// (Table 5) — single-substream form for the `bitstream_version
/// <= 1` path. Mirrors the existing `build_mono_toc()` /
/// `build_minimal_toc()` test helpers in `decoder.rs` so
/// `parse_ac4_toc` accepts the produced frame end-to-end.
fn write_presentation_v0(&self, bw: &mut BitWriter) {
// ac4_presentation_info():
bw.write_u32(1, 1); // b_single_substream
bw.write_u32(0, 1); // presentation_version = 0
bw.write_u32(0, 3); // md_compat
bw.write_u32(0, 1); // b_belongs_to_presentation_id
bw.write_u32(0, 1); // frame_rate_multiply_info bit
// emdf_info():
bw.write_u32(0, 2); // emdf_version
bw.write_u32(0, 3); // key_id
bw.write_u32(0, 1); // b_emdf_payloads_substream_info
bw.write_u32(0, 1); // emdf_reserved.b_more
// ac4_substream_info():
bw.write_u32(
self.channel_mode_value as u32,
self.channel_mode_bits as u32,
);
bw.write_u32(0, 1); // b_sf_multiplier
bw.write_u32(0, 1); // b_bitrate_info
bw.write_u32(0, 1); // b_content_type
bw.write_u32(1, 1); // b_iframe
bw.write_u32(0, 2); // substream_index
bw.write_u32(0, 1); // b_pre_virtualized
bw.write_u32(0, 1); // b_add_emdf_substreams
}
/// `ac4_presentation_v1_info()` per ETSI TS 103 190-2 §6.2.1.3 —
/// single-substream-group form for `bitstream_version >= 2`:
/// `b_single_substream_group = 1`, then `presentation_version() = 0`
/// (single zero-bit since `bitstream_version != 1`), `mdcompat = 0`,
/// `b_presentation_id = 0`, `frame_rate_multiply_info()` (one bit
/// for `frame_rate_index = 1`), `frame_rate_fractions_info()`
/// (zero bits for index 1), `emdf_info()` (minimum form),
/// `b_presentation_filter = 0`, `ac4_sgi_specifier()` referencing
/// `group_index = 0`, `b_pre_virtualized = 0`,
/// `b_add_emdf_substreams = 0`, and `ac4_presentation_substream_info()`
/// (b_alternative = 0, b_pres_ndot = !iframe, substream_index = 0).
fn write_presentation_v1_info(&self, bw: &mut BitWriter) {
// b_single_substream_group = 1.
bw.write_u32(1, 1);
// presentation_version() = 0 — single '0' bit (loop terminates
// immediately). Emitted for bitstream_version != 1.
bw.write_u32(0, 1);
// mdcompat = 0 (3 b) — emitted for bitstream_version != 1.
bw.write_u32(0, 3);
// b_presentation_id = 0.
bw.write_u32(0, 1);
// frame_rate_multiply_info(): single b_multiplier bit for
// frame_rate_index in {0, 1, 7, 8, 9}.
bw.write_u32(0, 1);
// frame_rate_fractions_info(): nothing for frame_rate_index < 5
// or > 12.
// emdf_info(): emdf_version=0 (2b), key_id=0 (3b),
// b_emdf_payloads_substream_info=0, emdf_reserved.b_more=0.
bw.write_u32(0, 2);
bw.write_u32(0, 3);
bw.write_u32(0, 1);
bw.write_u32(0, 1);
// b_presentation_filter = 0.
bw.write_u32(0, 1);
// ac4_sgi_specifier(): group_index = 0 (3 b, no variable_bits
// extension since group_index < 7).
bw.write_u32(0, 3);
// b_pre_virtualized = 0, b_add_emdf_substreams = 0.
bw.write_u32(0, 1);
bw.write_u32(0, 1);
// ac4_presentation_substream_info(): b_alternative = 0,
// b_pres_ndot = !b_iframe_global, substream_index = 0 (2 b).
bw.write_u32(0, 1);
bw.write_u32(if self.b_iframe_global { 0 } else { 1 }, 1);
bw.write_u32(0, 2);
}
/// `ac4_substream_group_info()` per ETSI TS 103 190-2 §6.3.2.5 —
/// single channel-coded substream skeleton matching the encoder's
/// `n_substreams = 1` substream_index_table.
fn write_substream_group_info(&self, bw: &mut BitWriter) {
// b_substreams_present = 1.
bw.write_u32(1, 1);
// b_hsf_ext = 0 — no high-sample-rate extension.
bw.write_u32(0, 1);
// b_single_substream = 1 — n_lf_substreams = 1.
bw.write_u32(1, 1);
// b_channel_coded = 1 — channel-based audio (vs object).
bw.write_u32(1, 1);
// ac4_substream_info_chan(b_substreams_present = 1):
// channel_mode = encoder field (1..7 b),
// fs_index == 1: b_sf_multiplier = 0,
// b_bitrate_info = 0,
// frame_rate_factor copies of b_audio_ndot = !iframe,
// substream_index = 0 (2 b, since b_substreams_present = 1).
bw.write_u32(
self.channel_mode_value as u32,
self.channel_mode_bits as u32,
);
if self.fs_index == 1 {
bw.write_u32(0, 1); // b_sf_multiplier
}
bw.write_u32(0, 1); // b_bitrate_info
// frame_rate_factor for {0,1,7,8,9} with
// b_multiplier=0 is 1; for {2,3,4} also 1; otherwise 1.
// → 1 b_audio_ndot bit.
bw.write_u32(if self.b_iframe_global { 0 } else { 1 }, 1);
bw.write_u32(0, 2); // substream_index
// b_content_type = 0.
bw.write_u32(0, 1);
}
}
impl Default for Ac4ImsEncoder {
fn default() -> Self {
Self::new()
}
}
/// Build a mono SIMPLE/ASF `ac4_substream()` body that injects a single
/// quantised spectral line at the specified scale-factor band. The
/// payload is sized for `transform_length = 1920` (24 fps @ 48 kHz)
/// with `max_sfb = 10`, matching the encoder's default frame layout.
///
/// `tone_cb_idx` selects the HCB5 codeword for the first spectral pair
/// — `49` (q0=+1, q1=0) is the simplest signal-bearing choice. The
/// remaining pairs all use codeword `40` (q0=0, q1=0). Reference scale
/// factor is 120 (`sf_gain = 32.0`).
///
/// The returned bytes are the substream body (no TOC) that should be
/// concatenated after the byte-aligned `ac4_toc()` element. They are
/// padded to `pad_target_bytes` bytes with zeros so the
/// `audio_size_value` field in the header matches the actual payload
/// length.
///
/// Per ETSI TS 103 190-1 §5.7 (SIMPLE mode) + §5.8 (ASF). The full
/// closed-form encoder for arbitrary input PCM (MDCT analysis +
/// scalefactor selection + entropy coding) is deferred — round 47
/// ships the canned-tone path so the encoder can produce non-silent
/// PCM end-to-end.
pub fn build_mono_simple_asf_tone_body(
transform_length: u32,
max_sfb: u32,
tone_cb_idx: usize,
tone_pair_idx: u32,
pad_target_bytes: usize,
) -> Vec<u8> {
let mut bw = BitWriter::new();
// ac4_substream() per §5.7.1: audio_size_value (15 b) + b_more_bits
// (1 b). We declare the announced size as the pad target so the
// outer demuxer reads the entire padded body. b_more_bits = 0 so
// the 15-bit field is taken literally.
let audio_size = pad_target_bytes as u32;
let audio_size_lo = audio_size & 0x7FFF;
bw.write_u32(audio_size_lo, 15);
bw.write_bit(false);
bw.align_to_byte();
// audio_data() for channel_mode = 0 (mono), b_iframe = 1:
// mono_codec_mode = 0 (SIMPLE), spec_frontend = 0 (ASF),
// asf_transform_info() with b_long_frame = 1,
// asf_psy_info(0, 0) with max_sfb[0] in 6 bits.
bw.write_u32(0, 1); // mono_codec_mode = SIMPLE
bw.write_u32(0, 1); // spec_frontend = ASF
bw.write_bit(true); // b_long_frame = 1
bw.write_u32(max_sfb, 6); // max_sfb[0]
// asf_section_data: one section covering 0..max_sfb with cb=5
// (HCB5, dim=2, signed). n_sect_bits = 3 (transf_length_idx=0
// for long frame).
bw.write_u32(5, 4); // sect_cb
write_sect_len_incr(&mut bw, max_sfb, 3, 7);
// asf_spectral_data: emit `tone_cb_idx` for pair `tone_pair_idx`,
// and codeword 40 (q0=0, q1=0) for every other pair.
let sfbo = crate::sfb_offset::sfb_offset_48(transform_length).expect("invalid tl");
let end_line = sfbo[max_sfb as usize] as u32;
let hcb = crate::huffman::asf_hcb(5u32).expect("HCB5 must exist");
let pairs = end_line / 2;
let zero_cw = hcb.cw[40];
let zero_len = hcb.len[40] as u32;
let tone_cw = hcb.cw[tone_cb_idx];
let tone_len = hcb.len[tone_cb_idx] as u32;
for p in 0..pairs {
if p == tone_pair_idx {
bw.write_u32(tone_cw, tone_len);
} else {
bw.write_u32(zero_cw, zero_len);
}
}
// asf_scalefac_data: reference_scale_factor = 120 → sf_gain = 32.0.
bw.write_u32(120, 8);
// asf_snf_data: b_snf_data_exists = 0.
bw.write_u32(0, 1);
bw.align_to_byte();
while bw.byte_len() < pad_target_bytes {
bw.write_u32(0, 8);
}
bw.finish()
}
/// Write a section-length increment sequence per §4.3.5.4
/// (Pseudocode 17). For `n_sect_bits = 3`, escape value 7,
/// `sect_len = 1 + 7k + incr`: emit `k` escape codes followed by one
/// non-escape `incr` (0..6).
fn write_sect_len_incr(bw: &mut BitWriter, sect_len: u32, n_sect_bits: u32, esc: u32) {
let base = sect_len.saturating_sub(1);
let k = base / esc;
let incr = base % esc;
for _ in 0..k {
bw.write_u32(esc, n_sect_bits);
}
bw.write_u32(incr, n_sect_bits);
}
impl Ac4ImsEncoder {
/// Encode one IMS v2 frame containing a mono SIMPLE/ASF audio
/// substream that injects a single quantised spectral tone (per
/// `tone_cb_idx` from the ETSI Annex A HCB5 codebook). The decoder
/// dequantises the tone via `rec_spec = sign(q)|q|^(4/3)` and the
/// IMDCT + KBD windowing produce real, non-silent PCM.
///
/// This is the canned-tone closed-form encoder mentioned in round-47
/// scope: full MDCT analysis + scalefactor optimisation + ASF
/// entropy coding for arbitrary PCM input is deferred. The shape
/// of this method (input PCM → bytes) is reserved for that future
/// work; for now it ignores its `_input_pcm` argument and emits
/// the canned tone payload.
///
/// Per ETSI TS 103 190-1 §5.7 + §5.8.
pub fn encode_frame_mono_tone(&mut self, tone_cb_idx: usize, tone_pair_idx: u32) -> Vec<u8> {
// Force mono channel_mode for the tone helper — the canned ASF
// body is mono SIMPLE only.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b0;
self.channel_mode_bits = 1;
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut frame = bw.finish();
// Append the canned-tone substream body. Size matches the test
// helpers in `decoder.rs` (420 bytes) so the substream parser
// sees a complete payload.
let body = build_mono_simple_asf_tone_body(1920, 10, tone_cb_idx, tone_pair_idx, 420);
frame.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
frame
}
/// Encode one IMS v2 mono frame from arbitrary float PCM input
/// (range `[-1.0, 1.0]`). Returns the produced frame bytes.
///
/// Pipeline (round 48):
/// 1. Forward MDCT analysis with KBD windowing across the 50% TDAC
/// boundary (carries prior-frame `N` samples in the per-encoder
/// [`EncoderMdctState`]).
/// 2. Per-band scalefactor selection (greedy nearest power-of-two
/// that keeps |q| within the chosen Huffman codebook's bound).
/// 3. Quantisation per Pseudocode 18 inverse:
/// `q = round(sign(c) * (|c|/sf_gain)^(3/4))`.
/// 4. ASF entropy coding via HCB5 (signed dim=2, q-range -4..=+4).
/// 5. Wrap in v2 IMS TOC + single-substream-group `audio_size` body.
///
/// Frame length is derived from the encoder's
/// `(fs_index, frame_rate_index)` pair via [`crate::toc::frame_rate_entry`].
/// For the default mono 48 kHz / 24 fps configuration `frame.len()` is
/// 1920 samples and `max_sfb` is 10 (matching the canned-tone helper).
///
/// Per ETSI TS 103 190-1 §5.5 (MDCT) + §5.7 / §5.8 (SIMPLE/ASF) +
/// TS 103 190-2 §6.2.1.1 (IMS TOC).
pub fn encode_frame_pcm(&mut self, frame: &[f32]) -> Vec<u8> {
// Default max_sfb = 40 (≤ 7.5 kHz at tl=1920) preserves
// round-48 behaviour for callers that haven't opted in to the
// wider-bandwidth encoder.
self.encode_frame_pcm_with_max_sfb(frame, 40)
}
/// Encode one IMS v2 mono frame from arbitrary float PCM input
/// (range `[-1.0, 1.0]`) at a caller-specified `max_sfb`. Larger
/// values widen the encoder's frequency coverage at the cost of
/// more bits per frame:
/// * `max_sfb = 40` → bins 0..508 → ~6.35 kHz @ tl=1920
/// * `max_sfb = 50` → bins 0..1216 → ~15.2 kHz @ tl=1920
/// * `max_sfb = 55` → bins 0..1600 → ~20.0 kHz @ tl=1920
///
/// `max_sfb` must satisfy `max_sfb <= num_sfb_48(frame_len)` (61 at
/// tl=1920). The pad budget scales with max_sfb so the announced
/// `audio_size` reliably exceeds the actual emission length.
pub fn encode_frame_pcm_with_max_sfb(&mut self, frame: &[f32], max_sfb: u32) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
assert_eq!(
frame.len(),
frame_len as usize,
"encode_frame_pcm: input length must match frame_len = {frame_len}"
);
// Force mono — the forward analysis path is mono-only. (Multi-
// channel needs SAP/M-S decision + per-channel state which is
// queued for round-50+.)
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b0;
self.channel_mode_bits = 1;
// 1. Forward MDCT analysis. Lazily build per-encoder state.
if self.mdct_state.is_none() || self.mdct_state.as_ref().unwrap().n != frame_len {
self.mdct_state = Some(EncoderMdctState::new(frame_len));
}
let coeffs = self.mdct_state.as_mut().unwrap().analyse_frame(frame);
// 2-4. Build the substream body (per-band codebook optimiser +
// entropy-coding). Pad target scales with max_sfb to keep the
// announced audio_size comfortably above the actual emission
// length: worst case is ~25 bits/pair (HCB11 with one escape
// per pair) × end_bin/2 pairs ≈ 3 × end_bin bytes.
let pad_target_bytes = match max_sfb {
0..=40 => 2048,
41..=50 => 4096,
_ => 8192,
};
let body = build_mono_simple_asf_body_from_pcm_spectrum(
frame_len,
max_sfb,
&coeffs,
pad_target_bytes,
);
// 5. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 stereo frame from arbitrary float PCM input
/// (range `[-1.0, 1.0]`) for both L and R. Returns the produced
/// frame bytes.
///
/// **Path A — 2× SCE (split-MDCT)** per ETSI TS 103 190-1 §5.3 +
/// §4.2.6.3 Table 22 (`stereo_data()` with
/// `b_enable_mdct_stereo_proc == 0`): each channel is encoded
/// independently with the shared forward analysis pipeline (KBD-
/// windowed MDCT, per-band scalefactor, DP-optimal sectioning,
/// HCB1..11 codebook selection, SNF emission). No joint M/S coding.
///
/// `frame_l` / `frame_r` must each be exactly `frame_len` samples
/// long (1920 samples for the default 48 kHz / 24 fps configuration).
/// The encoder forces stereo channel mode (`channel_mode_value =
/// 0b10`) for this call. The decoder's
/// [`crate::asf::parse_stereo_data_body_stateful`] split-MDCT path
/// consumes the frame and reconstructs both channels through the
/// shared ASF Huffman pipeline.
///
/// `max_sfb` defaults to 40 (matching the round-48 mono default,
/// covers bins 0..508 ≈ 0..6.35 kHz at tl = 1920) when called via
/// [`Self::encode_frame_pcm_stereo`]; use
/// [`Self::encode_frame_pcm_stereo_with_max_sfb`] for wider coverage.
/// The decoder's split-MDCT branch reads BOTH L and R `max_sfb` with
/// the full `n_msfb_bits` width (the spec's `b_side_limited` only
/// applies to joint-MDCT stereo per §4.3.6.2), so the encoder isn't
/// limited by the narrower `n_side_bits`.
///
/// Per ETSI TS 103 190-1 §5.3 + §4.2.6.3 + §5.5 (MDCT) +
/// §5.7 / §5.8 (SIMPLE/ASF) + TS 103 190-2 §6.2.1.1 (IMS TOC).
pub fn encode_frame_pcm_stereo(&mut self, frame_l: &[f32], frame_r: &[f32]) -> Vec<u8> {
// Default max_sfb = 40 (matches the round-48 mono default).
self.encode_frame_pcm_stereo_with_max_sfb(frame_l, frame_r, 40)
}
/// Round-52 heuristic threshold for joint M/S coding. When the
/// per-SFB average Pearson correlation between L and R MDCT spectra
/// exceeds this value, the encoder switches to Path B (joint M/S CPE,
/// `b_enable_mdct_stereo_proc == 1`); otherwise Path A (split-MDCT,
/// 2× SCE) is used. The 0.7 threshold matches the spec's §5.3
/// guidance plus the headline number cited in this crate's round-52
/// task brief.
pub const STEREO_JOINT_MS_CORRELATION_THRESHOLD: f32 = 0.7;
/// Encode one IMS v2 stereo frame from arbitrary float PCM input
/// (range `[-1.0, 1.0]`) at a caller-specified `max_sfb`. Both
/// channels use the same `max_sfb` — the encoder uses the full
/// `n_msfb_bits` field width for both. See
/// [`Self::encode_frame_pcm_stereo`].
///
/// **Round 52 — Path A vs Path B dispatch.** The encoder computes the
/// per-SFB average Pearson correlation between the L and R MDCT
/// spectra (via [`average_per_sfb_correlation`]) and, when it exceeds
/// [`Self::STEREO_JOINT_MS_CORRELATION_THRESHOLD`] (default 0.7),
/// switches to **joint M/S CPE (Path B,
/// `b_enable_mdct_stereo_proc == 1`)** per ETSI TS 103 190-1 §5.3 +
/// §4.2.6.3 Table 22 + §7.5 (Pseudocode 77). Otherwise it stays on
/// the round-51 split-MDCT path (Path A, 2× SCE,
/// `b_enable_mdct_stereo_proc == 0`). Per-SFB M/S vs L/R selection
/// within the joint path is driven by the natural-q bit-cost
/// comparison inside
/// [`build_stereo_simple_asf_joint_body_from_pcm_spectra`].
///
/// Use [`Self::encode_frame_pcm_stereo_split_with_max_sfb`] or
/// [`Self::encode_frame_pcm_stereo_joint_with_max_sfb`] to force a
/// specific path regardless of correlation.
pub fn encode_frame_pcm_stereo_with_max_sfb(
&mut self,
frame_l: &[f32],
frame_r: &[f32],
max_sfb: u32,
) -> Vec<u8> {
self.encode_frame_pcm_stereo_dispatched(frame_l, frame_r, max_sfb, None)
}
/// Force the split-MDCT (Path A: 2× SCE) encoder path regardless of
/// the L-vs-R correlation. Useful for tests / fixtures that need a
/// deterministic on-wire layout. See
/// [`Self::encode_frame_pcm_stereo_with_max_sfb`].
pub fn encode_frame_pcm_stereo_split_with_max_sfb(
&mut self,
frame_l: &[f32],
frame_r: &[f32],
max_sfb: u32,
) -> Vec<u8> {
self.encode_frame_pcm_stereo_dispatched(frame_l, frame_r, max_sfb, Some(false))
}
/// Force the joint-MDCT (Path B: M/S CPE) encoder path regardless of
/// the L-vs-R correlation. Useful for tests / fixtures that need a
/// deterministic on-wire layout. See
/// [`Self::encode_frame_pcm_stereo_with_max_sfb`].
pub fn encode_frame_pcm_stereo_joint_with_max_sfb(
&mut self,
frame_l: &[f32],
frame_r: &[f32],
max_sfb: u32,
) -> Vec<u8> {
self.encode_frame_pcm_stereo_dispatched(frame_l, frame_r, max_sfb, Some(true))
}
/// Shared body for the stereo encode dispatch — runs forward MDCT,
/// computes the cross-channel correlation (when `force_joint` is
/// `None`) and picks Path A vs Path B accordingly. `force_joint =
/// Some(true)` always emits joint M/S, `Some(false)` always emits
/// split-MDCT, `None` selects via the
/// [`Self::STEREO_JOINT_MS_CORRELATION_THRESHOLD`] threshold.
fn encode_frame_pcm_stereo_dispatched(
&mut self,
frame_l: &[f32],
frame_r: &[f32],
max_sfb: u32,
force_joint: Option<bool>,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
assert_eq!(
frame_l.len(),
frame_len as usize,
"encode_frame_pcm_stereo: L input length must match frame_len = {frame_len}"
);
assert_eq!(
frame_r.len(),
frame_len as usize,
"encode_frame_pcm_stereo: R input length must match frame_len = {frame_len}"
);
// Cap max_sfb at n_msfb_bits=6's max (63 for tl=1920) and at the
// transform's actual `num_sfb_48` cap (61 at tl=1920).
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force stereo channel_mode (prefix '10', 2 bits) — both the
// split-MDCT and joint-MDCT body builders require the TOC to
// declare 2 channels.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b10;
self.channel_mode_bits = 2;
// 1. Forward MDCT analysis per channel (separate state for
// independent 50% TDAC overlap continuity).
if self.mdct_state.is_none() || self.mdct_state.as_ref().unwrap().n != frame_len {
self.mdct_state = Some(EncoderMdctState::new(frame_len));
}
if self.mdct_state_r.is_none() || self.mdct_state_r.as_ref().unwrap().n != frame_len {
self.mdct_state_r = Some(EncoderMdctState::new(frame_len));
}
let coeffs_l = self.mdct_state.as_mut().unwrap().analyse_frame(frame_l);
let coeffs_r = self.mdct_state_r.as_mut().unwrap().analyse_frame(frame_r);
// 2. Path A vs Path B dispatch per round-52 heuristic.
let use_joint = match force_joint {
Some(b) => b,
None => {
let rho = average_per_sfb_correlation(frame_len, max_sfb, &coeffs_l, &coeffs_r);
rho >= Self::STEREO_JOINT_MS_CORRELATION_THRESHOLD
}
};
// 3-5. Build the stereo body. Pad budget is 2× the mono budget
// since we carry two spectra (joint or split).
let pad_target_bytes = match max_sfb {
0..=20 => 2048,
21..=40 => 4096,
41..=50 => 8192,
_ => 16384,
};
let body = if use_joint {
build_stereo_simple_asf_joint_body_from_pcm_spectra(
frame_len,
max_sfb,
&coeffs_l,
&coeffs_r,
pad_target_bytes,
)
} else {
build_stereo_simple_asf_split_body_from_pcm_spectra(
frame_len,
max_sfb,
&coeffs_l,
&coeffs_r,
pad_target_bytes,
)
};
// 6. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame from arbitrary float PCM input (range
/// `[-1.0, 1.0]`) for L, R, C, Ls, Rs.
///
/// **Path SIMPLE/Cfg3Five — 5 SCE multichannel forward analysis** per
/// ETSI TS 103 190-1 §4.2.6.6 Table 25 row `case SIMPLE: coding_config ==
/// 3` + §4.2.7.5 Table 29 (`five_channel_data()`): each of the five
/// channels is encoded independently with the shared forward-analysis
/// pipeline (KBD-windowed MDCT, per-band scalefactor, DP-optimal
/// section partition, HCB1..11 codebook selection, SNF emission). One
/// shared `sf_info(ASF, 0, 0)` precedes the per-channel data; the
/// `five_channel_info()` uses identity SAP (`sap_mode = 0` on every
/// `chparam_info()`, `chel_matsel = 0`) so no joint-MDCT mixing happens
/// at decode time — every output channel comes straight from its own
/// `sf_data(ASF)` body. This is the spec-mandated minimum for the 5.0
/// SIMPLE path and unblocks the encoder's path to multichannel.
///
/// `frames[i]` must each be exactly `frame_len` samples long
/// (1920 samples for the default 48 kHz / 24 fps configuration). The
/// slice order matches the 5.0 output layout (`L, R, C, Ls, Rs` —
/// Table 180 row `coding_config == 3`). The encoder forces the 5.0
/// channel mode (`channel_mode_value = 0b1101`, 4 b — Table 85
/// channel_mode 3) for this call.
///
/// The decoder's [`crate::mch::parse_5x_audio_data_outer`] for
/// `channels == 5` (no LFE) consumes the body, IMDCTs each per-channel
/// spectrum into slots 0..4, and emits 5-channel interleaved S16 PCM at
/// the declared sample rate. There is no companding / ASPX / A-CPL on
/// the SIMPLE path so the round-trip is purely the per-channel MDCT
/// quantisation noise (≥ 20 dB spectral SNR per channel on tone /
/// white-noise fixtures).
///
/// `max_sfb` defaults to 40 (matching the round-49 mono default).
/// Use [`Self::encode_frame_pcm_5_0_with_max_sfb`] for wider coverage.
///
/// Per ETSI TS 103 190-1 §4.2.6.6 + §4.2.7.5 + §5.5 (MDCT) +
/// §5.7 / §5.8 (SIMPLE/ASF) + TS 103 190-2 §6.2.1.1 (IMS TOC).
pub fn encode_frame_pcm_5_0(&mut self, frames: &[&[f32]; 5]) -> Vec<u8> {
// Default max_sfb = 40 (matches the round-48 mono default).
self.encode_frame_pcm_5_0_with_max_sfb(frames, 40)
}
/// Encode one IMS v2 5.0 frame from arbitrary float PCM input at a
/// caller-specified `max_sfb`. All five channels share the same
/// `max_sfb` (the joint `sf_info` header carries one value). See
/// [`Self::encode_frame_pcm_5_0`] for the rest of the contract.
pub fn encode_frame_pcm_5_0_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
max_sfb: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0: channel {ch} input length must match frame_len = {frame_len}"
);
}
// Cap max_sfb at n_msfb_bits=6's max (63 for tl=1920) and at the
// transform's actual `num_sfb_48` cap (61 at tl=1920).
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 5.0 channel_mode (prefix '1101', 4 bits — Table 85
// channel_mode 3). The body builder requires the TOC to declare
// 5 channels so the decoder's `walk_ac4_substream` dispatch
// routes through `parse_5x_audio_data_outer(b_has_lfe = false)`.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
// 1. Forward MDCT analysis per channel (separate state for
// independent 50% TDAC overlap continuity).
while self.mdct_states_multi.len() < 5 {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
// Run analyses sequentially — borrow each state mutably one at a
// time so we don't conflict on `self.mdct_states_multi`.
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(5);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// 2-4. Build the 5.0 SIMPLE/Cfg3Five body. Pad budget is 5× the
// mono budget since we carry five spectra independently.
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = build_5_0_simple_asf_body_from_pcm_spectra(
frame_len,
max_sfb,
&[
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
],
pad_target_bytes,
);
// 5. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.1 frame from float PCM input per ETSI
/// TS 103 190-1 §4.2.6.6 + §4.2.7.5 + TS 103 190-2 §6.2.1.1, building
/// on top of the 5.0 Cfg3Five forward analysis path with an extra
/// LFE `mono_data(1)` element per Table 25
/// (`if (b_has_lfe) mono_data(1);`).
///
/// `frames` is in `[L, R, C, Ls, Rs, LFE]` order. Each slice must
/// have length `frame_len` (1920 for the default 48 kHz / 24 fps
/// configuration); panics otherwise.
///
/// The encoder forces the 5.1 channel_mode prefix (`0b1110`, 4 b —
/// Table 85 channel_mode 4) so the decoder's
/// `walk_ac4_substream` dispatches `channels == 6` through
/// `parse_5x_audio_data_outer(b_has_lfe = true)`. The LFE channel
/// is coded with `sf_info_lfe()` (Table 35) carrying `max_sfb` in
/// `n_msfbl_bits` bits (Table 106 column 4 — 3 bits for `tl = 1920`
/// → max_sfb_lfe is capped at 7). The five non-LFE channels share
/// the same Cfg3Five `five_channel_data()` body as the 5.0 path
/// (identity SAP, independent per-channel SCE).
///
/// `max_sfb` defaults to 40 (matching the round-49 mono / round-74
/// 5.0 default); `max_sfb_lfe` defaults to 7 (the LFE-spec cap at
/// `tl = 1920`). Use [`Self::encode_frame_pcm_5_1_with_max_sfb`]
/// for wider coverage.
pub fn encode_frame_pcm_5_1(&mut self, frames: &[&[f32]; 6]) -> Vec<u8> {
self.encode_frame_pcm_5_1_with_max_sfb(frames, 40, 7)
}
/// Encode one IMS v2 5.1 frame from arbitrary float PCM input at
/// caller-specified `max_sfb` (non-LFE channels) and `max_sfb_lfe`
/// (LFE channel). See [`Self::encode_frame_pcm_5_1`] for the rest of
/// the contract.
pub fn encode_frame_pcm_5_1_with_max_sfb(
&mut self,
frames: &[&[f32]; 6],
max_sfb: u32,
max_sfb_lfe: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_1: channel {ch} input length must match frame_len = {frame_len}"
);
}
// Cap max_sfb at the non-LFE max_sfb width's max and at the actual
// num_sfb_48 cap.
let (n_msfb_bits, _, n_msfbl_bits) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
assert!(
n_msfbl_bits > 0,
"encode_frame_pcm_5_1: tl = {frame_len} not permitted for LFE"
);
let n_msfbl_cap = (1u32 << n_msfbl_bits) - 1;
let max_sfb_lfe = max_sfb_lfe.min(n_msfbl_cap);
// Force 5.1 channel_mode (prefix '1110', 4 bits — Table 85
// channel_mode 4). The body builder requires the TOC to declare
// 6 channels so the decoder's `walk_ac4_substream` dispatch
// routes through `parse_5x_audio_data_outer(b_has_lfe = true)`.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
// 1. Forward MDCT analysis per channel (separate state for
// independent 50% TDAC overlap continuity). Six channels here
// so the multi-channel state vector needs to grow.
while self.mdct_states_multi.len() < 6 {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(6);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// 2-4. Build the 5.1 SIMPLE/Cfg3Five body. Pad budget is 6× the
// mono budget since we carry six spectra independently.
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = build_5_1_simple_asf_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_lfe,
&[
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[5],
],
pad_target_bytes,
);
// 5. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 7.0 (3/4/0) frame from float PCM input per ETSI
/// TS 103 190-1 §4.2.6.14 Table 33 + §4.2.7.5 Table 29
/// (`five_channel_data()`) + §4.2.7.4 Table 26 (`two_channel_data()`).
/// The non-LFE immersive counterpart of
/// [`Self::encode_frame_pcm_7_1`] — same `7_X_codec_mode = SIMPLE` +
/// `coding_config = Cfg3Five` body shape, but the walker's
/// `if (b_has_lfe) mono_data(1);` branch is omitted (`b_has_lfe =
/// false` for channel_mode 5 / 7.0).
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb]` order — the inner
/// `five_channel_data()` (Table 180) carries the front/surround pair
/// `L/R/C/Ls/Rs` and the SIMPLE/ASPX additional-channel block carries
/// the immersive back pair `Lb/Rb` via a trailing
/// `two_channel_data()` per Table 26. The encoder uses identity SAP
/// (`b_use_sap_add_ch = 0`, `sap_mode = 0` on every `chparam_info`)
/// so no joint-MDCT mixing happens at decode time: every output
/// channel comes straight from its own `sf_data(ASF)` body.
///
/// The encoder forces the 7.0 channel_mode prefix (`0b1111000`, 7 b —
/// Table 88 channel_mode 5) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 7` through
/// `parse_7x_audio_data_outer(b_has_lfe = false)`. The five
/// front/surround channels share the same Cfg3Five
/// `five_channel_data()` body as the 5.0 / 5.1 / 7.1 paths; the
/// additional pair (Lb, Rb) rides the trailing `two_channel_data()`
/// which the decoder's `dispatch_7x_additional_channel_pair` (Table
/// 183 row "3/4/0.x" identity path) routes into output slots 5 / 6.
///
/// `max_sfb` defaults to 40 (matching the round-49 mono / round-74
/// 5.0 / round-80 5.1 / round-91 7.1 default); `max_sfb_add`
/// defaults to 40 (same width as the 7.0 non-additional channels).
/// Use [`Self::encode_frame_pcm_7_0_with_max_sfb`] for wider coverage.
pub fn encode_frame_pcm_7_0(&mut self, frames: &[&[f32]; 7]) -> Vec<u8> {
self.encode_frame_pcm_7_0_with_max_sfb(frames, 40, 40)
}
/// Encode one IMS v2 7.0 (3/4/0) frame from arbitrary float PCM input
/// at caller-specified `max_sfb` (five-channel front/surround SCEs)
/// and `max_sfb_add` (additional Lb/Rb pair). See
/// [`Self::encode_frame_pcm_7_0`] for the rest of the contract.
pub fn encode_frame_pcm_7_0_with_max_sfb(
&mut self,
frames: &[&[f32]; 7],
max_sfb: u32,
max_sfb_add: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_0: channel {ch} input length must match frame_len = {frame_len}"
);
}
// Cap max_sfb at the non-LFE max_sfb width's max and at the actual
// num_sfb_48 cap. Same cap applies to both the inner
// five_channel_data and the additional two_channel_data — they
// share the n_msfb_bits width.
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let max_sfb_add = max_sfb_add.min(n_msfb_cap);
// Force 7.0 (3/4/0) channel_mode (prefix '1111000', 7 bits —
// Table 88 channel_mode 5). The body builder requires the TOC to
// declare 7 channels so the decoder's `walk_ac4_substream`
// dispatch routes through `parse_7x_audio_data_outer(b_has_lfe =
// false)`.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111000;
self.channel_mode_bits = 7;
// 1. Forward MDCT analysis per channel (separate state for
// independent 50% TDAC overlap continuity). Seven channels
// here so the multi-channel state vector needs to grow.
while self.mdct_states_multi.len() < 7 {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(7);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// 2-4. Build the 7.0 SIMPLE/Cfg3Five body. Pad budget is ~7× the
// mono budget since we carry seven spectra independently.
// Capped at 32767 — the 15-bit `audio_size_value` field
// saturates there (extending via `b_more_bits` is permitted
// by §4.3.4.1 but not needed for the default max_sfb path).
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = build_7_0_simple_asf_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_add,
&[
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[5],
&coeffs_per_channel[6],
],
pad_target_bytes,
);
// 5. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 7.1 (3/4/0.1) frame from float PCM input per ETSI
/// TS 103 190-1 §4.2.6.14 Table 33 + §4.2.7.5 Table 29
/// (`five_channel_data()`) + §4.2.7.4 Table 26 (`two_channel_data()`),
/// building on top of the 5.1 Cfg3Five forward analysis path with an
/// extra trailing `two_channel_data()` for the immersive
/// additional-channel pair (Lb, Rb) per the SIMPLE/ASPX
/// additional-channel block in §4.2.6.14:
/// `b_use_sap_add_ch + two_channel_data()`.
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb, LFE]` order (matching
/// the decoder's output slot convention: slots 0..4 from
/// `five_channel_data()` per Table 180, slots 5/6 from the additional
/// `two_channel_data()` per `dispatch_7x_additional_channel_pair` /
/// Table 183 row "3/4/0.x" identity-SAP path, slot 7 from the LFE
/// `mono_data(1)`). Each slice must have length `frame_len` (1920
/// for the default 48 kHz / 24 fps configuration); panics otherwise.
///
/// The encoder forces the 7.1 (3/4/0.1) channel_mode prefix
/// (`0b1111001`, 7 b — Table 88 channel_mode 6) so the decoder's
/// `walk_ac4_substream` dispatches `channels == 8` through
/// `parse_7x_audio_data_outer(b_has_lfe = true)`. The LFE channel
/// is coded with `sf_info_lfe()` (Table 35) carrying `max_sfb` in
/// `n_msfbl_bits` bits (Table 106 column 4 — 3 bits for `tl = 1920`
/// → max_sfb_lfe is capped at 7). The five non-LFE front/surround
/// channels share the same Cfg3Five `five_channel_data()` body as
/// the 5.1 path; the additional pair (Lb, Rb) is coded as a single
/// `two_channel_data()` with identity SAP (`b_use_sap_add_ch = 0`,
/// `sap_mode = 0` on its `chparam_info`) so no joint-MDCT mixing
/// happens at decode time and slots 5/6 receive Lb/Rb directly.
///
/// `max_sfb` defaults to 40 (matching the round-49 mono / round-74
/// 5.0 / round-80 5.1 default); `max_sfb_add` defaults to 40 (same
/// width as the 5.1 non-LFE channels); `max_sfb_lfe` defaults to 7
/// (the LFE-spec cap at `tl = 1920`). Use
/// [`Self::encode_frame_pcm_7_1_with_max_sfb`] for wider coverage.
pub fn encode_frame_pcm_7_1(&mut self, frames: &[&[f32]; 8]) -> Vec<u8> {
self.encode_frame_pcm_7_1_with_max_sfb(frames, 40, 40, 7)
}
/// Encode one IMS v2 7.1 (3/4/0.1) frame from arbitrary float PCM
/// input at caller-specified `max_sfb` (five-channel front/surround
/// SCEs), `max_sfb_add` (additional Lb/Rb pair), and `max_sfb_lfe`
/// (LFE channel). See [`Self::encode_frame_pcm_7_1`] for the rest of
/// the contract.
pub fn encode_frame_pcm_7_1_with_max_sfb(
&mut self,
frames: &[&[f32]; 8],
max_sfb: u32,
max_sfb_add: u32,
max_sfb_lfe: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_1: channel {ch} input length must match frame_len = {frame_len}"
);
}
// Cap max_sfb at the non-LFE max_sfb width's max and at the actual
// num_sfb_48 cap. Same cap applies to both the inner
// five_channel_data and the additional two_channel_data — they
// share the n_msfb_bits width.
let (n_msfb_bits, _, n_msfbl_bits) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let max_sfb_add = max_sfb_add.min(n_msfb_cap);
assert!(
n_msfbl_bits > 0,
"encode_frame_pcm_7_1: tl = {frame_len} not permitted for LFE"
);
let n_msfbl_cap = (1u32 << n_msfbl_bits) - 1;
let max_sfb_lfe = max_sfb_lfe.min(n_msfbl_cap);
// Force 7.1 (3/4/0.1) channel_mode (prefix '1111001', 7 bits —
// Table 88 channel_mode 6). The body builder requires the TOC to
// declare 8 channels so the decoder's `walk_ac4_substream`
// dispatch routes through `parse_7x_audio_data_outer(b_has_lfe =
// true)`.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111001;
self.channel_mode_bits = 7;
// 1. Forward MDCT analysis per channel (separate state for
// independent 50% TDAC overlap continuity). Eight channels
// here so the multi-channel state vector needs to grow.
while self.mdct_states_multi.len() < 8 {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(8);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// 2-4. Build the 7.1 SIMPLE/Cfg3Five body. Pad budget is ~8× the
// mono budget since we carry eight spectra independently.
// Capped at 32767 — the 15-bit `audio_size_value` field
// saturates there (extending via `b_more_bits` is permitted
// by §4.3.4.1 but not needed for the default max_sfb path).
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = build_7_1_simple_asf_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_add,
max_sfb_lfe,
&[
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[5],
&coeffs_per_channel[6],
&coeffs_per_channel[7],
],
pad_target_bytes,
);
// 5. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.X frame in 5_X_codec_mode = ASPX_ACPL_3 per
/// ETSI TS 103 190-1 §4.2.6.6 Table 25 row `case ASPX_ACPL_3:`
/// (round 95). Symmetric counterpart to the decoder's round-34
/// [`crate::mch::parse_5x_audio_data_outer`] ASPX_ACPL_3 walker.
///
/// `frames` is in `[L, R, C]` order — three carrier channels. The
/// L/R pair feeds the `stereo_data()` body (split-MDCT path) and
/// drives the A-CPL Ls/Rs surround reconstruction via Pseudocode 118
/// at decode time. The centre carrier `C` is present in the
/// `coeffs_per_channel` slice but unused on the spec ASPX_ACPL_3
/// path — the decoder reconstructs the centre from
/// `cfg0_centre_mono.scaled_spec` (which the ASPX_ACPL_3 walker
/// doesn't populate), so the decoder's centre output is zero-filled.
///
/// The encoder forces the 5.0 channel_mode prefix (`0b1101`, 4 b —
/// Table 85 channel_mode 3) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 5` through
/// `parse_5x_audio_data_outer(b_has_lfe = false)` with
/// `5_X_codec_mode = AspxAcpl3`.
///
/// The ASPX/A-CPL parameter bits are emitted as
/// minimum-bit-cost zero-delta Huffman codewords (per round-95
/// "structural scaffold" mode — see [`crate::encoder_acpl3`]).
/// The decoder walks the full Table 25 body and produces
/// 5-channel `[L, R, C, Ls, Rs]` PCM via
/// [`crate::acpl_synth::run_acpl_5x_mch_pcm`]. With all-zero ACPL
/// parameter deltas the surround pair Ls/Rs collapses to the
/// ducker-driven reconstruction from the L/R carriers.
///
/// `max_sfb` defaults to 40 (matching the round-49 mono / round-74
/// 5.0 default).
pub fn encode_frame_pcm_5_0_acpl3(&mut self, frames: &[&[f32]; 3]) -> Vec<u8> {
self.encode_frame_pcm_5_x_acpl3_with_max_sfb(frames, None, 40, None)
}
/// Encode one IMS v2 5.1 frame in 5_X_codec_mode = ASPX_ACPL_3 with
/// an LFE channel per ETSI TS 103 190-1 §4.2.6.6 Table 25
/// (`if (b_has_lfe) mono_data(1);`) + §4.2.8 (`sf_info_lfe()`).
///
/// `frames` is in `[L, R, C, LFE]` order. The L/R carrier pair drives
/// the stereo body + A-CPL Ls/Rs reconstruction (same as
/// [`Self::encode_frame_pcm_5_0_acpl3`]); the LFE channel is coded
/// as a leading `mono_data(b_lfe = 1)` element per Table 21.
pub fn encode_frame_pcm_5_1_acpl3(&mut self, frames: &[&[f32]; 4]) -> Vec<u8> {
// Decompose into the 3-carrier slice + the LFE slice for the
// shared dispatcher.
let carriers: [&[f32]; 3] = [frames[0], frames[1], frames[2]];
self.encode_frame_pcm_5_x_acpl3_with_max_sfb(&carriers, Some(frames[3]), 40, Some(7))
}
/// Shared body for [`Self::encode_frame_pcm_5_0_acpl3`] and
/// [`Self::encode_frame_pcm_5_1_acpl3`]. `frames` carries the three
/// non-LFE channels (`[L, R, C]`); `lfe` is `Some` for the 5.1 path,
/// `None` for 5.0.
fn encode_frame_pcm_5_x_acpl3_with_max_sfb(
&mut self,
frames: &[&[f32]; 3],
lfe: Option<&[f32]>,
max_sfb: u32,
max_sfb_lfe: Option<u32>,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3: channel {ch} input length must match frame_len = {frame_len}"
);
}
if let Some(lfe_buf) = lfe {
assert_eq!(
lfe_buf.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3: LFE input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force the right channel_mode based on whether LFE is present.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
if lfe.is_some() {
// 5.1 channel_mode prefix '1110', 4 b → channel_mode 4.
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
} else {
// 5.0 channel_mode prefix '1101', 4 b → channel_mode 3.
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
}
// 1. Forward MDCT analysis per channel (separate state for
// independent 50% TDAC overlap continuity).
let n_channels = if lfe.is_some() { 4 } else { 3 };
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let coeffs_lfe: Option<Vec<f32>> = lfe.map(|buf| {
// LFE channel uses its own MDCT state at index 3.
self.mdct_states_multi[3].analyse_frame(buf)
});
// 2. Build the ASPX_ACPL_3 body via the shared builder. ASPX
// config: small low-res scale so the SBG counts stay small —
// keeps the ASPX_data_2ch body compact.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_modes Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_qm0 = crate::acpl::AcplQuantMode::Fine;
let acpl_qm1 = crate::acpl::AcplQuantMode::Fine;
// Pad budget: scale with max_sfb and channel count (3 or 4).
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_lfe,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
coeffs_lfe.as_deref(),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_qm0,
acpl_qm1,
pad_target_bytes,
);
// 3. Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
// sequence_counter wraps at 1024.
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
// Restore caller's channel_mode setting.
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame in 5_X_codec_mode = ASPX_ACPL_3 with
/// real per-parameter-band β1 / β2 extraction from the L / R
/// carrier energy distributions (round 193). Symmetric to
/// [`Self::encode_frame_pcm_5_0_acpl3`] but routes the substream
/// body builder through
/// [`crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_beta`]
/// so the β1 / β2 Huffman layers carry the carrier-driven decorrelator
/// gains instead of all-zero codewords.
///
/// `beta_scale` controls the wet/dry balance — see
/// [`crate::encoder_acpl3::extract_beta_q_per_band_carrier_energy`]
/// for the magnitude / scale relationship. Values in `0.05..=0.3`
/// produce noticeable surround reconstruction without saturating
/// the BETA codebook.
pub fn encode_frame_pcm_5_0_acpl3_real_beta(
&mut self,
frames: &[&[f32]; 3],
beta_scale: f32,
) -> Vec<u8> {
self.encode_frame_pcm_5_x_acpl3_real_beta_with_max_sfb(frames, None, 40, None, beta_scale)
}
/// 5.1 counterpart to [`Self::encode_frame_pcm_5_0_acpl3_real_beta`].
/// `frames` is in `[L, R, C, LFE]` order. The LFE channel is coded
/// as a leading `mono_data(b_lfe = 1)` element per Table 21 — same
/// path as [`Self::encode_frame_pcm_5_1_acpl3`].
pub fn encode_frame_pcm_5_1_acpl3_real_beta(
&mut self,
frames: &[&[f32]; 4],
beta_scale: f32,
) -> Vec<u8> {
let carriers: [&[f32]; 3] = [frames[0], frames[1], frames[2]];
self.encode_frame_pcm_5_x_acpl3_real_beta_with_max_sfb(
&carriers,
Some(frames[3]),
40,
Some(7),
beta_scale,
)
}
/// Shared body for the real-β ACPL_3 entry points. Mirrors
/// [`Self::encode_frame_pcm_5_x_acpl3_with_max_sfb`] but invokes the
/// real-β builder. Kept close to the parent so the two paths stay
/// in sync as the ASPX / ACPL config evolves.
fn encode_frame_pcm_5_x_acpl3_real_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 3],
lfe: Option<&[f32]>,
max_sfb: u32,
max_sfb_lfe: Option<u32>,
beta_scale: f32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
if let Some(lfe_buf) = lfe {
assert_eq!(
lfe_buf.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_beta: LFE input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
if lfe.is_some() {
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
} else {
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
}
let n_channels = if lfe.is_some() { 4 } else { 3 };
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let coeffs_lfe: Option<Vec<f32>> =
lfe.map(|buf| self.mdct_states_multi[3].analyse_frame(buf));
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_qm0 = crate::acpl::AcplQuantMode::Fine;
let acpl_qm1 = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_beta(
frame_len,
max_sfb,
max_sfb_lfe,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
coeffs_lfe.as_deref(),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_qm0,
acpl_qm1,
beta_scale,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame in 5_X_codec_mode = ASPX_ACPL_3 with
/// real per-parameter-band α₁ / α₂ extraction from the L↔R carrier
/// cross-correlation (round 196) **and** the round-193 real β₁ / β₂
/// extraction from the L / R carrier energies. Symmetric counterpart
/// to [`Self::encode_frame_pcm_5_0_acpl3_real_beta`] but routes the
/// substream body builder through
/// [`crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta`]
/// so the α₁ / α₂ Huffman layers carry correlation-driven dry-mix
/// balance indices in addition to the carrier-driven decorrelator
/// gains in β₁ / β₂.
///
/// `alpha_scale` controls the front/back-balance policy — see
/// [`crate::encoder_acpl3::extract_alpha_q_per_band_carrier_correlation`]
/// for the magnitude / scale relationship. Values in `0.25..=1.0`
/// produce a noticeable front/back bias on correlated content
/// without saturating the ALPHA codebook.
///
/// `beta_scale` retains its r193 meaning. With
/// `alpha_scale = beta_scale = 0.0` the output is byte-identical to
/// [`Self::encode_frame_pcm_5_0_acpl3`]'s round-95 scaffold.
pub fn encode_frame_pcm_5_0_acpl3_real_alpha_beta(
&mut self,
frames: &[&[f32]; 3],
alpha_scale: f32,
beta_scale: f32,
) -> Vec<u8> {
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_with_max_sfb(
frames,
None,
40,
None,
alpha_scale,
beta_scale,
)
}
/// 5.1 counterpart to
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta`]. `frames` is
/// in `[L, R, C, LFE]` order. The LFE channel is coded as a leading
/// `mono_data(b_lfe = 1)` element per Table 21 — same path as
/// [`Self::encode_frame_pcm_5_1_acpl3`].
pub fn encode_frame_pcm_5_1_acpl3_real_alpha_beta(
&mut self,
frames: &[&[f32]; 4],
alpha_scale: f32,
beta_scale: f32,
) -> Vec<u8> {
let carriers: [&[f32]; 3] = [frames[0], frames[1], frames[2]];
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_with_max_sfb(
&carriers,
Some(frames[3]),
40,
Some(7),
alpha_scale,
beta_scale,
)
}
/// Shared body for the real-α/β ACPL_3 entry points. Mirrors
/// [`Self::encode_frame_pcm_5_x_acpl3_real_beta_with_max_sfb`] but
/// invokes the real-α + real-β builder.
#[allow(clippy::too_many_arguments)]
fn encode_frame_pcm_5_x_acpl3_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 3],
lfe: Option<&[f32]>,
max_sfb: u32,
max_sfb_lfe: Option<u32>,
alpha_scale: f32,
beta_scale: f32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
if let Some(lfe_buf) = lfe {
assert_eq!(
lfe_buf.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta: LFE input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
if lfe.is_some() {
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
} else {
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
}
let n_channels = if lfe.is_some() { 4 } else { 3 };
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let coeffs_lfe: Option<Vec<f32>> =
lfe.map(|buf| self.mdct_states_multi[3].analyse_frame(buf));
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_qm0 = crate::acpl::AcplQuantMode::Fine;
let acpl_qm1 = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
max_sfb_lfe,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
coeffs_lfe.as_deref(),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_qm0,
acpl_qm1,
alpha_scale,
beta_scale,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame in 5_X_codec_mode = ASPX_ACPL_3 with
/// **real per-band α + β + γ5/γ6**. Layered on top of
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta`]: the γ5 / γ6
/// entropy layers now carry per-band magnitudes derived from a 2×2
/// least-squares fit of the centre channel
/// `C ≈ K · (γ5·L + γ6·R)` (Pseudocode 118 step 7 + step 11 with
/// `K = √2 · (1 + √2) / 2`). γ1..γ4 + β3 stay zero-delta.
///
/// `gamma_scale = 0.0` reproduces the round-196 real-α-β byte stream
/// exactly; `gamma_scale = 1.0` writes the full analytic γ pair
/// (clamped to the Table-208 ±2.0 bound). `alpha_scale = beta_scale
/// = gamma_scale = 0.0` reproduces the round-95 zero-delta scaffold
/// byte-for-byte.
///
/// `frames` is in `[L, R, C]` order. The decoder walks the same
/// Table 25 ASPX_ACPL_3 body; γ5 / γ6 feed the ACplModule2 instance
/// that synthesises the centre output channel (Pseudocode 119 with
/// `a = 1`, `b = 0`, `y = 0`). γ1..γ4 still at zero-delta keeps the
/// (L, R, Ls, Rs) sub-pipeline behaviour identical to the round-196
/// path.
pub fn encode_frame_pcm_5_0_acpl3_real_alpha_beta_gamma(
&mut self,
frames: &[&[f32]; 3],
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
) -> Vec<u8> {
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_gamma_with_max_sfb(
frames,
None,
40,
None,
alpha_scale,
beta_scale,
gamma_scale,
)
}
/// 5.1 counterpart to
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta_gamma`].
/// `frames` is in `[L, R, C, LFE]` order. The LFE channel is coded
/// as a leading `mono_data(b_lfe = 1)` element per Table 21 — same
/// path as [`Self::encode_frame_pcm_5_1_acpl3_real_alpha_beta`].
pub fn encode_frame_pcm_5_1_acpl3_real_alpha_beta_gamma(
&mut self,
frames: &[&[f32]; 4],
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
) -> Vec<u8> {
let carriers: [&[f32]; 3] = [frames[0], frames[1], frames[2]];
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_gamma_with_max_sfb(
&carriers,
Some(frames[3]),
40,
Some(7),
alpha_scale,
beta_scale,
gamma_scale,
)
}
/// Shared body for the real-α/β/γ5/γ6 ACPL_3 entry points. Mirrors
/// [`Self::encode_frame_pcm_5_x_acpl3_real_alpha_beta_with_max_sfb`]
/// but invokes the real-γ5/γ6 builder.
#[allow(clippy::too_many_arguments)]
fn encode_frame_pcm_5_x_acpl3_real_alpha_beta_gamma_with_max_sfb(
&mut self,
frames: &[&[f32]; 3],
lfe: Option<&[f32]>,
max_sfb: u32,
max_sfb_lfe: Option<u32>,
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta_gamma: channel {ch} input length must match frame_len = {frame_len}"
);
}
if let Some(lfe_buf) = lfe {
assert_eq!(
lfe_buf.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta_gamma: LFE input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
if lfe.is_some() {
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
} else {
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
}
let n_channels = if lfe.is_some() { 4 } else { 3 };
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let coeffs_lfe: Option<Vec<f32>> =
lfe.map(|buf| self.mdct_states_multi[3].analyse_frame(buf));
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_qm0 = crate::acpl::AcplQuantMode::Fine;
let acpl_qm1 = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body =
crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta_gamma(
frame_len,
max_sfb,
max_sfb_lfe,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
Some(&coeffs_per_channel[2]),
coeffs_lfe.as_deref(),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_qm0,
acpl_qm1,
alpha_scale,
beta_scale,
gamma_scale,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame in 5_X_codec_mode = ASPX_ACPL_3 with
/// **full** real per-parameter-band α₁ / α₂ / β₁ / β₂ / γ₁..γ₆
/// extraction (round 215) — the round-208 entry point
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta_gamma`] lifted
/// the centre γ₅ / γ₆ pair to real values; this entry point also
/// lifts γ₁ / γ₂ (driving the (L, Ls) pair via Pseudocode 118
/// step 5) and γ₃ / γ₄ (driving the (R, Rs) pair via Pseudocode 118
/// step 6), closing the README's long-standing "γ1..γ4 stay at the
/// round-95 zero-delta scaffold" deferral for the 5_X ACPL_3 path.
///
/// The γ₁ / γ₂ pair comes from a per-band 2×2 least-squares fit of
/// the (L, Ls) output sum `(L + Ls/√2)/(1 + √2)` onto the (L, R)
/// carrier pair; γ₃ / γ₄ come from the symmetric fit on the
/// (R, Rs) pair (see
/// [`crate::encoder_acpl3::extract_gamma_1_2_q_per_band_surround_least_squares`]
/// and
/// [`crate::encoder_acpl3::extract_gamma_3_4_q_per_band_surround_least_squares`]).
/// Both sums are independent of the α / β decorrelator
/// contributions and equal a `(1 + √2) · (γ·L + γ'·R)` linear
/// combination, so the resulting 2×2 normal-equations system is
/// identical in shape to the round-208 γ₅ / γ₆ centre fit.
///
/// `frames` is in `[L, R, C, Ls, Rs]` order. The L / R carriers
/// also feed the round-51 stereo `two_channel_data()` body the
/// ASPX_ACPL_3 path emits. β₃ stays at the round-95 zero-delta
/// scaffold — its analytic extraction requires a model for the
/// third decorrelator output `y₂` which is not observable at
/// encode time. The ASPX envelope layer also stays at the
/// minimum-bit-cost FIXFIX num_env=1 scaffold pending the
/// "real ASPX envelope coding" deferral elsewhere on the README.
///
/// `alpha_scale` / `beta_scale` / `gamma_scale` control the
/// extractor magnitude (typically `1.0` for the analytic
/// least-squares solution; `0.0` reproduces the prior-round
/// scaffold byte-for-byte at the corresponding layer position).
/// In particular `α/β/γ_scale = 0.0` reproduces the round-95
/// zero-delta scaffold ([`Self::encode_frame_pcm_5_0_acpl3`])
/// byte-for-byte; `γ_scale = 0.0` reproduces the round-196
/// real-α-β bytes exactly.
pub fn encode_frame_pcm_5_0_acpl3_real_alpha_beta_full_gamma(
&mut self,
frames: &[&[f32]; 5],
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
) -> Vec<u8> {
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_with_max_sfb(
frames,
None,
40,
None,
alpha_scale,
beta_scale,
gamma_scale,
)
}
/// 5.1 counterpart to
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta_full_gamma`].
/// `frames` is in `[L, R, C, Ls, Rs, LFE]` order. The LFE channel
/// is coded as a leading `mono_data(b_lfe = 1)` element per Table
/// 21 — same path as
/// [`Self::encode_frame_pcm_5_1_acpl3_real_alpha_beta_gamma`].
pub fn encode_frame_pcm_5_1_acpl3_real_alpha_beta_full_gamma(
&mut self,
frames: &[&[f32]; 6],
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
) -> Vec<u8> {
let surround: [&[f32]; 5] = [frames[0], frames[1], frames[2], frames[3], frames[4]];
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_with_max_sfb(
&surround,
Some(frames[5]),
40,
Some(7),
alpha_scale,
beta_scale,
gamma_scale,
)
}
/// Shared body for the real-α/β + full real-γ₁..γ₆ ACPL_3 entry
/// points. Mirrors
/// [`Self::encode_frame_pcm_5_x_acpl3_real_alpha_beta_gamma_with_max_sfb`]
/// but accepts a 5-channel `[L, R, C, Ls, Rs]` input and invokes
/// the
/// [`crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta_full_gamma`]
/// builder.
#[allow(clippy::too_many_arguments)]
fn encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
lfe: Option<&[f32]>,
max_sfb: u32,
max_sfb_lfe: Option<u32>,
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma: channel {ch} input length must match frame_len = {frame_len}"
);
}
if let Some(lfe_buf) = lfe {
assert_eq!(
lfe_buf.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma: LFE input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
if lfe.is_some() {
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
} else {
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
}
let n_channels = if lfe.is_some() { 6 } else { 5 };
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let coeffs_lfe: Option<Vec<f32>> =
lfe.map(|buf| self.mdct_states_multi[5].analyse_frame(buf));
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_qm0 = crate::acpl::AcplQuantMode::Fine;
let acpl_qm1 = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body =
crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta_full_gamma(
frame_len,
max_sfb,
max_sfb_lfe,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
Some(&coeffs_per_channel[2]),
Some(&coeffs_per_channel[3]),
Some(&coeffs_per_channel[4]),
coeffs_lfe.as_deref(),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_qm0,
acpl_qm1,
alpha_scale,
beta_scale,
gamma_scale,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame in 5_X_codec_mode = ASPX_ACPL_3 with
/// **real per-parameter-band α₁ / α₂ + β₁ / β₂ + γ₁..γ₆ + β₃**
/// extraction (round 285 — the β₃-real extension of
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta_full_gamma`]).
///
/// `frames` is in `[L, R, C, Ls, Rs]` order. β₃ (the gain on the
/// third decorrelator output `y₂` per §5.7.7.6.2 Pseudocode 118
/// steps 8–10) is energy-matched to the centre-channel
/// reconstruction residual left over after the γ₅ / γ₆ dry-mix fit
/// — see
/// [`crate::encoder_acpl3::extract_beta3_q_per_band_centre_residual`].
/// `beta3_scale = 0.0` reproduces the round-215 full-γ byte stream
/// exactly; `beta3_scale = 1.0` applies the full energy-matching
/// solution clamped to the Table-207 ±1.0 magnitude bound.
pub fn encode_frame_pcm_5_0_acpl3_real_alpha_beta_full_gamma_beta3(
&mut self,
frames: &[&[f32]; 5],
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
beta3_scale: f32,
) -> Vec<u8> {
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_beta3_with_max_sfb(
frames,
None,
40,
None,
alpha_scale,
beta_scale,
gamma_scale,
beta3_scale,
)
}
/// 5.1 counterpart to
/// [`Self::encode_frame_pcm_5_0_acpl3_real_alpha_beta_full_gamma_beta3`].
/// `frames` is in `[L, R, C, Ls, Rs, LFE]` order. The LFE channel
/// is coded as a leading `mono_data(b_lfe = 1)` element per Table
/// 21 — same path as
/// [`Self::encode_frame_pcm_5_1_acpl3_real_alpha_beta_full_gamma`].
pub fn encode_frame_pcm_5_1_acpl3_real_alpha_beta_full_gamma_beta3(
&mut self,
frames: &[&[f32]; 6],
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
beta3_scale: f32,
) -> Vec<u8> {
let surround: [&[f32]; 5] = [frames[0], frames[1], frames[2], frames[3], frames[4]];
self.encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_beta3_with_max_sfb(
&surround,
Some(frames[5]),
40,
Some(7),
alpha_scale,
beta_scale,
gamma_scale,
beta3_scale,
)
}
/// Shared body for the real-α/β/γ₁..γ₆/β₃ ACPL_3 entry points.
/// Mirrors
/// [`Self::encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_with_max_sfb`]
/// but invokes the
/// [`crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta_full_gamma_beta3`]
/// builder with the additional `beta3_scale` decision knob.
#[allow(clippy::too_many_arguments)]
fn encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_beta3_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
lfe: Option<&[f32]>,
max_sfb: u32,
max_sfb_lfe: Option<u32>,
alpha_scale: f32,
beta_scale: f32,
gamma_scale: f32,
beta3_scale: f32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_beta3: channel {ch} input length must match frame_len = {frame_len}"
);
}
if let Some(lfe_buf) = lfe {
assert_eq!(
lfe_buf.len(),
frame_len as usize,
"encode_frame_pcm_5_x_acpl3_real_alpha_beta_full_gamma_beta3: LFE input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
if lfe.is_some() {
self.channel_mode_value = 0b1110;
self.channel_mode_bits = 4;
} else {
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
}
let n_channels = if lfe.is_some() { 6 } else { 5 };
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let coeffs_lfe: Option<Vec<f32>> =
lfe.map(|buf| self.mdct_states_multi[5].analyse_frame(buf));
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_qm0 = crate::acpl::AcplQuantMode::Fine;
let acpl_qm1 = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body =
crate::encoder_acpl3::build_5_x_acpl3_body_from_pcm_spectra_real_alpha_beta_full_gamma_beta3(
frame_len,
max_sfb,
max_sfb_lfe,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
Some(&coeffs_per_channel[2]),
Some(&coeffs_per_channel[3]),
Some(&coeffs_per_channel[4]),
coeffs_lfe.as_deref(),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_qm0,
acpl_qm1,
alpha_scale,
beta_scale,
gamma_scale,
beta3_scale,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 5.0 frame in 5_X_codec_mode = ASPX_ACPL_2 per
/// ETSI TS 103 190-1 §4.2.6.6 Table 25 row `case ASPX_ACPL_2:`
/// (round 100). Symmetric counterpart to the decoder's round-25
/// [`crate::mch::parse_5x_audio_data_outer`] ASPX_ACPL_{1,2} inner-
/// body walker (Pseudocode 117).
///
/// `frames` is in `[L, R, C]` order — the L/R carrier pair feeds the
/// `two_channel_data()` body and drives the A-CPL Ls/Rs surround
/// reconstruction via [`crate::acpl_synth::run_acpl_5x_pair_pcm`] at
/// decode time; the centre carrier `C` is coded as a Cfg0
/// `mono_data(0)` element. ASPX_ACPL_2 has no surround carriers — the
/// Ls/Rs PCM is reconstructed entirely from the L/R carriers + the
/// two `acpl_data_1ch()` parameter sets.
///
/// The encoder forces the 5.0 channel_mode prefix (`0b1101`, 4 b —
/// Table 85 channel_mode 3) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 5` through
/// `parse_5x_audio_data_outer(b_has_lfe = false)` with
/// `5_X_codec_mode = AspxAcpl2`.
///
/// The ASPX/A-CPL parameter bits are emitted as minimum-bit-cost
/// zero-delta Huffman codewords (the round-95 "structural scaffold"
/// mode — see [`crate::encoder_acpl3`]). The decoder walks the full
/// Table 25 ASPX_ACPL_2 body and produces 5-channel `[L, R, C, Ls,
/// Rs]` PCM. With all-zero ACPL parameter deltas the surround pair
/// Ls/Rs collapses to the ducker-driven reconstruction from the L/R
/// carriers.
///
/// `max_sfb` defaults to 40 (matching the round-95 ACPL_3 default).
pub fn encode_frame_pcm_5_0_acpl2(&mut self, frames: &[&[f32]; 3]) -> Vec<u8> {
self.encode_frame_pcm_5_0_acpl2_with_max_sfb(frames, 40)
}
/// `max_sfb`-parameterised form of [`Self::encode_frame_pcm_5_0_acpl2`].
pub fn encode_frame_pcm_5_0_acpl2_with_max_sfb(
&mut self,
frames: &[&[f32]; 3],
max_sfb: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0_acpl2: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 5.0 channel_mode prefix '1101', 4 b → channel_mode 3.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
// Forward MDCT analysis per carrier channel (L, R, C — 3 states).
let n_channels = 3;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: small low-res scale so the SBG counts stay small —
// keeps the ASPX_data bodies compact. Matches the round-95
// ASPX_ACPL_3 config exactly.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl2_body_from_pcm_spectra(
frame_len,
max_sfb,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 5.0 SIMPLE/ASPX_ACPL_2
/// multichannel substream with **real per-parameter-band α + β
/// extraction** carried by the two trailing `acpl_data_1ch()` elements
/// (round 144 — the ACPL_2 5.0 counterpart to the round-132 ACPL_1 5.0
/// real α + β path).
///
/// Per ETSI TS 103 190-1 §5.7.7.5 Pseudocode 116 + §5.7.7.6.1
/// Pseudocode 117, the A-CPL surround reconstruction carries the
/// level component via α and a decorrelated residual via β:
///
/// ```text
/// α = 1 − 2·√2 · ⟨x_carrier, x_surround⟩ / ⟨x_carrier, x_carrier⟩
/// E[Ls²] = 0.5 · E[L²] · ( (1 − α)² + β² )
/// ⇒ β = √max(0, 2·E[Ls²]/E[L²] − (1 − α_dq)²)
/// ```
///
/// Unlike the ACPL_1 paths, ACPL_2 does **not** transmit the Ls/Rs
/// surround pair on the wire — the decoder reconstructs the surround
/// purely from the L/R carriers + the two `acpl_data_1ch()` parameter
/// sets. This entry point therefore still emits the round-100
/// ASPX_ACPL_2 body layout (no joint-MDCT residual layer, no
/// `acpl_config_1ch(PARTIAL)` qmf_band field), but extracts the α + β
/// indices from the caller's full 5-channel `[L, R, C, Ls, Rs]` input
/// rather than pinning them at the zero-codebook scaffold.
///
/// `frames` is in `[L, R, C, Ls, Rs]` order; β3 / γ stay at the
/// scaffold. The `acpl_config_1ch(FULL)` carries no `qmf_band` →
/// `start_band = 0` so every parameter band participates in the α + β
/// coding (in contrast to the ACPL_1 PARTIAL mode whose
/// `acpl_qmf_band` masks the low bands).
///
/// **Note (round-128 ALPHA F0 writer-side `alpha_q` desync —
/// deferred follow-up since round 132).** The shared
/// `write_acpl_alpha_f0_value` writer treats the signed `alpha_q ∈
/// [-N/2..+N/2]` returned by `quantise_alpha` as a raw F0 symbol
/// index without re-centering it against the table's shortest
/// codeword. The decoder's `dequantize_alpha_index` re-centers via
/// `lane = alpha_q + N/2`, so non-trivial α values do not round-trip
/// bit-exact through the full PCM→MDCT→writer→parser→synth chain
/// when the analytic α resolves to a non-center quantisation lane.
/// The on-wire β codewords for ACPL_2 are wired correctly per
/// §A.3 Table A.40 / A.41 (β uses unsigned-magnitude F0 with
/// `cb_off = 0`, no re-centering needed); the round-100 zero-α/β
/// scaffold is structurally superseded by this entry point. Once
/// the writer-side desync lands as a follow-up commit the on-wire β
/// recovery will be bit-exact end-to-end.
pub fn encode_frame_pcm_5_0_acpl2_real_alpha_beta(&mut self, frames: &[&[f32]; 5]) -> Vec<u8> {
self.encode_frame_pcm_5_0_acpl2_real_alpha_beta_with_max_sfb(frames, 40)
}
/// `max_sfb`-parameterised form of
/// [`Self::encode_frame_pcm_5_0_acpl2_real_alpha_beta`].
pub fn encode_frame_pcm_5_0_acpl2_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
max_sfb: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0_acpl2_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 5.0 channel_mode prefix '1101', 4 b → channel_mode 3.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
// Forward MDCT analysis per carrier channel (L, R, C, Ls, Rs — 5
// states). The Ls/Rs spectra feed the α + β extractors only — they
// are not emitted on the ACPL_2 wire (the decoder reconstructs the
// surround from L/R + the two acpl_data_1ch parameter sets).
let n_channels = 5;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: matches the round-95 / 100 / 103 ASPX_ACPL config.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl2_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 5.0 SIMPLE/ASPX_ACPL_1
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.6 Table 25 row
/// `case ASPX_ACPL_1:` (Pseudocode 117).
///
/// Unlike ASPX_ACPL_2 (which reconstructs the Ls/Rs surround pair
/// purely from the L/R carriers + the two `acpl_data_1ch()` parameter
/// sets), ASPX_ACPL_1 transmits the surround signal explicitly as a
/// **joint-MDCT residual layer** (`max_sfb_master + 2× chparam_info +
/// 2× sf_data(ASF)`) keyed by the `acpl_config_1ch(PARTIAL)` element's
/// `acpl_qmf_band` field. It therefore accepts a full 5-channel
/// `[L, R, C, Ls, Rs]` input: L/R become the `two_channel_data()`
/// carriers, C the Cfg0 `mono_data(0)`, and Ls/Rs the residual pair
/// (sSMP,3 / sSMP,4 per Table 181).
///
/// The encoder forces the 5.0 channel_mode prefix (`0b1101`, 4 b —
/// Table 85 channel_mode 3) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 5` through
/// `parse_5x_audio_data_outer(b_has_lfe = false)` with
/// `5_X_codec_mode = AspxAcpl1`. The ASPX/A-CPL parameter bits use the
/// round-95 minimum-bit-cost zero-delta Huffman scaffold. The decoder
/// walks the full Table 25 ASPX_ACPL_1 body — including the residual
/// layer that IMDCTs into the Ls/Rs PCM carriers — and produces
/// 5-channel `[L, R, C, Ls, Rs]` PCM via
/// [`crate::acpl_synth::run_acpl_5x_pair_pcm`] (Pseudocode 117).
///
/// `max_sfb` defaults to 40; `max_sfb_master` (the residual-layer band
/// budget) defaults to 20.
pub fn encode_frame_pcm_5_0_acpl1(&mut self, frames: &[&[f32]; 5]) -> Vec<u8> {
self.encode_frame_pcm_5_0_acpl1_with_max_sfb(frames, 40, 20)
}
/// `max_sfb` / `max_sfb_master`-parameterised form of
/// [`Self::encode_frame_pcm_5_0_acpl1`].
pub fn encode_frame_pcm_5_0_acpl1_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
max_sfb: u32,
max_sfb_master: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0_acpl1: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 5.0 channel_mode prefix '1101', 4 b → channel_mode 3.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
// Forward MDCT analysis per carrier channel (L, R, C, Ls, Rs — 5
// states).
let n_channels = 5;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: small low-res scale so the SBG counts stay small —
// keeps the ASPX_data bodies compact. Matches the round-95 / 100
// ASPX_ACPL_3 / ACPL_2 config exactly.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine;
// acpl_qmf_band_minus1 = 0 → qmf_band = 1 (PARTIAL mode).
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl1_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_master,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 5.0 SIMPLE/ASPX_ACPL_1
/// multichannel substream whose joint-MDCT residual layer is
/// **SAP-coded by decision** (round 279) — the automatic,
/// decision-driven counterpart of [`Self::encode_frame_pcm_5_0_acpl1`].
///
/// Per ETSI TS 103 190-1 §5.3.4.3.2 / Table 181 + §5.3.2 Pseudocode
/// 59, the encoder runs the round-271
/// [`crate::asf::select_alpha_q_for_pair`] least-squares decision per
/// `(L, Ls)` / `(R, Rs)` target pair, materialises the SAP-coded
/// `chparam_info()` rows via
/// [`crate::asf::build_chparam_info_sap_data_from_alpha_q`] (falling
/// back to the header-only `SapMode::None` row when no band
/// benefits), and transmits the Table-181 matrix-input carriers
/// `(sSMP_A, sSMP_B) = (M, ·)` plus the side prediction residual
/// `(sSMP_3, sSMP_4) = (S − g·M, ·)` recovered through
/// [`crate::asf::invert_sap_table_181`]. For a surround pair
/// correlated with its front carrier the residual sf_data collapses
/// to (near-)silence — the bits the identity path spends on the raw
/// Ls/Rs spectra are saved while the decoder's
/// `apply_sap_table_181` forward mix reproduces the same
/// preliminaries.
///
/// On-wire body layout is identical to
/// [`Self::encode_frame_pcm_5_0_acpl1`]; when the decision picks no
/// SAP band (e.g. `Ls = L`) the emitted frame is bit-for-bit
/// identical to the identity-SAP path.
pub fn encode_frame_pcm_5_0_acpl1_sap(&mut self, frames: &[&[f32]; 5]) -> Vec<u8> {
self.encode_frame_pcm_5_0_acpl1_sap_with_max_sfb(frames, 40, 20)
}
/// `max_sfb` / `max_sfb_master`-parameterised form of
/// [`Self::encode_frame_pcm_5_0_acpl1_sap`].
pub fn encode_frame_pcm_5_0_acpl1_sap_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
max_sfb: u32,
max_sfb_master: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0_acpl1_sap: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 5.0 channel_mode prefix '1101', 4 b → channel_mode 3.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
// Forward MDCT analysis per carrier channel (L, R, C, Ls, Rs).
let n_channels = 5;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// Same ASPX / ACPL parameterisation as the round-103 path.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl1_body_from_pcm_spectra_sap_auto(
frame_len,
max_sfb,
max_sfb_master,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 5.0 SIMPLE/ASPX_ACPL_1
/// multichannel substream with **real per-parameter-band α extraction**
/// (round 128 — replaces the round-103 zero-delta scaffold for the
/// α coefficient family; β / β3 / γ stay at the scaffold).
///
/// Body layout is identical to [`Self::encode_frame_pcm_5_0_acpl1`]
/// (delegates to [`crate::encoder_acpl3::build_5_x_acpl1_body_from_pcm_spectra_real_alpha`]);
/// the only on-wire difference is that the two `acpl_data_1ch()`
/// elements now emit ALPHA F0 + DF codewords with non-zero values
/// chosen to minimise the per-parameter-band residual against the
/// caller's (Ls, Rs) input vs (L, R) carrier energies. See
/// [`crate::encoder_acpl3`] §"Real per-band α extraction" for the
/// closed-form derivation (β = 0 ⇒ α = 1 − 2·√2·⟨carrier, surround⟩
/// / ⟨carrier, carrier⟩).
///
/// `frames` is in `[L, R, C, Ls, Rs]` order. The decoder's
/// [`crate::acpl_synth::run_acpl_5x_pair_pcm`] consumes the recovered
/// α and reconstructs Ls / Rs from the L / R carriers with measurably
/// better fidelity than the zero-α baseline when Ls / Rs aren't a
/// pure scaled copy of L / R.
pub fn encode_frame_pcm_5_0_acpl1_real_alpha(&mut self, frames: &[&[f32]; 5]) -> Vec<u8> {
self.encode_frame_pcm_5_0_acpl1_real_alpha_with_max_sfb(frames, 40, 20)
}
/// `max_sfb` / `max_sfb_master`-parameterised form of
/// [`Self::encode_frame_pcm_5_0_acpl1_real_alpha`].
pub fn encode_frame_pcm_5_0_acpl1_real_alpha_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
max_sfb: u32,
max_sfb_master: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0_acpl1_real_alpha: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 5.0 channel_mode prefix '1101', 4 b → channel_mode 3.
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
let n_channels = 5;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl1_body_from_pcm_spectra_real_alpha(
frame_len,
max_sfb,
max_sfb_master,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 5.0 SIMPLE/ASPX_ACPL_1
/// multichannel substream with **real per-parameter-band α + β
/// extraction** per ETSI TS 103 190-1 §5.7.7.5 Pseudocode 116 +
/// §5.7.7.6.1 Pseudocode 117 (round 132).
///
/// Extends [`Self::encode_frame_pcm_5_0_acpl1_real_alpha`] by emitting
/// real per-band β magnitudes alongside the existing real α — the
/// surround Ls/Rs reconstruction at the decoder is no longer a pure
/// level-only image of L/R but also carries the energy of the
/// decorrelated residual:
///
/// ```text
/// E[Ls²] = 0.5 · E[L²] · ( (1 − α)² + β² )
/// ```
///
/// `frames` is in `[L, R, C, Ls, Rs]` order; β / γ stay at the
/// round-95 / 100 / 103 / 128 scaffold for non-ACPL_1 paths.
pub fn encode_frame_pcm_5_0_acpl1_real_alpha_beta(&mut self, frames: &[&[f32]; 5]) -> Vec<u8> {
self.encode_frame_pcm_5_0_acpl1_real_alpha_beta_with_max_sfb(frames, 40, 20)
}
/// `max_sfb` / `max_sfb_master`-parameterised form of
/// [`Self::encode_frame_pcm_5_0_acpl1_real_alpha_beta`].
pub fn encode_frame_pcm_5_0_acpl1_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 5],
max_sfb: u32,
max_sfb_master: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_5_0_acpl1_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1101;
self.channel_mode_bits = 4;
let n_channels = 5;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 8192,
41..=50 => 16384,
_ => 32768,
};
let body = crate::encoder_acpl3::build_5_x_acpl1_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
max_sfb_master,
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[2],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.0 SIMPLE/ASPX_ACPL_2
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_2:` (round 107). The 7_X (immersive) symmetric
/// counterpart to the round-100 5_X ASPX_ACPL_2 encoder — it reuses the
/// same 1ch ACPL / ASPX parameter shape (Pseudocode 117) but emits the
/// 7_X channel element's distinct framing (2-bit `7_X_codec_mode`,
/// `companding_control(5)`, 2-bit `coding_config`, two `two_channel_data`
/// pairs, trailing centre `mono_data(0)`, and the two-`aspx_data_2ch`
/// envelope trailer).
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb]` order — the 7.0 (3/4/0)
/// surface layout. The L/R pair feeds the first `two_channel_data()`
/// carriers and drives the A-CPL Ls/Rs surround reconstruction via
/// [`crate::acpl_synth::run_acpl_5x_pair_pcm`] at decode time. The Ls/Rs
/// pair is coded as the second `two_channel_data()` (keeps the body
/// well-formed for the walker; the ACPL_2 dispatch reconstructs the
/// surround from L/R + params). The centre `C` is the trailing Cfg0
/// `mono_data(0)`. The back pair `Lb, Rb` is accepted for layout
/// completeness but not carried by the ASPX_ACPL_2 body (the decoder's
/// ACPL_2 7_X dispatch populates slots 0..4 only — slots 5/6 stay
/// silent), matching the decoder's documented Table 202 channel mapping.
///
/// The encoder forces the 7.0 (3/4/0) channel_mode prefix (`0b1111000`,
/// 7 b — Table 85 channel_mode 5) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 7` through
/// `parse_7x_audio_data_outer(b_has_lfe = false)` with
/// `7_X_codec_mode = AspxAcpl2`. The ASPX/A-CPL parameter bits use the
/// round-95 minimum-bit-cost zero-delta Huffman scaffold.
///
/// `max_sfb` defaults to 40.
pub fn encode_frame_pcm_7_0_acpl2(&mut self, frames: &[&[f32]; 7]) -> Vec<u8> {
self.encode_frame_pcm_7_0_acpl2_with_max_sfb(frames, 40)
}
/// `max_sfb`-parameterised form of [`Self::encode_frame_pcm_7_0_acpl2`].
pub fn encode_frame_pcm_7_0_acpl2_with_max_sfb(
&mut self,
frames: &[&[f32]; 7],
max_sfb: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_0_acpl2: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 7.0 (3/4/0) channel_mode prefix '1111000', 7 b →
// channel_mode 5 (Table 85). The decoder routes channels == 7
// through parse_7x_audio_data_outer(b_has_lfe = false).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111000;
self.channel_mode_bits = 7;
// Forward MDCT analysis per channel — seven SCE states (L, R, C,
// Ls, Rs, Lb, Rb). Only the first five feed the ASPX_ACPL_2 body;
// the back pair is analysed for state continuity but its spectra
// are not carried by the ACPL_2 path.
let n_channels = 7;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: small low-res scale so the SBG counts stay small —
// matches the round-95 / 100 / 103 ASPX_ACPL config exactly.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl2_body_from_pcm_spectra(
frame_len,
max_sfb,
None, // 7.0 — no LFE
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
None, // 7.0 — no LFE
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.1 (3/4/0.1) SIMPLE/ASPX_ACPL_2
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_2:` with `b_has_lfe = 1` (round 114). The LFE
/// counterpart of [`Self::encode_frame_pcm_7_0_acpl2`] — it emits the
/// identical 7_X ASPX_ACPL_2 body plus a leading `mono_data(b_lfe = 1)`
/// element (Table 21 + `sf_info_lfe()` Table 35) between the I-frame
/// config block and `companding_control(5)`, exactly where the decoder's
/// `parse_7x_audio_data_outer(b_has_lfe = true)` reads
/// `if (b_has_lfe) mono_data(1);`.
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb, LFE]` order — the 7.1
/// (3/4/0.1) surface layout. The L/R pair feeds the first
/// `two_channel_data()` carriers and drives the A-CPL Ls/Rs surround
/// reconstruction via [`crate::acpl_synth::run_acpl_5x_pair_pcm`] at
/// decode time; the Ls/Rs pair rides the second `two_channel_data()`;
/// the centre `C` is the trailing Cfg0 `mono_data(0)`; the LFE is the
/// leading `mono_data(1)`. The back pair `Lb, Rb` is accepted for layout
/// completeness but not carried by the ASPX_ACPL_2 body (the decoder's
/// 7_X ACPL_2 dispatch populates slots 0..4 + the LFE slot 7 — slots 5/6
/// stay silent), matching the round-107 documented Table 202 channel
/// mapping plus the round-80 LFE PCM render at decode time.
///
/// The encoder forces the 7.1 channel_mode prefix (`0b1111001`, 7 b —
/// Table 88 channel_mode 6) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 8` through
/// `parse_7x_audio_data_outer(b_has_lfe = true)` with
/// `7_X_codec_mode = AspxAcpl2`. The ASPX/A-CPL parameter bits use the
/// round-95 minimum-bit-cost zero-delta Huffman scaffold.
///
/// `max_sfb` defaults to 40; `max_sfb_lfe` defaults to 7 (the LFE-spec
/// cap at `tl = 1920`, `n_msfbl_bits = 3`).
pub fn encode_frame_pcm_7_1_acpl2(&mut self, frames: &[&[f32]; 8]) -> Vec<u8> {
self.encode_frame_pcm_7_1_acpl2_with_max_sfb(frames, 40, 7)
}
/// `max_sfb`-parameterised form of [`Self::encode_frame_pcm_7_1_acpl2`].
/// `max_sfb` governs the five front/surround carrier SCEs and the centre
/// mono; `max_sfb_lfe` governs the LFE `mono_data(1)` (clamped to the
/// `n_msfbl_bits` cap).
pub fn encode_frame_pcm_7_1_acpl2_with_max_sfb(
&mut self,
frames: &[&[f32]; 8],
max_sfb: u32,
max_sfb_lfe: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_1_acpl2: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, n_msfbl_bits) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
assert!(
n_msfbl_bits > 0,
"encode_frame_pcm_7_1_acpl2: tl = {frame_len} not permitted for LFE"
);
let n_msfbl_cap = (1u32 << n_msfbl_bits) - 1;
let max_sfb_lfe = max_sfb_lfe.min(n_msfbl_cap);
// Force 7.1 (3/4/0.1) channel_mode prefix '1111001', 7 b →
// channel_mode 6 (Table 88). The decoder routes channels == 8
// through parse_7x_audio_data_outer(b_has_lfe = true).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111001;
self.channel_mode_bits = 7;
// Forward MDCT analysis per channel — eight SCE states (L, R, C,
// Ls, Rs, Lb, Rb, LFE). The first five + LFE feed the ASPX_ACPL_2
// body; the back pair is analysed for state continuity but its
// spectra are not carried by the ACPL_2 path.
let n_channels = 8;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: matches the round-95 / 100 / 103 / 107 ASPX_ACPL
// config exactly (small low-res scale → small SBG counts).
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl2_body_from_pcm_spectra(
frame_len,
max_sfb,
Some(max_sfb_lfe),
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
Some(&coeffs_per_channel[7]),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.0 (3/4/0) SIMPLE/ASPX_ACPL_2
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_2:` with **real per-parameter-band α + β extraction**
/// (round 202). The 7_X (immersive) counterpart to the round-144 5.0
/// ACPL_2 real-α-β path
/// ([`Self::encode_frame_pcm_5_0_acpl2_real_alpha_beta`]) and the
/// real-α-β upgrade of the round-107 7.0 ACPL_2 zero-delta path
/// ([`Self::encode_frame_pcm_7_0_acpl2`]).
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb]` order — the 7.0 (3/4/0)
/// surface layout. The L/R pair feeds the first `two_channel_data()`
/// carriers and drives the A-CPL Ls/Rs surround reconstruction via
/// [`crate::acpl_synth::run_acpl_5x_pair_pcm`] at decode time; the
/// Ls/Rs pair rides the second `two_channel_data()` *and* feeds the
/// α + β extractors (D0 module models (L → Ls); D1 module models
/// (R → Rs)). `acpl_config_1ch(FULL)` carries no `qmf_band` →
/// `start_band = 0` so every parameter band participates. The centre
/// `C` is the trailing Cfg0 `mono_data(0)`. The back pair `Lb, Rb`
/// is accepted for layout completeness but not carried by the
/// ASPX_ACPL_2 body (the decoder's 7_X ACPL_2 dispatch populates
/// slots 0..4 — slots 5/6 stay silent), matching the round-107
/// documented Table 202 channel mapping.
///
/// The encoder forces the 7.0 channel_mode prefix (`0b1111000`, 7 b —
/// Table 85 channel_mode 5) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 7` through
/// `parse_7x_audio_data_outer(b_has_lfe = false)` with
/// `7_X_codec_mode = AspxAcpl2`.
///
/// `max_sfb` defaults to 40.
pub fn encode_frame_pcm_7_0_acpl2_real_alpha_beta(&mut self, frames: &[&[f32]; 7]) -> Vec<u8> {
self.encode_frame_pcm_7_0_acpl2_real_alpha_beta_with_max_sfb(frames, 40)
}
/// `max_sfb`-parameterised form of
/// [`Self::encode_frame_pcm_7_0_acpl2_real_alpha_beta`].
pub fn encode_frame_pcm_7_0_acpl2_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 7],
max_sfb: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_0_acpl2_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 7.0 (3/4/0) channel_mode prefix '1111000', 7 b →
// channel_mode 5 (Table 85).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111000;
self.channel_mode_bits = 7;
// Forward MDCT analysis per channel — seven SCE states (L, R, C,
// Ls, Rs, Lb, Rb). The first five feed the ASPX_ACPL_2 body;
// Ls / Rs additionally feed the α + β extractors. The back pair
// is analysed for state continuity but its spectra are not
// carried by the ACPL_2 path.
let n_channels = 7;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: matches the round-95 / 100 / 103 / 107 ASPX_ACPL
// config exactly.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl2_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
None, // 7.0 — no LFE
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
None, // 7.0 — no LFE
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.1 (3/4/0.1) SIMPLE/ASPX_ACPL_2
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_2:` with `b_has_lfe = 1` and **real per-parameter-band
/// α + β extraction** (round 202). The LFE counterpart of
/// [`Self::encode_frame_pcm_7_0_acpl2_real_alpha_beta`] — it emits the
/// identical 7_X ASPX_ACPL_2 real-α-β body plus a leading
/// `mono_data(b_lfe = 1)` element between the I-frame config block and
/// `companding_control(5)`, exactly where the decoder's
/// `parse_7x_audio_data_outer(b_has_lfe = true)` reads
/// `if (b_has_lfe) mono_data(1);`.
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb, LFE]` order. See
/// [`Self::encode_frame_pcm_7_0_acpl2_real_alpha_beta`] for the channel
/// routing contract; the LFE is the leading `mono_data(1)`.
///
/// The encoder forces the 7.1 channel_mode prefix (`0b1111001`, 7 b —
/// Table 88 channel_mode 6) so the decoder dispatches `channels == 8`
/// through `parse_7x_audio_data_outer(b_has_lfe = true)` with
/// `7_X_codec_mode = AspxAcpl2`.
///
/// `max_sfb` defaults to 40; `max_sfb_lfe` defaults to 7 (the LFE-spec
/// cap at `tl = 1920`, `n_msfbl_bits = 3`).
pub fn encode_frame_pcm_7_1_acpl2_real_alpha_beta(&mut self, frames: &[&[f32]; 8]) -> Vec<u8> {
self.encode_frame_pcm_7_1_acpl2_real_alpha_beta_with_max_sfb(frames, 40, 7)
}
/// `max_sfb` / `max_sfb_lfe`-parameterised form of
/// [`Self::encode_frame_pcm_7_1_acpl2_real_alpha_beta`].
pub fn encode_frame_pcm_7_1_acpl2_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 8],
max_sfb: u32,
max_sfb_lfe: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_1_acpl2_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, n_msfbl_bits) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
assert!(
n_msfbl_bits > 0,
"encode_frame_pcm_7_1_acpl2_real_alpha_beta: tl = {frame_len} not permitted for LFE"
);
let n_msfbl_cap = (1u32 << n_msfbl_bits) - 1;
let max_sfb_lfe = max_sfb_lfe.min(n_msfbl_cap);
// Force 7.1 (3/4/0.1) channel_mode prefix '1111001', 7 b →
// channel_mode 6 (Table 88).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111001;
self.channel_mode_bits = 7;
// Forward MDCT analysis per channel — eight SCE states (L, R, C,
// Ls, Rs, Lb, Rb, LFE).
let n_channels = 8;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: matches the round-95 / 100 / 103 / 107 / 114 ASPX_ACPL
// config exactly.
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine.
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl2_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
Some(max_sfb_lfe),
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
Some(&coeffs_per_channel[7]),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.0 (3/4/0) SIMPLE/ASPX_ACPL_1
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_1:` (round 118). The 7_X (immersive) counterpart to
/// the round-103 5_X ASPX_ACPL_1 encoder and the encoder side of the
/// decoder's round-27 `parse_7x_audio_data_outer` ASPX_ACPL_1 branch.
///
/// ASPX_ACPL_1 differs from the round-107 7.0 ASPX_ACPL_2 path in three
/// structural places (the same three that separate the 5_X ACPL_1 path
/// from the 5_X ACPL_2 path): `7_X_codec_mode = 2` (vs 3),
/// `acpl_config_1ch` is PARTIAL (vs FULL — carries the 3-bit
/// `acpl_qmf_band_minus1`), and the body carries an explicit joint-MDCT
/// residual layer (`max_sfb_master + 2× chparam_info + 2× sf_data(ASF)`)
/// transmitting the Ls/Rs surround pair (sSMP,3 / sSMP,4 per Table 181)
/// rather than reconstructing it purely from the L/R carriers.
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb]` order — the 7.0 (3/4/0)
/// surface layout. The L/R pair feeds the first `two_channel_data()`
/// carriers; the Ls/Rs pair rides the second `two_channel_data()` *and*
/// the joint-MDCT residual layer; the centre `C` is the trailing Cfg0
/// `mono_data(0)`. The back pair `Lb, Rb` is accepted for layout
/// completeness but not carried by the ASPX_ACPL_1 body (the decoder's
/// 7_X ACPL_1 dispatch populates slots 0..4 only — slots 5/6 stay
/// silent), matching the round-107 documented Table 202 channel mapping.
///
/// The encoder forces the 7.0 (3/4/0) channel_mode prefix (`0b1111000`,
/// 7 b — Table 85 channel_mode 5) so the decoder's `walk_ac4_substream`
/// dispatches `channels == 7` through
/// `parse_7x_audio_data_outer(b_has_lfe = false)` with
/// `7_X_codec_mode = AspxAcpl1`. The ASPX/A-CPL parameter bits use the
/// round-95 minimum-bit-cost zero-delta Huffman scaffold.
///
/// `max_sfb` defaults to 40; `max_sfb_master` (the residual band bound)
/// defaults to 20.
pub fn encode_frame_pcm_7_0_acpl1(&mut self, frames: &[&[f32]; 7]) -> Vec<u8> {
self.encode_frame_pcm_7_0_acpl1_with_max_sfb(frames, 40, 20)
}
/// `max_sfb` / `max_sfb_master`-parameterised form of
/// [`Self::encode_frame_pcm_7_0_acpl1`].
pub fn encode_frame_pcm_7_0_acpl1_with_max_sfb(
&mut self,
frames: &[&[f32]; 7],
max_sfb: u32,
max_sfb_master: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_0_acpl1: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 7.0 (3/4/0) channel_mode prefix '1111000', 7 b →
// channel_mode 5 (Table 85). The decoder routes channels == 7
// through parse_7x_audio_data_outer(b_has_lfe = false).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111000;
self.channel_mode_bits = 7;
// Forward MDCT analysis per channel — seven SCE states (L, R, C,
// Ls, Rs, Lb, Rb). Only the first five feed the ASPX_ACPL_1 body;
// the back pair is analysed for state continuity but its spectra
// are not carried by the ACPL_1 path.
let n_channels = 7;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: matches the round-95 / 100 / 103 / 107 ASPX_ACPL
// config exactly (small low-res scale → small SBG counts).
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine;
// acpl_qmf_band_minus1 = 0 → qmf_band = 1 (PARTIAL mode).
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl1_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_master,
None, // 7.0 — no LFE
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
None, // 7.0 — no LFE
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.0 (3/4/0) SIMPLE/ASPX_ACPL_1
/// multichannel substream with **real per-parameter-band α + β
/// extraction** per ETSI TS 103 190-1 §5.7.7.5 Pseudocode 116 +
/// §5.7.7.6.1 Pseudocode 117 (round 135).
///
/// The 7_X immersive counterpart of
/// [`Self::encode_frame_pcm_5_0_acpl1_real_alpha_beta`] and the real-
/// α+β upgrade of [`Self::encode_frame_pcm_7_0_acpl1`] (which emitted
/// both `acpl_data_1ch()` sets at the round-118 zero-delta scaffold).
/// The two trailing `acpl_data_1ch()` parameter sets now carry the
/// analytic α (from the L/Ls and R/Rs MDCT-energy correlation) and the
/// β magnitude that closes the surround/carrier energy balance after α
/// removes the level-only component:
///
/// ```text
/// E[Ls²] = 0.5 · E[L²] · ( (1 − α)² + β² )
/// ```
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb]` order — the 7.0 (3/4/0)
/// surface layout, identical to [`Self::encode_frame_pcm_7_0_acpl1`].
/// β / β3 / γ for non-ACPL_1 paths stay at the scaffold.
pub fn encode_frame_pcm_7_0_acpl1_real_alpha_beta(&mut self, frames: &[&[f32]; 7]) -> Vec<u8> {
self.encode_frame_pcm_7_0_acpl1_real_alpha_beta_with_max_sfb(frames, 40, 20)
}
/// `max_sfb` / `max_sfb_master`-parameterised form of
/// [`Self::encode_frame_pcm_7_0_acpl1_real_alpha_beta`].
pub fn encode_frame_pcm_7_0_acpl1_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 7],
max_sfb: u32,
max_sfb_master: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_0_acpl1_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, _) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
// Force 7.0 (3/4/0) channel_mode prefix '1111000', 7 b →
// channel_mode 5 (Table 85). The decoder routes channels == 7
// through parse_7x_audio_data_outer(b_has_lfe = false).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111000;
self.channel_mode_bits = 7;
let n_channels = 7;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl1_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
max_sfb_master,
None, // 7.0 — no LFE
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
None, // 7.0 — no LFE
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.1 (3/4/0.1) SIMPLE/ASPX_ACPL_1
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_1:` with `b_has_lfe = 1` (round 118). The LFE
/// counterpart of [`Self::encode_frame_pcm_7_0_acpl1`] — it emits the
/// identical 7_X ASPX_ACPL_1 body plus a leading `mono_data(b_lfe = 1)`
/// element (Table 21 + `sf_info_lfe()` Table 35) between the I-frame
/// config block and `companding_control(5)`, exactly where the decoder's
/// `parse_7x_audio_data_outer(b_has_lfe = true)` reads
/// `if (b_has_lfe) mono_data(1);`.
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb, LFE]` order — the 7.1
/// (3/4/0.1) surface layout. The LFE is the leading `mono_data(1)`; the
/// rest of the body matches the 7.0 ACPL_1 form. The encoder forces the
/// 7.1 channel_mode prefix (`0b1111001`, 7 b — Table 88 channel_mode 6)
/// so the decoder dispatches `channels == 8` through
/// `parse_7x_audio_data_outer(b_has_lfe = true)` with
/// `7_X_codec_mode = AspxAcpl1`; the LFE spectrum IMDCT's into slot 7
/// via the round-80 LFE PCM render.
///
/// `max_sfb` defaults to 40; `max_sfb_master` defaults to 20;
/// `max_sfb_lfe` defaults to 7 (the LFE-spec cap at `tl = 1920`,
/// `n_msfbl_bits = 3`).
pub fn encode_frame_pcm_7_1_acpl1(&mut self, frames: &[&[f32]; 8]) -> Vec<u8> {
self.encode_frame_pcm_7_1_acpl1_with_max_sfb(frames, 40, 20, 7)
}
/// `max_sfb`-parameterised form of [`Self::encode_frame_pcm_7_1_acpl1`].
/// `max_sfb` governs the five front/surround carrier SCEs and the centre
/// mono; `max_sfb_master` governs the joint-MDCT surround residual
/// layer; `max_sfb_lfe` governs the LFE `mono_data(1)` (clamped to the
/// `n_msfbl_bits` cap).
pub fn encode_frame_pcm_7_1_acpl1_with_max_sfb(
&mut self,
frames: &[&[f32]; 8],
max_sfb: u32,
max_sfb_master: u32,
max_sfb_lfe: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_1_acpl1: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, n_msfbl_bits) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
assert!(
n_msfbl_bits > 0,
"encode_frame_pcm_7_1_acpl1: tl = {frame_len} not permitted for LFE"
);
let n_msfbl_cap = (1u32 << n_msfbl_bits) - 1;
let max_sfb_lfe = max_sfb_lfe.min(n_msfbl_cap);
// Force 7.1 (3/4/0.1) channel_mode prefix '1111001', 7 b →
// channel_mode 6 (Table 88). The decoder routes channels == 8
// through parse_7x_audio_data_outer(b_has_lfe = true).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111001;
self.channel_mode_bits = 7;
// Forward MDCT analysis per channel — eight SCE states (L, R, C,
// Ls, Rs, Lb, Rb, LFE). The first five + LFE feed the ASPX_ACPL_1
// body; the back pair is analysed for state continuity but its
// spectra are not carried by the ACPL_1 path.
let n_channels = 8;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
// ASPX config: matches the round-95 / 100 / 103 / 107 ASPX_ACPL
// config exactly (small low-res scale → small SBG counts).
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0, // num_noise_sbgroups = 1
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
// ACPL: num_param_bands_id = 3 → 7 param bands; quant_mode Fine;
// acpl_qmf_band_minus1 = 0 → qmf_band = 1 (PARTIAL mode).
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl1_body_from_pcm_spectra(
frame_len,
max_sfb,
max_sfb_master,
Some(max_sfb_lfe),
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
Some(&coeffs_per_channel[7]),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
// Wrap in v2 IMS TOC.
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a 7.1 (3/4/0.1) SIMPLE/ASPX_ACPL_1
/// multichannel substream per ETSI TS 103 190-1 §4.2.6.14 Table 33 row
/// `case ASPX_ACPL_1:` with `b_has_lfe = 1`, with **real per-parameter-band
/// α + β extraction** carried by the two trailing `acpl_data_1ch()`
/// parameter sets (round 139 — the LFE counterpart of the round-135
/// 7.0 immersive real-α+β path,
/// [`Self::encode_frame_pcm_7_0_acpl1_real_alpha_beta`]).
///
/// The round-118 7.1 ASPX_ACPL_1 encoder emitted both `acpl_data_1ch()`
/// parameter sets at the zero-delta scaffold; this entry point upgrades
/// them to carry the analytic α (from the L/Ls and R/Rs MDCT-energy
/// correlation, §5.7.7.5 Pseudocode 116) plus the β magnitude that
/// closes the surround/carrier energy balance after α removes the
/// level-only component (§5.7.7.6.1 Pseudocode 117):
///
/// ```text
/// E[Ls²] = 0.5 · E[L²] · ( (1 − α)² + β² )
/// ⇒ β = √max(0, 2·E[Ls²]/E[L²] − (1 − α)²)
/// ```
///
/// `frames` is in `[L, R, C, Ls, Rs, Lb, Rb, LFE]` order — the 7.1
/// (3/4/0.1) surface layout, identical to
/// [`Self::encode_frame_pcm_7_1_acpl1`]. The leading `mono_data(b_lfe = 1)`
/// element (Table 21 + `sf_info_lfe()` Table 35) is emitted between the
/// I-frame config block and `companding_control(5)`. The on-wire body
/// structure is otherwise identical — decoder resolves
/// `SevenXCodecMode::AspxAcpl1` with `b_has_lfe = true`, both
/// `acpl_data_1ch_pair[0/1]` populated (now carrying real α + β),
/// joint-MDCT residual layer walked, LFE IMDCT'd into slot 7.
pub fn encode_frame_pcm_7_1_acpl1_real_alpha_beta(&mut self, frames: &[&[f32]; 8]) -> Vec<u8> {
self.encode_frame_pcm_7_1_acpl1_real_alpha_beta_with_max_sfb(frames, 40, 20, 7)
}
/// `max_sfb`-parameterised form of
/// [`Self::encode_frame_pcm_7_1_acpl1_real_alpha_beta`]. `max_sfb`
/// governs the five front/surround carrier SCEs and the centre mono;
/// `max_sfb_master` governs the joint-MDCT surround residual layer;
/// `max_sfb_lfe` governs the LFE `mono_data(1)` (clamped to the
/// `n_msfbl_bits` cap).
pub fn encode_frame_pcm_7_1_acpl1_real_alpha_beta_with_max_sfb(
&mut self,
frames: &[&[f32]; 8],
max_sfb: u32,
max_sfb_master: u32,
max_sfb_lfe: u32,
) -> Vec<u8> {
let (_fps_milli, frame_len) =
crate::toc::frame_rate_entry(self.frame_rate_index as u32, self.fs_index as u32);
let frame_len = if frame_len == 0 { 1920 } else { frame_len };
for (ch, f) in frames.iter().enumerate() {
assert_eq!(
f.len(),
frame_len as usize,
"encode_frame_pcm_7_1_acpl1_real_alpha_beta: channel {ch} input length must match frame_len = {frame_len}"
);
}
let (n_msfb_bits, _, n_msfbl_bits) =
crate::tables::n_msfb_bits_48(frame_len).expect("encoder: bad tl");
let n_msfb_cap = (1u32 << n_msfb_bits) - 1;
let max_sfb = max_sfb.min(n_msfb_cap);
assert!(
n_msfbl_bits > 0,
"encode_frame_pcm_7_1_acpl1_real_alpha_beta: tl = {frame_len} not permitted for LFE"
);
let n_msfbl_cap = (1u32 << n_msfbl_bits) - 1;
let max_sfb_lfe = max_sfb_lfe.min(n_msfbl_cap);
// Force 7.1 (3/4/0.1) channel_mode prefix '1111001', 7 b →
// channel_mode 6 (Table 88). The decoder routes channels == 8
// through parse_7x_audio_data_outer(b_has_lfe = true).
let saved_mode = (self.channel_mode_value, self.channel_mode_bits);
self.channel_mode_value = 0b1111001;
self.channel_mode_bits = 7;
let n_channels = 8;
while self.mdct_states_multi.len() < n_channels {
self.mdct_states_multi
.push(EncoderMdctState::new(frame_len));
}
for state in self.mdct_states_multi.iter_mut() {
if state.n != frame_len {
*state = EncoderMdctState::new(frame_len);
}
}
let mut coeffs_per_channel: Vec<Vec<f32>> = Vec::with_capacity(n_channels);
for (ch, f) in frames.iter().enumerate() {
let c = self.mdct_states_multi[ch].analyse_frame(f);
coeffs_per_channel.push(c);
}
let aspx_cfg = crate::aspx::AspxConfig {
quant_mode_env: crate::aspx::AspxQuantStep::Fine,
start_freq: 0,
stop_freq: 0,
master_freq_scale: crate::aspx::AspxMasterFreqScale::LowRes,
interpolation: false,
preflat: false,
limiter: false,
noise_sbg: 0,
num_env_bits_fixfix: 0,
freq_res_mode: crate::aspx::AspxFreqResMode::DurationDependent,
};
let acpl_num_param_bands_id: u8 = 3;
let acpl_quant_mode = crate::acpl::AcplQuantMode::Fine;
let acpl_qmf_band_minus1: u8 = 0;
let pad_target_bytes: usize = match max_sfb {
0..=20 => 4096,
21..=40 => 12288,
41..=50 => 24576,
_ => 32767,
};
let body = crate::encoder_acpl3::build_7_x_acpl1_body_from_pcm_spectra_real_alpha_beta(
frame_len,
max_sfb,
max_sfb_master,
Some(max_sfb_lfe),
self.b_iframe_global,
&coeffs_per_channel[0],
&coeffs_per_channel[1],
&coeffs_per_channel[3],
&coeffs_per_channel[4],
&coeffs_per_channel[2],
Some(&coeffs_per_channel[7]),
&aspx_cfg,
acpl_num_param_bands_id,
acpl_quant_mode,
acpl_qmf_band_minus1,
pad_target_bytes,
);
let mut bw = BitWriter::new();
self.write_toc(&mut bw);
bw.align_to_byte();
let mut out = bw.finish();
out.extend(body);
self.sequence_counter = (self.sequence_counter.wrapping_add(1)) & 0x3FF;
self.channel_mode_value = saved_mode.0;
self.channel_mode_bits = saved_mode.1;
out
}
/// Encode one IMS v2 frame containing a mono SIMPLE/ASF substream
/// whose injected tone falls on the spectral pair nearest the
/// requested frequency. With `tl = 1920` at 48 kHz the bin spacing
/// is 12.5 Hz; the chosen pair carries a single non-zero quantised
/// value at the lower bin of that pair.
///
/// Returns the encoded frame bytes plus the actual nominal centre
/// frequency the encoder targeted (lower-bin × bin_spacing).
pub fn encode_frame_mono_tone_at_hz(&mut self, target_hz: f32) -> (Vec<u8>, f32) {
let bin_spacing = 48_000.0 / (2.0 * 1_920.0); // 12.5 Hz
let target_bin = (target_hz / bin_spacing).round().max(0.0) as u32;
let pair_idx = target_bin / 2;
let actual_hz = (pair_idx * 2) as f32 * bin_spacing;
// cb_idx 49 → (q0=+1, q1=0): tone in lower bin of the pair.
let frame = self.encode_frame_mono_tone(49, pair_idx);
(frame, actual_hz)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encoder_emits_nonempty_frame() {
let mut enc = Ac4ImsEncoder::new();
let frame = enc.encode_frame(0);
assert!(!frame.is_empty(), "encoder must produce at least the TOC");
// sequence_counter rolled from 0 → 1.
assert_eq!(enc.sequence_counter, 1);
}
#[test]
fn encoder_sequence_counter_wraps_at_1024() {
let mut enc = Ac4ImsEncoder::new();
enc.sequence_counter = 1023;
let _ = enc.encode_frame(0);
// 1023 + 1 = 1024 → wraps to 0 (10-bit field).
assert_eq!(enc.sequence_counter, 0);
}
#[test]
fn v0_encoder_round_trips_through_parse_ac4_toc() {
// encode_frame_v0 emits a TS 103 190-1 TOC the existing
// `parse_ac4_toc` walker accepts without erroring. Round-trip
// (encode → parse) must return the same metadata we encoded:
// mono / 48 kHz / 24 fps / iframe_global / 1920 samples per
// frame.
let mut enc = Ac4ImsEncoder::new(); // mono default
let frame = enc.encode_frame_v0(64);
let info = crate::toc::parse_ac4_toc(&frame).expect("v0 TOC must parse");
assert_eq!(info.fs_index, 1);
assert_eq!(info.frame_rate_index, 1);
assert_eq!(info.frame_length, 1_920);
assert!(info.b_iframe_global);
assert_eq!(info.n_presentations, 1);
assert_eq!(info.n_substreams, 1);
// mono channel mode prefix '0' → 1 channel.
assert_eq!(info.channels, 1);
}
#[test]
fn v0_encoder_round_trips_stereo() {
let mut enc = Ac4ImsEncoder::new().with_v0().with_stereo();
let frame = enc.encode_frame(64);
let info = crate::toc::parse_ac4_toc(&frame).expect("v0 stereo TOC must parse");
assert_eq!(info.channels, 2);
assert!(info.b_iframe_global);
}
#[test]
fn v0_encoder_round_trips_5_1() {
let mut enc = Ac4ImsEncoder::new().with_v0().with_5_1();
let frame = enc.encode_frame(128);
let info = crate::toc::parse_ac4_toc(&frame).expect("v0 5.1 TOC must parse");
// channel_mode prefix '1110' → 6 channels (5.1) per Table 85.
assert_eq!(info.channels, 6);
}
#[test]
fn v0_encoder_decoder_roundtrip_emits_silent_frame() {
// Full encode → Ac4Decoder roundtrip on the v0 path. The
// decoder accepts the Auditor frame (TOC + zero body) and
// emits a structurally-valid silent AudioFrame at the
// declared 1920 samples / 48 kHz / mono shape.
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let mut enc = Ac4ImsEncoder::new(); // mono default
let frame_bytes = enc.encode_frame_v0(64);
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), frame_bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
// mono S16 layout: 1920 samples × 1 ch × 2 bytes.
assert_eq!(af.data.len(), 1);
assert_eq!(af.data[0].len(), 1_920 * 2);
// All bytes should be zero (silent placeholder).
assert!(af.data[0].iter().all(|&b| b == 0));
}
#[test]
fn v2_encoder_emits_first_two_bits_as_bitstream_version_2() {
// Auditor-mode contract: the first two bits of the produced
// frame are `bitstream_version = 0b10` (i.e. value 2). This
// is the spec invariant from Table 74 — every TS 103 190-2
// IMS bitstream MUST start with these bits.
let mut enc = Ac4ImsEncoder::new(); // bitstream_version = 2
let frame = enc.encode_frame(0);
assert!(!frame.is_empty());
let bv = (frame[0] >> 6) & 0b11;
assert_eq!(bv, 0b10, "IMS frame must start with bitstream_version = 2");
}
#[test]
fn v0_encoder_emits_first_two_bits_as_bitstream_version_0() {
let mut enc = Ac4ImsEncoder::new().with_v0();
let frame = enc.encode_frame(0);
assert!(!frame.is_empty());
let bv = (frame[0] >> 6) & 0b11;
assert_eq!(bv, 0b00, "v0 frame must start with bitstream_version = 0");
}
#[test]
fn v2_encoder_round_trips_through_parse_ac4_toc() {
// Round-47 contract: the v2 TOC emitted by `encode_frame()`
// round-trips through `parse_ac4_toc`. Mono / 48 kHz / 24 fps /
// iframe_global / 1920 samples per frame should land on the
// returned `Ac4FrameInfo` exactly as configured.
let mut enc = Ac4ImsEncoder::new(); // v2 default, mono
let frame = enc.encode_frame(64);
let info = crate::toc::parse_ac4_toc(&frame).expect("v2 TOC must parse");
assert_eq!(info.bitstream_version, 2);
assert_eq!(info.fs_index, 1);
assert_eq!(info.frame_rate_index, 1);
assert_eq!(info.frame_length, 1_920);
assert!(info.b_iframe_global);
assert_eq!(info.n_presentations, 1);
assert_eq!(info.n_substreams, 1);
}
#[test]
fn v2_encoder_round_trips_stereo() {
let mut enc = Ac4ImsEncoder::new().with_stereo(); // v2, stereo
let frame = enc.encode_frame(64);
let info = crate::toc::parse_ac4_toc(&frame).expect("v2 stereo TOC must parse");
assert_eq!(info.bitstream_version, 2);
assert!(info.b_iframe_global);
}
#[test]
fn v2_encoder_round_trips_5_1() {
let mut enc = Ac4ImsEncoder::new().with_5_1(); // v2, 5.1
let frame = enc.encode_frame(128);
let info = crate::toc::parse_ac4_toc(&frame).expect("v2 5.1 TOC must parse");
assert_eq!(info.bitstream_version, 2);
}
#[test]
fn v2_encoder_mono_tone_roundtrip_emits_nonsilent_pcm() {
// Round-47 IMS audio body: encode v2 frame containing a mono
// SIMPLE/ASF substream with a single quantised spectral line at
// (sfb=0, bin=0). Through the decoder's full Huffman → IMDCT →
// KBD overlap-add chain this should produce real PCM with
// non-trivial energy.
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let mut enc = Ac4ImsEncoder::new(); // v2, mono
// cb_idx 49 → (q0=+1, q1=0); pair_idx 0 → bin 0.
let frame_bytes = enc.encode_frame_mono_tone(49, 0);
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), frame_bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
assert_eq!(af.data.len(), 1);
assert_eq!(af.data[0].len(), 1_920 * 2);
// Decoded PCM must be non-silent.
let samples_i16: Vec<i16> = af.data[0]
.chunks_exact(2)
.map(|c| i16::from_le_bytes([c[0], c[1]]))
.collect();
let nonzero_count = samples_i16.iter().filter(|&&s| s != 0).count();
assert!(
nonzero_count > 100,
"expected non-silent PCM from IMS tone encoder, got {nonzero_count} non-zero samples"
);
let energy: i64 = samples_i16.iter().map(|&s| (s as i64) * (s as i64)).sum();
assert!(energy > 0, "zero-energy tone output from IMS encoder");
// Substream parse must have surfaced non-zero scaled spectra at
// bin 0 (the tone we injected).
let sub = dec.last_substream.as_ref().unwrap();
let scaled = sub.tools.scaled_spec_primary.as_ref().unwrap();
assert!(scaled[0].abs() > 0.0, "DC bin must carry the injected tone");
}
#[test]
fn v2_encoder_mono_tone_at_440hz_has_spectral_peak_near_target() {
// Round-47 closed-form tone encoder targeting 440 Hz. With
// tl = 1920 / fs = 48 kHz, bin_spacing = 12.5 Hz so the tone
// pair lands at pair 17 (bin 34, ~425 Hz). The decoder's
// scaled spectrum should carry a non-zero value at the
// targeted bin.
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let mut enc = Ac4ImsEncoder::new();
let (frame_bytes, actual_hz) = enc.encode_frame_mono_tone_at_hz(440.0);
// Encoder rounded 440 Hz → bin 35 → pair 17 → bin 34 (lower-of-pair).
// Actual emitted frequency is 34 × 12.5 = 425.0 Hz.
assert!(
(actual_hz - 425.0).abs() < 1.0,
"expected ~425 Hz target, got {actual_hz}"
);
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), frame_bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
// Spectral peak: scaled_spec[34] (lower bin of the targeted
// pair) must be non-zero; the surrounding bins must NOT carry
// the same peak (proves the tone is localised).
let sub = dec.last_substream.as_ref().unwrap();
let scaled = sub.tools.scaled_spec_primary.as_ref().unwrap();
let target_bin = 34usize;
assert!(
scaled[target_bin].abs() > 0.0,
"expected non-zero spectral coefficient at bin {target_bin}, got {}",
scaled[target_bin]
);
// PCM should still be non-silent.
let samples_i16: Vec<i16> = af.data[0]
.chunks_exact(2)
.map(|c| i16::from_le_bytes([c[0], c[1]]))
.collect();
let nonzero_count = samples_i16.iter().filter(|&&s| s != 0).count();
assert!(
nonzero_count > 100,
"expected non-silent PCM at 440 Hz, got {nonzero_count} non-zero samples"
);
}
#[test]
fn v2_encoder_decoder_roundtrip_emits_silent_frame() {
// Full encode → Ac4Decoder roundtrip on the v2 path. The
// decoder accepts the IMS frame (TOC + zero body) and emits a
// structurally-valid silent AudioFrame at the declared 1920
// samples / 48 kHz / mono shape.
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let mut enc = Ac4ImsEncoder::new(); // v2 default, mono
let frame_bytes = enc.encode_frame(64);
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), frame_bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
// mono S16 layout: 1920 samples × 1 ch × 2 bytes.
assert_eq!(af.data.len(), 1);
assert_eq!(af.data[0].len(), 1_920 * 2);
// All bytes should be zero (silent placeholder for the v2
// audio body, which the encoder emits as raw zero bits).
assert!(af.data[0].iter().all(|&b| b == 0));
}
// ------------------------------------------------------------------
// Round 48 — encode_frame_pcm: arbitrary float PCM input through the
// full forward MDCT + scalefactor + ASF entropy chain.
// ------------------------------------------------------------------
/// Helper: feed a sequence of PCM frames through the encoder, then
/// the decoder, and return the decoded i16 PCM concatenated. The
/// first decoded frame loses half a window to the encoder's zero
/// history; callers that compare against the input should ignore it.
fn encode_decode_frames(frames: &[Vec<f32>]) -> Vec<Vec<i16>> {
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new(); // v2, mono, 48 kHz, 24 fps
let mut out: Vec<Vec<i16>> = Vec::with_capacity(frames.len());
for (idx, f) in frames.iter().enumerate() {
let bytes = enc.encode_frame_pcm(f);
let _ = idx;
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
assert_eq!(af.data.len(), 1);
let pcm: Vec<i16> = af.data[0]
.chunks_exact(2)
.map(|c| i16::from_le_bytes([c[0], c[1]]))
.collect();
out.push(pcm);
}
out
}
/// 1 kHz pure tone @ 48 kHz: encode → decode → assert spectral peak
/// in the right neighbourhood. With tl = 1920, bin_spacing =
/// 48_000 / (2 * 1920) = 12.5 Hz, so 1000 Hz lands at bin 80.
#[test]
fn encode_frame_pcm_1khz_tone_round_trips_with_spectral_peak() {
// Generate 4 frames of a continuous 1 kHz sine wave so the MDCT
// overlap-add reaches steady state.
let n = 1920usize;
let fs = 48_000.0_f32;
let f = 1000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * f * t).sin()
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..4).map(|i| make_frame(i * n)).collect();
let decoded = encode_decode_frames(&frames);
// Steady-state decoded frame: index 2.
let pcm = &decoded[2];
// Verify non-silent output.
let nonzero = pcm.iter().filter(|&&s| s != 0).count();
assert!(
nonzero > 100,
"expected non-silent PCM from 1 kHz tone, got {nonzero} non-zero samples"
);
// Energy must be substantial (input amplitude was 0.3 → expect
// peak |i16| >= ~1000 at the centre of the steady-state frame).
let peak = pcm.iter().map(|&s| s.abs()).max().unwrap_or(0);
assert!(peak > 1000, "expected peak amplitude > 1000, got {peak}");
}
/// Multi-tone audio: encode → decode → assert SNR > 10 dB on the
/// steady-state frame. Uses a sum of three pure tones (250 Hz +
/// 500 Hz + 1 kHz at amplitude 0.2 each) so the input is non-trivial
/// (multi-line spectrum) but bandlimited well below the encoder's
/// 7.5 kHz max_sfb=40 cutoff. This stands in for the spec's
/// "white-noise SNR > 30 dB" target — round 48's HCB5-only quantiser
/// caps |q| ≤ 4 (~12 dB SNR ceiling per band) and only codes
/// 0..7.5 kHz, so true white noise is out of reach until round 49
/// adds a wider codebook selector and a wider max_sfb.
#[test]
fn encode_frame_pcm_multitone_round_trips_with_positive_snr() {
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
let pi2 = 2.0 * std::f32::consts::PI;
0.2 * (pi2 * 250.0 * t).sin()
+ 0.2 * (pi2 * 500.0 * t).sin()
+ 0.2 * (pi2 * 1000.0 * t).sin()
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..5).map(|i| make_frame(i * n)).collect();
let decoded = encode_decode_frames(&frames);
// Steady-state frame: index 2 (well past the leading transient).
let orig = &frames[2];
let recon_i16 = &decoded[2];
let recon: Vec<f32> = recon_i16.iter().map(|&s| s as f32 / 32767.0).collect();
let mut sig_e = 0.0_f64;
let mut err_e = 0.0_f64;
for (o, r) in orig.iter().zip(recon.iter()) {
sig_e += (*o as f64).powi(2);
err_e += (*o as f64 - *r as f64).powi(2);
}
let snr_db = 10.0 * (sig_e / err_e.max(1e-30)).log10();
assert!(
snr_db > 10.0,
"multi-tone round-trip SNR too low: {snr_db:.1} dB \
(expected > 10 dB; HCB5-only encoder caps q at ±4 — \
round 49 will widen the codebook selector)"
);
}
/// Silence: encode → decode → assert decoded amplitude is small.
/// HCB5-only encoder always emits a non-zero-padded frame so we
/// expect ε > 0 noise floor — but it should be << peak amplitude.
#[test]
fn encode_frame_pcm_silence_round_trips_to_silence() {
let n = 1920usize;
let frames: Vec<Vec<f32>> = (0..4).map(|_| vec![0.0_f32; n]).collect();
let decoded = encode_decode_frames(&frames);
// Steady-state frame must be effectively silent.
let pcm = &decoded[2];
let peak = pcm.iter().map(|&s| s.abs()).max().unwrap_or(0);
// i16 peak < 50 = -56 dBFS; comfortably below any audible threshold.
assert!(
peak < 50,
"expected silent reconstruction, got peak amplitude {peak}"
);
}
/// Encoder bumps the sequence_counter once per `encode_frame_pcm`
/// call, identical to `encode_frame()`.
#[test]
fn encode_frame_pcm_bumps_sequence_counter() {
let mut enc = Ac4ImsEncoder::new();
assert_eq!(enc.sequence_counter, 0);
let frame = vec![0.0_f32; 1920];
let _ = enc.encode_frame_pcm(&frame);
assert_eq!(enc.sequence_counter, 1);
let _ = enc.encode_frame_pcm(&frame);
assert_eq!(enc.sequence_counter, 2);
}
// ------------------------------------------------------------------
// Round 49 — HCB1..11 codebook selection optimiser + wider max_sfb.
// ------------------------------------------------------------------
fn encode_decode_frames_with_max_sfb(frames: &[Vec<f32>], max_sfb: u32) -> Vec<Vec<i16>> {
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new();
let mut out: Vec<Vec<i16>> = Vec::with_capacity(frames.len());
for f in frames {
let bytes = enc.encode_frame_pcm_with_max_sfb(f, max_sfb);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
assert_eq!(af.data.len(), 1);
let pcm: Vec<i16> = af.data[0]
.chunks_exact(2)
.map(|c| i16::from_le_bytes([c[0], c[1]]))
.collect();
out.push(pcm);
}
out
}
/// White-noise input: encode via the round-49 optimiser, then decode
/// and pull the decoder's reconstructed scaled spectrum
/// (`scaled_spec_primary`) directly out of the substream. Compare
/// bin-for-bin against the encoder's input MDCT spectrum to measure
/// the codebook-selection / quantisation SNR — this isolates the
/// quantiser's noise contribution from the bandlimit / IMDCT
/// reconstruction noise that dominates a time-domain comparison.
///
/// Round-48 HCB5-only baseline: ~12 dB SNR (|q| ≤ 4 ceiling).
/// Round-49 HCB1..11 with q_target = 12: ≥ 18 dB SNR.
#[test]
fn encode_frame_pcm_white_noise_snr_exceeds_hcb5_only_ceiling() {
use crate::decoder::Ac4Decoder;
use crate::encoder_mdct::EncoderMdctState;
use oxideav_core::{CodecId, CodecParameters, Decoder, Packet, TimeBase};
let n = 1920usize;
let max_sfb = 50u32;
let sfbo = crate::sfb_offset::sfb_offset_48(n as u32).unwrap();
let end_bin = sfbo[max_sfb as usize] as usize;
let make_frame = |seed_off: u64| -> Vec<f32> {
let mut s: u64 = 0xACE4_u64.wrapping_add(seed_off);
(0..n)
.map(|_| {
s = s
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let u = (s >> 33) as u32;
(u as f32 / (1u32 << 31) as f32 - 1.0) * 0.3
})
.collect()
};
// Encode + decode 3 frames; pull the third for steady-state.
let frames: Vec<Vec<f32>> = (0..3).map(|i| make_frame(i as u64 * n as u64)).collect();
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new();
let mut last_recon_spec: Option<Vec<f32>> = None;
let mut mdct_in = EncoderMdctState::new(n as u32);
let mut last_orig_spec: Option<Vec<f32>> = None;
for f in &frames {
// Mirror the encoder's MDCT on the input.
let orig_coeffs = mdct_in.analyse_frame(f);
last_orig_spec = Some(orig_coeffs.clone());
let bytes = enc.encode_frame_pcm_with_max_sfb(f, max_sfb);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let _ = dec.receive_frame().expect("receive_frame");
let sub = dec.last_substream.as_ref().unwrap();
let scaled = sub.tools.scaled_spec_primary.as_ref().unwrap().clone();
last_recon_spec = Some(scaled);
}
let orig = last_orig_spec.unwrap();
let recon = last_recon_spec.unwrap();
let mut sig_e = 0.0_f64;
let mut err_e = 0.0_f64;
for k in 0..end_bin {
let o = orig[k] as f64;
let r = recon[k] as f64;
sig_e += o * o;
err_e += (o - r) * (o - r);
}
let snr_db = 10.0 * (sig_e / err_e.max(1e-30)).log10();
eprintln!("ROUND-49 white-noise spectral SNR (HCB1..11 optimiser, q_target=12, max_sfb=50): {snr_db:.1} dB");
assert!(
snr_db > 18.0,
"white-noise spectral SNR did not improve over HCB5-only ceiling: \
{snr_db:.1} dB (expected > 18 dB; round-48 HCB5-only baseline was ~12 dB)"
);
}
/// Wider max_sfb=55: 1 kHz tone reconstruction has ≥80% of input
/// energy preserved (vs ~40% with the round-48 max_sfb=40 default).
#[test]
fn encode_frame_pcm_max_sfb_55_preserves_tone_energy() {
let n = 1920usize;
let fs = 48_000.0_f32;
let f = 1000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * f * t).sin()
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..4).map(|i| make_frame(i * n)).collect();
let decoded = encode_decode_frames_with_max_sfb(&frames, 55);
let orig = &frames[2];
let recon_i16 = &decoded[2];
let recon: Vec<f32> = recon_i16.iter().map(|&s| s as f32 / 32767.0).collect();
let orig_e: f64 = orig.iter().map(|&v| (v as f64).powi(2)).sum();
let recon_e: f64 = recon.iter().map(|&v| (v as f64).powi(2)).sum();
let ratio = recon_e / orig_e.max(1e-30);
eprintln!(
"ROUND-49 max_sfb=55 1 kHz tone energy preservation: {:.1}%",
ratio * 100.0
);
assert!(
ratio >= 0.80,
"expected ≥80% energy preservation at max_sfb=55, got {:.1}%",
ratio * 100.0
);
}
/// Backwards compatibility: `encode_frame_pcm` without an explicit
/// max_sfb still uses the round-48 default of 40, and the existing
/// 1 kHz tone fixture still round-trips through the decoder with the
/// optimiser-driven codebook selection enabled.
#[test]
fn encode_frame_pcm_default_max_sfb_still_works() {
let n = 1920usize;
let fs = 48_000.0_f32;
let f = 1000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * f * t).sin()
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..4).map(|i| make_frame(i * n)).collect();
let decoded = encode_decode_frames(&frames); // default max_sfb=40
let pcm = &decoded[2];
let peak = pcm.iter().map(|&s| s.abs()).max().unwrap_or(0);
assert!(
peak > 1000,
"expected peak amplitude > 1000 at default max_sfb=40, got {peak}"
);
}
/// Sanity baseline: with the HCB5-only encoder configuration
/// (`q_target = 4`) the white-noise spectral SNR caps near 12 dB.
/// We simulate this via a one-shot helper that uses HCB5 only on
/// every band, mirroring the round-48 build_mono_simple_asf body.
/// This test exists as a benchmark anchor so future regressions
/// against the round-48 baseline are visible at a glance.
#[test]
fn baseline_hcb5_only_white_noise_snr_logs_for_comparison() {
use crate::asf_data::{
dequantise_and_scale, parse_asf_scalefac_data, parse_asf_section_data,
parse_asf_spectral_data,
};
use crate::encoder_asf::{
pick_scalefactor_for_band, single_section, write_scalefac_data, write_sect_len_incr,
write_spectral_data_single_section,
};
use crate::encoder_mdct::EncoderMdctState;
use oxideav_core::bits::{BitReader, BitWriter};
let n = 1920usize;
let max_sfb = 50u32;
let sfbo = crate::sfb_offset::sfb_offset_48(n as u32).unwrap();
let end_bin = sfbo[max_sfb as usize] as usize;
let mut s: u64 = 0xACE4u64;
let pcm: Vec<f32> = (0..n)
.map(|_| {
s = s
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let u = (s >> 33) as u32;
(u as f32 / (1u32 << 31) as f32 - 1.0) * 0.3
})
.collect();
let mut mdct = EncoderMdctState::new(n as u32);
let _ = mdct.analyse_frame(&pcm);
let coeffs = mdct.analyse_frame(&pcm);
// HCB5-only encoder body (round-48 path).
let cb: u8 = 5;
let q_max = 4u32;
let mut qspec = vec![0i32; end_bin];
let mut sf_per_band = vec![100i32; max_sfb as usize];
let mut max_quant_idx = vec![0u32; max_sfb as usize];
for sfb in 0..max_sfb as usize {
let a = sfbo[sfb] as usize;
let b = sfbo[sfb + 1] as usize;
let band = &coeffs[a..b.min(coeffs.len())];
let (sf, q) = pick_scalefactor_for_band(band, q_max);
sf_per_band[sfb] = sf;
for (i, &qi) in q.iter().enumerate() {
qspec[a + i] = qi;
max_quant_idx[sfb] = max_quant_idx[sfb].max(qi.unsigned_abs());
}
}
let mut bw = BitWriter::new();
bw.write_u32(4096, 15);
bw.write_bit(false);
bw.align_to_byte();
bw.write_u32(0, 1);
bw.write_u32(0, 1);
bw.write_bit(true);
let (n_msfb_bits, _, _) = crate::tables::n_msfb_bits_48(n as u32).unwrap();
bw.write_u32(max_sfb, n_msfb_bits);
bw.write_u32(cb as u32, 4);
write_sect_len_incr(&mut bw, max_sfb, 3, 7);
write_spectral_data_single_section(&mut bw, &qspec, sfbo, max_sfb, cb as u32);
let sections = single_section(max_sfb, cb);
write_scalefac_data(
&mut bw,
&sf_per_band,
§ions.sfb_cb,
&max_quant_idx,
max_sfb,
);
bw.write_u32(0, 1);
bw.align_to_byte();
while bw.byte_len() < 4096 {
bw.write_u32(0, 8);
}
let body = bw.finish();
// Walk through parser, then dequantise + compare.
let mut br = BitReader::new(&body);
let _ = br.read_u32(15).unwrap();
let _ = br.read_bit().unwrap();
br.align_to_byte();
let _ = br.read_u32(1).unwrap();
let _ = br.read_u32(1).unwrap();
let _ = br.read_bit().unwrap();
let _ = br.read_u32(n_msfb_bits).unwrap();
let parsed = parse_asf_section_data(&mut br, 0, n as u32, max_sfb).unwrap();
let (qs, mqi) = parse_asf_spectral_data(&mut br, &parsed, sfbo, max_sfb).unwrap();
let sfg = parse_asf_scalefac_data(&mut br, &parsed, &mqi, max_sfb, n as u32).unwrap();
let scaled = dequantise_and_scale(&qs, &sfg, sfbo, max_sfb);
let mut sig_e = 0.0_f64;
let mut err_e = 0.0_f64;
for k in 0..end_bin {
let o = coeffs[k] as f64;
let r = scaled[k] as f64;
sig_e += o * o;
err_e += (o - r) * (o - r);
}
let snr_db = 10.0 * (sig_e / err_e.max(1e-30)).log10();
eprintln!("ROUND-48 baseline white-noise spectral SNR (HCB5-only, q_target=4, max_sfb=50): {snr_db:.1} dB");
// Sanity: round-48 should be in the 8-15 dB range.
assert!(
snr_db < 18.0,
"round-48 HCB5-only baseline unexpectedly high: {snr_db:.1} dB"
);
}
// ------------------------------------------------------------------
// Round 50 — DP section optimiser + SNF emission integration tests.
// ------------------------------------------------------------------
/// SNF-bit-on round-trip: encode a tone+noise input, then verify
/// that the decoded reconstruction has non-zero magnitude in
/// high-frequency bins that the quantiser collapsed to zero. The
/// `b_snf_data_exists` bit must round-trip through the parser
/// without erroring.
#[test]
fn encode_frame_pcm_white_noise_with_snf_fills_zero_quant_bands() {
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Packet, TimeBase};
let n = 1920usize;
let max_sfb = 55u32;
let sfbo = crate::sfb_offset::sfb_offset_48(n as u32).unwrap();
let end_bin = sfbo[max_sfb as usize] as usize;
// Low-energy white noise — most high bands quantise to cb=0,
// exercising the SNF emission path.
let make_frame = |seed_off: u64| -> Vec<f32> {
let mut s: u64 = 0xACE4_u64.wrapping_add(seed_off);
(0..n)
.map(|_| {
s = s
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let u = (s >> 33) as u32;
(u as f32 / (1u32 << 31) as f32 - 1.0) * 0.05 // low energy
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..3).map(|i| make_frame(i as u64 * n as u64)).collect();
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new();
let mut last_recon: Option<Vec<f32>> = None;
for f in &frames {
let bytes = enc.encode_frame_pcm_with_max_sfb(f, max_sfb);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let _ = dec.receive_frame().expect("receive_frame");
let sub = dec.last_substream.as_ref().unwrap();
let scaled = sub.tools.scaled_spec_primary.as_ref().unwrap().clone();
last_recon = Some(scaled);
}
let recon = last_recon.unwrap();
// Count non-zero bins in the recon — with SNF on, even bands that
// collapsed to cb=0 should have non-zero magnitude from injected
// noise (clamped by what the SNF index range allows).
let nonzero = recon[..end_bin].iter().filter(|&&v| v.abs() > 0.0).count();
// We don't insist on every bin being non-zero (some bands may have
// SNF idx 0 = "no fill"); the assertion is that the bitstream
// round-trips without error and decodes to a non-silent spectrum.
assert!(
nonzero > 0,
"expected at least one non-zero bin in SNF reconstruction, got {nonzero}"
);
}
/// SNF integration: SNF-on bitstream parses cleanly through the
/// existing decoder. This is the smoke test for the new emission
/// path — it MUST not break decode of non-SNF frames either.
#[test]
fn encode_frame_pcm_silence_with_snf_off_round_trips() {
// Pure silence input: no band has measurable energy → SNF should
// be `None` → b_snf_data_exists = 0 in the bitstream.
let n = 1920usize;
let frames: Vec<Vec<f32>> = (0..2).map(|_| vec![0.0_f32; n]).collect();
let decoded = encode_decode_frames_with_max_sfb(&frames, 50);
let pcm = &decoded[1];
let peak = pcm.iter().map(|&s| s.abs()).max().unwrap_or(0);
// Silence input → silence output (no SNF fill since no energy).
assert_eq!(
peak, 0,
"silence + SNF-off should decode to silence, peak={peak}"
);
}
/// max_sfb wider than the round-48 default: encoder emits a frame
/// the decoder parses without erroring.
#[test]
fn encode_frame_pcm_max_sfb_50_round_trips() {
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
let pi2 = 2.0 * std::f32::consts::PI;
// Tones across the wider band: 1 kHz + 8 kHz.
0.2 * (pi2 * 1000.0 * t).sin() + 0.2 * (pi2 * 8000.0 * t).sin()
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..4).map(|i| make_frame(i * n)).collect();
let decoded = encode_decode_frames_with_max_sfb(&frames, 50);
// Steady-state frame must be substantially non-silent.
let pcm = &decoded[2];
let nonzero = pcm.iter().filter(|&&s| s != 0).count();
assert!(nonzero > 100, "expected non-silent recon, got {nonzero}");
}
/// Round 52 sanity: identical L=R PCM → MDCT spectra are bit-identical
/// → per-SFB energy-weighted correlation is exactly 1.0; the
/// dispatcher would route this frame to Path B (joint M/S).
#[test]
fn round52_correlation_identical_channels_is_one() {
use crate::encoder_asf::average_per_sfb_correlation;
use crate::encoder_mdct::EncoderMdctState;
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
})
.collect()
};
let mut mdct_l = EncoderMdctState::new(n as u32);
let mut mdct_r = EncoderMdctState::new(n as u32);
let mut rhos: Vec<f32> = Vec::new();
for i in 0..3 {
let f = make_frame(i * n);
let cl = mdct_l.analyse_frame(&f);
let cr = mdct_r.analyse_frame(&f);
let rho = average_per_sfb_correlation(n as u32, 40, &cl, &cr);
rhos.push(rho);
}
for (i, &rho) in rhos.iter().enumerate() {
assert!(
(rho - 1.0).abs() < 1e-4,
"frame {i} rho expected 1.0, got {rho}"
);
}
}
/// Round 52 sanity: 440 Hz L + 660 Hz R independent channels have
/// well-separated MDCT spectra → energy-weighted per-SFB correlation
/// falls below the 0.7 dispatch threshold; Path A is chosen.
#[test]
fn round52_correlation_independent_tones_below_threshold() {
use crate::encoder_asf::average_per_sfb_correlation;
use crate::encoder_mdct::EncoderMdctState;
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame = |freq: f32, start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * freq * t).sin()
})
.collect()
};
let mut mdct_l = EncoderMdctState::new(n as u32);
let mut mdct_r = EncoderMdctState::new(n as u32);
let mut rhos: Vec<f32> = Vec::new();
for i in 0..3 {
let fl = make_frame(440.0, i * n);
let fr = make_frame(660.0, i * n);
let cl = mdct_l.analyse_frame(&fl);
let cr = mdct_r.analyse_frame(&fr);
rhos.push(average_per_sfb_correlation(n as u32, 40, &cl, &cr));
}
for (i, &rho) in rhos.iter().enumerate() {
assert!(rho.abs() < 0.6, "frame {i} rho expected < 0.6, got {rho}");
}
}
// ------------------------------------------------------------------
// Round 51 — Stereo SIMPLE/ASF split-MDCT (Path A, 2× SCE) tests.
// ------------------------------------------------------------------
/// Helper: encode a sequence of stereo PCM frames (each `(L, R)`)
/// through `encode_frame_pcm_stereo`, then decode them via
/// `Ac4Decoder` and return per-frame deinterleaved `(L, R)` i16 PCM.
fn encode_decode_stereo_frames(
frames_lr: &[(Vec<f32>, Vec<f32>)],
) -> Vec<(Vec<i16>, Vec<i16>)> {
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Frame, Packet, TimeBase};
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new();
let mut out: Vec<(Vec<i16>, Vec<i16>)> = Vec::with_capacity(frames_lr.len());
for (l, r) in frames_lr {
let bytes = enc.encode_frame_pcm_stereo(l, r);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let Frame::Audio(af) = dec.receive_frame().expect("receive_frame") else {
panic!("expected audio frame");
};
assert_eq!(af.samples, 1_920);
assert_eq!(af.data.len(), 1);
// Stereo S16 interleaved: 1920 samples × 2 ch × 2 bytes.
assert_eq!(af.data[0].len(), 1_920 * 2 * 2);
let buf = &af.data[0];
let mut pcm_l: Vec<i16> = Vec::with_capacity(1_920);
let mut pcm_r: Vec<i16> = Vec::with_capacity(1_920);
for i in 0..1_920usize {
let off_l = i * 4;
let off_r = off_l + 2;
pcm_l.push(i16::from_le_bytes([buf[off_l], buf[off_l + 1]]));
pcm_r.push(i16::from_le_bytes([buf[off_r], buf[off_r + 1]]));
}
out.push((pcm_l, pcm_r));
}
out
}
/// Stereo encoder bumps sequence_counter once per frame, just like
/// the mono path.
#[test]
fn encode_frame_pcm_stereo_bumps_sequence_counter() {
let mut enc = Ac4ImsEncoder::new();
assert_eq!(enc.sequence_counter, 0);
let frame = vec![0.0_f32; 1920];
let _ = enc.encode_frame_pcm_stereo(&frame, &frame);
assert_eq!(enc.sequence_counter, 1);
let _ = enc.encode_frame_pcm_stereo(&frame, &frame);
assert_eq!(enc.sequence_counter, 2);
}
/// Stereo encoder produces a frame whose TOC declares 2 channels and
/// whose decoded PCM layout is stereo (1920 × 2 × 2 bytes).
#[test]
fn encode_frame_pcm_stereo_produces_stereo_layout_pcm() {
let n = 1920usize;
let frames: Vec<(Vec<f32>, Vec<f32>)> = (0..2)
.map(|_| (vec![0.0_f32; n], vec![0.0_f32; n]))
.collect();
let decoded = encode_decode_stereo_frames(&frames);
// Both decoded frames have the stereo S16 byte layout.
for (l, r) in &decoded {
assert_eq!(l.len(), 1_920);
assert_eq!(r.len(), 1_920);
}
}
/// Stereo encoder roundtrip: decoder produces non-silent PCM in
/// both channels with peak amplitudes reflecting the input level.
#[test]
fn encode_frame_pcm_stereo_440hz_steady_state_nonsilent_both_channels() {
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
})
.collect()
};
let frames_lr: Vec<(Vec<f32>, Vec<f32>)> = (0..5)
.map(|i| (make_frame(i * n), make_frame(i * n)))
.collect();
let decoded = encode_decode_stereo_frames(&frames_lr);
let (l, r) = &decoded[2];
let nz_l = l.iter().filter(|&&s| s != 0).count();
let nz_r = r.iter().filter(|&&s| s != 0).count();
let peak_l = l.iter().map(|&s| s.abs()).max().unwrap_or(0);
let peak_r = r.iter().map(|&s| s.abs()).max().unwrap_or(0);
assert!(nz_l > 100, "L too few non-zero samples: {nz_l}");
assert!(nz_r > 100, "R too few non-zero samples: {nz_r}");
// 0.3 input amplitude → ~0.3 * 32767 ≈ 9830 i16 peak. The
// encoder/decoder lossy round-trip stays comfortably above 1000.
assert!(peak_l > 1000, "L peak too low: {peak_l}");
assert!(peak_r > 1000, "R peak too low: {peak_r}");
}
/// Stereo encoder TOC declares 2 channels and the substream parser
/// surfaces both per-channel scaled spectra. Round 52 update: with
/// identical channels (L=R), the cross-channel correlation is 1.0 so
/// the dispatcher routes the frame through Path B (joint M/S CPE,
/// `b_enable_mdct_stereo_proc == 1`). Force the split-MDCT path so
/// this structural test continues to exercise Path A.
#[test]
fn encode_frame_pcm_stereo_substream_parses() {
use crate::decoder::Ac4Decoder;
use oxideav_core::{CodecId, CodecParameters, Decoder, Packet, TimeBase};
let mut enc = Ac4ImsEncoder::new();
let n = 1920usize;
let fs = 48_000.0_f32;
let frame: Vec<f32> = (0..n)
.map(|i| {
let t = i as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
})
.collect();
let bytes = enc.encode_frame_pcm_stereo_split_with_max_sfb(&frame, &frame, 40);
let info = crate::toc::parse_ac4_toc(&bytes).expect("parse_ac4_toc");
assert_eq!(info.channels, 2);
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let _ = dec.receive_frame().expect("receive_frame");
let sub = dec.last_substream.as_ref().expect("substream parsed");
// SIMPLE stereo mode + b_enable_mdct_stereo_proc = 0 (split-MDCT
// path forced by `encode_frame_pcm_stereo_split_with_max_sfb`).
// Both channels' spectra populated.
assert!(matches!(
sub.tools.stereo_mode,
Some(crate::asf::StereoCodecMode::Simple)
));
assert!(!sub.tools.mdct_stereo_proc);
assert!(sub.tools.scaled_spec_primary.is_some());
assert!(sub.tools.scaled_spec_secondary.is_some());
}
/// Round 48 stereo SNR target: 440 Hz tone on L + 440 Hz tone on R
/// (identical content) round-trips with **spectral SNR ≥ 20 dB** on
/// the steady-state frame for both channels.
///
/// Spectral SNR is measured by mirroring the encoder's forward MDCT
/// over the input PCM and comparing the input MDCT spectrum bin-for-
/// bin against the decoder's reconstructed `scaled_spec_*`. This
/// isolates the encoder's quantisation contribution from the IMDCT/
/// KBD overlap-add reconstruction noise (which dominates a time-
/// domain comparison since the IMDCT introduces a half-frame phase
/// shift between the original and reconstructed waveforms even for
/// perfect-reconstruction transforms — same convention used by the
/// round-49 white-noise test
/// `encode_frame_pcm_white_noise_snr_exceeds_hcb5_only_ceiling`).
#[test]
fn encode_frame_pcm_stereo_440hz_both_channels_snr_exceeds_20db() {
use crate::decoder::Ac4Decoder;
use crate::encoder_mdct::EncoderMdctState;
use oxideav_core::{CodecId, CodecParameters, Decoder, Packet, TimeBase};
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame = |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin()
})
.collect()
};
let frames: Vec<Vec<f32>> = (0..3).map(|i| make_frame(i * n)).collect();
// Mirror the encoder's MDCT on the input for both channels (same
// PCM here, so we only need one mirror state).
let mut mdct_in = EncoderMdctState::new(n as u32);
let mut last_input_spec: Option<Vec<f32>> = None;
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new();
let mut last_pri: Option<Vec<f32>> = None;
let mut last_sec: Option<Vec<f32>> = None;
for f in &frames {
let input_coeffs = mdct_in.analyse_frame(f);
last_input_spec = Some(input_coeffs);
let bytes = enc.encode_frame_pcm_stereo(f, f);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let _ = dec.receive_frame().expect("receive_frame");
let sub = dec.last_substream.as_ref().unwrap();
last_pri = sub.tools.scaled_spec_primary.clone();
last_sec = sub.tools.scaled_spec_secondary.clone();
}
let input = last_input_spec.unwrap();
let pri = last_pri.unwrap();
let sec = last_sec.unwrap();
let snr = |orig: &[f32], recon: &[f32]| -> f64 {
let mut sig_e = 0.0_f64;
let mut err_e = 0.0_f64;
let n_compare = orig.len().min(recon.len());
for k in 0..n_compare {
let o = orig[k] as f64;
let r = recon[k] as f64;
sig_e += o * o;
err_e += (o - r) * (o - r);
}
10.0 * (sig_e / err_e.max(1e-30)).log10()
};
let snr_l = snr(&input, &pri);
let snr_r = snr(&input, &sec);
eprintln!(
"ROUND-51 stereo 440Hz L+R spectral SNR: SNR_L = {snr_l:.1} dB, SNR_R = {snr_r:.1} dB"
);
assert!(
snr_l > 20.0,
"L channel spectral SNR too low: {snr_l:.1} dB (expected > 20 dB)"
);
assert!(
snr_r > 20.0,
"R channel spectral SNR too low: {snr_r:.1} dB (expected > 20 dB)"
);
}
/// Round 48 stereo independence target: 440 Hz tone on L + 660 Hz
/// tone on R round-trips with **spectral SNR ≥ 20 dB** on the
/// steady-state frame for both channels (proves channels are encoded
/// independently — no cross-channel bleed). See the docstring on
/// [`encode_frame_pcm_stereo_440hz_both_channels_snr_exceeds_20db`]
/// for why we compare in the spectral domain.
#[test]
fn encode_frame_pcm_stereo_440l_660r_independent_channels_snr_exceeds_20db() {
use crate::decoder::Ac4Decoder;
use crate::encoder_mdct::EncoderMdctState;
use oxideav_core::{CodecId, CodecParameters, Decoder, Packet, TimeBase};
let n = 1920usize;
let fs = 48_000.0_f32;
let make_frame_at = |freq: f32| -> Box<dyn Fn(usize) -> Vec<f32>> {
Box::new(move |start: usize| -> Vec<f32> {
(0..n)
.map(|i| {
let t = (start + i) as f32 / fs;
0.3 * (2.0 * std::f32::consts::PI * freq * t).sin()
})
.collect()
})
};
let make_l = make_frame_at(440.0);
let make_r = make_frame_at(660.0);
let frames_lr: Vec<(Vec<f32>, Vec<f32>)> =
(0..3).map(|i| (make_l(i * n), make_r(i * n))).collect();
// Mirror MDCT on each channel's input independently.
let mut mdct_l = EncoderMdctState::new(n as u32);
let mut mdct_r = EncoderMdctState::new(n as u32);
let mut last_in_l: Option<Vec<f32>> = None;
let mut last_in_r: Option<Vec<f32>> = None;
let params = CodecParameters::audio(CodecId::new("ac4"));
let mut dec = Ac4Decoder::new(¶ms);
let mut enc = Ac4ImsEncoder::new();
let mut last_pri: Option<Vec<f32>> = None;
let mut last_sec: Option<Vec<f32>> = None;
for (l, r) in &frames_lr {
last_in_l = Some(mdct_l.analyse_frame(l));
last_in_r = Some(mdct_r.analyse_frame(r));
let bytes = enc.encode_frame_pcm_stereo(l, r);
let pkt = Packet::new(0, TimeBase::new(1, 48_000), bytes);
dec.send_packet(&pkt).expect("send_packet");
let _ = dec.receive_frame().expect("receive_frame");
let sub = dec.last_substream.as_ref().unwrap();
last_pri = sub.tools.scaled_spec_primary.clone();
last_sec = sub.tools.scaled_spec_secondary.clone();
}
let in_l = last_in_l.unwrap();
let in_r = last_in_r.unwrap();
let pri = last_pri.unwrap();
let sec = last_sec.unwrap();
let snr = |orig: &[f32], recon: &[f32]| -> f64 {
let mut sig_e = 0.0_f64;
let mut err_e = 0.0_f64;
let n_compare = orig.len().min(recon.len());
for k in 0..n_compare {
let o = orig[k] as f64;
let r = recon[k] as f64;
sig_e += o * o;
err_e += (o - r) * (o - r);
}
10.0 * (sig_e / err_e.max(1e-30)).log10()
};
let snr_l = snr(&in_l, &pri);
let snr_r = snr(&in_r, &sec);
eprintln!(
"ROUND-51 stereo 440L+660R independent spectral SNR: SNR_L = {snr_l:.1} dB, SNR_R = {snr_r:.1} dB"
);
assert!(
snr_l > 20.0,
"L (440 Hz) channel spectral SNR too low: {snr_l:.1} dB (expected > 20 dB)"
);
assert!(
snr_r > 20.0,
"R (660 Hz) channel spectral SNR too low: {snr_r:.1} dB (expected > 20 dB)"
);
// Independence sanity check: L and R reconstructions should differ
// (different input frequencies → different waveforms in the
// spectrum).
let differs = pri
.iter()
.zip(sec.iter())
.filter(|(a, b)| (*a - *b).abs() > 0.01)
.count();
assert!(
differs > 10,
"L and R reconstructed spectra should differ for independent tones (got {differs} diffs)"
);
}
}