jixel 0.5.13

JPEG XL encoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
/*
 * // Copyright (c) Radzivon Bartoshyk 5/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#![allow(clippy::excessive_precision)]

use crate::ac_context::{
    fine_block_context, fine_non_zero_context, fine_zero_density_contexts_offset,
    zero_density_context, zero_density_context_8x8,
};
use crate::dc_group_data::{
    AcStrategyImage, DcGroupData, STRATEGY_AFV0, STRATEGY_AFV1, STRATEGY_AFV2, STRATEGY_AFV3,
    STRATEGY_DCT, STRATEGY_DCT2X2, STRATEGY_DCT4X4, STRATEGY_DCT4X8, STRATEGY_DCT8X4,
    STRATEGY_DCT8X16, STRATEGY_DCT8X32, STRATEGY_DCT16X8, STRATEGY_DCT16X16, STRATEGY_DCT16X32,
    STRATEGY_DCT32X8, STRATEGY_DCT32X16, STRATEGY_DCT32X32, STRATEGY_DCT32X64, STRATEGY_DCT64X32,
    STRATEGY_DCT64X64, STRATEGY_IDENTITY,
};
#[cfg(feature = "extraslow")]
use crate::dc_group_data::{STRATEGY_DCT64X128, STRATEGY_DCT128X64, STRATEGY_DCT128X128};
use crate::dct::{DctInput, dc_from_dct8x16, dc_from_dct16x8, dc_from_dct16x16, fmla};
use crate::encoding_context::EncodingContext;
use crate::entropy::{FrozenTokenPrices, Token, pack_signed};
use crate::image::{Image3B, Image3F, Image3S, Rect};
use crate::inflated_cost::Footprint;
use crate::quant_weights::INV_DC_QUANT;
use crate::util::{HeapMatrix, heap_array, round_i32};
use std::sync::OnceLock;

mod trellis;

use trellis::{
    RESTORE_FEW_COLORS_PENALTY, RESTORE_FEW_COLORS_PER_BLOCK, RdoqScratch, RdoqSearch, TrellisTail,
    few_colors, rdoq_block,
};
pub(crate) use trellis::{chroma_rdoq_weight, rdoq_channel_weights, rdoq_lambda};

const K_GROUP_DIM_IN_BLOCKS: usize = 32;

// The 128 family is placed only by ExtraSlow's closed loop. Keep ordinary
// encodes' per-worker buffers sized for the largest enabled transform.
pub(crate) const MAX_BLOCK_COEFFICIENTS: usize = if cfg!(feature = "extraslow") {
    128 * 128
} else {
    64 * 64
};

#[inline]
/// A memo channel's stored levels of the transform at block (`bx`, `lby`).
fn copy_cached_levels(
    m: &AcBlockCache,
    c: usize,
    lby: usize,
    bx: usize,
    cov_x: usize,
    cov_y: usize,
    out: &mut [i32],
) {
    let len = cov_x * 64;
    for j in 0..cov_y {
        let slot = ((lby + j) * m.xsize_blocks + bx) * 64;
        out[j * len..(j + 1) * len].copy_from_slice(&m.quantized[c][slot..slot + len]);
    }
}

pub(crate) fn predict_from_top_and_left(
    row_top: Option<&[u8]>,
    row: &[u8],
    x: usize,
    default_val: u8,
) -> u8 {
    if x == 0 {
        match row_top {
            Some(t) => t[x],
            None => default_val,
        }
    } else if row_top.is_none() {
        row[x - 1]
    } else {
        (row_top.unwrap()[x] as u16 + row[x - 1] as u16).div_ceil(2) as u8
    }
}

/// Number of non-zero coefficients in an 8×8 quantized block, excluding the
/// DC position (k=0). Returns the count for use as nzeros token.
#[inline]
fn num_nonzero_except_dc(block: &[i32; 64]) -> i32 {
    let mut count: i32 = 0;
    for &z in block[1..64].iter() {
        if z != 0 {
            count += 1;
        }
    }
    count
}

/// Multi-block analog: counts nonzeros in `size = cx*cy*64` coefficients
/// excluding the `cx × cy` LLF positions. For DCT16X8/DCT8X16 (cx=2, cy=1
/// after the cx>=cy swap), the LLF positions are coeffs[0] and coeffs[1] in
/// the 8x16 stride-16 layout — contiguous. For DCT16X16 (cx=cy=2) the LLF
/// positions are {0, 1, 16, 17} in the 16x16 stride-16 layout — NOT
/// contiguous, so we mask them explicitly using the row-stride.
#[inline]
fn num_nonzero_except_llf(block: &[i32], cx: usize, cy: usize) -> i32 {
    let row_stride = cx * 8;
    let xsize_pixels = cx * 8;
    let ysize_pixels = cy * 8;
    let mut count: i32 = 0;
    for v in 0..ysize_pixels {
        for u in 0..xsize_pixels {
            if v < cy && u < cx {
                continue;
            }
            if block[v * row_stride + u] != 0 {
                count += 1;
            }
        }
    }
    count
}

/// Generalized AC quantization for an `xsize × ysize` (in 8x8 blocks) region.
/// `xsize=1, ysize=1` reproduces the 8×8 path. The block buffer has
/// `xsize*ysize*64` floats in row-major order with row stride `xsize*8`.
///
/// Thresholds mirror libjxl-tiny: per-quadrant in the 8×8 case; biased lower
/// for multi-block; for the 1×N or N×1 case the second half of the columns
/// (or rows for ysize=1, xsize=1 special) uses the second threshold pair.
pub(crate) type QuantizeBlockAcFn = fn(
    block_in: &[f32],
    c: usize,
    qm: &[f32],
    quant: i32,
    scale: f32,
    qm_multiplier: f32,
    distance: f32,
    xsize: usize,
    ysize: usize,
    block_out: &mut [i32],
);

pub(crate) type QuantizeDcFn = fn(input: &[f32], scale: f32, output: &mut [i16]);
pub(crate) type QuantizeDcCflFn =
    fn(input: &[f32], y_quant: &[i16], scale: f32, cfl: f32, output: &mut [i16]);
pub(crate) type QuantizeDcI32Fn = fn(input: &[f32], scale: f32, output: &mut [i32]);
pub(crate) type QuantizeDcCflI32Fn =
    fn(input: &[f32], y_quant: &[i32], scale: f32, cfl: f32, output: &mut [i32]);

#[derive(Clone, Copy)]
pub(crate) struct QuantizeDcMethods {
    pub(crate) quantize: QuantizeDcFn,
    pub(crate) quantize_cfl: QuantizeDcCflFn,
    pub(crate) quantize_i32: QuantizeDcI32Fn,
    pub(crate) quantize_cfl_i32: QuantizeDcCflI32Fn,
}

/// The DC values of one channel's coefficient block, one per covered 8x8
/// block in `iy * cov_x + ix` order. Single-block transforms carry their DC in
/// `coeffs[0]`; larger ones derive it from the lowest frequencies.
pub(crate) fn dc_from_coefficients(
    ctx: &EncodingContext,
    raw_strategy: u8,
    coeffs: &[f32],
    dc: &mut [f32],
) {
    match raw_strategy {
        STRATEGY_DCT
        | STRATEGY_IDENTITY
        | STRATEGY_DCT2X2
        | STRATEGY_DCT4X4
        | STRATEGY_DCT4X8
        | STRATEGY_DCT8X4
        | STRATEGY_AFV0..=STRATEGY_AFV3 => dc[0] = coeffs[0],
        STRATEGY_DCT16X8 => dc_from_dct16x8(
            coeffs.first_chunk::<128>().unwrap(),
            dc.first_chunk_mut::<2>().unwrap(),
        ),
        STRATEGY_DCT8X16 => dc_from_dct8x16(
            coeffs.first_chunk::<128>().unwrap(),
            dc.first_chunk_mut::<2>().unwrap(),
        ),
        // [TL, TR, BL, BR], the [iy][ix] grid.
        STRATEGY_DCT16X16 => dc_from_dct16x16(
            coeffs.first_chunk::<256>().unwrap(),
            dc.first_chunk_mut::<4>().unwrap(),
        ),
        STRATEGY_DCT32X32 => (ctx.dc_from_dct32x32)(
            coeffs.first_chunk::<1024>().unwrap(),
            dc.first_chunk_mut::<16>().unwrap(),
        ),
        STRATEGY_DCT64X64 => (ctx.dc_from_dct64x64)(
            coeffs.first_chunk::<4096>().unwrap(),
            dc.first_chunk_mut::<64>().unwrap(),
        ),
        STRATEGY_DCT64X32 => (ctx.dc_from_dct64x32)(
            coeffs.first_chunk::<2048>().unwrap(),
            dc.first_chunk_mut::<32>().unwrap(),
        ),
        STRATEGY_DCT32X64 => (ctx.dc_from_dct32x64)(
            coeffs.first_chunk::<2048>().unwrap(),
            dc.first_chunk_mut::<32>().unwrap(),
        ),
        // 4 rows x 2 columns (cov_x = 2, cov_y = 4).
        STRATEGY_DCT32X16 => (ctx.dc_from_dct32x16)(
            coeffs.first_chunk::<512>().unwrap(),
            dc.first_chunk_mut::<8>().unwrap(),
        ),
        // 2 rows x 4 columns (cov_x = 4, cov_y = 2).
        STRATEGY_DCT16X32 => (ctx.dc_from_dct16x32)(
            coeffs.first_chunk::<512>().unwrap(),
            dc.first_chunk_mut::<8>().unwrap(),
        ),
        // Four values along the long axis, a 4x1 column or a 1x4 row.
        STRATEGY_DCT32X8 | STRATEGY_DCT8X32 => (ctx.dc_from_dct8x32)(
            coeffs.first_chunk::<256>().unwrap(),
            dc.first_chunk_mut::<4>().unwrap(),
        ),
        #[cfg(feature = "extraslow")]
        STRATEGY_DCT128X128 => (ctx.dc_from_dct128x128)(
            coeffs.first_chunk::<16384>().unwrap(),
            dc.first_chunk_mut::<256>().unwrap(),
        ),
        #[cfg(feature = "extraslow")]
        STRATEGY_DCT128X64 => (ctx.dc_from_dct128x64)(
            coeffs.first_chunk::<8192>().unwrap(),
            dc.first_chunk_mut::<128>().unwrap(),
        ),
        #[cfg(feature = "extraslow")]
        STRATEGY_DCT64X128 => (ctx.dc_from_dct64x128)(
            coeffs.first_chunk::<8192>().unwrap(),
            dc.first_chunk_mut::<128>().unwrap(),
        ),
        _ => unreachable!("invalid raw strategy {raw_strategy}"),
    }
}

/// Wide levels used by DC-step pricing and the plain modular lattice. Keep
/// Rust's ties-away rounding and saturating float-to-integer conversion.
#[allow(dead_code)]
pub(crate) fn quantize_dc_i32_scalar(input: &[f32], scale: f32, output: &mut [i32]) {
    debug_assert_eq!(input.len(), output.len());
    for (&value, target) in input.iter().zip(output) {
        *target = round_i32(value * scale);
    }
}

#[allow(dead_code)]
pub(crate) fn quantize_dc_cfl_i32_scalar(
    input: &[f32],
    y_quant: &[i32],
    scale: f32,
    cfl: f32,
    output: &mut [i32],
) {
    debug_assert_eq!(input.len(), y_quant.len());
    debug_assert_eq!(input.len(), output.len());
    for ((&value, &yq), target) in input.iter().zip(y_quant).zip(output) {
        *target = round_i32(fmla(value, scale, -(yq as f32) * cfl));
    }
}

#[allow(dead_code)]
pub(crate) fn quantize_dc_scalar(input: &[f32], scale: f32, output: &mut [i16]) {
    debug_assert_eq!(input.len(), output.len());
    for (&value, target) in input.iter().zip(output) {
        *target = (value * scale).round() as i16;
    }
}

#[allow(dead_code)]
pub(crate) fn quantize_dc_cfl_scalar(
    input: &[f32],
    y_quant: &[i16],
    scale: f32,
    cfl: f32,
    output: &mut [i16],
) {
    debug_assert_eq!(input.len(), y_quant.len());
    debug_assert_eq!(input.len(), output.len());
    for ((&value, &yq), target) in input.iter().zip(y_quant).zip(output) {
        *target = fmla(value, scale, -(yq as f32) * cfl).round() as i16;
    }
}

static QUANTIZE_DC_METHODS: OnceLock<QuantizeDcMethods> = OnceLock::new();

#[cfg(all(target_arch = "wasm32", target_feature = "simd128", feature = "wasm"))]
fn select_quantize_dc_methods() -> QuantizeDcMethods {
    QuantizeDcMethods {
        quantize: crate::wasm::quantize_dc_wasm,
        quantize_cfl: crate::wasm::quantize_dc_cfl_wasm,
        quantize_i32: crate::wasm::quantize_dc_i32_wasm,
        quantize_cfl_i32: crate::wasm::quantize_dc_cfl_i32_wasm,
    }
}

#[cfg(all(target_arch = "aarch64", feature = "neon"))]
fn select_quantize_dc_methods() -> QuantizeDcMethods {
    QuantizeDcMethods {
        quantize: |input, scale, output| unsafe {
            crate::neon::quantize_dc_neon(input, scale, output)
        },
        quantize_cfl: |input, y_quant, scale, cfl, output| unsafe {
            crate::neon::quantize_dc_cfl_neon(input, y_quant, scale, cfl, output)
        },
        quantize_i32: |input, scale, output| unsafe {
            crate::neon::quantize_dc_i32_neon(input, scale, output)
        },
        quantize_cfl_i32: |input, y_quant, scale, cfl, output| unsafe {
            crate::neon::quantize_dc_cfl_i32_neon(input, y_quant, scale, cfl, output)
        },
    }
}

#[cfg(not(any(
    all(target_arch = "wasm32", target_feature = "simd128", feature = "wasm"),
    all(target_arch = "aarch64", feature = "neon")
)))]
fn select_quantize_dc_methods() -> QuantizeDcMethods {
    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
        return QuantizeDcMethods {
            quantize: |input, scale, output| unsafe {
                crate::avx::quantize_dc_avx2(input, scale, output)
            },
            quantize_cfl: |input, y_quant, scale, cfl, output| unsafe {
                crate::avx::quantize_dc_cfl_avx2(input, y_quant, scale, cfl, output)
            },
            quantize_i32: |input, scale, output| unsafe {
                crate::avx::quantize_dc_i32_avx2(input, scale, output)
            },
            quantize_cfl_i32: |input, y_quant, scale, cfl, output| unsafe {
                crate::avx::quantize_dc_cfl_i32_avx2(input, y_quant, scale, cfl, output)
            },
        };
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    if is_x86_feature_detected!("sse4.1") {
        return QuantizeDcMethods {
            quantize: |input, scale, output| unsafe {
                crate::sse::quantize_dc_sse41(input, scale, output)
            },
            quantize_cfl: |input, y_quant, scale, cfl, output| unsafe {
                crate::sse::quantize_dc_cfl_sse41(input, y_quant, scale, cfl, output)
            },
            quantize_i32: |input, scale, output| unsafe {
                crate::sse::quantize_dc_i32_sse41(input, scale, output)
            },
            quantize_cfl_i32: |input, y_quant, scale, cfl, output| unsafe {
                crate::sse::quantize_dc_cfl_i32_sse41(input, y_quant, scale, cfl, output)
            },
        };
    }

    QuantizeDcMethods {
        quantize: quantize_dc_scalar,
        quantize_cfl: quantize_dc_cfl_scalar,
        quantize_i32: quantize_dc_i32_scalar,
        quantize_cfl_i32: quantize_dc_cfl_i32_scalar,
    }
}

pub(crate) fn selected_quantize_dc_methods() -> QuantizeDcMethods {
    *QUANTIZE_DC_METHODS.get_or_init(select_quantize_dc_methods)
}

static QUANTIZE_BLOCK_AC_METHOD: OnceLock<QuantizeBlockAcFn> = OnceLock::new();

#[inline]
pub(crate) fn quantize_ac_thresholds(
    c: usize,
    xsize: usize,
    ysize: usize,
    distance: f32,
) -> [f32; 4] {
    quantize_ac_thresholds_scaled(c, xsize, ysize, distance, 1.0)
}

const X_THRESHOLD_EXTRA: f32 = 0.08;
const X_FIRST_THRESHOLD_WINDOW: f32 = 0.5;
static X_DEADZONE_WINDOW: [f32; 4] = [0.5, 0.75, 1.5, 2.0];

#[inline]
fn x_deadzone_window(distance: f32) -> f32 {
    let [a, b, c, d] = X_DEADZONE_WINDOW;
    let up = ((distance - a) / (b - a)).clamp(0.0, 1.0);
    let down = ((d - distance) / (d - c)).clamp(0.0, 1.0);
    up.min(down)
}

/// Quantization zero thresholds for the effective per-channel precision.
/// Frames which already spend bits on finer B precision preserve near-one
/// high-frequency B levels instead of applying the ordinary 0.75 deadzone.
/// This only changes the constants loaded by the existing scalar/SIMD loop.
#[inline]
pub(crate) fn quantize_ac_thresholds_scaled(
    c: usize,
    xsize: usize,
    ysize: usize,
    distance: f32,
    qm_multiplier: f32,
) -> [f32; 4] {
    let mut normal = [0.58f32, 0.635, 0.66, 0.7];
    if c == 0 {
        let w = x_deadzone_window(distance);
        normal[0] += w * (X_FIRST_THRESHOLD_WINDOW - normal[0]);
        for t in &mut normal[1..] {
            *t += (1.0 - w) * X_THRESHOLD_EXTRA;
        }
    }
    if c == 2 {
        let b_hf_threshold = if qm_multiplier > 1.0 { 0.65 } else { 0.75 };
        for t in &mut normal[1..] {
            *t = b_hf_threshold;
        }
    }
    if xsize > 1 || ysize > 1 {
        // The area clamp was never calibrated past 32px
        let delta =
            (0.003_f32 * xsize as f32 * ysize as f32).clamp(0.0, if c > 0 { 0.08 } else { 0.12 });
        for t in &mut normal {
            *t -= delta;
        }
    }
    let high_quality = match c {
        1 => [0.50, 0.51, 0.52, 0.54],
        0 | 2 => normal,
        _ => unreachable!("invalid channel {c}"),
    };
    let t = ((distance - 0.1) / 0.9).clamp(0.0, 1.0);
    std::array::from_fn(|i| high_quality[i] + t * (normal[i] - high_quality[i]))
}

#[inline]
pub(crate) fn quantize_ac_q_scaled(quant: i32, scale: f32, qm_multiplier: f32) -> f32 {
    scale * quant as f32 * qm_multiplier
}

fn select_quantize_block_ac_fn() -> QuantizeBlockAcFn {
    #[cfg(all(target_arch = "wasm32", target_feature = "simd128", feature = "wasm"))]
    {
        crate::wasm::quantize_block_ac_wasm
    }

    #[cfg(all(target_arch = "aarch64", feature = "neon"))]
    {
        |block_in, c, qm, quant, scale, qm_multiplier, distance, xsize, ysize, block_out| unsafe {
            crate::neon::quantize_block_ac_neon(
                block_in,
                c,
                qm,
                quant,
                scale,
                qm_multiplier,
                distance,
                xsize,
                ysize,
                block_out,
            );
        }
    }

    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    {
        if is_x86_feature_detected!("avx2") {
            return |block_in,
                    c,
                    qm,
                    quant,
                    scale,
                    qm_multiplier,
                    distance,
                    xsize,
                    ysize,
                    block_out| unsafe {
                crate::avx::quantize_block_ac_avx2(
                    block_in,
                    c,
                    qm,
                    quant,
                    scale,
                    qm_multiplier,
                    distance,
                    xsize,
                    ysize,
                    block_out,
                );
            };
        }
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    {
        if is_x86_feature_detected!("sse4.1") {
            return |block_in,
                    c,
                    qm,
                    quant,
                    scale,
                    qm_multiplier,
                    distance,
                    xsize,
                    ysize,
                    block_out| unsafe {
                crate::sse::quantize_block_ac_sse41(
                    block_in,
                    c,
                    qm,
                    quant,
                    scale,
                    qm_multiplier,
                    distance,
                    xsize,
                    ysize,
                    block_out,
                );
            };
        }
    }
    #[cfg(not(any(
        all(target_arch = "aarch64", feature = "neon"),
        all(target_arch = "wasm32", target_feature = "simd128", feature = "wasm")
    )))]
    {
        quantize_block_ac_scalar
    }
}

#[inline]
pub(crate) fn selected_quantize_block_ac_fn() -> QuantizeBlockAcFn {
    *QUANTIZE_BLOCK_AC_METHOD.get_or_init(select_quantize_block_ac_fn)
}

#[allow(dead_code)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn quantize_block_ac_scalar(
    block_in: &[f32],
    c: usize,
    qm: &[f32],
    quant: i32,
    scale: f32,
    qm_multiplier: f32,
    distance: f32,
    xsize: usize,
    ysize: usize,
    block_out: &mut [i32],
) {
    let thr = quantize_ac_thresholds_scaled(c, xsize, ysize, distance, qm_multiplier);
    let q_scaled = quantize_ac_q_scaled(quant, scale, qm_multiplier);
    let width = xsize * 8;
    let height = ysize * 8;
    // The quant matrix, input, and output must all be sized for this transform.
    // A mismatch here means the caller selected the wrong matrix for the
    // strategy (e.g. handing the 64-entry DCT8 matrix to a DCT16X8/DCT16X16
    // block). Fail with a clear message rather than an opaque index panic.
    debug_assert_eq!(
        qm.len(),
        width * height,
        "quant matrix size {} != transform size {}x{}={} (wrong matrix for strategy?)",
        qm.len(),
        width,
        height,
        width * height
    );
    debug_assert!(block_in.len() >= width * height, "block_in too small");
    debug_assert!(block_out.len() >= width * height, "block_out too small");
    let n = width * height;
    let qm = &qm[..n];
    let block_in = &block_in[..n];
    let block_out = &mut block_out[..n];
    let half = width / 2;
    for (y, ((qm_row, in_row), out_row)) in qm
        .chunks_exact(width)
        .zip(block_in.chunks_exact(width))
        .zip(block_out.chunks_exact_mut(width))
        .take(height)
        .enumerate()
    {
        let yfix = if y >= height / 2 { 2 } else { 0 };
        let thr_lo = thr[yfix];
        let thr_hi = thr[yfix + 1];
        for (x, ((&qmv, &inv), out)) in qm_row
            .iter()
            .zip(in_row.iter())
            .zip(out_row.iter_mut())
            .enumerate()
        {
            let threshold = if x >= half { thr_hi } else { thr_lo };
            let q = qmv * q_scaled;
            let val = q * inv;
            *out = if val.abs() >= threshold {
                val.round() as i32
            } else {
                0
            };
        }
    }
}

/// libjxl `kDefaultQuantBias` (X, Y, B, numerator): what an `all_default`
/// CustomTransformData signals.
pub(crate) static DEFAULT_QUANT_BIASES: [f32; 4] = [
    1.0 - 0.05465007330715401,
    1.0 - 0.07005449891748593,
    1.0 - 0.049935103337343655,
    0.145,
];

/// The explicit CustomTransformData biases written with a non-default opsin
/// matrix (as f16): X/Y keep the defaults, B's ±1 reconstructs a full step.
pub(crate) static EXPLICIT_QUANT_BIASES: [f32; 4] =
    [1.0 - 0.054_650_075, 1.0 - 0.070_054_5, 1.0, 0.145];

/// Levels below this magnitude read `numerator / |q|` from a table instead of
/// dividing; the tables hold the same correctly rounded quotients.
const BIAS_QUOTIENTS: usize = 64;

/// `numerator / q` for `q` in `2..BIAS_QUOTIENTS` (entries 0 and 1 unused).
const fn bias_quotients(numerator: f32) -> [f32; BIAS_QUOTIENTS] {
    let mut table = [0.0; BIAS_QUOTIENTS];
    let mut q = 2;
    while q < BIAS_QUOTIENTS {
        table[q] = numerator / q as f32;
        q += 1;
    }
    table
}

static DEFAULT_BIAS_QUOTIENTS: [f32; BIAS_QUOTIENTS] = bias_quotients(DEFAULT_QUANT_BIASES[3]);

/// The tables of a numerator: the default one's is built at compile time, the
/// explicit bundle's f16 numerator gets its own on first use.
fn bias_quotients_for(numerator: f32) -> &'static [f32; BIAS_QUOTIENTS] {
    if numerator.to_bits() == DEFAULT_QUANT_BIASES[3].to_bits() {
        return &DEFAULT_BIAS_QUOTIENTS;
    }
    static EXPLICIT: std::sync::OnceLock<(u32, [f32; BIAS_QUOTIENTS])> = std::sync::OnceLock::new();
    let (bits, table) = EXPLICIT.get_or_init(|| {
        let mut table = [0.0; BIAS_QUOTIENTS];
        for (q, t) in table.iter_mut().enumerate().skip(2) {
            *t = numerator / q as f32;
        }
        (numerator.to_bits(), table)
    });
    // The explicit numerator is a constant's f16 round trip, so it is the
    // same on every call.
    assert_eq!(
        *bits,
        numerator.to_bits(),
        "a third dequantization numerator"
    );
    table
}

/// The decoder's dequantization of one channel's integer AC levels
/// (libjxl `AdjustQuantBias`): `±one` at |q| = 1, `q - numerator / q` above.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct DequantBias {
    pub(crate) one: f32,
    pub(crate) numerator: f32,
    /// [`bias_quotients`] of `numerator`.
    quotients: &'static [f32; BIAS_QUOTIENTS],
    /// [`Self::level`] of `0..SMALL_LEVELS`: the SIMD kernels gather from
    /// this table instead of dividing (the entries are the same correctly
    /// rounded values, so the paths agree bit for bit).
    pub(crate) small_levels: [f32; SMALL_LEVELS],
}

/// Number of entries in [`DequantBias::small_levels`]: one 64-byte NEON
/// table lookup, or two 8-lane AVX2 permutes.
pub(crate) const SMALL_LEVELS: usize = 16;

/// `|q| - numerator / |q|` for `q` in `2..SMALL_LEVELS`, with `0` and `one`
/// in the first two slots.
const fn small_levels(one: f32, quotients: &[f32; BIAS_QUOTIENTS]) -> [f32; SMALL_LEVELS] {
    let mut table = [0.0; SMALL_LEVELS];
    table[1] = one;
    let mut q = 2;
    while q < SMALL_LEVELS {
        table[q] = q as f32 - quotients[q];
        q += 1;
    }
    table
}

impl DequantBias {
    pub(crate) const DEFAULT: [DequantBias; 3] = [
        DequantBias::new(DEFAULT_QUANT_BIASES[0]),
        DequantBias::new(DEFAULT_QUANT_BIASES[1]),
        DequantBias::new(DEFAULT_QUANT_BIASES[2]),
    ];

    const fn new(one: f32) -> Self {
        Self {
            one,
            numerator: DEFAULT_QUANT_BIASES[3],
            quotients: &DEFAULT_BIAS_QUOTIENTS,
            small_levels: small_levels(one, &DEFAULT_BIAS_QUOTIENTS),
        }
    }

    /// Per-channel biases the decoder applies: the defaults, or the explicit
    /// bundle after its f16 round trip.
    pub(crate) fn channels(explicit: bool) -> [DequantBias; 3] {
        if !explicit {
            return Self::DEFAULT;
        }
        let f16 = |v: f32| crate::util::f16_bits_to_f32(crate::util::f32_to_f16_bits(v));
        let numerator = f16(EXPLICIT_QUANT_BIASES[3]);
        let quotients = bias_quotients_for(numerator);
        std::array::from_fn(|c| {
            let one = f16(EXPLICIT_QUANT_BIASES[c]);
            DequantBias {
                one,
                numerator,
                quotients,
                small_levels: small_levels(one, quotients),
            }
        })
    }

    /// [`Self::level`] for a float-valued (but integer) level, as produced by
    /// the encoder-side quantizers before conversion to `i32`.
    #[inline]
    pub(crate) fn level_f32(self, quant: f32) -> f32 {
        let aq = quant.abs();
        if aq < 1.125 {
            if quant == 0.0 {
                0.0
            } else {
                self.one.copysign(quant)
            }
        } else {
            let a = aq as usize;
            if a < BIAS_QUOTIENTS && a as f32 == aq {
                // numerator / -a is exactly -(numerator / a).
                let t = self.quotients[a];
                quant - if quant < 0.0 { -t } else { t }
            } else {
                quant - self.numerator / quant
            }
        }
    }

    #[inline]
    pub(crate) fn level(self, quant: i32) -> f32 {
        let a = quant.unsigned_abs();
        if a <= 1 {
            if quant == 0 {
                0.0
            } else if quant > 0 {
                self.one
            } else {
                -self.one
            }
        } else {
            let q = quant as f32;
            if (a as usize) < BIAS_QUOTIENTS {
                // numerator / -a is exactly -(numerator / a).
                let t = self.quotients[a as usize];
                q - if quant < 0 { -t } else { t }
            } else {
                q - self.numerator / q
            }
        }
    }
}

/// Y-channel quantize then dequantize-with-bias for CfL roundtrip. `inout`
/// holds size=xsize*ysize*64 floats. `quantized` holds size integers.
fn quantize_roundtrip_y_block(
    ctx: &EncodingContext,
    qm: &[f32],
    dqm: &[f32],
    scale: f32,
    quant: i32,
    distance: f32,
    xsize: usize,
    ysize: usize,
    inout: &mut [f32],
    quantized: &mut [i32],
) {
    (ctx.quantize_block_ac)(
        inout, 1, qm, quant, scale, 1.0, distance, xsize, ysize, quantized,
    );
    let inv_qac = 1.0 / (scale * quant as f32);
    let bias = ctx.dequant_bias(1);
    let size = xsize * ysize * 64;
    for (out, (&q, &dq)) in inout[..size]
        .iter_mut()
        .zip(quantized[..size].iter().zip(dqm[..size].iter()))
    {
        *out = bias.level(q) * dq * inv_qac;
    }
}

/// Reconstruction capture: the
/// group-local plane, the pixel row offset of the current stripe in it, and
/// optional pass-0 token start indices for the closed-loop quant field.
pub(crate) type ReconCapture<'a> = (
    &'a mut crate::image::Image3F,
    usize,
    Option<&'a mut Vec<(u16, u16, u32)>>,
);

/// Per-block memo of one AC group for the closed-loop quant field: a block's
/// quantized coefficients, DC levels and reconstruction are a function of its
/// field value and of the nonzero-count contexts predicted from its
/// neighbors, so a re-encode after a one-tile change recomputes only the
/// blocks whose key changed and tokenizes the rest from the memo.
pub(crate) struct AcBlockCache {
    xsize_blocks: usize,
    /// Per channel and first block: the key its stored channel was computed
    /// under. Y: field value and Y nonzero context; X/B: field value, own and
    /// Y contexts (CfL reads the dequantized Y) and the channel's qm scale.
    keys: [Vec<u32>; 3],
    quantized: [Vec<i32>; 3],
    dc: Image3S,
    /// Unquantized DC per cell and channel (the chroma saturation test reads it).
    dc_f: [Vec<f32>; 3],
    recon: Image3F,
    /// Token streams per block and channel (single-pass frames): one arena per
    /// output stream, `spans[(block * 3 + c) * streams + s]` = (start, len),
    /// and the shifted nonzero count stored in the context map per channel.
    tokens: Vec<Vec<Token>>,
    spans: Vec<(u32, u32)>,
    nz_shift: Vec<[u8; 3]>,
    /// Evaluation counter and, per block cell, the evaluation that last
    /// recomputed it: an evaluation synced at `s` needs the cells with
    /// `cell_gen > s`.
    pub(crate) epoch: u32,
    cell_gen: Vec<u32>,
    /// Frozen-price bits of each first block's first stream, per channel.
    bits: Vec<[f32; 3]>,
    /// Per first block and channel, the trellis's last row, keyed by the
    /// memo key it was computed under. A tail is only read while that key is
    /// still the channel's stored key, so restores and invalidations (which
    /// rewrite keys) retire it without being snapshotted.
    tails: Vec<[TrellisTail; 3]>,
    /// Trial evaluation: a cached channel adds its bits to `trial_bits`
    /// instead of copying its tokens (the group's token streams are partial).
    pub(crate) trial: bool,
    pub(crate) trial_bits: f64,
}

impl AcBlockCache {
    pub(crate) fn new(
        xsize_blocks: usize,
        ysize_blocks: usize,
        xsize: usize,
        ysize: usize,
    ) -> Self {
        let n = xsize_blocks * ysize_blocks;
        Self {
            xsize_blocks,
            keys: std::array::from_fn(|_| vec![u32::MAX; n]),
            quantized: std::array::from_fn(|_| vec![0; n * 64]),
            dc: Image3S::new(xsize_blocks, ysize_blocks),
            dc_f: std::array::from_fn(|_| vec![0.0; n]),
            recon: Image3F::new(xsize, ysize),
            tokens: Vec::new(),
            spans: Vec::new(),
            nz_shift: vec![[0; 3]; n],
            epoch: 0,
            cell_gen: vec![0; n],
            bits: vec![[f32::NAN; 3]; n],
            tails: vec![[TrellisTail::default(); 3]; n],
            trial: false,
            trial_bits: 0.0,
        }
    }

    #[cfg(feature = "extraslow")]
    /// Forget the blocks of a group-local block region (its transform layout
    /// changed, which the keys do not carry).
    pub(crate) fn invalidate(&mut self, x: usize, y: usize, w: usize, h: usize) {
        for row in y..y + h {
            for key in &mut self.keys {
                key[row * self.xsize_blocks + x..row * self.xsize_blocks + x + w].fill(u32::MAX);
            }
            self.tails[row * self.xsize_blocks + x..row * self.xsize_blocks + x + w]
                .fill([TrellisTail::default(); 3]);
        }
    }

    #[cfg(feature = "extraslow")]
    /// Reclaim superseded token versions between trials, when no snapshot
    /// holds arena offsets. Keep every referenced span, including cells hidden
    /// by a larger transform: restoring a layout can make those cells live again.
    pub(crate) fn compact_tokens(&mut self) {
        let streams = self.tokens.len();
        for (s, arena) in self.tokens.iter_mut().enumerate() {
            let live: usize = self.spans[s..]
                .iter()
                .step_by(streams)
                .map(|&(_, len)| len as usize)
                .sum();
            // Amortize the copy over at least one whole live set of discarded
            // tokens. Tiny streams do not justify repeated allocations.
            if arena.len() <= live.saturating_mul(2).max(4096) {
                continue;
            }
            let mut compact = Vec::with_capacity(live);
            for (start, len) in self.spans[s..].iter_mut().step_by(streams) {
                let old_start = *start as usize;
                *start = compact.len() as u32;
                compact.extend_from_slice(&arena[old_start..old_start + *len as usize]);
            }
            *arena = compact;
        }
    }

    /// The settled polish baseline prices pass 0. Keep its cache hits and
    /// release the alternative-order arenas before assembling the frame.
    #[cfg(feature = "extraslow")]
    pub(crate) fn keep_primary_tokens(&mut self) {
        let streams = self.tokens.len();
        if streams <= 1 {
            return;
        }
        self.tokens.truncate(1);
        let channels = self.spans.len() / streams;
        for i in 1..channels {
            self.spans[i] = self.spans[i * streams];
        }
        self.spans.truncate(channels);
    }

    #[cfg(feature = "extraslow")]
    /// Everything the memo holds for the cells of a group-local block region,
    /// so a trial layout there can be undone without re-encoding. Between the
    /// snapshot and its restore/discard, arenas must stay append-only.
    pub(crate) fn snapshot(&self, x: usize, y: usize, w: usize, h: usize) -> MemoSnapshot {
        let streams = if self.keys[0].is_empty() {
            0
        } else {
            self.spans.len() / (self.keys[0].len() * 3)
        };
        let (pw, ph) = (self.recon.xsize(), self.recon.ysize());
        let pixel_x = (x * 8).min(pw)..((x + w) * 8).min(pw);
        let pixel_y = (y * 8).min(ph)..((y + h) * 8).min(ph);
        let cells = w * h;
        let mut snap = MemoSnapshot {
            rect: (x, y, w, h),
            streams,
            keys: Vec::with_capacity(3 * cells),
            quantized: Vec::with_capacity(3 * cells * 64),
            dc: Vec::with_capacity(3 * cells),
            dc_f: Vec::with_capacity(3 * cells),
            spans: Vec::with_capacity(3 * cells * streams),
            nz_shift: Vec::with_capacity(cells),
            bits: Vec::with_capacity(cells),
            recon: Vec::with_capacity(3 * pixel_x.len() * pixel_y.len()),
        };
        for row in y..y + h {
            let cells = row * self.xsize_blocks + x..row * self.xsize_blocks + x + w;
            for c in 0..3 {
                snap.keys.extend_from_slice(&self.keys[c][cells.clone()]);
                snap.quantized
                    .extend_from_slice(&self.quantized[c][cells.start * 64..cells.end * 64]);
                snap.dc
                    .extend_from_slice(&self.dc.plane_row(c, row)[x..x + w]);
                snap.dc_f.extend_from_slice(&self.dc_f[c][cells.clone()]);
            }
            if streams > 0 {
                snap.spans.extend_from_slice(
                    &self.spans[cells.start * 3 * streams..cells.end * 3 * streams],
                );
            }
            snap.nz_shift
                .extend_from_slice(&self.nz_shift[cells.clone()]);
            snap.bits.extend_from_slice(&self.bits[cells]);
        }
        for c in 0..3 {
            for py in pixel_y.clone() {
                snap.recon
                    .extend_from_slice(&self.recon.plane_row(c, py)[pixel_x.clone()]);
            }
        }
        snap
    }

    #[cfg(feature = "extraslow")]
    /// Undo everything since `snapshot` for its region (the spans layout must
    /// not have changed in between).
    pub(crate) fn restore(&mut self, snap: &MemoSnapshot) {
        let (x, y, w, h) = snap.rect;
        let streams = if self.keys[0].is_empty() {
            0
        } else {
            self.spans.len() / (self.keys[0].len() * 3)
        };
        let (pw, ph) = (self.recon.xsize(), self.recon.ysize());
        let (mut k, mut q, mut sp, mut n) = (0, 0, 0, 0);
        for row in y..y + h {
            let cells = row * self.xsize_blocks + x..row * self.xsize_blocks + x + w;
            // Tails are not snapshotted: the restored levels may predate them.
            self.tails[cells.clone()].fill([TrellisTail::default(); 3]);
            for c in 0..3 {
                self.keys[c][cells.clone()].copy_from_slice(&snap.keys[k..k + w]);
                self.quantized[c][cells.start * 64..cells.end * 64]
                    .copy_from_slice(&snap.quantized[q..q + w * 64]);
                self.dc.plane_row_mut(c, row)[x..x + w].copy_from_slice(&snap.dc[k..k + w]);
                self.dc_f[c][cells.clone()].copy_from_slice(&snap.dc_f[k..k + w]);
                k += w;
                q += w * 64;
            }
            if streams > 0 && streams == snap.streams {
                let len = w * 3 * streams;
                self.spans[cells.start * 3 * streams..cells.end * 3 * streams]
                    .copy_from_slice(&snap.spans[sp..sp + len]);
                sp += len;
            } else if streams > 0 {
                // The span table was (re)allocated after the snapshot.
                for key in &mut self.keys {
                    key[cells.clone()].fill(u32::MAX);
                }
            }
            self.nz_shift[cells.clone()].copy_from_slice(&snap.nz_shift[n..n + w]);
            self.bits[cells.clone()].copy_from_slice(&snap.bits[n..n + w]);
            // Pixels went back to the snapshot: mark them recomputed so a
            // later sync compares (and skips equal) cells.
            self.cell_gen[cells].fill(self.epoch);
            n += w;
        }
        let mut r = 0;
        for c in 0..3 {
            for py in (y * 8).min(ph)..((y + h) * 8).min(ph) {
                let row =
                    &mut self.recon.plane_row_mut(c, py)[(x * 8).min(pw)..((x + w) * 8).min(pw)];
                let len = row.len();
                row.copy_from_slice(&snap.recon[r..r + len]);
                r += len;
            }
        }
    }

    /// The memo's reconstruction of the group; the capture target of every
    /// evaluation that uses the memo.
    pub(crate) fn recon_mut(&mut self) -> &mut Image3F {
        &mut self.recon
    }

    #[cfg(feature = "extraslow")]
    /// Copy into `dst` (offset `x0`, `y0`) the cells recomputed after
    /// evaluation `synced` whose pixels differ from it; returns their pixel
    /// bounding box in `dst` coordinates. Cells recomputed to the values
    /// `dst` already holds (a rejected move re-encoded back) are skipped, so
    /// the box covers the change itself and not every cell touched since.
    pub(crate) fn sync_into(
        &self,
        synced: u32,
        dst: &mut Image3F,
        x0: usize,
        y0: usize,
    ) -> Option<(usize, usize, usize, usize)> {
        let (mut rx0, mut ry0, mut rx1, mut ry1) = (usize::MAX, usize::MAX, 0usize, 0usize);
        let (w, h) = (self.recon.xsize(), self.recon.ysize());
        for (i, &g) in self.cell_gen.iter().enumerate() {
            if g <= synced {
                continue;
            }
            let (bx, by) = (i % self.xsize_blocks, i / self.xsize_blocks);
            let (cx0, cy0) = (bx * 8, by * 8);
            let (cx1, cy1) = ((cx0 + 8).min(w), (cy0 + 8).min(h));
            if cx0 >= cx1 || cy0 >= cy1 {
                continue;
            }
            let differs = (0..3).any(|c| {
                (cy0..cy1).any(|y| {
                    self.recon.plane_row(c, y)[cx0..cx1]
                        != dst.plane_row(c, y0 + y)[x0 + cx0..x0 + cx1]
                })
            });
            if !differs {
                continue;
            }
            for c in 0..3 {
                for y in cy0..cy1 {
                    dst.plane_row_mut(c, y0 + y)[x0 + cx0..x0 + cx1]
                        .copy_from_slice(&self.recon.plane_row(c, y)[cx0..cx1]);
                }
            }
            rx0 = rx0.min(x0 + cx0);
            ry0 = ry0.min(y0 + cy0);
            rx1 = rx1.max(x0 + cx1);
            ry1 = ry1.max(y0 + cy1);
        }
        (rx1 > 0).then_some((rx0, ry0, rx1, ry1))
    }
}

#[cfg(feature = "extraslow")]
/// See [`AcBlockCache::snapshot`].
pub(crate) struct MemoSnapshot {
    rect: (usize, usize, usize, usize),
    streams: usize,
    keys: Vec<u32>,
    quantized: Vec<i32>,
    dc: Vec<i16>,
    dc_f: Vec<f32>,
    spans: Vec<(u32, u32)>,
    nz_shift: Vec<[u8; 3]>,
    bits: Vec<[f32; 3]>,
    recon: Vec<f32>,
}

#[derive(Default)]
struct ReconScratch {
    err: Vec<f32>,
    pix: Vec<f32>,
}

impl ReconScratch {
    fn block(&mut self, size: usize) -> (&mut [f32], &mut [f32]) {
        if self.err.len() < size {
            self.err.resize(size, 0.0);
            self.pix.resize(size, 0.0);
        }
        (&mut self.err[..size], &mut self.pix[..size])
    }
}

/// Add an inverse-transformed error over the visible portion of its footprint.
#[inline]
fn capture_reconstruction(
    source: &crate::image::Plane<f32>,
    target: &mut crate::image::Plane<f32>,
    footprint: Footprint,
    (x, y): (usize, usize),
    error: &[f32],
) {
    let width = footprint
        .width
        .min(source.xsize().saturating_sub(footprint.x))
        .min(target.xsize().saturating_sub(x));
    let height = footprint
        .height
        .min(source.ysize().saturating_sub(footprint.y))
        .min(target.ysize().saturating_sub(y));
    if width == 0 {
        return;
    }
    for (row, delta) in error.chunks_exact(footprint.width).take(height).enumerate() {
        let src = &source.row(footprint.y + row)[footprint.x..footprint.x + width];
        let dst = &mut target.row_mut(y + row)[x..x + width];
        for ((out, &sample), &change) in dst.iter_mut().zip(src).zip(delta) {
            *out = sample + change;
        }
    }
}

#[cfg(feature = "extraslow")]
pub(crate) type PolisherSlot = Option<Box<crate::coef_polish::CoefPolisher>>;
#[cfg(not(feature = "extraslow"))]
pub(crate) type PolisherSlot = Option<Box<()>>;

pub(crate) struct AcGroupScratch {
    /// Study: decoder-feedback coefficient polish, set by the closed loop's
    /// serial polish pass.
    pub(crate) polisher: PolisherSlot,
    coeffs: HeapMatrix<f32, 3, MAX_BLOCK_COEFFICIENTS>,
    quantized: HeapMatrix<i32, 3, MAX_BLOCK_COEFFICIENTS>,
    /// Saved luma coefficients for RDOQ or reconstruction capture.
    source_y: Option<Box<[f32]>>,
    /// Materialized pass coefficients, needed only when the full block cannot be used.
    block: Option<Box<[i32]>>,
    rdoq: Option<RdoqScratch>,
    /// Edge-replicated pixels of a footprint that crosses the image edge.
    gather: Box<[f32; MAX_BLOCK_COEFFICIENTS]>,
    /// Distinct source colors, reused across RDOQ blocks and groups.
    few_color_keys: Vec<u64>,
    /// Y coefficient error and its pixel-domain image for the recon capture.
    recon: Option<Box<ReconScratch>>,
    clip: Option<Box<crate::clip_continuation::ClipScratch>>,
}

impl AcGroupScratch {
    /// The coefficient planes and edge gather buffer, for forward transforms
    /// taken outside the writer.
    pub(crate) fn transform_buffers(
        &mut self,
    ) -> (
        &mut [[f32; MAX_BLOCK_COEFFICIENTS]; 3],
        &mut [f32; MAX_BLOCK_COEFFICIENTS],
    ) {
        (&mut self.coeffs, &mut self.gather)
    }
}

impl Default for AcGroupScratch {
    fn default() -> Self {
        Self {
            polisher: None,
            coeffs: HeapMatrix::new(0.0),
            quantized: HeapMatrix::new(0),
            source_y: None,
            block: None,
            rdoq: None,
            gather: heap_array(0.0),
            few_color_keys: Vec::new(),
            clip: None,
            recon: None,
        }
    }
}

/// Unrounded Y and B DC of an AC group.
#[derive(Clone)]
pub(crate) struct SourceDc {
    pub(crate) y: crate::image::Plane<f32>,
    pub(crate) b: crate::image::Plane<f32>,
    pub(crate) x: crate::image::Plane<f32>,
}

/// The part of quantized coefficient `c` that pass `pass` transmits. Each
/// pass sends the remainder rounded toward zero (libjxl's split), so a small
/// coefficient stays zero in the earlier passes instead of landing in every
/// pass with opposite signs; the decoder sums `sent << shift` over passes.
#[inline]
fn pass_coefficient(c: i32, coeff_shifts: &[u32], pass: usize) -> i32 {
    let mut remaining = c;
    let mut sent = 0;
    for &shift in &coeff_shifts[..=pass] {
        sent = remaining.signum() * (remaining.abs() >> shift);
        remaining -= sent << shift;
    }
    sent
}

/// Process and tokenize one stripe of an AC group, pushing tokens into `out`.
/// Callers buffer tokens across all AC groups, build an adaptive entropy code
/// from the aggregate distribution, then emit them in `encode_frame`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_ac_group(
    ctx: &EncodingContext,
    scratch: &mut AcGroupScratch,
    opsin: &Image3F,
    opsin_origin: (usize, usize),
    group_brect: Rect,
    scale: f32,
    scale_dc: f32,
    dc_step: [f32; 3],
    distance: f32,
    x_qm_scale: u32,
    dc_data: &DcGroupData,
    ytob_dc: i32,
    quant_dc: &mut Image3S,
    mut source_dc: Option<&mut SourceDc>,
    qorigin_x: usize,
    qorigin_y: usize,
    num_nzeros: &mut [Image3B],
    coeff_shifts: &[u32],
    rdoq_prices: Option<&FrozenTokenPrices>,
    coeff_orders: &crate::coeff_order::CoeffOrders,
    alternative_orders: &[crate::coeff_order::CoeffOrders],
    mut order_stats: Option<&mut crate::coeff_order::OrderStats>,
    measure_chroma_distortion: bool,
    qf_threshold: u32,
    mut recon_y: Option<ReconCapture<'_>>,
    mut memo: Option<&mut AcBlockCache>,
    out: &mut [Vec<Token>],
) -> f32 {
    let (out, alternative_out) = out.split_at_mut(coeff_shifts.len());
    debug_assert_eq!(alternative_out.len(), alternative_orders.len());
    debug_assert!(alternative_out.is_empty() || coeff_shifts.len() == 1);
    let matrices = ctx.matrices();
    let xsize_blocks = group_brect.xsize;
    let ysize_blocks = group_brect.ysize;

    let inv_factor = [
        INV_DC_QUANT[0] / dc_step[0] * scale_dc,
        INV_DC_QUANT[1] / dc_step[1] * scale_dc,
        INV_DC_QUANT[2] / dc_step[2] * scale_dc,
    ];
    // `base_correlation_b` (= 1) plus the frame's signaled `ytob_dc / 84`,
    // converted from dequantized XYB into stored-B-DC units. Folded into the
    // quantizer below so the slope costs no extra rounding error.
    let cfl_factor_b = crate::color_correlation::dc_cfl_factor(dc_step, ytob_dc, ctx.cfl_frame());
    let x_qm_mul = 1.25f32.powf(x_qm_scale as f32 - 2.0);

    let nzeros_by0 = group_brect.y0 % K_GROUP_DIM_IN_BLOCKS;
    let mut chroma_distortion = 0.0f32;
    let cfl_factor_x = crate::color_correlation::dc_cfl_factor_x(dc_step, ctx.cfl_base_x());

    // All the big per-block buffers live in the worker scratch: re-creating them
    // per group cost ~130 KB of zeroing. The pass buffer is written over
    // `..size` before it is read, so it can also carry storage across groups.
    let AcGroupScratch {
        polisher,
        coeffs,
        quantized,
        source_y,
        block: pblock,
        rdoq,
        gather,
        few_color_keys,
        recon: recon_scratch,
        clip: clip_scratch,
    } = scratch;
    #[cfg(not(feature = "extraslow"))]
    let _ = polisher;

    // Reuse this small vector across channels and blocks. Only memo misses
    // need the offsets; ordinary encodes never read them.
    let mut stream_starts = Vec::new();
    for by in 0..ysize_blocks {
        let nz_by = nzeros_by0 + by;
        let global_by = group_brect.y0 + by;

        for bx in 0..xsize_blocks {
            let global_bx = group_brect.x0 + bx;

            // Skip non-first blocks of multi-block transforms.
            if !dc_data.ac_strategy.is_first_block(global_bx, global_by) {
                continue;
            }
            if let Some((_, _, Some(starts))) = recon_y.as_mut() {
                starts.push((global_bx as u16, global_by as u16, out[0].len() as u32));
            }

            let raw_strategy = dc_data.ac_strategy.raw_strategy(global_bx, global_by);
            let cov_x = AcStrategyImage::covered_blocks_x_of(raw_strategy);
            let cov_y = AcStrategyImage::covered_blocks_y_of(raw_strategy);
            // libjxl-tiny normalizes: cx >= cy. For DCT16X8 (1×2) and DCT8X16
            // (2×1), both end up as cx=2, cy=1, matching the 8×16 storage.
            let (cx, cy) = if cov_y > cov_x {
                (cov_y, cov_x)
            } else {
                (cov_x, cov_y)
            };
            let size = cx * cy * 64;
            let quant_ac = dc_data.raw_quant_field.row(global_by)[global_bx] as i32;

            // ---- Block memo ----
            // Per channel: a block's channel is a function of the field value,
            // the nonzero contexts predicted from its neighbors, Y's context
            // for the CfL residuals and the channel's qm scale.
            let lby = global_by - qorigin_y;
            let predicted_ctx: [u8; 3] = std::array::from_fn(|c| {
                let nzero_map = &num_nzeros[0];
                let row_top = (nz_by != 0).then(|| nzero_map.plane_row(c, nz_by - 1));
                predict_from_top_and_left(row_top, nzero_map.plane_row(c, nz_by), bx, 32)
            });
            let memo_keys: [u32; 3] = [
                quant_ac as u32
                    | u32::from(predicted_ctx[0]) << 8
                    | u32::from(predicted_ctx[1]) << 16
                    | x_qm_scale << 24,
                quant_ac as u32 | u32::from(predicted_ctx[1]) << 8,
                quant_ac as u32
                    | u32::from(predicted_ctx[2]) << 8
                    | u32::from(predicted_ctx[1]) << 16
                    | ctx.b_qm_scale() << 24,
            ];
            let bi = lby * memo.as_deref().map_or(0, |m| m.xsize_blocks) + bx;
            // Token streams are memoized for single-pass frames (the key
            // carries the first pass's contexts) and never while tallying
            // orders. The capture image is the memo's own reconstruction, so
            // a hit copies no pixels.
            let streams = out.len() + alternative_out.len();
            let token_memo = coeff_shifts.len() == 1 && order_stats.is_none();
            let tokens_cached = token_memo
                && memo
                    .as_deref()
                    .is_some_and(|m| m.spans.len() == m.keys[0].len() * streams * 3);
            let hit: [bool; 3] = std::array::from_fn(|c| {
                memo.as_deref()
                    .is_some_and(|m| m.keys[c][bi] == memo_keys[c])
            });
            // A missed channel whose field and qm scale match its stored key
            // differs only in the predicted nonzero contexts, which the
            // trellis reads at its last step alone: its stored tail re-picks.
            // Chroma also needs Y's levels unchanged (CfL reads them).
            let cached_tail: [Option<TrellisTail>; 3] = std::array::from_fn(|c| {
                let m = memo.as_deref()?;
                let stored = m.keys[c][bi];
                let tail = m.tails[bi][c];
                let same_inputs = stored & 0xff == memo_keys[c] & 0xff
                    && (c == 1 || stored >> 24 == memo_keys[c] >> 24);
                (!hit[c] && stored != u32::MAX && tail.key == stored && same_inputs).then_some(tail)
            });
            let mut new_tails = [TrellisTail::default(); 3];
            // Channels whose re-picked levels equal the stored ones: their
            // reconstruction in the memo's capture image is already current.
            let mut reused = [false; 3];
            let mut y_levels_kept = hit[1];
            debug_assert!(memo.is_none() || !measure_chroma_distortion);
            // A hit channel's levels (unless its tokens are cached too) and DC.
            if let Some(m) = memo.as_deref() {
                for c in 0..3 {
                    if !hit[c] {
                        continue;
                    }
                    for j in 0..cov_y {
                        if !tokens_cached {
                            let slot = ((lby + j) * m.xsize_blocks + bx) * 64;
                            let len = cov_x * 64;
                            let k = j * len;
                            quantized[c][k..k + len]
                                .copy_from_slice(&m.quantized[c][slot..slot + len]);
                        }
                        let src = &m.dc.plane_row(c, lby + j)[bx..bx + cov_x];
                        quant_dc.plane_row_mut(c, lby + j)[bx..bx + cov_x].copy_from_slice(src);
                    }
                }
            }
            let memo_hit = hit.iter().all(|&h| h);
            if !memo_hit {
                // ---- Forward DCT for all 3 channels ----
                let footprint = Footprint::of_strategy(
                    opsin,
                    opsin_origin.0 + bx * 8,
                    opsin_origin.1 + by * 8,
                    raw_strategy,
                );
                debug_assert_eq!((footprint.width, footprint.height), (cov_x * 8, cov_y * 8));
                // Padding is never shown, so RDOQ charges coefficient error by
                // the footprint's visible area.
                let visible = footprint.visible_fraction();
                let restore_penalty = if rdoq_prices.is_some() {
                    let x0 = opsin_origin.0 + bx * 8;
                    let y0 = opsin_origin.1 + by * 8;
                    let x1 = (x0 + cov_x * 8).min(opsin.xsize());
                    let y1 = (y0 + cov_y * 8).min(opsin.ysize());
                    let limit = RESTORE_FEW_COLORS_PER_BLOCK * cov_x * cov_y;
                    if few_colors(opsin, x0, y0, x1, y1, limit, few_color_keys) {
                        RESTORE_FEW_COLORS_PENALTY
                    } else {
                        1.0
                    }
                } else {
                    1.0
                };
                let (inv_qm_y, qm_y): (&[f32], &[f32]) = match raw_strategy {
                STRATEGY_DCT => (&matrices.inv_matrix(1)[..], &matrices.matrix(1)[..]),
                STRATEGY_IDENTITY => (
                    &matrices.inv_matrix_identity(1)[..],
                    &matrices.matrix_identity(1)[..],
                ),
                STRATEGY_DCT2X2 => (
                    &matrices.inv_matrix_dct2x2(1)[..],
                    &matrices.matrix_dct2x2(1)[..],
                ),
                STRATEGY_DCT4X4 => (&matrices.inv_matrix_4x4(1)[..], &matrices.matrix_4x4(1)[..]),
                STRATEGY_DCT4X8 | STRATEGY_DCT8X4 => {
                    (&matrices.inv_matrix_4x8(1)[..], &matrices.matrix_4x8(1)[..])
                }
                STRATEGY_AFV0..=STRATEGY_AFV3 => {
                    (&matrices.inv_matrix_afv(1)[..], &matrices.matrix_afv(1)[..])
                }
                STRATEGY_DCT16X16 => (&matrices.inv_matrix_16x16(1)[..], &matrices.matrix_16x16(1)[..]),
                STRATEGY_DCT32X32 => (&matrices.inv_matrix_32x32(1)[..], &matrices.matrix_32x32(1)[..]),
                STRATEGY_DCT64X64 => (&matrices.inv_matrix_64x64(1)[..], &matrices.matrix_64x64(1)[..]),
                #[cfg(feature = "extraslow")]
                STRATEGY_DCT128X128 | STRATEGY_DCT128X64 | STRATEGY_DCT64X128 => (
                    matrices.inv_matrix_128(raw_strategy, 1),
                    matrices.matrix_128(raw_strategy, 1),
                ),
                STRATEGY_DCT64X32 | STRATEGY_DCT32X64 => {
                    (&matrices.inv_matrix_64x32(1)[..], &matrices.matrix_64x32(1)[..])
                }
                STRATEGY_DCT32X16 | STRATEGY_DCT16X32 => {
                    (&matrices.inv_matrix_32x16(1)[..], &matrices.matrix_32x16(1)[..])
                }
                STRATEGY_DCT32X8 | STRATEGY_DCT8X32 => {
                    (&matrices.inv_matrix_8x32(1)[..], &matrices.matrix_8x32(1)[..])
                }
                _ /* 16X8/8X16 */ => (&matrices.inv_matrix_16x8(1)[..], &matrices.matrix_16x8(1)[..]),
            };
                // Saturated pixels get a free target beyond the clip limit;
                // the shift rides on Y and B, so either one recomputing needs it.
                let clip_shift = ctx.speed.effort().clip_continuation && (!hit[1] || !hit[2]) && {
                    let (input, stride) = footprint.pixels(opsin.plane(1), &mut gather[..]);
                    crate::clip_continuation::continue_saturated(
                        ctx,
                        raw_strategy,
                        cx,
                        cy,
                        inv_qm_y,
                        qm_y,
                        quant_ac,
                        scale,
                        distance,
                        input,
                        stride,
                        clip_scratch.get_or_insert_with(Default::default),
                    )
                };
                for c in 0..3 {
                    if hit[c] {
                        continue;
                    }
                    let (input, stride) = footprint.pixels(opsin.plane(c), &mut gather[..]);
                    let (input, stride) = if clip_shift && c != 0 {
                        let (pw, ph) = crate::inflated_cost::strategy_pixel_dims(raw_strategy);
                        (
                            crate::clip_continuation::shifted_input(
                                clip_scratch.as_mut().expect("shift computed"),
                                input,
                                stride,
                                pw,
                                ph,
                            ),
                            pw,
                        )
                    } else {
                        (input, stride)
                    };
                    match raw_strategy {
                        STRATEGY_DCT => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.dct8x8)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_IDENTITY => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.identity8x8)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT2X2 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.dct2x2_8x8)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT16X8 => {
                            let dst: &mut [f32; 128] = coeffs[c].first_chunk_mut::<128>().unwrap();
                            (ctx.dct16x8)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT8X16 => {
                            let dst: &mut [f32; 128] = coeffs[c].first_chunk_mut::<128>().unwrap();
                            (ctx.dct8x16)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT16X16 => {
                            let dst: &mut [f32; 256] = coeffs[c].first_chunk_mut::<256>().unwrap();
                            (ctx.dct16x16)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT32X32 => {
                            let dst: &mut [f32; 1024] =
                                coeffs[c].first_chunk_mut::<1024>().unwrap();
                            (ctx.dct32x32)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT64X64 => {
                            let dst: &mut [f32; 4096] =
                                coeffs[c].first_chunk_mut::<4096>().unwrap();
                            (ctx.dct64x64)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT64X32 => {
                            let dst: &mut [f32; 2048] =
                                coeffs[c].first_chunk_mut::<2048>().unwrap();
                            (ctx.dct64x32)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT32X64 => {
                            let dst: &mut [f32; 2048] =
                                coeffs[c].first_chunk_mut::<2048>().unwrap();
                            (ctx.dct32x64)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT4X4 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.dct4x4)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT4X8 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.dct4x8)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT8X4 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.dct8x4)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT32X16 => {
                            let dst: &mut [f32; 512] = coeffs[c].first_chunk_mut::<512>().unwrap();
                            (ctx.dct32x16)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT16X32 => {
                            let dst: &mut [f32; 512] = coeffs[c].first_chunk_mut::<512>().unwrap();
                            (ctx.dct16x32)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT32X8 => {
                            let dst: &mut [f32; 256] = coeffs[c].first_chunk_mut::<256>().unwrap();
                            (ctx.dct32x8)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_DCT8X32 => {
                            let dst: &mut [f32; 256] = coeffs[c].first_chunk_mut::<256>().unwrap();
                            (ctx.dct8x32)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_AFV0 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.afv0)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_AFV1 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.afv1)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_AFV2 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.afv2)(DctInput::new(input, stride), dst);
                        }
                        STRATEGY_AFV3 => {
                            let dst: &mut [f32; 64] = coeffs[c].first_chunk_mut::<64>().unwrap();
                            (ctx.afv3)(DctInput::new(input, stride), dst);
                        }
                        #[cfg(feature = "extraslow")]
                        STRATEGY_DCT128X128 => {
                            let dst = coeffs[c].first_chunk_mut::<16384>().unwrap();
                            (ctx.dct128x128)(DctInput::new(input, stride), dst);
                        }
                        #[cfg(feature = "extraslow")]
                        STRATEGY_DCT128X64 => {
                            let dst = coeffs[c].first_chunk_mut::<8192>().unwrap();
                            (ctx.dct128x64)(DctInput::new(input, stride), dst);
                        }
                        #[cfg(feature = "extraslow")]
                        STRATEGY_DCT64X128 => {
                            let dst = coeffs[c].first_chunk_mut::<8192>().unwrap();
                            (ctx.dct64x128)(DctInput::new(input, stride), dst);
                        }
                        _ => unreachable!("invalid raw strategy {}", raw_strategy),
                    }
                }

                // For DCT8, DC = coeffs[0]. For multi-block, use DCFromLowestFrequencies.
                // dc_vals[c] holds up to 4 DC values (DCT16X16 = 2×2 covered blocks);
                // indexing is didx = iy * cov_x + ix.
                let mut dc_vals = [[0.0f32; 256]; 3];
                for c in 0..3 {
                    if !hit[c] {
                        dc_from_coefficients(ctx, raw_strategy, &coeffs[c], &mut dc_vals[c]);
                    }
                }

                // Hit channels: the DC values the skipped transform would have given.
                if let Some(m) = memo.as_deref() {
                    for c in 0..3 {
                        if hit[c] {
                            for iy in 0..cov_y {
                                let row = (lby + iy) * m.xsize_blocks;
                                dc_vals[c][iy * cov_x..(iy + 1) * cov_x]
                                    .copy_from_slice(&m.dc_f[c][row + bx..row + bx + cov_x]);
                            }
                        }
                    }
                }
                // DC for storage (per covered block, using pre-swap cov_x/cov_y).
                let covered_dc = cov_x * cov_y;
                let mut y_dc_q = [0i16; 256];
                if let Some(m) = memo.as_deref().filter(|_| hit[1]) {
                    for iy in 0..cov_y {
                        y_dc_q[iy * cov_x..(iy + 1) * cov_x]
                            .copy_from_slice(&m.dc.plane_row(1, lby + iy)[bx..bx + cov_x]);
                    }
                } else {
                    (ctx.quantize_dc)(
                        &dc_vals[1][..covered_dc],
                        inv_factor[1],
                        &mut y_dc_q[..covered_dc],
                    );
                }
                if let Some(source) = source_dc.as_mut() {
                    for iy in 0..cov_y {
                        let bx = global_bx - qorigin_x;
                        source.y.row_mut(global_by - qorigin_y + iy)[bx..bx + cov_x]
                            .copy_from_slice(&dc_vals[1][iy * cov_x..(iy + 1) * cov_x]);
                    }
                }
                for iy in 0..cov_y {
                    let lbx = global_bx - qorigin_x;
                    let quant_target = &mut quant_dc.plane_row_mut(1, global_by - qorigin_y + iy)
                        [lbx..lbx + cov_x];
                    let row_start = iy * cov_x;
                    quant_target.copy_from_slice(&y_dc_q[row_start..row_start + cov_x]);
                }
                // Quantize Y AC with roundtrip (modifies coeffs[1] to dequantized).
                // Matrix selection: DCT8 uses 8×8 weights, DCT16X8/8X16 share the
                // 128-float 16×8 weights, DCT16X16 uses the 256-float 16×16 weights.
                if let Some(m) = memo.as_deref().filter(|_| hit[1]) {
                    // The levels are skipped above when the tokens are cached too.
                    if tokens_cached {
                        for j in 0..cov_y {
                            let slot = ((lby + j) * m.xsize_blocks + bx) * 64;
                            let len = cov_x * 64;
                            let k = j * len;
                            quantized[1][k..k + len]
                                .copy_from_slice(&m.quantized[1][slot..slot + len]);
                        }
                    }
                    let inv_qac = 1.0 / (scale * quant_ac as f32);
                    for (out, (&q, &dq)) in coeffs[1][..size]
                        .iter_mut()
                        .zip(quantized[1][..size].iter().zip(qm_y[..size].iter()))
                    {
                        *out = ctx.dequant_bias(1).level(q) * dq * inv_qac;
                    }
                } else {
                    if rdoq_prices.is_some() || recon_y.is_some() {
                        match source_y {
                            Some(saved) if saved.len() >= size => {
                                saved[..size].copy_from_slice(&coeffs[1][..size]);
                            }
                            _ => *source_y = Some(coeffs[1][..size].into()),
                        }
                    }
                    quantize_roundtrip_y_block(
                        ctx,
                        inv_qm_y,
                        qm_y,
                        scale,
                        quant_ac,
                        distance,
                        cx,
                        cy,
                        &mut coeffs[1][..size],
                        &mut quantized[1][..size],
                    );
                    if let Some(prices) = rdoq_prices {
                        let strategy_code = dc_data.ac_strategy.strategy_code(global_bx, global_by);
                        let nzero_map = &num_nzeros[0];
                        let row_top = (nz_by != 0).then(|| nzero_map.plane_row(1, nz_by - 1));
                        let predicted = predict_from_top_and_left(
                            row_top,
                            nzero_map.plane_row(1, nz_by),
                            bx,
                            32,
                        );
                        let qf_hi = quant_ac as u32 > qf_threshold;
                        let lambda =
                            rdoq_lambda(ctx.arbiter, quant_ac as f32 / qf_threshold.max(1) as f32)
                                / visible;
                        let inputs = TrellisTail::inputs(
                            raw_strategy,
                            quantize_ac_q_scaled(quant_ac, scale, 1.0),
                            lambda,
                            restore_penalty,
                            distance,
                            &quantized[1][..size],
                        );
                        if let Some(tail) = cached_tail[1].filter(|t| {
                            t.same_pick(inputs, prices, 1, strategy_code, qf_hi, predicted, lambda)
                        }) && let Some(m) = memo.as_deref()
                        {
                            copy_cached_levels(m, 1, lby, bx, cov_x, cov_y, &mut quantized[1]);
                            new_tails[1] = tail;
                            y_levels_kept = true;
                            reused[1] = true;
                        } else {
                            rdoq_block(
                                rdoq_channel_weights(ctx.coding)[1],
                                prices,
                                coeff_orders.scan_for(strategy_code, 1),
                                &source_y.as_ref().expect("luma saved for RDOQ")[..size],
                                inv_qm_y,
                                quantize_ac_q_scaled(quant_ac, scale, 1.0),
                                &mut quantized[1][..size],
                                raw_strategy,
                                strategy_code,
                                1,
                                ctx.dequant_bias(1),
                                predicted,
                                cx,
                                cy,
                                distance,
                                qf_hi,
                                lambda,
                                restore_penalty,
                                RdoqSearch::of(ctx.speed.effort()),
                                rdoq.get_or_insert_with(RdoqScratch::default),
                                Some(&mut new_tails[1]),
                            );
                            new_tails[1].inputs = inputs;
                        }
                        let inv_qac = 1.0 / (scale * quant_ac as f32);
                        for (out, (&q, &dq)) in coeffs[1][..size]
                            .iter_mut()
                            .zip(quantized[1][..size].iter().zip(qm_y[..size].iter()))
                        {
                            *out = ctx.dequant_bias(1).level(q) * dq * inv_qac;
                        }
                    }
                }
                // ---- Luma reconstruction capture (closed-loop quant field) ----
                // Source plus the inverse-transformed Y quantization error, the
                // rerank's reconstruction model; the cx*cy lowest frequencies ride
                // on the DC path and are excluded.
                if !hit[1]
                    && !reused[1]
                    && let Some((recon, y_off, _)) = recon_y.as_mut()
                {
                    let (recon_err, recon_pix) =
                        recon_scratch.get_or_insert_with(Box::default).block(size);
                    let source_y = source_y.as_ref().expect("luma saved for reconstruction");
                    for ((e, &q), &src) in recon_err
                        .iter_mut()
                        .zip(&coeffs[1][..size])
                        .zip(&source_y[..size])
                    {
                        *e = q - src;
                    }
                    let wc = cx * 8;
                    for row in recon_err[..cy * wc].chunks_exact_mut(wc) {
                        row[..cx].fill(0.0);
                    }
                    crate::inflated_cost::reconstruct_error(
                        ctx.idct,
                        raw_strategy,
                        recon_err,
                        recon_pix,
                    );
                    capture_reconstruction(
                        opsin.plane(1),
                        recon.plane_mut(1),
                        footprint,
                        (bx * 8, *y_off + by * 8),
                        recon_pix,
                    );
                }

                // ---- Per-tile CfL factors ----
                let tx = global_bx / 8;
                let ty = global_by / 8;
                let cmap_x = dc_data.ytox_map.row(ty)[tx];
                let cmap_b = dc_data.ytob_map.row(ty)[tx];
                // y_to_x = 0 + cmap_x / 84;  y_to_b = 1 + cmap_b / 84.
                let x_factor = crate::color_correlation::y_to_x_ratio(ctx.cfl_frame(), cmap_x);
                let b_factor = crate::color_correlation::y_to_b_ratio(ctx.cfl_frame(), cmap_b);

                // ---- Apply CfL: X -= x_factor·Y, B -= b_factor·Y on every coefficient ----
                // The decoder reverses CfL in coefficient space (DequantLane) using the
                // dequantized Y AC coefficients, whose cx*cy LLF positions are zero at
                // that point — they are filled from the DC plane (LowestFrequenciesFromDC)
                // only afterwards. So the encoder must subtract using a Y whose LLF
                // positions are likewise zero; otherwise the AC-quantized LLF energy of Y
                // gets folded into the B/X DC (via the DCFromLowestFrequencies extraction
                // below) with no decoder-side counterpart, corrupting chroma by up to a
                // full-scale per-block shift (worst on B, where b_factor ≈ 1).
                {
                    let wc = cx * 8;
                    for row in coeffs[1][..cy * wc].chunks_exact_mut(wc) {
                        row[..cx].fill(0.0);
                    }
                }
                {
                    let [c0, c1, c2] = &mut **coeffs;
                    (ctx.apply_cfl)(
                        &mut c0[..size],
                        &c1[..size],
                        &mut c2[..size],
                        [x_factor, 0.0, b_factor],
                    );
                }
                // ---- Extract post-CfL X and B DC ----
                let mut x_dc_post = [0.0f32; 256];
                let mut b_dc_post = [0.0f32; 256];
                match raw_strategy {
                    STRATEGY_DCT
                    | STRATEGY_IDENTITY
                    | STRATEGY_DCT2X2
                    | STRATEGY_DCT4X4
                    | STRATEGY_DCT4X8
                    | STRATEGY_DCT8X4
                    | STRATEGY_AFV0..=STRATEGY_AFV3 => {
                        x_dc_post[0] = coeffs[0][0];
                        b_dc_post[0] = coeffs[2][0];
                    }
                    STRATEGY_DCT16X8 => {
                        let xb: &[f32; 128] = coeffs[0].first_chunk::<128>().unwrap();
                        let bb: &[f32; 128] = coeffs[2].first_chunk::<128>().unwrap();
                        dc_from_dct16x8(xb, x_dc_post.first_chunk_mut::<2>().unwrap());
                        dc_from_dct16x8(bb, b_dc_post.first_chunk_mut::<2>().unwrap());
                    }
                    STRATEGY_DCT8X16 => {
                        let xb: &[f32; 128] = coeffs[0].first_chunk::<128>().unwrap();
                        let bb: &[f32; 128] = coeffs[2].first_chunk::<128>().unwrap();
                        dc_from_dct8x16(xb, x_dc_post.first_chunk_mut::<2>().unwrap());
                        dc_from_dct8x16(bb, b_dc_post.first_chunk_mut::<2>().unwrap());
                    }
                    STRATEGY_DCT16X16 => {
                        let xb: &[f32; 256] = coeffs[0].first_chunk::<256>().unwrap();
                        let bb: &[f32; 256] = coeffs[2].first_chunk::<256>().unwrap();
                        dc_from_dct16x16(xb, x_dc_post.first_chunk_mut::<4>().unwrap());
                        dc_from_dct16x16(bb, b_dc_post.first_chunk_mut::<4>().unwrap());
                    }
                    STRATEGY_DCT32X32 => {
                        let xb: &[f32; 1024] = coeffs[0].first_chunk::<1024>().unwrap();
                        let bb: &[f32; 1024] = coeffs[2].first_chunk::<1024>().unwrap();
                        (ctx.dc_from_dct32x32)(xb, x_dc_post.first_chunk_mut::<16>().unwrap());
                        (ctx.dc_from_dct32x32)(bb, b_dc_post.first_chunk_mut::<16>().unwrap());
                    }
                    STRATEGY_DCT64X64 => {
                        let xb: &[f32; 4096] = coeffs[0].first_chunk::<4096>().unwrap();
                        let bb: &[f32; 4096] = coeffs[2].first_chunk::<4096>().unwrap();
                        (ctx.dc_from_dct64x64)(xb, x_dc_post.first_chunk_mut::<64>().unwrap());
                        (ctx.dc_from_dct64x64)(bb, b_dc_post.first_chunk_mut::<64>().unwrap());
                    }
                    STRATEGY_DCT64X32 => {
                        let xb: &[f32; 2048] = coeffs[0].first_chunk::<2048>().unwrap();
                        let bb: &[f32; 2048] = coeffs[2].first_chunk::<2048>().unwrap();
                        (ctx.dc_from_dct64x32)(xb, x_dc_post.first_chunk_mut::<32>().unwrap());
                        (ctx.dc_from_dct64x32)(bb, b_dc_post.first_chunk_mut::<32>().unwrap());
                    }
                    STRATEGY_DCT32X64 => {
                        let xb: &[f32; 2048] = coeffs[0].first_chunk::<2048>().unwrap();
                        let bb: &[f32; 2048] = coeffs[2].first_chunk::<2048>().unwrap();
                        (ctx.dc_from_dct32x64)(xb, x_dc_post.first_chunk_mut::<32>().unwrap());
                        (ctx.dc_from_dct32x64)(bb, b_dc_post.first_chunk_mut::<32>().unwrap());
                    }
                    STRATEGY_DCT32X16 => {
                        let xb: &[f32; 512] = coeffs[0].first_chunk::<512>().unwrap();
                        let bb: &[f32; 512] = coeffs[2].first_chunk::<512>().unwrap();
                        (ctx.dc_from_dct32x16)(xb, x_dc_post.first_chunk_mut::<8>().unwrap());
                        (ctx.dc_from_dct32x16)(bb, b_dc_post.first_chunk_mut::<8>().unwrap());
                    }
                    STRATEGY_DCT16X32 => {
                        let xb: &[f32; 512] = coeffs[0].first_chunk::<512>().unwrap();
                        let bb: &[f32; 512] = coeffs[2].first_chunk::<512>().unwrap();
                        (ctx.dc_from_dct16x32)(xb, x_dc_post.first_chunk_mut::<8>().unwrap());
                        (ctx.dc_from_dct16x32)(bb, b_dc_post.first_chunk_mut::<8>().unwrap());
                    }
                    STRATEGY_DCT32X8 | STRATEGY_DCT8X32 => {
                        let xb: &[f32; 256] = coeffs[0].first_chunk::<256>().unwrap();
                        let bb: &[f32; 256] = coeffs[2].first_chunk::<256>().unwrap();
                        (ctx.dc_from_dct8x32)(xb, x_dc_post.first_chunk_mut::<4>().unwrap());
                        (ctx.dc_from_dct8x32)(bb, b_dc_post.first_chunk_mut::<4>().unwrap());
                    }
                    #[cfg(feature = "extraslow")]
                    STRATEGY_DCT128X128 => {
                        (ctx.dc_from_dct128x128)(
                            coeffs[0].first_chunk::<16384>().unwrap(),
                            x_dc_post.first_chunk_mut::<256>().unwrap(),
                        );
                        (ctx.dc_from_dct128x128)(
                            coeffs[2].first_chunk::<16384>().unwrap(),
                            b_dc_post.first_chunk_mut::<256>().unwrap(),
                        );
                    }
                    #[cfg(feature = "extraslow")]
                    STRATEGY_DCT128X64 => {
                        (ctx.dc_from_dct128x64)(
                            coeffs[0].first_chunk::<8192>().unwrap(),
                            x_dc_post.first_chunk_mut::<128>().unwrap(),
                        );
                        (ctx.dc_from_dct128x64)(
                            coeffs[2].first_chunk::<8192>().unwrap(),
                            b_dc_post.first_chunk_mut::<128>().unwrap(),
                        );
                    }
                    #[cfg(feature = "extraslow")]
                    STRATEGY_DCT64X128 => {
                        (ctx.dc_from_dct64x128)(
                            coeffs[0].first_chunk::<8192>().unwrap(),
                            x_dc_post.first_chunk_mut::<128>().unwrap(),
                        );
                        (ctx.dc_from_dct64x128)(
                            coeffs[2].first_chunk::<8192>().unwrap(),
                            b_dc_post.first_chunk_mut::<128>().unwrap(),
                        );
                    }
                    _ => unreachable!(),
                }

                // ---- X channel: write post-CfL DC, quantize AC ----
                let inv_qm_x: &[f32] = match raw_strategy {
                    STRATEGY_DCT => &matrices.inv_matrix(0)[..],
                    STRATEGY_IDENTITY => &matrices.inv_matrix_identity(0)[..],
                    STRATEGY_DCT2X2 => &matrices.inv_matrix_dct2x2(0)[..],
                    STRATEGY_DCT4X4 => &matrices.inv_matrix_4x4(0)[..],
                    STRATEGY_DCT4X8 | STRATEGY_DCT8X4 => &matrices.inv_matrix_4x8(0)[..],
                    STRATEGY_AFV0..=STRATEGY_AFV3 => &matrices.inv_matrix_afv(0)[..],
                    STRATEGY_DCT16X16 => &matrices.inv_matrix_16x16(0)[..],
                    STRATEGY_DCT32X32 => &matrices.inv_matrix_32x32(0)[..],
                    STRATEGY_DCT64X64 => &matrices.inv_matrix_64x64(0)[..],
                    #[cfg(feature = "extraslow")]
                    STRATEGY_DCT128X128 | STRATEGY_DCT128X64 | STRATEGY_DCT64X128 => {
                        matrices.inv_matrix_128(raw_strategy, 0)
                    }
                    STRATEGY_DCT64X32 | STRATEGY_DCT32X64 => &matrices.inv_matrix_64x32(0)[..],
                    STRATEGY_DCT32X16 | STRATEGY_DCT16X32 => &matrices.inv_matrix_32x16(0)[..],
                    STRATEGY_DCT32X8 | STRATEGY_DCT8X32 => &matrices.inv_matrix_8x32(0)[..],
                    _ => &matrices.inv_matrix_16x8(0)[..],
                };
                let mut chroma_dc_q = [0i16; 256];
                if !hit[0] {
                    if cfl_factor_x != 0.0 {
                        (ctx.quantize_dc_cfl)(
                            &x_dc_post[..covered_dc],
                            &y_dc_q[..covered_dc],
                            inv_factor[0],
                            cfl_factor_x,
                            &mut chroma_dc_q[..covered_dc],
                        );
                    } else {
                        (ctx.quantize_dc)(
                            &x_dc_post[..covered_dc],
                            inv_factor[0],
                            &mut chroma_dc_q[..covered_dc],
                        );
                    }
                    for iy in 0..cov_y {
                        let lbx = global_bx - qorigin_x;
                        let quant_dc_row = &mut quant_dc
                            .plane_row_mut(0, global_by - qorigin_y + iy)
                            [lbx..lbx + cov_x];
                        let row_start = iy * cov_x;
                        quant_dc_row.copy_from_slice(&chroma_dc_q[row_start..row_start + cov_x]);
                    }
                    (ctx.quantize_block_ac)(
                        &coeffs[0][..size],
                        0,
                        inv_qm_x,
                        quant_ac,
                        scale,
                        x_qm_mul,
                        distance,
                        cx,
                        cy,
                        &mut quantized[0][..size],
                    );
                    // Chroma RDOQ (review §8): the trellis is channel-generic — the
                    // CfL residuals are the source, contexts/prices/orders are
                    // channel-specific, and unlike Y the input coefficients are not
                    // overwritten afterwards. Runs at every distance with the
                    // transform's calibrated weights and the distance-scheduled X/B
                    // multiplier (`chroma_rdoq_weight`).
                    if let Some(prices) = rdoq_prices {
                        let strategy_code = dc_data.ac_strategy.strategy_code(global_bx, global_by);
                        let nzero_map = &num_nzeros[0];
                        let row_top = (nz_by != 0).then(|| nzero_map.plane_row(0, nz_by - 1));
                        let predicted = predict_from_top_and_left(
                            row_top,
                            nzero_map.plane_row(0, nz_by),
                            bx,
                            32,
                        );
                        let qf_hi = quant_ac as u32 > qf_threshold;
                        let lambda =
                            rdoq_lambda(ctx.arbiter, quant_ac as f32 / qf_threshold.max(1) as f32)
                                / visible;
                        let inputs = TrellisTail::inputs(
                            raw_strategy,
                            quantize_ac_q_scaled(quant_ac, scale, x_qm_mul),
                            lambda,
                            restore_penalty,
                            distance,
                            &quantized[0][..size],
                        );
                        if let Some(tail) = cached_tail[0].filter(|t| {
                            y_levels_kept
                                && t.same_pick(
                                    inputs,
                                    prices,
                                    0,
                                    strategy_code,
                                    qf_hi,
                                    predicted,
                                    lambda,
                                )
                        }) && let Some(m) = memo.as_deref()
                        {
                            copy_cached_levels(m, 0, lby, bx, cov_x, cov_y, &mut quantized[0]);
                            new_tails[0] = tail;
                            reused[0] = true;
                        } else {
                            rdoq_block(
                                rdoq_channel_weights(ctx.coding)[0],
                                prices,
                                coeff_orders.scan_for(strategy_code, 0),
                                &coeffs[0][..size],
                                inv_qm_x,
                                quantize_ac_q_scaled(quant_ac, scale, x_qm_mul),
                                &mut quantized[0][..size],
                                raw_strategy,
                                strategy_code,
                                0,
                                ctx.dequant_bias(0),
                                predicted,
                                cx,
                                cy,
                                distance,
                                qf_hi,
                                lambda,
                                restore_penalty,
                                RdoqSearch::of(ctx.speed.effort()),
                                rdoq.get_or_insert_with(RdoqScratch::default),
                                Some(&mut new_tails[0]),
                            );
                            new_tails[0].inputs = inputs;
                        }
                    }
                }
                // Every transform spans a power-of-two number of blocks, so a
                // coefficient index splits into (row, column) by shift and mask.
                let row_stride = cx * 8;
                debug_assert!(row_stride.is_power_of_two());
                let row_shift = row_stride.trailing_zeros();
                let column_mask = row_stride - 1;

                // Keep the fractional source for the DC predictor check. Y DC
                // and these B lowest frequencies are unchanged by AC reranking.
                if let Some(source) = source_dc.as_mut() {
                    for iy in 0..cov_y {
                        let bx = global_bx - qorigin_x;
                        source.b.row_mut(global_by - qorigin_y + iy)[bx..bx + cov_x]
                            .copy_from_slice(&b_dc_post[iy * cov_x..(iy + 1) * cov_x]);
                        source.x.row_mut(global_by - qorigin_y + iy)[bx..bx + cov_x]
                            .copy_from_slice(&x_dc_post[iy * cov_x..(iy + 1) * cov_x]);
                    }
                }
                // ---- B channel: write CfL'd DC, quantize AC ----
                let inv_qm_b: &[f32] = match raw_strategy {
                    STRATEGY_DCT => &matrices.inv_matrix(2)[..],
                    STRATEGY_IDENTITY => &matrices.inv_matrix_identity(2)[..],
                    STRATEGY_DCT2X2 => &matrices.inv_matrix_dct2x2(2)[..],
                    STRATEGY_DCT4X4 => &matrices.inv_matrix_4x4(2)[..],
                    STRATEGY_DCT4X8 | STRATEGY_DCT8X4 => &matrices.inv_matrix_4x8(2)[..],
                    STRATEGY_AFV0..=STRATEGY_AFV3 => &matrices.inv_matrix_afv(2)[..],
                    STRATEGY_DCT16X16 => &matrices.inv_matrix_16x16(2)[..],
                    STRATEGY_DCT32X32 => &matrices.inv_matrix_32x32(2)[..],
                    STRATEGY_DCT64X64 => &matrices.inv_matrix_64x64(2)[..],
                    #[cfg(feature = "extraslow")]
                    STRATEGY_DCT128X128 | STRATEGY_DCT128X64 | STRATEGY_DCT64X128 => {
                        matrices.inv_matrix_128(raw_strategy, 2)
                    }
                    STRATEGY_DCT64X32 | STRATEGY_DCT32X64 => &matrices.inv_matrix_64x32(2)[..],
                    STRATEGY_DCT32X16 | STRATEGY_DCT16X32 => &matrices.inv_matrix_32x16(2)[..],
                    STRATEGY_DCT32X8 | STRATEGY_DCT8X32 => &matrices.inv_matrix_8x32(2)[..],
                    _ => &matrices.inv_matrix_16x8(2)[..],
                };
                if !hit[2] {
                    (ctx.quantize_dc_cfl)(
                        &b_dc_post[..covered_dc],
                        &y_dc_q[..covered_dc],
                        inv_factor[2],
                        cfl_factor_b,
                        &mut chroma_dc_q[..covered_dc],
                    );
                    for iy in 0..cov_y {
                        let lbx = global_bx - qorigin_x;
                        let quant_dc_row = &mut quant_dc
                            .plane_row_mut(2, global_by - qorigin_y + iy)
                            [lbx..lbx + cov_x];
                        let row_start = iy * cov_x;
                        quant_dc_row.copy_from_slice(&chroma_dc_q[row_start..row_start + cov_x]);
                    }
                    (ctx.quantize_block_ac)(
                        &coeffs[2][..size],
                        2,
                        inv_qm_b,
                        quant_ac,
                        scale,
                        ctx.b_qm_mul(),
                        distance,
                        cx,
                        cy,
                        &mut quantized[2][..size],
                    );
                    if let Some(prices) = rdoq_prices {
                        let strategy_code = dc_data.ac_strategy.strategy_code(global_bx, global_by);
                        let nzero_map = &num_nzeros[0];
                        let row_top = (nz_by != 0).then(|| nzero_map.plane_row(2, nz_by - 1));
                        let predicted = predict_from_top_and_left(
                            row_top,
                            nzero_map.plane_row(2, nz_by),
                            bx,
                            32,
                        );
                        let qf_hi = quant_ac as u32 > qf_threshold;
                        let lambda =
                            rdoq_lambda(ctx.arbiter, quant_ac as f32 / qf_threshold.max(1) as f32)
                                / visible;
                        let inputs = TrellisTail::inputs(
                            raw_strategy,
                            quantize_ac_q_scaled(quant_ac, scale, ctx.b_qm_mul()),
                            lambda,
                            restore_penalty,
                            distance,
                            &quantized[2][..size],
                        );
                        if let Some(tail) = cached_tail[2].filter(|t| {
                            y_levels_kept
                                && t.same_pick(
                                    inputs,
                                    prices,
                                    2,
                                    strategy_code,
                                    qf_hi,
                                    predicted,
                                    lambda,
                                )
                        }) && let Some(m) = memo.as_deref()
                        {
                            copy_cached_levels(m, 2, lby, bx, cov_x, cov_y, &mut quantized[2]);
                            new_tails[2] = tail;
                            reused[2] = true;
                        } else {
                            rdoq_block(
                                rdoq_channel_weights(ctx.coding)[2],
                                prices,
                                coeff_orders.scan_for(strategy_code, 2),
                                &coeffs[2][..size],
                                inv_qm_b,
                                quantize_ac_q_scaled(quant_ac, scale, ctx.b_qm_mul()),
                                &mut quantized[2][..size],
                                raw_strategy,
                                strategy_code,
                                2,
                                ctx.dequant_bias(2),
                                predicted,
                                cx,
                                cy,
                                distance,
                                qf_hi,
                                lambda,
                                restore_penalty,
                                RdoqSearch::of(ctx.speed.effort()),
                                rdoq.get_or_insert_with(RdoqScratch::default),
                                Some(&mut new_tails[2]),
                            );
                            new_tails[2].inputs = inputs;
                        }
                    }
                }
                if measure_chroma_distortion && !hit[0] {
                    let q_scaled_x = quantize_ac_q_scaled(quant_ac, scale, x_qm_mul);
                    let bias_x = ctx.dequant_bias(0);
                    for i in 0..size {
                        let v = i >> row_shift;
                        let u = i & column_mask;
                        if v < cy && u < cx {
                            continue;
                        }
                        let ideal = coeffs[0][i] * inv_qm_x[i] * q_scaled_x;
                        let error = ideal - bias_x.level(quantized[0][i]);
                        chroma_distortion += ctx.channel_weight(0) * error * error;
                    }
                }
                if measure_chroma_distortion && !hit[2] {
                    let q_scaled_b = quantize_ac_q_scaled(quant_ac, scale, ctx.b_qm_mul());
                    let bias_b = ctx.dequant_bias(2);
                    for i in 0..size {
                        let v = i >> row_shift;
                        let u = i & column_mask;
                        if v < cy && u < cx {
                            continue;
                        }
                        let ideal = coeffs[2][i] * inv_qm_b[i] * q_scaled_b;
                        let error = ideal - bias_b.level(quantized[2][i]);
                        chroma_distortion =
                            fmla(ctx.channel_weight(2), error * error, chroma_distortion);
                    }
                }
                // ---- Chroma reconstruction capture (closed-loop quant field) ----
                // CfL was applied against the dequantized Y, so the decoder's chroma
                // error is the residual's own quantization error.
                if let Some((recon, y_off, _)) = recon_y.as_mut() {
                    let (recon_err, recon_pix) =
                        recon_scratch.get_or_insert_with(Box::default).block(size);
                    let y_off = *y_off;
                    let q_x = quantize_ac_q_scaled(quant_ac, scale, x_qm_mul);
                    let q_b = quantize_ac_q_scaled(quant_ac, scale, ctx.b_qm_mul());
                    for (c, q_scaled) in [(0usize, q_x), (2, q_b)] {
                        if hit[c] || reused[c] {
                            continue;
                        }
                        let bias = ctx.dequant_bias(c);
                        // Dequantize through the forward matrix: no division.
                        let qm = matrices.matrix_of(raw_strategy, c);
                        let inv_q_scaled = 1.0 / q_scaled;
                        for i in 0..size {
                            let (v, u) = (i >> row_shift, i & column_mask);
                            recon_err[i] = if v < cy && u < cx {
                                0.0
                            } else {
                                bias.level(quantized[c][i]) * (qm[i] * inv_q_scaled) - coeffs[c][i]
                            };
                        }
                        crate::inflated_cost::reconstruct_error(
                            ctx.idct,
                            raw_strategy,
                            recon_err,
                            recon_pix,
                        );
                        capture_reconstruction(
                            opsin.plane(c),
                            recon.plane_mut(c),
                            footprint,
                            (bx * 8, y_off + by * 8),
                            recon_pix,
                        );
                    }
                }
                if let Some(m) = memo.as_deref_mut() {
                    let epoch = m.epoch;
                    for j in 0..cov_y {
                        let row = (lby + j) * m.xsize_blocks;
                        m.cell_gen[row + bx..row + bx + cov_x].fill(epoch);
                    }
                    for c in 0..3 {
                        if hit[c] {
                            continue;
                        }
                        m.keys[c][bi] = memo_keys[c];
                        let mut tail = new_tails[c];
                        if tail.key != u32::MAX {
                            tail.key = memo_keys[c];
                        }
                        m.tails[bi][c] = tail;
                        for j in 0..cov_y {
                            let row = (lby + j) * m.xsize_blocks;
                            m.dc_f[c][row + bx..row + bx + cov_x]
                                .copy_from_slice(&dc_vals[c][j * cov_x..(j + 1) * cov_x]);
                            let slot = (row + bx) * 64;
                            let len = cov_x * 64;
                            let k = j * len;
                            m.quantized[c][slot..slot + len]
                                .copy_from_slice(&quantized[c][k..k + len]);
                            let src = &quant_dc.plane_row(c, lby + j)[bx..bx + cov_x];
                            m.dc.plane_row_mut(c, lby + j)[bx..bx + cov_x].copy_from_slice(src);
                        }
                    }
                }
                // ---- Study: decoder-feedback coefficient polish ----
                #[cfg(feature = "extraslow")]
                if let (Some(p), Some(prices), Some((plane, y_off, _))) = (
                    polisher.as_deref_mut().filter(|p| p.is_current()),
                    rdoq_prices,
                    recon_y.as_mut(),
                ) {
                    let strategy_code = dc_data.ac_strategy.strategy_code(global_bx, global_by);
                    let qf_hi = quant_ac as u32 > qf_threshold;
                    let weights = rdoq_channel_weights(ctx.coding);
                    let cw = chroma_rdoq_weight(distance);
                    macro_rules! channel {
                        ($c:expr, $source:expr, $inv_qm:expr, $q_scaled:expr) => {{
                            let c: usize = $c;
                            let block_ctx = fine_block_context(c, strategy_code, qf_hi);
                            crate::coef_polish::PolishChannel {
                                source: $source,
                                inv_qm: $inv_qm,
                                q_scaled: $q_scaled,
                                bias: ctx.dequant_bias(c),
                                weight: weights[c] * if c == 1 { 1.0 } else { cw },
                                scan: coeff_orders.scan_for(strategy_code, c),
                                histo_offset: fine_zero_density_contexts_offset(block_ctx),
                                nzero_ctx: fine_non_zero_context(
                                    predicted_ctx[c] as u32,
                                    block_ctx,
                                ),
                            }
                        }};
                    }
                    let (pw, ph) = crate::inflated_cost::strategy_pixel_dims(raw_strategy);
                    let source_y = source_y.as_ref().expect("luma saved for polish");
                    let block = crate::coef_polish::PolishBlock {
                        raw_strategy,
                        cx,
                        cy,
                        size,
                        px0: opsin_origin.0 + bx * 8,
                        py0: opsin_origin.1 + by * 8,
                        pw,
                        ph,
                        lambda: rdoq_lambda(
                            ctx.arbiter,
                            quant_ac as f32 / qf_threshold.max(1) as f32,
                        ) / visible,
                        channels: [
                            channel!(
                                0,
                                &coeffs[0][..size],
                                inv_qm_x,
                                quantize_ac_q_scaled(quant_ac, scale, x_qm_mul)
                            ),
                            channel!(
                                1,
                                &source_y[..size],
                                inv_qm_y,
                                quantize_ac_q_scaled(quant_ac, scale, 1.0)
                            ),
                            channel!(
                                2,
                                &coeffs[2][..size],
                                inv_qm_b,
                                quantize_ac_q_scaled(quant_ac, scale, ctx.b_qm_mul())
                            ),
                        ],
                        cfl: [x_factor, 1.0, b_factor],
                    };
                    let [q0, q1, q2] = &mut **quantized;
                    p.polish(
                        ctx,
                        prices,
                        &block,
                        &mut [&mut q0[..size], &mut q1[..size], &mut q2[..size]],
                        (&mut **plane, bx * 8, *y_off + by * 8),
                    );
                }
            }
            // Hit channels skipped their transforms: the memo holds every
            // channel's unrounded DC (X and B equal post-CfL, Y's LLF being zero).
            if let (Some(source), Some(m)) = (source_dc.as_mut(), memo.as_deref()) {
                for iy in 0..cov_y {
                    let row = (lby + iy) * m.xsize_blocks;
                    for (c, plane) in [(0, &mut source.x), (1, &mut source.y), (2, &mut source.b)] {
                        plane.row_mut(lby + iy)[bx..bx + cov_x]
                            .copy_from_slice(&m.dc_f[c][row + bx..row + bx + cov_x]);
                    }
                }
            }
            // ---- Tokenize in order Y, X, B ----
            if let Some(m) = memo.as_deref_mut()
                && token_memo
                && m.spans.len() != m.keys[0].len() * streams * 3
            {
                m.spans = vec![(0, 0); m.keys[0].len() * streams * 3];
                m.tokens = vec![Vec::new(); streams];
            }
            let strategy_code = dc_data.ac_strategy.strategy_code(global_bx, global_by);
            let covered_blocks = cx * cy;
            // log2(covered_blocks): 0/1/2/4 for 1/2/4/16 covered blocks.
            let log2_covered_blocks = match covered_blocks {
                1 => 0,
                2 => 1,
                4 => 2,
                8 => 3,
                16 => 4,
                32 => 5,
                64 => 6,
                128 => 7,
                256 => 8,
                _ => unreachable!("invalid covered_blocks {}", covered_blocks),
            };
            for &c in &[1usize, 0, 2] {
                // A cached channel: copy its token streams and context cells.
                if tokens_cached
                    && hit[c]
                    && let Some(m) = memo.as_deref_mut()
                {
                    if m.trial && m.bits[bi][c].is_finite() {
                        m.trial_bits += f64::from(m.bits[bi][c]);
                        for iy in 0..cov_y {
                            num_nzeros[0].plane_row_mut(c, nz_by + iy)[bx..bx + cov_x]
                                .fill(m.nz_shift[bi][c]);
                        }
                        continue;
                    }
                    for s in 0..streams {
                        let (start, len) = m.spans[(bi * 3 + c) * streams + s];
                        let (start, len) = (start as usize, len as usize);
                        let dst = if s < out.len() {
                            &mut out[s]
                        } else {
                            &mut alternative_out[s - out.len()]
                        };
                        dst.extend_from_slice(&m.tokens[s][start..start + len]);
                    }
                    for iy in 0..cov_y {
                        num_nzeros[0].plane_row_mut(c, nz_by + iy)[bx..bx + cov_x]
                            .fill(m.nz_shift[bi][c]);
                    }
                    continue;
                }
                if token_memo && memo.is_some() {
                    stream_starts.clear();
                    stream_starts.extend(
                        out.iter()
                            .map(Vec::len)
                            .chain(alternative_out.iter().map(Vec::len)),
                    );
                }
                let full_block = &quantized[c][..size];

                for pass in 0..coeff_shifts.len() {
                    // Materialize the coefficients pass `pass` transmits. With
                    // decreasing per-pass shifts ending at 0, the decoder sums
                    // (sent_p << shift_p) over passes to recover `full_block`
                    // (jxl-vardct hf_coeff.rs:185,191).
                    let block = if pass == 0 && coeff_shifts[0] == 0 {
                        full_block
                    } else {
                        if pblock.as_ref().is_none_or(|block| block.len() < size) {
                            *pblock = Some(vec![0; size].into_boxed_slice());
                        }
                        let pblock = pblock.as_deref_mut().expect("pass buffer");
                        for k in 0..size {
                            pblock[k] = pass_coefficient(full_block[k], coeff_shifts, pass);
                        }
                        &pblock[..size]
                    };
                    let num_nzeros = &mut num_nzeros[pass];
                    let out = &mut out[pass];

                    let nzeros = if covered_blocks == 1 {
                        num_nonzero_except_dc(block.first_chunk::<64>().unwrap())
                    } else {
                        num_nonzero_except_llf(block, cx, cy)
                    };

                    // libjxl-tiny: NumNonZeroExceptLLF stores `(nzeros + covered_blocks - 1) >> log2_covered_blocks`
                    // to all covered cells in num_nzeros.
                    let shifted =
                        ((nzeros as usize + covered_blocks - 1) >> log2_covered_blocks) as u8;
                    if pass == 0
                        && let Some(m) = memo.as_deref_mut()
                    {
                        m.nz_shift[lby * m.xsize_blocks + bx][c] = shifted;
                    }
                    // Pre-swap iteration (cov_x, cov_y from raw strategy).
                    for iy in 0..cov_y {
                        let target_row =
                            &mut num_nzeros.plane_row_mut(c, nz_by + iy)[bx..bx + cov_x];
                        for target in target_row.iter_mut() {
                            *target = shifted;
                        }
                    }

                    // Predict from top and left.
                    let row_top: Option<&[u8]> = if nz_by == 0 {
                        None
                    } else {
                        Some(num_nzeros.plane_row(c, nz_by - 1))
                    };
                    let row = num_nzeros.plane_row(c, nz_by);
                    let predicted = predict_from_top_and_left(row_top, row, bx, 32);

                    let block_ctx =
                        fine_block_context(c, strategy_code, quant_ac as u32 > qf_threshold);
                    let nzero_ctx = fine_non_zero_context(predicted as u32, block_ctx);
                    let histo_offset = fine_zero_density_contexts_offset(block_ctx);

                    let token_start = out.len();
                    write_token_into(Token::new(nzero_ctx, nzeros as u32), out);

                    let mut prev: usize = if nzeros as usize > size / 16 { 0 } else { 1 };
                    let mut remaining = nzeros;
                    // Hoisted so the per-coefficient lookup stays one indexed
                    // load, as it was with the static natural-order tables.
                    let scan = coeff_orders.scan_for(strategy_code, c);
                    // First pass only: tally which raw positions actually carry
                    // nonzeros, so a shorter scan can be derived for pass two.
                    // Counted over the whole block, not just the walked prefix,
                    // so the tally does not depend on the current scan.
                    if pass == 0
                        && let Some(stats) = order_stats.as_deref_mut()
                        && let Some(slot) = crate::coeff_order::order_slot_of(strategy_code)
                    {
                        // `c` iterates [1, 0, 2] with the pass loop nested
                        // inside, so pin the block tally to one (channel, pass).
                        if c == 1 && pass == 0 {
                            stats.tally_block(slot);
                        }
                        for (raw, &coef) in block[..size].iter().enumerate() {
                            if coef != 0 {
                                stats.tally(slot, c, raw);
                            }
                        }
                    }
                    // Skip the first `covered_blocks` positions (LF).
                    let mut k = covered_blocks;
                    while k < size && remaining != 0 {
                        let raw = scan[k] as usize;
                        let coef = block[raw];
                        let ctx = histo_offset as usize
                            + if covered_blocks == 1 {
                                zero_density_context_8x8(remaining as usize, k, prev)
                            } else {
                                zero_density_context(
                                    remaining as usize,
                                    k,
                                    covered_blocks,
                                    log2_covered_blocks,
                                    prev,
                                )
                            };
                        write_token_into(Token::new(ctx as u32, pack_signed(coef)), out);
                        prev = if coef != 0 { 1 } else { 0 };
                        if coef != 0 {
                            remaining -= 1;
                        }
                        k += 1;
                    }
                    for (alternative_out, orders) in
                        alternative_out.iter_mut().zip(alternative_orders)
                    {
                        let alternative_scan = orders.scan_for(strategy_code, c);
                        if alternative_scan == scan {
                            alternative_out.extend_from_slice(&out[token_start..]);
                            continue;
                        }
                        write_token_into(Token::new(nzero_ctx, nzeros as u32), alternative_out);
                        let scan = alternative_scan;
                        let mut prev = if nzeros as usize > size / 16 { 0 } else { 1 };
                        let mut remaining = nzeros;
                        let mut k = covered_blocks;
                        while k < size && remaining != 0 {
                            let raw = scan[k] as usize;
                            let coef = block[raw];
                            let ctx = histo_offset as usize
                                + if covered_blocks == 1 {
                                    zero_density_context_8x8(remaining as usize, k, prev)
                                } else {
                                    zero_density_context(
                                        remaining as usize,
                                        k,
                                        covered_blocks,
                                        log2_covered_blocks,
                                        prev,
                                    )
                                };
                            write_token_into(
                                Token::new(ctx as u32, pack_signed(coef)),
                                alternative_out,
                            );
                            prev = if coef != 0 { 1 } else { 0 };
                            if coef != 0 {
                                remaining -= 1;
                            }
                            k += 1;
                        }
                    }
                    debug_assert_eq!(
                        remaining, 0,
                        "remaining nzeros at end: strategy={} c={} pass={}",
                        strategy_code, c, pass
                    );
                }
                if token_memo && let Some(m) = memo.as_deref_mut() {
                    for s in 0..streams {
                        let src = if s < out.len() {
                            &out[s]
                        } else {
                            &alternative_out[s - out.len()]
                        };
                        let new_tokens = &src[stream_starts[s]..];
                        if s == 0 {
                            m.bits[bi][c] = rdoq_prices.map_or(f32::NAN, |p| {
                                new_tokens.iter().map(|&k| p.token_bits(k)).sum()
                            });
                        }
                        let arena = &mut m.tokens[s];
                        m.spans[(bi * 3 + c) * streams + s] =
                            (arena.len() as u32, new_tokens.len() as u32);
                        arena.extend_from_slice(new_tokens);
                    }
                }
            }
        }
    }
    chroma_distortion
}

#[inline]
fn write_token_into(t: Token, out: &mut Vec<Token>) {
    out.push(t);
}

#[cfg(test)]
mod tests {
    #[test]
    fn capture_clips_source_and_target_at_independent_origins() {
        use crate::image::Plane;
        use crate::inflated_cost::Footprint;

        let mut source = Plane::<f32>::new(11, 10);
        for (i, value) in source.as_mut_slice().iter_mut().enumerate() {
            *value = (i as f32 - 31.0) / 7.0;
        }
        let mut target = Plane::new_fill(12, 11, -0.0f32);
        let footprint = Footprint::new(16, 16, 8, 8, 8, 8);
        let error: Vec<_> = (0..64).map(|i| i as f32 / -11.0).collect();
        super::capture_reconstruction(&source, &mut target, footprint, (10, 5), &error);
        super::capture_reconstruction(&source, &mut target, footprint, (13, 5), &error);

        for y in 0..11 {
            for x in 0..12 {
                let expected = if (5..7).contains(&y) && x >= 10 {
                    source.row(8 + y - 5)[8 + x - 10] + error[(y - 5) * 8 + x - 10]
                } else {
                    -0.0
                };
                assert_eq!(target.row(y)[x].to_bits(), expected.to_bits());
            }
        }
    }

    /// The quotient tables must reproduce the division bit for bit.
    #[test]
    fn dequant_bias_tables_match_the_division() {
        use super::DequantBias;
        use std::hint::black_box;
        for explicit in [false, true] {
            for bias in DequantBias::channels(explicit) {
                let numerator = black_box(bias.numerator);
                for quant in -300i32..=300 {
                    let want = match quant.unsigned_abs() {
                        0 => 0.0,
                        1 => bias.one.copysign(quant as f32),
                        _ => quant as f32 - numerator / black_box(quant as f32),
                    };
                    assert_eq!(bias.level(quant).to_bits(), want.to_bits(), "q = {quant}");
                    let level = bias.level_f32(quant as f32);
                    assert_eq!(level.to_bits(), want.to_bits(), "q = {quant} (f32)");
                }
                for quant in [2.5f32, -7.25, 63.5, 1.5, -1.75, 1e9] {
                    let want = quant - numerator / black_box(quant);
                    assert_eq!(
                        bias.level_f32(quant).to_bits(),
                        want.to_bits(),
                        "q = {quant}"
                    );
                }
            }
        }
    }

    #[cfg(feature = "extraslow")]
    #[test]
    fn block_memo_compaction_preserves_all_streams_and_snapshot_rollback() {
        use super::AcBlockCache;
        use crate::entropy::Token;

        let mut memo = AcBlockCache::new(2, 2, 16, 16);
        memo.tokens = vec![Vec::new(); 3];
        memo.spans = vec![(0, 0); 4 * 3 * 3];
        let write = |memo: &mut AcBlockCache, cell: usize, version: u32| {
            for c in 0..3 {
                for s in 0..3 {
                    let arena = &mut memo.tokens[s];
                    let start = arena.len() as u32;
                    // Include empty spans and different lengths across streams.
                    let len = (cell + c + s) * 47;
                    arena.extend(
                        (0..len)
                            .map(|i| Token::new((cell * 3 + c) as u32, version * 1000 + i as u32)),
                    );
                    memo.spans[(cell * 3 + c) * 3 + s] = (start, len as u32);
                }
            }
        };
        let read = |memo: &AcBlockCache| -> Vec<Vec<(u32, u32)>> {
            memo.spans
                .iter()
                .enumerate()
                .map(|(i, &(start, len))| {
                    memo.tokens[i % 3][start as usize..(start + len) as usize]
                        .iter()
                        .map(|t| (t.context, t.value))
                        .collect()
                })
                .collect()
        };
        for version in 0..80 {
            write(&mut memo, version as usize % 4, version);
            let expected = read(&memo);
            memo.compact_tokens();
            assert_eq!(read(&memo), expected);
            for s in 0..3 {
                let live: usize = memo.spans[s..]
                    .iter()
                    .step_by(3)
                    .map(|&(_, len)| len as usize)
                    .sum();
                assert!(memo.tokens[s].len() <= (2 * live).max(4096));
            }
        }
        // Snapshot offsets must remain valid until restore, even though the
        // trial appends replacements both inside and outside the saved region.
        let before = read(&memo);
        let snapshot = memo.snapshot(1, 0, 1, 1);
        write(&mut memo, 1, 100);
        write(&mut memo, 2, 101);
        let changed = read(&memo);
        memo.restore(&snapshot);
        drop(snapshot);
        memo.compact_tokens();
        let restored = read(&memo);
        assert_eq!(&restored[9..18], &before[9..18]);
        assert_eq!(&restored[18..27], &changed[18..27]);

        let mut primary = AcBlockCache::new(2, 2, 16, 16);
        primary.tokens.clone_from(&memo.tokens);
        primary.spans.clone_from(&memo.spans);
        primary.keep_primary_tokens();
        primary.compact_tokens();
        assert_eq!(primary.tokens.len(), 1);
        assert_eq!(primary.spans.len(), 12);
        for ((start, len), expected) in primary
            .spans
            .iter()
            .copied()
            .zip(restored.iter().step_by(3))
        {
            let actual: Vec<_> = primary.tokens[0][start as usize..(start + len) as usize]
                .iter()
                .map(|t| (t.context, t.value))
                .collect();
            assert_eq!(&actual, expected);
        }

        // An entirely dead stream releases its old arena too.
        memo.spans.fill((0, 0));
        for arena in &mut memo.tokens {
            arena.resize(8192, Token::new(0, 0));
        }
        memo.compact_tokens();
        assert!(memo.tokens.iter().all(|arena| arena.capacity() == 0));
        AcBlockCache::new(0, 0, 0, 0).compact_tokens();
    }

    #[test]
    fn ac_scratch_allocates_optional_buffers_only_for_active_tools_and_reuses_them() {
        use super::{AcGroupScratch, write_ac_group};
        use crate::coeff_order::CoeffOrders;
        use crate::dc_group_data::DcGroupData;
        use crate::encoding_context::EncodingContext;
        use crate::entropy::{FrozenTokenPrices, Token, build_entropy_code_no_cluster};
        use crate::image::{Image3B, Image3F, Image3S, Rect};

        let (w, h) = (17, 19);
        let mut image = Image3F::new(w, h);
        for c in 0..3 {
            for (i, value) in image.plane_mut(c).as_mut_slice().iter_mut().enumerate() {
                *value = ((i * 97 + c * 13) % 257) as f32 / 257.0;
            }
        }
        let mut dc = DcGroupData::new(w.div_ceil(8), h.div_ceil(8)).unwrap();
        dc.raw_quant_field.as_mut_slice().fill(8);
        let orders = CoeffOrders::natural();
        let samples: Vec<_> = (0..4096).map(|i| Token::new(i % 2, i % 17)).collect();
        let mut code = build_entropy_code_no_cluster(&samples, 2, &mut Vec::new());
        code.context_map = (0..crate::ac_context::K_NUM_FINE_AC_CONTEXTS)
            .map(|i| (i % 2) as u8)
            .collect();
        let prices = FrozenTokenPrices::new(&code);
        let run = |ctx: &EncodingContext,
                   scratch: &mut AcGroupScratch,
                   rdoq: bool,
                   capture: bool,
                   shifts: &[u32]| {
            let mut quant_dc = Image3S::new(w.div_ceil(8), h.div_ceil(8));
            let mut nzeros: Vec<_> = shifts.iter().map(|_| Image3B::new(32, 32)).collect();
            let mut tokens: Vec<_> = shifts.iter().map(|_| Vec::new()).collect();
            let mut recon = Image3F::new(w, h);
            let mut starts = Vec::new();
            write_ac_group(
                ctx,
                scratch,
                &image,
                (0, 0),
                Rect::new(0, 0, w.div_ceil(8), h.div_ceil(8)),
                1.0,
                1.0,
                [1.0; 3],
                2.0,
                2,
                &dc,
                0,
                &mut quant_dc,
                None,
                0,
                0,
                &mut nzeros,
                shifts,
                rdoq.then_some(&prices),
                &orders,
                &[],
                None,
                false,
                8,
                capture.then_some((&mut recon, 0, Some(&mut starts))),
                None,
                &mut tokens,
            );
            (
                tokens
                    .into_iter()
                    .map(|stream| {
                        stream
                            .into_iter()
                            .map(|t| (t.context, t.value))
                            .collect::<Vec<_>>()
                    })
                    .collect::<Vec<_>>(),
                [0, 1, 2].map(|c| {
                    recon
                        .plane_data(c)
                        .iter()
                        .map(|v| v.to_bits())
                        .collect::<Vec<_>>()
                }),
            )
        };
        let pointers = |scratch: &AcGroupScratch| {
            (
                scratch.source_y.as_ref().map(|v| v.as_ptr()),
                scratch.rdoq.as_ref().map(|v| {
                    (
                        v.choices.as_ptr(),
                        v.costs.as_ref().map(|costs| costs[0].as_ptr()),
                    )
                }),
                scratch
                    .recon
                    .as_ref()
                    .map(|v| (v.err.as_ptr(), v.pix.as_ptr())),
            )
        };
        for speed in [
            crate::Speed::UltraFast,
            crate::Speed::Fastest,
            crate::Speed::Fast,
            crate::Speed::Medium,
        ] {
            let ctx = EncodingContext::new(
                speed,
                crate::Arbiter::Ssimulacra2,
                crate::xyb::XybMatrix::SPEC,
                2.0,
                1,
            );
            let mut scratch = AcGroupScratch::default();
            for shifts in [&[0u32][..], &[2, 0]] {
                run(&ctx, &mut scratch, false, false, shifts);
                assert_eq!(pointers(&scratch), (None, None, None));
                assert_eq!(
                    scratch.block.as_deref().map(<[i32]>::len),
                    (shifts.len() > 1).then_some(64)
                );
            }
        }
        let ctx = EncodingContext::new(
            crate::Speed::Slow,
            crate::Arbiter::Ssimulacra2,
            crate::xyb::XybMatrix::SPEC,
            2.0,
            1,
        );
        for (rdoq, capture) in [(true, false), (false, true), (true, true)] {
            let mut scratch = AcGroupScratch::default();
            for shifts in [&[0u32][..], &[2, 0]] {
                let expected = run(&ctx, &mut scratch, rdoq, capture, shifts);
                assert_eq!(scratch.source_y.as_deref().map(<[f32]>::len), Some(64));
                assert_eq!(scratch.rdoq.is_some(), rdoq);
                assert_eq!(scratch.recon.is_some(), capture);
                let storage = pointers(&scratch);
                assert_eq!(run(&ctx, &mut scratch, rdoq, capture, shifts), expected);
                assert_eq!(pointers(&scratch), storage);
                let mut fresh = AcGroupScratch::default();
                assert_eq!(run(&ctx, &mut fresh, rdoq, capture, shifts), expected);
            }
        }
    }

    /// A warm block memo must reproduce a fresh evaluation of the same
    /// candidate: tokens, quantized DC and the unrounded source DC, on full
    /// hits and when only B misses (a B matrix-scale change keeps Y cached).
    #[cfg(feature = "extraslow")]
    #[test]
    fn block_memo_matches_fresh_evaluation_on_partial_and_full_hits() {
        use super::{AcBlockCache, AcGroupScratch, SourceDc, write_ac_group};
        use crate::coeff_order::CoeffOrders;
        use crate::dc_group_data::DcGroupData;
        use crate::encoding_context::EncodingContext;
        use crate::entropy::{FrozenTokenPrices, Token, build_entropy_code_no_cluster};
        use crate::image::{Image3B, Image3F, Image3S, Plane, Rect};
        use crate::xyb::rgb_to_xyb_pixel_f32;

        let ctx = EncodingContext::new(
            crate::Speed::Slow,
            crate::Arbiter::Ssimulacra2,
            crate::xyb::XybMatrix::SPEC,
            2.0,
            1,
        );
        assert!(ctx.speed.effort().clip_continuation);
        // Black/white edges at a different column in every 8x8 block.
        let (w, h) = (56, 16);
        let black = rgb_to_xyb_pixel_f32(&ctx.xyb, 0.0, 0.0, 0.0);
        let white = rgb_to_xyb_pixel_f32(&ctx.xyb, 1.0, 1.0, 1.0);
        let mut image = Image3F::new(w, h);
        for y in 0..h {
            for x in 0..w {
                let edge = (x / 8 + y / 8) % 7 + 1;
                let (vx, vy, vb) = if x % 8 < edge { black } else { white };
                image.plane_row_mut(0, y)[x] = vx;
                image.plane_row_mut(1, y)[x] = vy;
                image.plane_row_mut(2, y)[x] = vb;
            }
        }
        let (bw, bh) = (w / 8, h / 8);
        let orders = CoeffOrders::natural();
        let samples: Vec<_> = (0..4096).map(|i| Token::new(i % 2, i % 17)).collect();
        let mut code = build_entropy_code_no_cluster(&samples, 2, &mut Vec::new());
        code.context_map = (0..crate::ac_context::K_NUM_FINE_AC_CONTEXTS)
            .map(|i| (i % 2) as u8)
            .collect();
        let prices = FrozenTokenPrices::new(&code);
        let run = |dc: &DcGroupData, b_scale: u32, memo: Option<&mut AcBlockCache>| {
            ctx.set_b_qm_scale(b_scale);
            let mut scratch = AcGroupScratch::default();
            let mut quant_dc = Image3S::new(bw, bh);
            let mut source = SourceDc {
                y: Plane::new(bw, bh),
                b: Plane::new(bw, bh),
                x: Plane::new(bw, bh),
            };
            let mut nzeros = vec![Image3B::new(32, 32)];
            let mut tokens = vec![Vec::new()];
            let mut starts = Vec::new();
            let mut memo = memo;
            let mut recon = match memo.as_deref_mut() {
                Some(m) => std::mem::replace(m.recon_mut(), Image3F::new(0, 0)),
                None => Image3F::new(w, h),
            };
            write_ac_group(
                &ctx,
                &mut scratch,
                &image,
                (0, 0),
                Rect::new(0, 0, bw, bh),
                1.0,
                1.0,
                [1.0; 3],
                2.0,
                2,
                dc,
                0,
                &mut quant_dc,
                Some(&mut source),
                0,
                0,
                &mut nzeros,
                &[0],
                Some(&prices),
                &orders,
                &[],
                None,
                false,
                8,
                Some((&mut recon, 0, Some(&mut starts))),
                memo.as_deref_mut(),
                &mut tokens,
            );
            if let Some(m) = memo {
                *m.recon_mut() = recon;
            }
            let bits =
                |p: &Plane<f32>| p.as_slice().iter().map(|v| v.to_bits()).collect::<Vec<_>>();
            (
                tokens[0]
                    .iter()
                    .map(|t| (t.context, t.value))
                    .collect::<Vec<_>>(),
                [0, 1, 2].map(|c| quant_dc.plane_data(c).to_vec()),
                [bits(&source.x), bits(&source.y), bits(&source.b)],
            )
        };
        for qf in [6u8, 10, 16] {
            let mut dc = DcGroupData::new(bw, bh).unwrap();
            dc.raw_quant_field.as_mut_slice().fill(qf);
            let mut memo = AcBlockCache::new(bw, bh, w, h);
            let warm = run(&dc, 6, Some(&mut memo));
            assert_eq!(warm, run(&dc, 6, None), "cold memo, qf {qf}");
            for b_scale in [7, 7] {
                let fresh = run(&dc, b_scale, None);
                assert_eq!(
                    run(&dc, b_scale, Some(&mut memo)),
                    fresh,
                    "qf {qf} b {b_scale}"
                );
            }
        }
    }

    #[test]
    fn pass_split_sums_back_and_rounds_toward_zero() {
        for shifts in [&[1, 0][..], &[2, 0], &[3, 0], &[2, 1, 0], &[3, 2, 1, 0]] {
            for c in -40..=40 {
                let sent: Vec<i32> = (0..shifts.len())
                    .map(|p| super::pass_coefficient(c, shifts, p))
                    .collect();
                let sum: i32 = sent.iter().zip(shifts).map(|(&v, &s)| v << s).sum();
                assert_eq!(sum, c, "{shifts:?} {c}");
                assert!(sent.iter().all(|&v| v == 0 || v.signum() == c.signum()));
                assert_eq!(sent[0], c.signum() * (c.abs() >> shifts[0]));
            }
        }
    }

    use super::{
        QuantizeDcMethods, quantize_ac_thresholds, quantize_ac_thresholds_scaled,
        quantize_dc_cfl_scalar, quantize_dc_scalar, selected_quantize_dc_methods,
    };

    fn check_dc_quantizers(methods: QuantizeDcMethods) {
        let input = [
            f32::NEG_INFINITY,
            -40_000.5,
            -32_768.5,
            -3.5,
            -2.5,
            -1.5,
            -0.5,
            -0.0,
            0.0,
            0.5,
            1.5,
            2.5,
            3.5,
            32_767.0,
            32_767.5,
            40_000.5,
            f32::INFINITY,
            f32::NAN,
            11.25,
        ];
        let y_quant = [
            -31i16, -29, -23, -19, -17, -13, -11, -7, -5, -3, 2, 4, 8, 10, 14, 16, 20, 22, 26,
        ];
        let input: Vec<f32> = (0..260).map(|i| input[i % input.len()]).collect();
        let y_quant: Vec<i16> = (0..260).map(|i| y_quant[i % y_quant.len()]).collect();

        for len in (0..=33).chain([63, 64, 65, 127, 128, 129, 257]) {
            for offset in [0, 1, 3] {
                let input = &input[offset..offset + len];
                let y_quant = &y_quant[offset..offset + len];
                for scale in [0.0, 0.5, 1.0, -1.25] {
                    let mut want = vec![0x1234i16; len + offset + 2];
                    let mut got = want.clone();
                    quantize_dc_scalar(input, scale, &mut want[offset..offset + len]);
                    (methods.quantize)(input, scale, &mut got[offset..offset + len]);
                    assert_eq!(
                        got, want,
                        "plain DC length {len}, offset={offset}, scale={scale}"
                    );

                    for cfl in [0.0, 0.5, -0.75] {
                        quantize_dc_cfl_scalar(
                            input,
                            y_quant,
                            scale,
                            cfl,
                            &mut want[offset..offset + len],
                        );
                        (methods.quantize_cfl)(
                            input,
                            y_quant,
                            scale,
                            cfl,
                            &mut got[offset..offset + len],
                        );
                        assert_eq!(
                            got, want,
                            "CfL DC length {len}, offset={offset}, scale={scale}, cfl={cfl}"
                        );
                    }
                }
            }
        }

        check_dc_i32_quantizers(methods);
    }

    fn check_dc_i32_quantizers(methods: QuantizeDcMethods) {
        let special = [
            f32::NEG_INFINITY,
            f32::INFINITY,
            f32::NAN,
            -0.0,
            0.0,
            -0.5,
            0.5,
            -1.5,
            1.5,
            -2.5,
            2.5,
            f32::from_bits(0.5f32.to_bits() - 1),
            f32::from_bits(0.5f32.to_bits() + 1),
            -f32::from_bits(0.5f32.to_bits() - 1),
            -f32::from_bits(0.5f32.to_bits() + 1),
            -65_535.5,
            65_535.5,
            f32::from_bits(2_147_483_648.0f32.to_bits() - 1),
            2_147_483_648.0,
            -2_147_483_648.0,
            -4_294_967_296.0,
        ];
        let input: Vec<f32> = (0..257)
            .map(|i| {
                if i % 3 == 0 {
                    special[i / 3 % special.len()]
                } else {
                    f32::from_bits(0x3b00_0000 + (i as u32 * 7919) % 0x1000_0000)
                        * if i % 2 == 0 { 1.0 } else { -1.0 }
                }
            })
            .collect();
        let y_quant: Vec<i32> = (0..257)
            .map(|i| match i % 7 {
                0 => i32::MIN,
                1 => i32::MAX,
                _ => (i * 7919) - 900_000,
            })
            .collect();
        for len in (0..=33).chain([63, 64, 65, 127, 128, 129, 257]) {
            for scale in [0.0, -0.0, 0.5, 1.0, -1.25, 1.137, 65535.0] {
                let mut want = vec![0x1234_5678i32; len + 2];
                let mut got = want.clone();
                super::quantize_dc_i32_scalar(&input[..len], scale, &mut want[1..=len]);
                (methods.quantize_i32)(&input[..len], scale, &mut got[1..=len]);
                assert_eq!(got, want, "wide DC length {len}, scale={scale}");
                for cfl in [0.0, -0.0, 0.5, -0.75, 0.137] {
                    super::quantize_dc_cfl_i32_scalar(
                        &input[..len],
                        &y_quant[..len],
                        scale,
                        cfl,
                        &mut want[1..=len],
                    );
                    (methods.quantize_cfl_i32)(
                        &input[..len],
                        &y_quant[..len],
                        scale,
                        cfl,
                        &mut got[1..=len],
                    );
                    assert_eq!(got, want, "wide CfL length {len}, scale={scale}, cfl={cfl}");
                }
            }
        }
    }

    #[test]
    fn selected_dc_quantizers_match_scalar() {
        check_dc_quantizers(selected_quantize_dc_methods());
    }

    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    #[test]
    fn avx2_dc_quantizers_match_scalar() {
        if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {
            check_dc_quantizers(QuantizeDcMethods {
                quantize: |input, scale, output| unsafe {
                    crate::avx::quantize_dc_avx2(input, scale, output)
                },
                quantize_cfl: |input, y_quant, scale, cfl, output| unsafe {
                    crate::avx::quantize_dc_cfl_avx2(input, y_quant, scale, cfl, output)
                },
                quantize_i32: |input, scale, output| unsafe {
                    crate::avx::quantize_dc_i32_avx2(input, scale, output)
                },
                quantize_cfl_i32: |input, y_quant, scale, cfl, output| unsafe {
                    crate::avx::quantize_dc_cfl_i32_avx2(input, y_quant, scale, cfl, output)
                },
            });
        }
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    #[test]
    fn sse41_dc_quantizers_match_scalar() {
        if std::is_x86_feature_detected!("sse4.1") {
            check_dc_quantizers(QuantizeDcMethods {
                quantize: |input, scale, output| unsafe {
                    crate::sse::quantize_dc_sse41(input, scale, output)
                },
                quantize_cfl: |input, y_quant, scale, cfl, output| unsafe {
                    crate::sse::quantize_dc_cfl_sse41(input, y_quant, scale, cfl, output)
                },
                quantize_i32: |input, scale, output| unsafe {
                    crate::sse::quantize_dc_i32_sse41(input, scale, output)
                },
                quantize_cfl_i32: |input, y_quant, scale, cfl, output| unsafe {
                    crate::sse::quantize_dc_cfl_i32_sse41(input, y_quant, scale, cfl, output)
                },
            });
        }
    }

    #[test]
    fn deadzones_fade_to_existing_values_by_distance_one() {
        assert_eq!(
            quantize_ac_thresholds(1, 1, 1, 0.1),
            [0.50, 0.51, 0.52, 0.54]
        );
        assert_eq!(
            quantize_ac_thresholds(2, 1, 1, 0.1),
            [0.58, 0.75, 0.75, 0.75]
        );
        assert_eq!(
            quantize_ac_thresholds(1, 1, 1, 1.0),
            [0.58, 0.635, 0.66, 0.7]
        );
        assert_eq!(
            quantize_ac_thresholds(2, 1, 1, 1.0),
            [0.58, 0.75, 0.75, 0.75]
        );
        assert_eq!(
            quantize_ac_thresholds_scaled(2, 1, 1, 1.0, 1.25),
            [0.58, 0.65, 0.65, 0.65]
        );
        assert_eq!(
            quantize_ac_thresholds_scaled(1, 1, 1, 1.0, 1.25),
            quantize_ac_thresholds(1, 1, 1, 1.0)
        );
    }
}