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
/*
 * // 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.
 */

//! ExtraSlow quant-field, transform-layout and chroma refinement against the decoder metric.

use super::ac_groups::{
    AcGroupCapture, PendingAcGroup, RefinedAcGroup, paste_group, process_ac_group,
};
use super::loop_arbiter::LoopArbiter;
use super::loop_group_map::LoopGroupMap;
use super::quantization::DistanceParams;
use super::{
    ImageDim, K_BLOCK_DIM, K_DC_GROUP_DIM, K_GROUP_DIM, K_GROUP_DIM_IN_BLOCKS, K_TILE_DIM_IN_BLOCKS,
};
use crate::Arbiter;
use crate::coder_scratch::CoderScratch;
use crate::dc_group_data::{DcGroupData, STRATEGY_DCT};
use crate::encoding_context::EncodingContext;
use crate::entropy::TokenSlice;
use crate::image::{Image3F, Image3S};
use crate::util::EncodeError;

/// Closed-loop quant-field refinement (ExtraSlow). Every group is re-quantized
/// the way pass 2 codes it (custom scan orders, RDOQ at the frozen token
/// prices), priced with those prices and reconstructed in luma (source plus
/// the inverse-transformed Y quantization error, the rerank's model). The
/// whole field moved one step coarser and one step finer gives the global
/// exchange rate (SSIMULACRA2 deficit per percent of bits); the finer shift's
/// deficit change is attributed to 32px tiles in proportion to their share of
/// the current linearized map, against each tile's bit change. Tiles whose
/// return beats the global rate are candidates, verified one by one on the
/// arbiter's exact metric and kept only if `-deficit - slope * log rate`
/// improves.
#[allow(clippy::too_many_arguments)]
/// Re-runs the frame's DC-group setup (quant field, layout, CfL and the
/// frame-level follow-ups) under the context's current selection tables.
pub(super) type Reselect<'a> =
    &'a mut dyn FnMut(&mut CoderScratch) -> Result<Vec<DcGroupData>, EncodeError>;

pub(super) fn run_quant_field_loop(
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
    opsin: &Image3F,
    dim: &ImageDim,
    distp: &DistanceParams,
    dc_datas: &mut [DcGroupData],
    ac_tasks: &[(usize, usize, usize)],
    group_coords: &[(usize, usize)],
    num_passes: usize,
    coeff_shifts: &[u32],
    coeff_orders: &crate::coeff_order::CoeffOrders,
    order_alternatives: &[crate::coeff_order::CoeffOrders],
    ytob_dc: i32,
    qf_threshold: u32,
    prices: &crate::entropy::FrozenTokenPrices,
    want_recon: bool,
    dc_polish: Option<&mut super::dc_polish::Handoff>,
    reselect: Option<Reselect<'_>>,
) -> Option<(Vec<RefinedAcGroup>, DistanceParams, Option<Image3F>)> {
    /// Marginals and slope come from plain quantization; the ratio of deficit
    /// to bits is what the trellis preserves, at a third of the cost.
    const SHIFT_RDOQ: bool = false;
    /// The mean of the finer and coarser chords overstates the tangent of a
    /// convex rate-distortion curve.
    const SLOPE_SCALE: f32 = 0.85;
    const TILE_BLOCKS: usize = 4;
    const MAX_ITERS: usize = 3;
    // Candidates verified exactly per iteration; with the block memo each
    // costs ~0.4 ms at 1 MP, and 300 (vs 40) buys SS2 −0.3 / cvvdp −0.15 for +0.27×.
    const GREEDY: usize = 300;
    // At most this many candidates per AC group per iteration: each extra
    // candidate in a group costs another serial round (one group encode).
    const PER_GROUP: usize = 12;
    const MAX_MOVE_FRACTION: f32 = 0.3;
    const MAX_ABS_MOVE: i8 = 2;
    const MIN_FIELD: u8 = 1;
    /// Luma gradient density above which the selection-scale race runs.
    const SELECTION_RACE_TEXTURE: f32 = 0.03;
    /// Rate gap (% of the incumbent's bits) within which a race arm is
    /// compared at its own rate.
    const RACE_RATE_MATCH_TOLERANCE: f32 = 0.5;

    let (w, h) = (dim.xsize, dim.ysize);
    let (xb, yb) = (w.div_ceil(K_BLOCK_DIM), h.div_ceil(K_BLOCK_DIM));
    if xb < TILE_BLOCKS || yb < TILE_BLOCKS {
        return None;
    }
    let reference = crate::ssimulacra2::Ssimulacra2Reference::new(opsin)?;
    let blocks_per_dc = K_DC_GROUP_DIM / K_BLOCK_DIM;

    let group_map = LoopGroupMap::new(w, h, group_coords, ac_tasks);
    let locate = |bx, by| group_map.locate(bx, by);
    let task_of_block = &group_map.task_of_block;

    #[derive(Clone)]
    struct Eval {
        recon: Image3F,
        pending: Vec<Option<PendingAcGroup>>,
        quant_dc: Vec<Option<Image3S>>,
        /// Unrounded DC image values of each task's blocks.
        source_dc: Vec<Option<crate::group::SourceDc>>,
        starts: Vec<Vec<(u16, u16, u32)>>,
        capture: AcGroupCapture,
        /// Per task, the memo evaluation `recon` was last synced with.
        synced: Vec<u32>,
        /// Trial evaluations take cached blocks' bits instead of their tokens.
        trial: bool,
        hit_bits: Vec<f32>,
    }
    // Re-quantize, price and reconstruct the given AC groups under the fields.
    #[allow(clippy::too_many_arguments)]
    fn evaluate(
        ctx: &EncodingContext,
        scratch: &mut CoderScratch,
        opsin: &Image3F,
        dim: &ImageDim,
        distp: &DistanceParams,
        dc_datas: &[DcGroupData],
        ac_tasks: &[(usize, usize, usize)],
        group_coords: &[(usize, usize)],
        num_passes: usize,
        coeff_shifts: &[u32],
        coeff_orders: &crate::coeff_order::CoeffOrders,
        order_alternatives: &[crate::coeff_order::CoeffOrders],
        ytob_dc: i32,
        qf_threshold: u32,
        prices: Option<&crate::entropy::FrozenTokenPrices>,
        tasks: &[usize],
        memo: Option<&[std::sync::Mutex<Option<crate::group::AcBlockCache>>]>,
        eval: &mut Eval,
    ) -> Vec<crate::ssimulacra2::Rect> {
        let eval_trial = eval.trial;
        let capture_mode = eval.capture;
        let results = ctx
            .thread_pool
            .steal_map(scratch, tasks.len(), |i, scratch| {
                let t = tasks[i];
                let mut memo_slot = memo.map(|m| m[t].lock().expect("block memo"));
                if let Some(Some(m)) = memo_slot.as_deref_mut() {
                    m.trial = eval_trial;
                    m.trial_bits = 0.0;
                }
                let (dc_idx, gx, gy) = ac_tasks[t];
                let (dc_gx, dc_gy) = group_coords[dc_idx];
                let (p, local, source, _, capture) = process_ac_group(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    &dc_datas[dc_idx],
                    num_passes,
                    coeff_shifts,
                    dc_gx,
                    dc_gy,
                    gx,
                    gy,
                    ytob_dc,
                    prices,
                    coeff_orders,
                    order_alternatives,
                    false,
                    qf_threshold,
                    capture_mode,
                    memo_slot.as_deref_mut(),
                );
                let (plane, starts) = capture.expect("recon capture");
                let hit_bits = match memo_slot.as_deref_mut() {
                    Some(Some(m)) => {
                        m.trial = false;
                        m.trial_bits as f32
                    }
                    _ => 0.0,
                };
                (
                    t,
                    p,
                    local,
                    source,
                    starts,
                    plane,
                    (dc_gx, dc_gy, gx, gy),
                    hit_bits,
                )
            });
        let mut dirty = Vec::with_capacity(results.len());
        for (t, p, local, source, starts, plane, (dc_gx, dc_gy, gx, gy), hit_bits) in results {
            eval.hit_bits[t] = hit_bits;
            eval.pending[t] = Some(p);
            eval.quant_dc[t] = Some(local);
            eval.source_dc[t] = source;
            eval.starts[t] = starts;
            let x0 = dc_gx * K_DC_GROUP_DIM + gx * K_GROUP_DIM;
            let y0 = dc_gy * K_DC_GROUP_DIM + gy * K_GROUP_DIM;
            let empty = crate::ssimulacra2::Rect {
                x0: 0,
                y0: 0,
                x1: 0,
                y1: 0,
            };
            let rect = match memo {
                Some(memo) => {
                    // Only the cells recomputed since this evaluation last
                    // synced with the memo differ from `eval.recon`.
                    let guard = memo[t].lock().expect("block memo");
                    let m = guard.as_ref().expect("memo filled by the evaluation");
                    let rect = m.sync_into(eval.synced[t], &mut eval.recon, x0, y0).map_or(
                        empty,
                        |(rx0, ry0, rx1, ry1)| crate::ssimulacra2::Rect {
                            x0: rx0,
                            y0: ry0,
                            x1: rx1,
                            y1: ry1,
                        },
                    );
                    eval.synced[t] = m.epoch;
                    rect
                }
                None => {
                    for c in 0..3 {
                        for y in 0..plane.ysize() {
                            let src = &plane.plane_row(c, y)[..plane.xsize()];
                            eval.recon.plane_row_mut(c, y0 + y)[x0..x0 + src.len()]
                                .copy_from_slice(src);
                        }
                    }
                    crate::ssimulacra2::Rect {
                        x0,
                        y0,
                        x1: x0 + plane.xsize(),
                        y1: y0 + plane.ysize(),
                    }
                }
            };
            dirty.push(rect);
        }
        dirty
    }
    let new_eval = || Eval {
        recon: Image3F::new(w, h),
        pending: vec![None; ac_tasks.len()],
        quant_dc: vec![None; ac_tasks.len()],
        source_dc: vec![None; ac_tasks.len()],
        starts: vec![Vec::new(); ac_tasks.len()],
        capture: AcGroupCapture::Loop,
        synced: vec![0; ac_tasks.len()],
        trial: false,
        hit_bits: vec![0.0; ac_tasks.len()],
    };
    // Trials overwrite a task's tokens and starts before reading them. Only
    // pixels, DC and memo sync points are needed for untouched tasks.
    let trial_eval = |e: &Eval| Eval {
        recon: e.recon.clone(),
        pending: vec![None; ac_tasks.len()],
        quant_dc: e.quant_dc.clone(),
        source_dc: e.source_dc.clone(),
        starts: vec![Vec::new(); ac_tasks.len()],
        capture: AcGroupCapture::Loop,
        synced: e.synced.clone(),
        trial: false,
        hit_bits: vec![0.0; ac_tasks.len()],
    };
    let fill_decoded_dc =
        |e: &Eval, dp: &DistanceParams, rect: crate::ssimulacra2::Rect, out: &mut Image3F| {
            use crate::quant_weights::INV_DC_QUANT;
            let steps: [f32; 3] =
                std::array::from_fn(|c| dp.dc_step[c] / (INV_DC_QUANT[c] * dp.scale_dc));
            let cfl = ctx.cfl_frame();
            let cfl_b = crate::color_correlation::dc_cfl_factor(dp.dc_step, ytob_dc, cfl);
            let cfl_x = crate::color_correlation::dc_cfl_factor_x(dp.dc_step, cfl.base_x);
            group_map.reconstruct_dc(
                &e.quant_dc,
                [cfl_x, cfl_b],
                steps,
                ctx.dc_rows.reconstruct,
                rect,
                out,
            );
            // The judge adds each cell's DC error to the AC-only reconstruction:
            // decoded minus the unrounded DC image value of the same transform.
            let (bx0, by0) = (rect.x0 / K_BLOCK_DIM, rect.y0 / K_BLOCK_DIM);
            let (bx1, by1) = (
                rect.x1.div_ceil(K_BLOCK_DIM).min(xb),
                rect.y1.div_ceil(K_BLOCK_DIM).min(yb),
            );
            for by in by0..by1 {
                for bx in bx0..bx1 {
                    let t = task_of_block[by * xb + bx];
                    let Some(source) = e.source_dc[t].as_ref() else {
                        continue;
                    };
                    let (dc_idx, gx, gy) = ac_tasks[t];
                    let (dc_gx, dc_gy) = group_coords[dc_idx];
                    let lx = bx - (dc_gx * blocks_per_dc + gx * K_GROUP_DIM_IN_BLOCKS);
                    let ly = by - (dc_gy * blocks_per_dc + gy * K_GROUP_DIM_IN_BLOCKS);
                    for (c, plane) in [&source.x, &source.y, &source.b].into_iter().enumerate() {
                        out.plane_row_mut(c, by)[bx] -= plane.row(ly)[lx];
                    }
                }
            }
        };
    let decoded_dc = |e: &Eval, dp: &DistanceParams| -> Image3F {
        let mut out = Image3F::new(xb, yb);
        fill_decoded_dc(e, dp, crate::ssimulacra2::Rect::new(0, 0, w, h), &mut out);
        out
    };
    // The coefficient polish's ColorVideoVDP judge keeps the decoded DC minus
    // block means it was tuned with. Judging coefficient moves on the exact
    // DC error loses 2-3 % cvvdp at matched rate (8/8), unlike the quant-field
    // loop, which gains 1-3 % on every metric from it.
    let legacy_dc = |e: &Eval, dp: &DistanceParams, means: &Image3F| -> Image3F {
        use crate::quant_weights::INV_DC_QUANT;
        let mut out = Image3F::new(xb, yb);
        let steps: [f32; 3] =
            std::array::from_fn(|c| dp.dc_step[c] / (INV_DC_QUANT[c] * dp.scale_dc));
        let cfl = ctx.cfl_frame();
        let cfl_b = crate::color_correlation::dc_cfl_factor(dp.dc_step, ytob_dc, cfl);
        let cfl_x = crate::color_correlation::dc_cfl_factor_x(dp.dc_step, cfl.base_x);
        group_map.reconstruct_dc(
            &e.quant_dc,
            [cfl_x, cfl_b],
            steps,
            ctx.dc_rows.reconstruct,
            crate::ssimulacra2::Rect::new(0, 0, w, h),
            &mut out,
        );
        for c in 0..3 {
            for (v, &mean) in out
                .plane_mut(c)
                .as_mut_slice()
                .iter_mut()
                .zip(means.plane_data(c))
            {
                *v -= mean;
            }
        }
        out
    };
    // Small trials reuse one plane and reconstruct only cells the judge reads.
    let mut trial_dc = None;
    let frame_bits = |e: &Eval| {
        prices.adaptive_bits(e.pending.iter().map(|p| {
            p.as_ref()
                .map_or(TokenSlice::Wide(&[]), |p| p.tokens[0].as_slice())
        }))
    };
    // Frozen-price bits of every first block, indexed by frame block.
    let block_bits = |e: &Eval| -> Vec<f32> {
        let mut out = vec![0f32; xb * yb];
        for (t, starts) in e.starts.iter().enumerate() {
            let (dc_gx, dc_gy) = group_coords[ac_tasks[t].0];
            let toks = e.pending[t]
                .as_ref()
                .map_or(TokenSlice::Wide(&[]), |p| p.tokens[0].as_slice());
            for (i, &(lbx, lby, start)) in starts.iter().enumerate() {
                let end = starts.get(i + 1).map_or(toks.len(), |s| s.2 as usize);
                let bits: f32 = toks
                    .slice(start as usize..end)
                    .iter()
                    .map(|k| prices.token_bits(k))
                    .sum();
                let bx = dc_gx * blocks_per_dc + lbx as usize;
                let by = dc_gy * blocks_per_dc + lby as usize;
                out[by * xb + bx] += bits;
            }
        }
        out
    };

    let (tiles_x, tiles_y) = (xb.div_ceil(TILE_BLOCKS), yb.div_ceil(TILE_BLOCKS));
    let n_tiles = tiles_x * tiles_y;
    let tile_of_block = |bx: usize, by: usize| (by / TILE_BLOCKS) * tiles_x + bx / TILE_BLOCKS;
    let tile_blocks = |t: usize| -> Vec<(usize, usize)> {
        let (tx, ty) = (t % tiles_x, t / tiles_x);
        let xs = tx * TILE_BLOCKS..((tx + 1) * TILE_BLOCKS).min(xb);
        let ys = ty * TILE_BLOCKS..((ty + 1) * TILE_BLOCKS).min(yb);
        let mut blocks = Vec::with_capacity(xs.len() * ys.len());
        for by in ys {
            blocks.extend(xs.clone().map(|bx| (bx, by)));
        }
        blocks
    };
    // Sum a per-pixel map over each tile.
    let tile_sums = |map: &[f32]| -> Vec<f64> {
        let mut out = vec![0f64; n_tiles];
        let tile_px = TILE_BLOCKS * K_BLOCK_DIM;
        for y in 0..h {
            let ty = y / tile_px;
            let row = &map[y * w..(y + 1) * w];
            for (x, &v) in row.iter().enumerate() {
                out[ty * tiles_x + x / tile_px] += v as f64;
            }
        }
        out
    };
    let tile_bits = |blk: &[f32]| -> Vec<f32> {
        let mut out = vec![0f32; n_tiles];
        for by in 0..yb {
            for bx in 0..xb {
                out[tile_of_block(bx, by)] += blk[by * xb + bx];
            }
        }
        out
    };
    /// Fields a move overwrote, for an exact restore (the clamp at the bounds
    /// makes the inverse step inexact).
    struct Saved(Vec<(usize, usize, usize, u8)>);
    // Apply `moves` (tile, step) to the fields; returns the touched AC tasks
    // and the previous values.
    let apply = |dc_datas: &mut [DcGroupData], moves: &[(usize, i8)]| -> (Vec<usize>, Saved) {
        let mut tasks = Vec::new();
        let mut saved = Vec::new();
        for &(t, step) in moves {
            for (bx, by) in tile_blocks(t) {
                let (dc_idx, lbx, lby) = locate(bx, by);
                let v = &mut dc_datas[dc_idx].raw_quant_field.row_mut(lby)[lbx];
                saved.push((dc_idx, lbx, lby, *v));
                *v = (*v as i16 + step as i16).clamp(MIN_FIELD as i16, 255) as u8;
                let task = task_of_block[by * xb + bx];
                if !tasks.contains(&task) {
                    tasks.push(task);
                }
            }
        }
        (tasks, Saved(saved))
    };
    let restore = |dc_datas: &mut [DcGroupData], saved: Saved| {
        for (dc_idx, lbx, lby, v) in saved.0 {
            dc_datas[dc_idx].raw_quant_field.row_mut(lby)[lbx] = v;
        }
    };
    let all_tasks: Vec<usize> = (0..ac_tasks.len()).collect();
    let all_moves = |step: i8| -> Vec<(usize, i8)> { (0..n_tiles).map(|t| (t, step)).collect() };
    // Per-group block memo shared by every priced evaluation of the loop.
    let memo: Vec<std::sync::Mutex<Option<crate::group::AcBlockCache>>> = (0..ac_tasks.len())
        .map(|_| std::sync::Mutex::new(None))
        .collect();
    let memo: Option<&[_]> = Some(&memo[..]);
    // Only between trials: layout snapshots retain offsets into these arenas.
    let compact_memos = |tasks: &[usize]| {
        if let Some(memo) = memo {
            for &t in tasks {
                if let Some(m) = memo[t].lock().expect("block memo").as_mut() {
                    m.compact_tokens();
                }
            }
        }
    };
    let mut cur = new_eval();
    evaluate(
        ctx,
        scratch,
        opsin,
        dim,
        distp,
        dc_datas,
        ac_tasks,
        group_coords,
        num_passes,
        coeff_shifts,
        coeff_orders,
        order_alternatives,
        ytob_dc,
        qf_threshold,
        Some(prices),
        &all_tasks,
        memo,
        &mut cur,
    );
    let ref_bits = frame_bits(&cur);
    let finish = |e: Eval,
                  distp: DistanceParams,
                  recon: Option<Image3F>|
     -> Option<(Vec<RefinedAcGroup>, DistanceParams, Option<Image3F>)> {
        Some((
            e.pending
                .into_iter()
                .zip(e.quant_dc)
                .enumerate()
                .map(|(t, (p, q))| {
                    let (dc_idx, gx, gy) = ac_tasks[t];
                    (
                        dc_idx,
                        gx,
                        gy,
                        p.expect("pending group"),
                        q.expect("group dc"),
                    )
                })
                .collect(),
            distp,
            recon,
        ))
    };
    if ref_bits <= 0.0 {
        let recon = want_recon.then(|| std::mem::replace(&mut cur.recon, Image3F::new(0, 0)));
        return finish(cur, *distp, recon);
    }
    let rate_term = |bits: f32| 100.0 * (bits / ref_bits).ln();
    let mut cur_bits = ref_bits;

    // ---- Selection-scale race (synthetic content) ----
    // The selector's large-transform calibration is right for photos but
    // image- and distance-dependent on screen and synthetic content, where
    // it is worth 2..10 % at matched quality. Re-run the DC-group setup with
    // the 16/32 tables scaled for selection only (coding tables and header
    // unchanged) and keep the layout the exact metric prefers.
    // Gate: saturated content and high-contrast fine detail (game art,
    // line illustrations, dense texture: luma gradient density ≥ 0.03 on
    // the probe corpora, where photos sit at 0.002–0.03). Screenshots are
    // left out: the ExtraSlow layout loop already handles them and forced
    // scales lose there. Arms are compared at the incumbent's rate, so no
    // exchange rate is needed here.
    if let Some(reselect) = reselect
        && ctx.arbiter == Arbiter::Ssimulacra2
        && ctx.coding.is_xyb()
        && (ctx.chroma_heavy() || ctx.luma_texture() >= SELECTION_RACE_TEXTURE)
    {
        static FAMILY_WALK: [f32; 3] = [1.25, 1.6, 0.85];
        {
            // Layouts move the rate by several percent, beyond what the
            // linear exchange rate prices well. Each arm is judged at the
            // incumbent's rate instead: its deficit is interpolated between
            // its own field and the field shifted one step towards the
            // incumbent's bits, and the evaluation nearer that rate is what
            // gets adopted.
            let mut cur_d = reference.deficit(&cur.recon);
            let mut adopted = false;
            // Fresh DC groups carry no retained source DC; where the frame
            // keeps it, the adopted evaluation's per-task planes rebuild it.
            let keep_source: Vec<bool> = dc_datas.iter().map(|d| d.source_dc_y.is_some()).collect();
            // 1.25 first; finer only if it won, coarser only if it lost.
            let mut i = 0;
            while i < FAMILY_WALK.len() {
                let family = FAMILY_WALK[i];
                ctx.set_selection_family(distp.distance, Some(family));
                let datas = reselect(scratch);
                ctx.set_selection_family(distp.distance, None);
                let Ok(mut datas) = datas else { break };
                let mut e = new_eval();
                evaluate(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    &datas,
                    ac_tasks,
                    group_coords,
                    num_passes,
                    coeff_shifts,
                    coeff_orders,
                    order_alternatives,
                    ytob_dc,
                    qf_threshold,
                    Some(prices),
                    &all_tasks,
                    None,
                    &mut e,
                );
                let mut bits = frame_bits(&e);
                let r_cur = rate_term(cur_bits);
                let (r0, d0) = (rate_term(bits), reference.deficit(&e.recon));
                let mut d_at = d0;
                if (r0 - r_cur).abs() > RACE_RATE_MATCH_TOLERANCE {
                    let step: i8 = if r0 < r_cur { 1 } else { -1 };
                    let (_, saved) = apply(&mut datas, &all_moves(step));
                    let mut shifted = new_eval();
                    evaluate(
                        ctx,
                        scratch,
                        opsin,
                        dim,
                        distp,
                        &datas,
                        ac_tasks,
                        group_coords,
                        num_passes,
                        coeff_shifts,
                        coeff_orders,
                        order_alternatives,
                        ytob_dc,
                        qf_threshold,
                        Some(prices),
                        &all_tasks,
                        None,
                        &mut shifted,
                    );
                    let bits1 = frame_bits(&shifted);
                    let (r1, d1) = (rate_term(bits1), reference.deficit(&shifted.recon));
                    if (r1 - r0).abs() > 1e-3 {
                        d_at = d0 + (d1 - d0) * (r_cur - r0) / (r1 - r0);
                    }
                    if (r1 - r_cur).abs() < (r0 - r_cur).abs() {
                        e = shifted;
                        bits = bits1;
                    } else {
                        restore(&mut datas, saved);
                    }
                }
                let won = d_at < cur_d - 1e-6;
                if won {
                    for (slot, data) in dc_datas.iter_mut().zip(datas) {
                        *slot = data;
                    }
                    cur_d = reference.deficit(&e.recon);
                    cur = e;
                    cur_bits = bits;
                    adopted = true;
                }
                i = match (i, won) {
                    (0, true) => 1,
                    (0, false) => 2,
                    _ => FAMILY_WALK.len(),
                };
            }
            if adopted {
                if let Some(memo) = memo {
                    // The memo describes the previous layout's blocks.
                    for m in memo {
                        *m.lock().expect("block memo") = None;
                    }
                }
                for (t, source) in cur.source_dc.iter().enumerate() {
                    let (dc_idx, gx, gy) = ac_tasks[t];
                    let (Some(source), true) = (source, keep_source[dc_idx]) else {
                        continue;
                    };
                    let dc = &mut dc_datas[dc_idx];
                    let (w, h) = (dc.quant_dc.xsize(), dc.quant_dc.ysize());
                    let ox = gx * K_GROUP_DIM_IN_BLOCKS;
                    let oy = gy * K_GROUP_DIM_IN_BLOCKS;
                    for (target, plane) in [
                        (&mut dc.source_dc_y, &source.y),
                        (&mut dc.source_dc_b, &source.b),
                        (&mut dc.source_dc_x, &source.x),
                    ] {
                        let target = target.get_or_insert_with(|| crate::image::Plane::new(w, h));
                        for y in 0..plane.ysize() {
                            target.row_mut(oy + y)[ox..ox + plane.xsize()]
                                .copy_from_slice(plane.row(y));
                        }
                    }
                }
            }
        }
    }
    // The incremental state follows every accepted move exactly. Defer the
    // SSIM state until after the full-frame marginal scores: their temporary
    // images would otherwise overlap its retained reconstruction pyramids.
    // Under the ColorVideoVDP arbiter it is also the exact metric; the
    // marginals that rank candidates still come from SSIMULACRA2.
    let cv_judge = (ctx.arbiter == Arbiter::Cvvdp && ctx.coding.is_xyb())
        .then(|| crate::cvvdp_arbiter::CvvdpArbiter::new(opsin))
        .flatten();
    let mut loop_state = cv_judge.map(|mut judge| {
        judge.reset(&cur.recon, &decoded_dc(&cur, distp));
        LoopArbiter::Cvvdp(Box::new(judge))
    });
    if SHIFT_RDOQ && loop_state.is_none() {
        loop_state = Some(LoopArbiter::Ssimulacra2(Box::new(
            reference.state(&cur.recon),
        )));
    }
    let mut cur_d = loop_state.as_ref().map_or(f32::NAN, LoopArbiter::deficit);
    let mut cur_map = if SHIFT_RDOQ {
        loop_state.as_ref().expect("shift judge").map()
    } else {
        Vec::new()
    };
    let mut moved = vec![0i8; n_tiles];

    let mut cached_slope = 0f32;
    // Under the ColorVideoVDP arbiter its own exchange rate, from the same
    // shift evaluations, prices every decision it arbitrates.
    let mut cv_slope = 0f32;
    // The coefficient polish also judges on ColorVideoVDP; its exchange rate
    // comes from the same uniform shifts as the loop's.
    let polish_wanted = ctx.speed.effort().coef_polish()
        && ctx.arbiter == Arbiter::Ssimulacra2
        && ctx.coding.is_xyb();
    let mut polish_cv = polish_wanted
        .then(|| crate::cvvdp_arbiter::CvvdpArbiter::new(opsin))
        .flatten();
    let mut polish_cv_slope = 0f32;
    let mut polish_cv_inputs = None;
    let mut cached_moves: Vec<(f32, usize, i8)> = Vec::new();
    let mut accepted_moves: Vec<(usize, i8)> = Vec::new();
    // Moves the exact arbiter already rejected are not tried again: later
    // iterations rejected them again at the cost of half the evaluations.
    let mut rejected_moves: std::collections::HashSet<(usize, i8)> = Default::default();
    // Allocate the greedy scratch after the full-frame marginal evaluations.
    let mut greedy_eval = None;
    for iter in 0..MAX_ITERS {
        // Later iterations reuse the first iteration's marginals: the greedy
        // pass arbitrates every candidate exactly, so only the ranking is stale.
        let (slope, moves): (f32, Vec<(f32, usize, i8)>) = if iter > 0 {
            let moves: Vec<(f32, usize, i8)> = cached_moves
                .iter()
                .filter(|&&(_, t, step)| {
                    if step > 0 {
                        moved[t] < MAX_ABS_MOVE
                    } else {
                        moved[t] > -MAX_ABS_MOVE
                    }
                })
                .filter(|&&(_, t, step)| !accepted_moves.contains(&(t, step)))
                .filter(|&&(_, t, step)| !rejected_moves.contains(&(t, step)))
                .copied()
                .collect();
            (cached_slope, moves)
        } else {
            // Marginals and exchange rate from a plain-quantization triple: the
            // current field, the whole field one step finer, and every other
            // group one step coarser (half an evaluation; the ratio of two
            // half-frame deltas is unbiased). The one-sided finer chord
            // undervalues the tangent of a convex curve, so the two chords are
            // averaged.
            let plain = if SHIFT_RDOQ {
                cur.clone()
            } else {
                let mut e = new_eval();
                evaluate(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    dc_datas,
                    ac_tasks,
                    group_coords,
                    num_passes,
                    coeff_shifts,
                    coeff_orders,
                    &[],
                    ytob_dc,
                    qf_threshold,
                    None,
                    &all_tasks,
                    None,
                    &mut e,
                );
                e
            };
            let r_p = rate_term(frame_bits(&plain));
            let shift_prices = SHIFT_RDOQ.then_some(prices);
            let (_, saved) = apply(dc_datas, &all_moves(1));
            let mut fine = new_eval();
            evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                distp,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                &[],
                ytob_dc,
                qf_threshold,
                shift_prices,
                &all_tasks,
                None,
                &mut fine,
            );
            restore(dc_datas, saved);
            let r_f = rate_term(frame_bits(&fine));
            if r_f - r_p < 1e-3 {
                break;
            }
            // Score one full-frame workspace at a time. Retain only tile
            // summaries, then reuse the plain evaluation for the coarse arm.
            // Each score and token reduction is identical to the independent
            // full-frame comparisons; only their storage lifetimes change.
            let (d_p, map_p) = if SHIFT_RDOQ {
                (cur_d, cur_map.clone())
            } else {
                reference.deficit_and_map(&plain.recon)
            };
            let map_0 = tile_sums(&map_p);
            drop(map_p);
            let d_f = reference.deficit(&fine.recon);
            let bits_f = tile_bits(&block_bits(&fine));
            let bits_0 = tile_bits(&block_bits(&plain));
            let cv_pf = loop_state
                .as_mut()
                .and_then(LoopArbiter::cvvdp)
                .map(|judge| {
                    [&plain, &fine].map(|e| judge.deficit_of(&e.recon, &decoded_dc(e, distp)))
                });
            let pcv_pf = polish_cv.as_mut().map(|judge| {
                // The shift trials and the settled polish share the same source.
                let mut means = Image3F::new(xb, yb);
                for c in 0..3 {
                    for by in 0..yb {
                        let rows = by * K_BLOCK_DIM..((by + 1) * K_BLOCK_DIM).min(h);
                        let n_rows = rows.len() as f32;
                        for (bx, mean) in means.plane_row_mut(c, by).iter_mut().enumerate() {
                            let cols = bx * K_BLOCK_DIM..((bx + 1) * K_BLOCK_DIM).min(w);
                            let n = n_rows * cols.len() as f32;
                            let sum: f32 = rows
                                .clone()
                                .map(|y| opsin.plane_row(c, y)[cols.clone()].iter().sum::<f32>())
                                .sum();
                            *mean = sum / n;
                        }
                    }
                }
                let scores = [&plain, &fine]
                    .map(|e| judge.deficit_of(&e.recon, &legacy_dc(e, distp, &means)));
                (scores, means)
            });
            drop(fine);
            // The coarser shift covers half the groups (slope estimate only).
            let half_tasks: Vec<usize> = (0..ac_tasks.len()).step_by(2).collect();
            let half_moves: Vec<(usize, i8)> = (0..n_tiles)
                .filter(|&t| {
                    let (bx, by) = tile_blocks(t)[0];
                    half_tasks.contains(&task_of_block[by * xb + bx])
                })
                .map(|t| (t, -1))
                .collect();
            let (_, saved) = apply(dc_datas, &half_moves);
            let mut coarse = plain;
            evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                distp,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                &[],
                ytob_dc,
                qf_threshold,
                shift_prices,
                &half_tasks,
                None,
                &mut coarse,
            );
            restore(dc_datas, saved);
            let r_c = rate_term(frame_bits(&coarse));
            let d_c = reference.deficit(&coarse.recon);
            let s_fine = (d_p - d_f) / (r_f - r_p);
            let s_coarse = if r_p - r_c > 1e-3 {
                (d_c - d_p) / (r_p - r_c)
            } else {
                s_fine
            };
            let slope = SLOPE_SCALE * 0.5 * (s_fine + s_coarse);
            if !(slope.is_finite() && slope > 0.0) {
                break;
            }
            let mut cv_flat = false;
            if let Some([cv_p, cv_f]) = cv_pf {
                let judge = loop_state
                    .as_mut()
                    .and_then(LoopArbiter::cvvdp)
                    .expect("CV judge");
                let cv_c = judge.deficit_of(&coarse.recon, &decoded_dc(&coarse, distp));
                let s_fine = (cv_p - cv_f) / (r_f - r_p);
                let s_coarse = if r_p - r_c > 1e-3 {
                    (cv_c - cv_p) / (r_p - r_c)
                } else {
                    s_fine
                };
                cv_slope = SLOPE_SCALE * 0.5 * (s_fine + s_coarse);
                cv_flat = !(cv_slope.is_finite() && cv_slope > 0.0);
            }
            if let (Some(([cv_p, cv_f], means)), Some(mut judge)) = (pcv_pf, polish_cv.take()) {
                let cv_c = judge.deficit_of(&coarse.recon, &legacy_dc(&coarse, distp, &means));
                let s_fine = (cv_p - cv_f) / (r_f - r_p);
                let s_coarse = if r_p - r_c > 1e-3 {
                    (cv_c - cv_p) / (r_p - r_c)
                } else {
                    s_fine
                };
                polish_cv_slope = SLOPE_SCALE * 0.5 * (s_fine + s_coarse);
                // Near transparency the shifts do not separate. With a usable
                // exchange rate, retain the prepared source for polishing and
                // release the full-frame comparison scratch now.
                if polish_cv_slope.is_finite() && polish_cv_slope > 0.0 {
                    polish_cv_inputs = Some((judge.into_reference(), means));
                }
            }
            drop(coarse);
            // Near transparency ColorVideoVDP no longer separates the shifts;
            // SSIMULACRA2 arbitrates the frame instead of the loop stopping.
            if cv_flat {
                cv_slope = 0.0;
                let state = LoopArbiter::Ssimulacra2(Box::new(reference.state(&cur.recon)));
                cur_d = state.deficit();
                loop_state = Some(state);
            }
            // Per tile: deficit gain (frame units) minus slope times rate cost (%).
            // Only finer moves: coarsening smooth tiles is a blind spot of mean
            // MS-SSIM that SSIMULACRA2 punishes, and edge-difference terms did not
            // close it.
            let mut moves: Vec<(f32, usize, i8)> = Vec::new();
            // The frame's measured deficit change is attributed to tiles in
            // proportion to their share of the current linearized map. The
            // per-tile differences of the finer map carry pooling cross-talk
            // from neighboring tiles and rank worse.
            let sum_map_0: f64 = map_0.iter().sum();
            if sum_map_0 <= 0.0 {
                break;
            }
            for t in 0..n_tiles {
                let gain = ((map_0[t] / sum_map_0) * f64::from(d_p - d_f)) as f32;
                let rate = 100.0 * (bits_f[t] - bits_0[t]) / ref_bits;
                let net = gain - slope * rate;
                if net > 1e-7 && moved[t] < MAX_ABS_MOVE {
                    moves.push((net, t, 1));
                }
            }
            moves.sort_by(|a, b| b.0.total_cmp(&a.0));
            moves.truncate(((MAX_MOVE_FRACTION * n_tiles as f32) as usize).max(1));
            cached_slope = slope;
            cached_moves = moves.clone();
            (slope, moves)
        };
        if loop_state.is_none() {
            let state = LoopArbiter::Ssimulacra2(Box::new(reference.state(&cur.recon)));
            cur_d = state.deficit();
            loop_state = Some(state);
        }
        if moves.is_empty() {
            break;
        }
        // Pixels and DC follow `cur`; evaluated tasks replace their tokens.
        let cand = greedy_eval.get_or_insert_with(|| trial_eval(&cur));
        // Moves are ranked on SSIMULACRA2 marginals and accepted on the judge's.
        let slope = if loop_state.as_ref().is_some_and(LoopArbiter::needs_dc) {
            cv_slope
        } else {
            slope
        };
        let mut j_cur = -cur_d - slope * rate_term(cur_bits);
        let mut accepted = false;
        // Evaluate the top candidates one at a time with the real metric.
        // The state follows every accepted move exactly, so it is built once.
        let state = loop_state.as_mut().expect("loop judge");
        // Tokens and starts are overwritten by the next evaluation. Restore
        // only DC and pixels on rejection; move the token buffers on acceptance.
        let sync_tasks =
            |from: &Eval, to: &mut Eval, tasks: &[usize], r: crate::ssimulacra2::Rect| {
                for &task in tasks {
                    to.quant_dc[task] = from.quant_dc[task].clone();
                    to.source_dc[task] = from.source_dc[task].clone();
                    to.synced[task] = from.synced[task];
                }
                for c in 0..3 {
                    for y in r.y0..r.y1 {
                        to.recon.plane_row_mut(c, y)[r.x0..r.x1]
                            .copy_from_slice(&from.recon.plane_row(c, y)[r.x0..r.x1]);
                    }
                }
            };
        let group_bits = |e: &Eval, task: usize| -> f32 {
            e.pending[task].as_ref().map_or(0.0, |p| {
                p.tokens[0].iter().map(|k| prices.token_bits(k)).sum()
            })
        };
        // The incumbent only changes on acceptance. Preserve each reduction's
        // exact f32 order, but do not repeat it for every rejected trial.
        let mut cur_gbits: Vec<f32> = (0..ac_tasks.len()).map(|t| group_bits(&cur, t)).collect();
        let mut cand_gbits = vec![0.0; ac_tasks.len()];
        // Rounds: candidates in distinct AC groups are re-encoded together in
        // one parallel pass, then arbitrated one by one with the exact metric.
        // At most `per_group` candidates per AC group per iteration: each extra
        // candidate in a group costs another serial round (one group encode).
        let mut per_group_count = vec![0usize; ac_tasks.len()];
        let mut aq_checkpoint = state.checkpoint();
        let mut remaining: Vec<(usize, i8)> = moves
            .iter()
            .take(GREEDY)
            .map(|m| (m.1, m.2))
            .filter(|&(t, _)| {
                let (bx, by) = tile_blocks(t)[0];
                let task = task_of_block[by * xb + bx];
                per_group_count[task] += 1;
                per_group_count[task] <= PER_GROUP
            })
            .collect();
        while !remaining.is_empty() {
            let mut round: Vec<(usize, i8, Vec<usize>, Saved)> = Vec::new();
            let mut used_tasks: Vec<usize> = Vec::new();
            let mut deferred = Vec::new();
            for &(t, step) in &remaining {
                let (bx, by) = tile_blocks(t)[0];
                let task = task_of_block[by * xb + bx];
                if used_tasks.contains(&task) {
                    deferred.push((t, step));
                    continue;
                }
                let (tasks, saved) = apply(dc_datas, &[(t, step)]);
                used_tasks.extend(tasks.iter().copied());
                round.push((t, step, tasks, saved));
            }
            remaining = deferred;
            let round_tasks: Vec<usize> = round.iter().flat_map(|r| r.2.iter().copied()).collect();
            compact_memos(&round_tasks);
            let dirty = evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                distp,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                order_alternatives,
                ytob_dc,
                qf_threshold,
                Some(prices),
                &round_tasks,
                memo,
                cand,
            );
            for (t, step, tasks, saved) in round {
                let mut region = crate::ssimulacra2::Rect {
                    x0: usize::MAX,
                    y0: usize::MAX,
                    x1: 0,
                    y1: 0,
                };
                let mut delta_bits = 0f32;
                for &task in &tasks {
                    // pixels the re-encode changed: the cells it recomputed
                    let r = dirty[round_tasks
                        .iter()
                        .position(|&x| x == task)
                        .expect("round task")];
                    if r.x1 > r.x0 {
                        region.x0 = region.x0.min(r.x0);
                        region.y0 = region.y0.min(r.y0);
                        region.x1 = region.x1.max(r.x1);
                        region.y1 = region.y1.max(r.y1);
                    }
                    cand_gbits[task] = group_bits(cand, task);
                    delta_bits += cand_gbits[task] - cur_gbits[task];
                }
                let d = if region.x1 > 0 {
                    let dc = state.needs_dc().then(|| {
                        let out = trial_dc.get_or_insert_with(|| Image3F::new(xb, yb));
                        fill_decoded_dc(cand, distp, region, out);
                        &*out
                    });
                    state.update_checkpointed(&cand.recon, dc, region, &mut aq_checkpoint)
                } else {
                    cur_d
                };
                let bits = cur_bits + delta_bits;
                let j = -d - slope * rate_term(bits);
                let region = if region.x1 > 0 {
                    region
                } else {
                    crate::ssimulacra2::Rect {
                        x0: 0,
                        y0: 0,
                        x1: 0,
                        y1: 0,
                    }
                };
                if j > j_cur + 1e-7 {
                    moved[t] += step;
                    accepted_moves.push((t, step));
                    for &task in &tasks {
                        std::mem::swap(&mut cand.pending[task], &mut cur.pending[task]);
                        std::mem::swap(&mut cand.starts[task], &mut cur.starts[task]);
                        cur_gbits[task] = cand_gbits[task];
                    }
                    sync_tasks(cand, &mut cur, &tasks, region);
                    cur_bits = bits;
                    cur_d = d;
                    j_cur = j;
                    accepted = true;
                } else {
                    if region.x1 > 0 {
                        state.rollback(&aq_checkpoint);
                    }
                    rejected_moves.insert((t, step));
                    sync_tasks(&cur, cand, &tasks, region);
                    restore(dc_datas, saved);
                }
            }
        }
        // exact frame bits after the round's approximate per-group deltas
        cur_bits = frame_bits(&cur);
        if SHIFT_RDOQ {
            cur_map = state.map();
        }
        if !accepted {
            break;
        }
    }
    drop(greedy_eval);
    drop(cur_map);
    drop(polish_cv);
    // ---- 128-family placement arbitrated by the loop's target ----
    // Each 128x128 site tries the 128 layouts (rect halves, rect pairs, the
    // square) on top of the current frame, re-encoded exactly (block memo,
    // frozen prices) and arbitrated by the incremental SSIMULACRA2 state at the
    // loop's exchange rate. One site per AC group is encoded per parallel round.
    if ctx.speed.effort().dct128_loop() && cached_slope > 0.0 {
        use crate::dc_group_data::{
            AcStrategyImage, STRATEGY_DCT64X128, STRATEGY_DCT128X64, STRATEGY_DCT128X128,
        };
        /// Incumbent bits per pixel of a variant's region above which no 128
        /// layout paid.
        const MAX_INCUMBENT_BPP: f32 = 1.0;
        // (strategy, dx, dy) parts of each variant, site-relative in blocks,
        // and the region (x, y, w, h) it covers. Halves come first: a pair is
        // tried only if both its halves gain, the square only if any half does.
        type Variant = (&'static [(u8, usize, usize)], (usize, usize, usize, usize));
        const HALVES: [Variant; 4] = [
            (&[(STRATEGY_DCT128X64, 0, 0)], (0, 0, 8, 16)),
            (&[(STRATEGY_DCT128X64, 8, 0)], (8, 0, 8, 16)),
            (&[(STRATEGY_DCT64X128, 0, 0)], (0, 0, 16, 8)),
            (&[(STRATEGY_DCT64X128, 0, 8)], (0, 8, 16, 8)),
        ];
        const WHOLE: (usize, usize, usize, usize) = (0, 0, 16, 16);
        const PAIRS: [(Variant, [usize; 2]); 2] = [
            (
                (
                    &[(STRATEGY_DCT128X64, 0, 0), (STRATEGY_DCT128X64, 8, 0)],
                    WHOLE,
                ),
                [0, 1],
            ),
            (
                (
                    &[(STRATEGY_DCT64X128, 0, 0), (STRATEGY_DCT64X128, 0, 8)],
                    WHOLE,
                ),
                [2, 3],
            ),
        ];
        const SQUARE: Variant = (&[(STRATEGY_DCT128X128, 0, 0)], WHOLE);

        let slope = if loop_state.as_ref().is_some_and(LoopArbiter::needs_dc) {
            cv_slope
        } else {
            cached_slope
        };
        let state = loop_state.as_mut().expect("loop judge");
        let mut checkpoint = state.checkpoint();
        let mut cand = trial_eval(&cur);
        let mut j_cur = -cur_d - slope * rate_term(cur_bits);
        // Sites of each AC task, DC-group-local block coordinates.
        let sites: Vec<Vec<(usize, usize)>> = ac_tasks
            .iter()
            .map(|&(dc_idx, gx, gy)| {
                let strategy = &dc_datas[dc_idx].ac_strategy;
                let mut v = Vec::new();
                for sy in [0, 16] {
                    for sx in [0, 16] {
                        let x = gx * K_GROUP_DIM_IN_BLOCKS + sx;
                        let y = gy * K_GROUP_DIM_IN_BLOCKS + sy;
                        if strategy.can_place_strategy(x, y, STRATEGY_DCT128X128) {
                            v.push((x, y));
                        }
                    }
                }
                v
            })
            .collect();
        /// What placing a variant overwrote: layout, field and memo of the site.
        struct Placed {
            task: usize,
            site: (usize, usize),
            cells: Vec<u8>,
            field: Vec<u8>,
            memo: Option<crate::group::MemoSnapshot>,
            memo_was_empty: bool,
        }
        let distance = distp.distance;
        let place = |dc_datas: &mut [DcGroupData],
                     task: usize,
                     (x, y): (usize, usize),
                     parts: &[(u8, usize, usize)]|
         -> Placed {
            let (dc_idx, gx, gy) = ac_tasks[task];
            let data = &mut dc_datas[dc_idx];
            let cells = data.ac_strategy.save_region(x, y, 16, 16);
            let field: Vec<u8> = (y..y + 16)
                .flat_map(|r| data.raw_quant_field.row(r)[x..x + 16].to_vec())
                .collect();
            for &(s, dx, dy) in parts {
                let (px, py) = (x + dx, y + dy);
                data.ac_strategy.set_first(px, py, s);
                let w = AcStrategyImage::covered_blocks_x_of(s);
                let h = AcStrategyImage::covered_blocks_y_of(s);
                let (mut max_q, mut sum) = (0u8, 0u32);
                for r in py..py + h {
                    for &q in &data.raw_quant_field.row(r)[px..px + w] {
                        max_q = max_q.max(q);
                        sum += u32::from(q);
                    }
                }
                let q = crate::ac_strategy::aggregate_quant(max_q, sum, w * h, distance);
                for r in py..py + h {
                    data.raw_quant_field.row_mut(r)[px..px + w].fill(q);
                }
            }
            // The memo keys do not carry the layout: forget the new
            // transforms' cells, and keep the rest for an exact undo. An
            // empty memo is filled under the trial layout: undo empties it.
            let memo_was_empty =
                memo.is_some_and(|memo| memo[task].lock().expect("block memo").is_none());
            let memo_snapshot = memo.and_then(|memo| {
                let mut guard = memo[task].lock().expect("block memo");
                let m = guard.as_mut()?;
                m.compact_tokens();
                let (lx, ly) = (
                    x - gx * K_GROUP_DIM_IN_BLOCKS,
                    y - gy * K_GROUP_DIM_IN_BLOCKS,
                );
                let snapshot = m.snapshot(lx, ly, 16, 16);
                for &(s, dx, dy) in parts {
                    m.invalidate(
                        lx + dx,
                        ly + dy,
                        AcStrategyImage::covered_blocks_x_of(s),
                        AcStrategyImage::covered_blocks_y_of(s),
                    );
                }
                Some(snapshot)
            });
            Placed {
                task,
                site: (x, y),
                cells,
                field,
                memo: memo_snapshot,
                memo_was_empty,
            }
        };
        let unplace = |dc_datas: &mut [DcGroupData], p: Placed| {
            let (dc_idx, _, _) = ac_tasks[p.task];
            let data = &mut dc_datas[dc_idx];
            let (x, y) = p.site;
            data.ac_strategy.restore_region(x, y, 16, &p.cells);
            for (i, row) in p.field.as_chunks::<16>().0.iter().enumerate() {
                data.raw_quant_field.row_mut(y + i)[x..x + 16].copy_from_slice(row);
            }
            if let Some(memo) = memo {
                let mut slot = memo[p.task].lock().expect("block memo");
                if p.memo_was_empty {
                    *slot = None;
                } else if let (Some(m), Some(snapshot)) = (slot.as_mut(), &p.memo) {
                    m.restore(snapshot);
                }
            }
        };
        let group_bits = |e: &Eval, task: usize| -> f32 {
            e.pending[task].as_ref().map_or(0.0, |p| {
                p.tokens[0].iter().map(|k| prices.token_bits(k)).sum()
            })
        };
        let mut cur_gbits: Vec<f32> = (0..ac_tasks.len()).map(|t| group_bits(&cur, t)).collect();
        let sync_task = |from: &Eval, to: &mut Eval, task: usize, r: crate::ssimulacra2::Rect| {
            to.quant_dc[task] = from.quant_dc[task].clone();
            to.source_dc[task] = from.source_dc[task].clone();
            to.synced[task] = from.synced[task];
            for c in 0..3 {
                for y in r.y0..r.y1 {
                    to.recon.plane_row_mut(c, y)[r.x0..r.x1]
                        .copy_from_slice(&from.recon.plane_row(c, y)[r.x0..r.x1]);
                }
            }
        };
        let mut accepted_sites: Vec<(usize, (usize, usize))> = Vec::new();
        let max_sites = sites.iter().map(Vec::len).max().unwrap_or(0);
        for si in 0..max_sites {
            let active: Vec<usize> = (0..ac_tasks.len())
                .filter(|&t| si < sites[t].len())
                .collect();
            let incumbent_bits = block_bits(&cur);
            let region_bpp = |t: usize, (rx, ry, rw, rh): (usize, usize, usize, usize)| {
                let (dc_gx, dc_gy) = group_coords[ac_tasks[t].0];
                let (x, y) = sites[t][si];
                let (x0, y0) = (
                    dc_gx * blocks_per_dc + x + rx,
                    dc_gy * blocks_per_dc + y + ry,
                );
                let bits: f32 = (y0..y0 + rh)
                    .map(|by| {
                        incumbent_bits[by * xb + x0..by * xb + x0 + rw]
                            .iter()
                            .sum::<f32>()
                    })
                    .sum();
                bits / (rw * rh * 64) as f32
            };
            // J of each half per task; the best variant and its J per task.
            let mut half_j = vec![[f32::NEG_INFINITY; 4]; ac_tasks.len()];
            let mut best: Vec<(f32, Option<Variant>)> = vec![(j_cur, None); ac_tasks.len()];
            // Evaluate `variant` at the tasks `keep` admits; returns each J.
            let mut try_variant = |dc_datas: &mut [DcGroupData],
                                   scratch: &mut CoderScratch,
                                   variant: Variant,
                                   keep: &dyn Fn(usize) -> bool|
             -> Vec<(usize, f32)> {
                let tasks: Vec<usize> = active
                    .iter()
                    .copied()
                    .filter(|&t| {
                        let (x, y) = sites[t][si];
                        let (rx, ry, rw, rh) = variant.1;
                        keep(t)
                            && dc_datas[ac_tasks[t].0].ac_strategy.region_closed(
                                x + rx,
                                y + ry,
                                rw,
                                rh,
                            )
                            && region_bpp(t, variant.1) <= MAX_INCUMBENT_BPP
                    })
                    .collect();
                if tasks.is_empty() {
                    return Vec::new();
                }
                let placed: Vec<Placed> = tasks
                    .iter()
                    .map(|&t| place(dc_datas, t, sites[t][si], variant.0))
                    .collect();
                let dirty = evaluate(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    dc_datas,
                    ac_tasks,
                    group_coords,
                    num_passes,
                    coeff_shifts,
                    coeff_orders,
                    order_alternatives,
                    ytob_dc,
                    qf_threshold,
                    Some(prices),
                    &tasks,
                    memo,
                    &mut cand,
                );
                let mut out = Vec::with_capacity(tasks.len());
                for (k, &t) in tasks.iter().enumerate() {
                    let r = dirty[k];
                    let d = if r.x1 > r.x0 {
                        let dc = state.needs_dc().then(|| {
                            let out = trial_dc.get_or_insert_with(|| Image3F::new(xb, yb));
                            fill_decoded_dc(&cand, distp, r, out);
                            &*out
                        });
                        let d = state.update_checkpointed(&cand.recon, dc, r, &mut checkpoint);
                        state.rollback(&checkpoint);
                        d
                    } else {
                        cur_d
                    };
                    let bits = cur_bits + group_bits(&cand, t) - cur_gbits[t];
                    out.push((t, -d - slope * rate_term(bits)));
                    sync_task(&cur, &mut cand, t, r);
                }
                for p in placed {
                    unplace(dc_datas, p);
                }
                out
            };
            for (h, half) in HALVES.iter().enumerate() {
                for (t, j) in try_variant(dc_datas, scratch, *half, &|_| true) {
                    half_j[t][h] = j;
                    if j > best[t].0 + 1e-7 {
                        best[t] = (j, Some(*half));
                    }
                }
            }
            for (pair, [a, b]) in PAIRS {
                let keep = |t: usize| half_j[t][a] > j_cur && half_j[t][b] > j_cur;
                for (t, j) in try_variant(dc_datas, scratch, pair, &keep) {
                    if j > best[t].0 + 1e-7 {
                        best[t] = (j, Some(pair));
                    }
                }
            }
            let keep = |t: usize| half_j[t].iter().any(|&j| j > j_cur);
            for (t, j) in try_variant(dc_datas, scratch, SQUARE, &keep) {
                if j > best[t].0 + 1e-7 {
                    best[t] = (j, Some(SQUARE));
                }
            }
            // Commit each task's winner, re-encode them together and accept
            // them one at a time on the running state.
            let winners: Vec<(usize, Variant)> = active
                .iter()
                .filter_map(|&t| best[t].1.map(|v| (t, v)))
                .collect();
            if winners.is_empty() {
                continue;
            }
            let placed: Vec<Placed> = winners
                .iter()
                .map(|&(t, v)| place(dc_datas, t, sites[t][si], v.0))
                .collect();
            let tasks: Vec<usize> = winners.iter().map(|w| w.0).collect();
            let dirty = evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                distp,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                order_alternatives,
                ytob_dc,
                qf_threshold,
                Some(prices),
                &tasks,
                memo,
                &mut cand,
            );
            for ((k, &t), p) in tasks.iter().enumerate().zip(placed) {
                let r = dirty[k];
                let d = if r.x1 > r.x0 {
                    let dc = state.needs_dc().then(|| {
                        let out = trial_dc.get_or_insert_with(|| Image3F::new(xb, yb));
                        fill_decoded_dc(&cand, distp, r, out);
                        &*out
                    });
                    state.update_checkpointed(&cand.recon, dc, r, &mut checkpoint)
                } else {
                    cur_d
                };
                let cand_gbits = group_bits(&cand, t);
                let bits = cur_bits + cand_gbits - cur_gbits[t];
                let j = -d - slope * rate_term(bits);
                if j > j_cur + 1e-7 {
                    std::mem::swap(&mut cand.pending[t], &mut cur.pending[t]);
                    std::mem::swap(&mut cand.starts[t], &mut cur.starts[t]);
                    sync_task(&cand, &mut cur, t, r);
                    cur_gbits[t] = cand_gbits;
                    cur_bits = bits;
                    cur_d = d;
                    j_cur = j;
                    accepted_sites.push((t, p.site));
                } else {
                    if r.x1 > r.x0 {
                        state.rollback(&checkpoint);
                    }
                    sync_task(&cur, &mut cand, t, r);
                    unplace(dc_datas, p);
                }
            }
        }
        // The chroma DC passes after the loop read the retained source DC,
        // which depends on the layout (a large transform's DC comes from its
        // lowest frequencies): recapture it under the accepted sites.
        let mut refresh: Vec<usize> = accepted_sites.iter().map(|a| a.0).collect();
        refresh.sort_unstable();
        refresh.dedup();
        let sources = ctx
            .thread_pool
            .steal_map(scratch, refresh.len(), |i, scratch| {
                let (dc_idx, gx, gy) = ac_tasks[refresh[i]];
                let (dc_gx, dc_gy) = group_coords[dc_idx];
                let (_, _, source, _, _) = process_ac_group(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    &dc_datas[dc_idx],
                    num_passes,
                    coeff_shifts,
                    dc_gx,
                    dc_gy,
                    gx,
                    gy,
                    ytob_dc,
                    None,
                    coeff_orders,
                    &[],
                    true,
                    qf_threshold,
                    AcGroupCapture::None,
                    None,
                );
                source.expect("source dc")
            });
        for (&task, source) in refresh.iter().zip(sources) {
            let (dc_idx, gx, gy) = ac_tasks[task];
            let (ox, oy) = (gx * K_GROUP_DIM_IN_BLOCKS, gy * K_GROUP_DIM_IN_BLOCKS);
            let dc = &mut dc_datas[dc_idx];
            for &(_, (x, y)) in accepted_sites.iter().filter(|a| a.0 == task) {
                for (target, src) in [
                    (&mut dc.source_dc_y, &source.y),
                    (&mut dc.source_dc_b, &source.b),
                    (&mut dc.source_dc_x, &source.x),
                ] {
                    if let Some(target) = target.as_mut() {
                        for r in y..y + 16 {
                            target.row_mut(r)[x..x + 16]
                                .copy_from_slice(&src.row(r - oy)[x - ox..x - ox + 16]);
                        }
                    }
                }
            }
        }
        cur_bits = frame_bits(&cur);
    }
    // ---- 16x16 layouts arbitrated by the loop's target ----
    // Every closed 2x2-block site (no transform crosses it) tries the other
    // layouts of its family: four DCT8, DCT16X16 and the two rectangle pairs.
    // Each is re-encoded exactly (block memo, frozen prices; cached blocks
    // contribute their stored bits instead of their tokens) and arbitrated by the
    // incremental SSIMULACRA2 state at the loop's exchange rate. One site per
    // AC group per parallel round; the best variant is re-encoded in full and
    // kept if it still improves.
    if ctx.speed.effort().layout_loop() && cached_slope > 0.0 {
        use crate::dc_group_data::{
            AcStrategyImage, NUM_STRATEGIES, STRATEGY_DCT8X16, STRATEGY_DCT16X8, STRATEGY_DCT16X16,
        };
        type Parts = Vec<(u8, usize, usize)>;
        let cv_judged = loop_state.as_ref().is_some_and(LoopArbiter::needs_dc);
        let slope = if cv_judged { cv_slope } else { cached_slope };
        let state = loop_state.as_mut().expect("loop judge");
        let mut checkpoint = state.checkpoint();
        let mut cand = trial_eval(&cur);
        let mut j_cur = -cur_d - slope * rate_term(cur_bits);
        // Only layouts whose classes the frame already uses (matrices, orders).
        let class = |st: usize| {
            (
                crate::quant_weights::quant_table_slot_of(st as u8),
                crate::ac_context::K_STRATEGY_ORDER
                    [crate::dc_group_data::STRATEGY_CODE_LUT[st] as usize],
            )
        };
        let mut used = [false; NUM_STRATEGIES];
        for d in dc_datas.iter() {
            for (_, _, st) in d.ac_strategy.iter_first_blocks() {
                used[st as usize] = true;
            }
        }
        // A transpose shares both classes with the transform the frame uses.
        let present: [bool; NUM_STRATEGIES] = std::array::from_fn(|st| {
            used[st]
                || class(st).0.is_some()
                    && (0..NUM_STRATEGIES).any(|o| used[o] && class(o) == class(st))
        });
        let mut variants: Vec<Parts> = vec![vec![
            (STRATEGY_DCT, 0, 0),
            (STRATEGY_DCT, 1, 0),
            (STRATEGY_DCT, 0, 1),
            (STRATEGY_DCT, 1, 1),
        ]];
        if present[STRATEGY_DCT16X16 as usize] {
            variants.push(vec![(STRATEGY_DCT16X16, 0, 0)]);
        }
        if present[STRATEGY_DCT16X8 as usize] {
            variants.push(vec![(STRATEGY_DCT16X8, 0, 0), (STRATEGY_DCT16X8, 1, 0)]);
        }
        if present[STRATEGY_DCT8X16 as usize] {
            variants.push(vec![(STRATEGY_DCT8X16, 0, 0), (STRATEGY_DCT8X16, 0, 1)]);
        }
        /// A region the loop re-chooses: a 2x2 site with the 16x16-family
        /// variants, or a region the exact re-tiling proposed, with that
        /// proposal as its only variant.
        struct Site {
            x: usize,
            y: usize,
            w: usize,
            h: usize,
            proposal: Option<Parts>,
        }
        // Sites of each AC task, DC-group-local block coordinates: the
        // aligned 2x2 grid, the three odd-offset grids (the format allows
        // unaligned blocks; none may cross a 64px CfL tile), then the
        // proposed regions, judged against the refined layout.
        let sites: Vec<Vec<Site>> = ac_tasks
            .iter()
            .map(|&(dc_idx, gx, gy)| {
                let st = &dc_datas[dc_idx].ac_strategy;
                let mut v = Vec::new();
                for (px, py) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
                    for sy in (py..K_GROUP_DIM_IN_BLOCKS - 1).step_by(2) {
                        for sx in (px..K_GROUP_DIM_IN_BLOCKS - 1).step_by(2) {
                            if sx % K_TILE_DIM_IN_BLOCKS == K_TILE_DIM_IN_BLOCKS - 1
                                || sy % K_TILE_DIM_IN_BLOCKS == K_TILE_DIM_IN_BLOCKS - 1
                            {
                                continue;
                            }
                            let x = gx * K_GROUP_DIM_IN_BLOCKS + sx;
                            let y = gy * K_GROUP_DIM_IN_BLOCKS + sy;
                            if x + 2 <= st.xsize() && y + 2 <= st.ysize() {
                                v.push(Site {
                                    x,
                                    y,
                                    w: 2,
                                    h: 2,
                                    proposal: None,
                                });
                            }
                        }
                    }
                }
                for region in &dc_datas[dc_idx].dp_regions {
                    let inside = region.bx / K_GROUP_DIM_IN_BLOCKS == gx
                        && region.by / K_GROUP_DIM_IN_BLOCKS == gy;
                    if inside && region.pieces.iter().all(|&(st, _, _)| present[st as usize]) {
                        v.push(Site {
                            x: region.bx,
                            y: region.by,
                            w: region.w,
                            h: region.h,
                            proposal: Some(region.pieces.clone()),
                        });
                    }
                }
                v
            })
            .collect();
        // The current layout of a closed site, sorted like `variants`.
        let site_parts = |st: &AcStrategyImage, site: &Site| -> Option<Parts> {
            let mut parts = Vec::new();
            let mut covered = 0;
            for dy in 0..site.h {
                for dx in 0..site.w {
                    if st.is_first_block(site.x + dx, site.y + dy) {
                        let raw = st.raw_strategy(site.x + dx, site.y + dy);
                        let cw = AcStrategyImage::covered_blocks_x_of(raw);
                        let ch = AcStrategyImage::covered_blocks_y_of(raw);
                        if dx + cw > site.w || dy + ch > site.h {
                            return None;
                        }
                        covered += cw * ch;
                        parts.push((raw, dx, dy));
                    }
                }
            }
            (covered == site.w * site.h).then_some(parts)
        };
        /// What placing a variant overwrote: layout, field and memo of the site.
        struct Placed {
            task: usize,
            site: (usize, usize),
            size: (usize, usize),
            cells: Vec<u8>,
            field: Vec<u8>,
            memo: Option<crate::group::MemoSnapshot>,
            memo_was_empty: bool,
        }
        let distance = distp.distance;
        let place =
            |dc_datas: &mut [DcGroupData], task: usize, site: &Site, parts: &Parts| -> Placed {
                let (dc_idx, gx, gy) = ac_tasks[task];
                let data = &mut dc_datas[dc_idx];
                let (x, y, w, h) = (site.x, site.y, site.w, site.h);
                let cells = data.ac_strategy.save_region(x, y, w, h);
                let field: Vec<u8> = (y..y + h)
                    .flat_map(|r| data.raw_quant_field.row(r)[x..x + w].to_vec())
                    .collect();
                for &(st, dx, dy) in parts {
                    let (px, py) = (x + dx, y + dy);
                    data.ac_strategy.set_first(px, py, st);
                    let w = AcStrategyImage::covered_blocks_x_of(st);
                    let h = AcStrategyImage::covered_blocks_y_of(st);
                    if w * h > 1 {
                        let (mut max_q, mut sum) = (0u8, 0u32);
                        for r in py..py + h {
                            for &q in &data.raw_quant_field.row(r)[px..px + w] {
                                max_q = max_q.max(q);
                                sum += u32::from(q);
                            }
                        }
                        let q = crate::ac_strategy::aggregate_quant(max_q, sum, w * h, distance);
                        for r in py..py + h {
                            data.raw_quant_field.row_mut(r)[px..px + w].fill(q);
                        }
                    }
                }
                // An empty memo is filled under the trial layout: undo empties it.
                let memo_was_empty =
                    memo.is_some_and(|memo| memo[task].lock().expect("block memo").is_none());
                let memo_snapshot = memo.and_then(|memo| {
                    let mut guard = memo[task].lock().expect("block memo");
                    let m = guard.as_mut()?;
                    m.compact_tokens();
                    let (lx, ly) = (
                        x - gx * K_GROUP_DIM_IN_BLOCKS,
                        y - gy * K_GROUP_DIM_IN_BLOCKS,
                    );
                    let snapshot = m.snapshot(lx, ly, w, h);
                    m.invalidate(lx, ly, w, h);
                    Some(snapshot)
                });
                Placed {
                    task,
                    site: (x, y),
                    size: (w, h),
                    cells,
                    field,
                    memo: memo_snapshot,
                    memo_was_empty,
                }
            };
        let unplace = |dc_datas: &mut [DcGroupData], p: Placed| {
            let (dc_idx, _, _) = ac_tasks[p.task];
            let data = &mut dc_datas[dc_idx];
            let (x, y) = p.site;
            let (w, _) = p.size;
            data.ac_strategy.restore_region(x, y, w, &p.cells);
            for (i, row) in p.field.chunks_exact(w).enumerate() {
                data.raw_quant_field.row_mut(y + i)[x..x + w].copy_from_slice(row);
            }
            if let Some(memo) = memo {
                let mut slot = memo[p.task].lock().expect("block memo");
                if p.memo_was_empty {
                    *slot = None;
                } else if let (Some(m), Some(snapshot)) = (slot.as_mut(), &p.memo) {
                    m.restore(snapshot);
                }
            }
        };
        let group_bits = |e: &Eval, task: usize| -> f32 {
            e.hit_bits[task]
                + e.pending[task].as_ref().map_or(0.0, |p| {
                    p.tokens[0]
                        .iter()
                        .map(|k| prices.token_bits(k))
                        .sum::<f32>()
                })
        };
        // A rejected trial restores only the pixels and the sync point: the
        // task's next evaluation overwrites its tokens.
        let restore_task =
            |from: &Eval, to: &mut Eval, task: usize, r: crate::ssimulacra2::Rect| {
                to.synced[task] = from.synced[task];
                for c in 0..3 {
                    for y in r.y0..r.y1 {
                        to.recon.plane_row_mut(c, y)[r.x0..r.x1]
                            .copy_from_slice(&from.recon.plane_row(c, y)[r.x0..r.x1]);
                    }
                }
            };
        let accept_task =
            |from: &mut Eval, to: &mut Eval, task: usize, r: crate::ssimulacra2::Rect| {
                std::mem::swap(&mut to.pending[task], &mut from.pending[task]);
                std::mem::swap(&mut to.quant_dc[task], &mut from.quant_dc[task]);
                std::mem::swap(&mut to.source_dc[task], &mut from.source_dc[task]);
                std::mem::swap(&mut to.starts[task], &mut from.starts[task]);
                to.synced[task] = from.synced[task];
                for c in 0..3 {
                    for y in r.y0..r.y1 {
                        to.recon.plane_row_mut(c, y)[r.x0..r.x1]
                            .copy_from_slice(&from.recon.plane_row(c, y)[r.x0..r.x1]);
                    }
                }
            };
        let mut cur_gbits: Vec<f32> = (0..ac_tasks.len()).map(|t| group_bits(&cur, t)).collect();
        /// An accepted site: its task, origin and size in blocks.
        type Accepted = (usize, (usize, usize), (usize, usize));
        let mut accepted_sites: Vec<Accepted> = Vec::new();
        let max_sites = sites.iter().map(Vec::len).max().unwrap_or(0);
        for si in 0..max_sites {
            // The variants of each task's site that differ from its layout.
            let vars: Vec<Vec<&Parts>> = (0..ac_tasks.len())
                .map(|t| {
                    let Some(site) = sites[t].get(si) else {
                        return Vec::new();
                    };
                    let st = &dc_datas[ac_tasks[t].0].ac_strategy;
                    let Some(mut current) = site_parts(st, site) else {
                        return Vec::new();
                    };
                    current.sort_unstable();
                    let differs = |v: &Parts| {
                        let mut k = v.clone();
                        k.sort_unstable();
                        k != current
                    };
                    match &site.proposal {
                        Some(proposal) => {
                            if differs(proposal) {
                                vec![proposal]
                            } else {
                                Vec::new()
                            }
                        }
                        None => variants.iter().filter(|v| differs(v)).collect(),
                    }
                })
                .collect();
            let max_v = vars.iter().map(Vec::len).max().unwrap_or(0);
            let mut best: Vec<(f32, Option<usize>)> = vec![(j_cur, None); ac_tasks.len()];
            for vi in 0..max_v {
                let tasks: Vec<usize> = (0..ac_tasks.len())
                    .filter(|&t| vi < vars[t].len())
                    .collect();
                let placed: Vec<Placed> = tasks
                    .iter()
                    .map(|&t| place(dc_datas, t, &sites[t][si], vars[t][vi]))
                    .collect();
                cand.trial = true;
                let dirty = evaluate(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    dc_datas,
                    ac_tasks,
                    group_coords,
                    num_passes,
                    coeff_shifts,
                    coeff_orders,
                    order_alternatives,
                    ytob_dc,
                    qf_threshold,
                    Some(prices),
                    &tasks,
                    memo,
                    &mut cand,
                );
                cand.trial = false;
                for (k, &t) in tasks.iter().enumerate() {
                    let r = dirty[k];
                    let d = if r.x1 > r.x0 {
                        let dc = state.needs_dc().then(|| {
                            let out = trial_dc.get_or_insert_with(|| Image3F::new(xb, yb));
                            fill_decoded_dc(&cand, distp, r, out);
                            &*out
                        });
                        let d = state.update_checkpointed(&cand.recon, dc, r, &mut checkpoint);
                        state.rollback(&checkpoint);
                        d
                    } else {
                        cur_d
                    };
                    let bits = cur_bits + group_bits(&cand, t) - cur_gbits[t];
                    let j = -d - slope * rate_term(bits);
                    if j > best[t].0 + 1e-7 {
                        best[t] = (j, Some(vi));
                    }
                    restore_task(&cur, &mut cand, t, r);
                }
                for p in placed {
                    unplace(dc_datas, p);
                }
            }
            // Commit each task's winner, re-encode them in full and accept
            // them one at a time on the running state.
            let winners: Vec<(usize, usize)> = (0..ac_tasks.len())
                .filter_map(|t| best[t].1.map(|v| (t, v)))
                .collect();
            if winners.is_empty() {
                continue;
            }
            let placed: Vec<Placed> = winners
                .iter()
                .map(|&(t, v)| place(dc_datas, t, &sites[t][si], vars[t][v]))
                .collect();
            let tasks: Vec<usize> = winners.iter().map(|w| w.0).collect();
            let dirty = evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                distp,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                order_alternatives,
                ytob_dc,
                qf_threshold,
                Some(prices),
                &tasks,
                memo,
                &mut cand,
            );
            for ((k, &t), p) in tasks.iter().enumerate().zip(placed) {
                let r = dirty[k];
                let d = if r.x1 > r.x0 {
                    let dc = state.needs_dc().then(|| {
                        let out = trial_dc.get_or_insert_with(|| Image3F::new(xb, yb));
                        fill_decoded_dc(&cand, distp, r, out);
                        &*out
                    });
                    state.update_checkpointed(&cand.recon, dc, r, &mut checkpoint)
                } else {
                    cur_d
                };
                let cand_gbits = group_bits(&cand, t);
                let bits = cur_bits + cand_gbits - cur_gbits[t];
                let j = -d - slope * rate_term(bits);
                if j > j_cur + 1e-7 {
                    accept_task(&mut cand, &mut cur, t, r);
                    cur_gbits[t] = cand_gbits;
                    cur_bits = bits;
                    cur_d = d;
                    j_cur = j;
                    accepted_sites.push((t, p.site, p.size));
                } else {
                    if r.x1 > r.x0 {
                        state.rollback(&checkpoint);
                    }
                    restore_task(&cur, &mut cand, t, r);
                    unplace(dc_datas, p);
                }
            }
        }
        // The chroma DC passes after the loop read the retained source DC,
        // which depends on the layout: recapture it under the accepted sites.
        let mut refresh: Vec<usize> = accepted_sites.iter().map(|a| a.0).collect();
        refresh.sort_unstable();
        refresh.dedup();
        let sources = ctx
            .thread_pool
            .steal_map(scratch, refresh.len(), |i, scratch| {
                let (dc_idx, gx, gy) = ac_tasks[refresh[i]];
                let (dc_gx, dc_gy) = group_coords[dc_idx];
                let (_, _, source, _, _) = process_ac_group(
                    ctx,
                    scratch,
                    opsin,
                    dim,
                    distp,
                    &dc_datas[dc_idx],
                    num_passes,
                    coeff_shifts,
                    dc_gx,
                    dc_gy,
                    gx,
                    gy,
                    ytob_dc,
                    None,
                    coeff_orders,
                    &[],
                    true,
                    qf_threshold,
                    AcGroupCapture::None,
                    None,
                );
                source.expect("source dc")
            });
        for (&task, source) in refresh.iter().zip(sources) {
            let (dc_idx, gx, gy) = ac_tasks[task];
            let (ox, oy) = (gx * K_GROUP_DIM_IN_BLOCKS, gy * K_GROUP_DIM_IN_BLOCKS);
            let dc = &mut dc_datas[dc_idx];
            for &(_, (x, y), (w, h)) in accepted_sites.iter().filter(|a| a.0 == task) {
                for (target, src) in [
                    (&mut dc.source_dc_y, &source.y),
                    (&mut dc.source_dc_b, &source.b),
                    (&mut dc.source_dc_x, &source.x),
                ] {
                    if let Some(target) = target.as_mut() {
                        for r in y..y + h {
                            target.row_mut(r)[x..x + w]
                                .copy_from_slice(&src.row(r - oy)[x - ox..x - ox + w]);
                        }
                    }
                }
            }
        }
        cur_bits = frame_bits(&cur);
    }
    // ---- Frame-level chroma precision race ----
    // The X and B quant-matrix scales are 3-bit header fields set by distance
    // and content gates (higher = finer). A coordinate search, X then B, arbitrates
    // each neighbor of the current pair on the loop's target with a full
    // priced encode; the block memo keys the chroma channels by their scale, so
    // an arm recomputes only the channel it changes.
    let mut distp_out = *distp;
    // Each arbiter races on its own metric and exchange rate.
    let race_slope = if loop_state.as_ref().is_some_and(LoopArbiter::needs_dc) {
        cv_slope
    } else {
        cached_slope
    };
    if race_slope > 0.0 && ctx.coding.is_xyb() {
        let slope = race_slope;
        let b_start = ctx.b_qm_scale();
        // No more regional updates: full-frame comparisons do not read the
        // incremental pyramid, or any accepted evaluation's reconstruction.
        let mut judge = match loop_state.take() {
            Some(LoopArbiter::Cvvdp(mut judge)) => {
                judge.finish_updates();
                Some(judge)
            }
            _ => None,
        };
        if !want_recon {
            cur.recon = Image3F::new(0, 0);
        }
        let mut score = |e: &Eval| -> f32 {
            match judge.as_deref_mut() {
                Some(judge) => judge.deficit_of(&e.recon, &decoded_dc(e, distp)),
                None => reference.deficit(&e.recon),
            }
        };
        let arm_eval = |x: u32, b: u32, scratch: &mut CoderScratch| -> (Eval, f32) {
            let mut dp = *distp;
            dp.x_qm_scale = x;
            ctx.set_b_qm_scale(b);
            let mut e = new_eval();
            compact_memos(&all_tasks);
            evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                &dp,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                order_alternatives,
                ytob_dc,
                qf_threshold,
                Some(prices),
                &all_tasks,
                memo,
                &mut e,
            );
            ctx.set_b_qm_scale(b_start);
            let bits = frame_bits(&e);
            (e, bits)
        };
        let cur_score = cur_d;
        let mut best = (
            -cur_score - slope * rate_term(cur_bits),
            distp.x_qm_scale,
            b_start,
        );
        let mut tried: Vec<(u32, u32)> = vec![(best.1, best.2)];
        let mut best_eval: Option<Eval> = None;
        for coord in 0..2usize {
            for dir in [1i32, -1] {
                loop {
                    let (mut x, mut b) = (best.1 as i32, best.2 as i32);
                    if coord == 0 {
                        x += dir;
                    } else {
                        b += dir;
                    }
                    if !(1..=7).contains(&x) || !(2..=7).contains(&b) {
                        break;
                    }
                    let (x, b) = (x as u32, b as u32);
                    // The reverse direction after a walk re-visits a point already scored.
                    if tried.contains(&(x, b)) {
                        break;
                    }
                    let (mut e, bits) = arm_eval(x, b, scratch);
                    let d = score(&e);
                    let j = -d - slope * rate_term(bits);
                    tried.push((x, b));
                    if j > best.0 + 1e-6 {
                        best = (j, x, b);
                        if !want_recon {
                            e.recon = Image3F::new(0, 0);
                        }
                        best_eval = Some(e);
                    } else {
                        break;
                    }
                }
            }
        }
        if let Some(e) = best_eval {
            cur = e;
            distp_out.x_qm_scale = best.1;
            ctx.set_b_qm_scale(best.2);
        }
    }
    // ---- Decoder-feedback coefficient polish (`coef_polish`) ----
    // The settled frame's levels are revisited coefficient by coefficient
    // against the exact metric states; see `crate::coef_polish`.
    if polish_wanted && race_slope > 0.0 {
        use std::sync::atomic::Ordering;
        use std::sync::{Arc, Mutex};

        drop(loop_state);
        drop(cur);
        let mut e = new_eval();
        e.capture = AcGroupCapture::Pixels;
        let mut rate = prices.adaptive_rate();
        // Once a batch's pixels and DC are synced, retain only its aggregate
        // token counts for the frame rate. Apply the Shannon reduction once.
        let batch_size = ctx.thread_pool.num_threads();
        for tasks in all_tasks.chunks(batch_size) {
            if let Some(memo) = memo {
                for &task in tasks {
                    if let Some(cache) = memo[task].lock().expect("block memo").as_mut() {
                        cache.keep_primary_tokens();
                        cache.compact_tokens();
                    }
                }
            }
            evaluate(
                ctx,
                scratch,
                opsin,
                dim,
                &distp_out,
                dc_datas,
                ac_tasks,
                group_coords,
                num_passes,
                coeff_shifts,
                coeff_orders,
                &[],
                ytob_dc,
                qf_threshold,
                Some(prices),
                tasks,
                memo,
                &mut e,
            );
            for &task in tasks {
                let p = e.pending[task].take().expect("polish baseline tokens");
                rate.add(p.tokens[0].as_slice());
            }
            if let Some(memo) = memo {
                for &task in tasks {
                    *memo[task].lock().expect("block memo") = None;
                }
            }
        }
        let bits0 = rate.bits();
        let recon = std::mem::replace(&mut e.recon, Image3F::new(0, 0));
        let cv_inputs = polish_cv_inputs
            .map(|(reference, means)| (reference, Arc::new(legacy_dc(&e, &distp_out, &means))));
        let cv_lambda = polish_cv_slope * 100.0 / bits0;
        let lambda_bits = race_slope * 100.0 / bits0;
        if let Some(out) = dc_polish {
            out.lambda_bits = lambda_bits;
            out.cv_lambda = cv_lambda;
        }
        drop(e);
        // Every AC group is polished on its own crop of the frame, from the
        // same baseline: the judges' cost and memory do not grow with the
        // frame, every worker has groups to take, and scheduling cannot
        // affect decisions.
        const POLISH_MARGIN: usize = 64;
        crate::coef_polish::POLISH_EPOCH.fetch_add(1, Ordering::Relaxed);
        let area_budget = crate::ac_strategy::content_selection_enabled(ctx, distp.distance);
        let build = |gx: usize, gy: usize| -> Option<Box<crate::coef_polish::CoefPolisher>> {
            let margin = POLISH_MARGIN;
            let x0 = (gx * K_GROUP_DIM).saturating_sub(margin);
            let y0 = (gy * K_GROUP_DIM).saturating_sub(margin);
            let x1 = ((gx + 1) * K_GROUP_DIM + margin).min(w);
            let y1 = ((gy + 1) * K_GROUP_DIM + margin).min(h);
            let source = super::dc_polish::crop(opsin, x0, y0, x1, y1);
            let baseline = Arc::new(super::dc_polish::crop(&recon, x0, y0, x1, y1));
            let state = crate::ssimulacra2::Ssimulacra2Reference::new(&source)?.state(&baseline);
            // Both deficits are means over the judged pixels: a change
            // weighs more in the crop than in the frame the exchange rates
            // were measured on.
            let share = (w * h) as f32 / ((x1 - x0) * (y1 - y0)) as f32;
            let cv = match &cv_inputs {
                Some((_, dc)) => {
                    let dc = Arc::new(super::dc_polish::crop(
                        dc,
                        x0 / 8,
                        y0 / 8,
                        x1.div_ceil(8),
                        y1.div_ceil(8),
                    ));
                    let mut judge = crate::cvvdp_arbiter::CvvdpArbiter::new(&source)?;
                    judge.reset(&baseline, &dc);
                    Some(crate::coef_polish::CvJudge::new(
                        judge,
                        dc,
                        cv_lambda * share,
                    ))
                }
                None => None,
            };
            let mut polisher = crate::coef_polish::CoefPolisher::new(
                baseline,
                state,
                lambda_bits * share,
                cv,
                ctx.add_scaled,
            );
            polisher.set_origin((x0, y0));
            polisher.set_area_budget(area_budget);
            Some(Box::new(polisher))
        };
        // Publish each finished capture immediately. Only the active workers
        // hold group images alongside the optional frame output.
        let output_recon = want_recon.then(|| Mutex::new(None));
        let work = ctx
            .thread_pool
            .steal_map(scratch, all_tasks.len(), |ti, scratch| {
                let mut polished = Vec::with_capacity(1);
                {
                    let t = all_tasks[ti];
                    let (dc_idx, gx, gy) = ac_tasks[t];
                    let (dc_gx, dc_gy) = group_coords[dc_idx];
                    let groups_per_dc = K_DC_GROUP_DIM / K_GROUP_DIM;
                    scratch.ac_group.polisher =
                        build(dc_gx * groups_per_dc + gx, dc_gy * groups_per_dc + gy);
                    let (p, local, _, _, capture) = process_ac_group(
                        ctx,
                        scratch,
                        opsin,
                        dim,
                        &distp_out,
                        &dc_datas[dc_idx],
                        num_passes,
                        coeff_shifts,
                        dc_gx,
                        dc_gy,
                        gx,
                        gy,
                        ytob_dc,
                        Some(prices),
                        coeff_orders,
                        order_alternatives,
                        false,
                        qf_threshold,
                        AcGroupCapture::Pixels,
                        None,
                    );
                    if let (Some(target), Some((image, _))) = (&output_recon, capture) {
                        let mut target = target.lock().unwrap();
                        let target = target.get_or_insert_with(|| Image3F::new(w, h));
                        paste_group(target, dim, p.group_idx, &image);
                    }
                    polished.push((t, p, local));
                }
                scratch.ac_group.polisher = None;
                polished
            });
        // Stale from now on: nothing else in this encode may polish.
        crate::coef_polish::POLISH_EPOCH.fetch_add(1, Ordering::Relaxed);
        let mut out = Eval {
            recon: output_recon
                .and_then(|recon| recon.into_inner().unwrap())
                .unwrap_or_else(|| Image3F::new(0, 0)),
            pending: vec![None; ac_tasks.len()],
            quant_dc: vec![None; ac_tasks.len()],
            source_dc: vec![None; ac_tasks.len()],
            starts: Vec::new(),
            capture: AcGroupCapture::None,
            synced: Vec::new(),
            trial: false,
            hit_bits: Vec::new(),
        };
        for (t, p, local) in work.into_iter().flatten() {
            out.pending[t] = Some(p);
            out.quant_dc[t] = Some(local);
        }
        cur = out;
    }
    let recon = want_recon.then(|| std::mem::replace(&mut cur.recon, Image3F::new(0, 0)));
    finish(cur, distp_out, recon)
}