oxideav-av1 0.1.21

Pure-Rust AV1 codec โ€” orphan-rebuild scaffold pending clean-room re-implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
//! Conformance-grade single-reference inter P-frame encoder (r411).
//!
//! Extends the r409/r410 KEY-frame driver ([`super::key_frame`]) into
//! a GOP encoder: [`encode_gop_yuv420_with_q`] emits one KEY frame
//! followed by INTER P-frames, each predicting from the previous
//! frame's reconstruction (`LAST_FRAME`, every ยง7.20 slot refreshed
//! per frame), through the REAL ยง5.11.18 `inter_frame_mode_info()`
//! syntax (the r411 [`super::partition_tree`] write arm, whose output
//! the spec decode walker replays bit-for-bit).
//!
//! ## Scope (r411, extended r412; every ยง6.4.1 format pairing r427)
//!
//! * Any ยง6.4.1 (bit depth, chroma format) pairing ([`YuvFrame`] โ€”
//!   8 / 10 / 12-bit ร— 4:2:0 / 4:2:2 / 4:4:4 / monochrome; the
//!   historical [`Yuv420Frame`] entries widen into the same core),
//!   dimensions per the KEY-frame rules (multiples of 8 in
//!   `[8, KEY_FRAME_MAX_DIM]`). Under 4:2:2 the ยง5.11.38
//!   admissibility rule bars the tall partition shapes from the RD
//!   ladder.
//! * P-frame header: `error_resilient_mode = 1` (forcing
//!   `primary_ref_frame = PRIMARY_REF_NONE` โ€” per-frame default CDFs),
//!   the r412 two-slot reference rotation (frame `k` refreshes slot
//!   `(k - 1) & 1`; LAST reads the previous frame's slot, GOLDEN the
//!   frame before it), identity ยง5.9.24 global motion, SWITCHABLE
//!   frame filter (per-leaf ยง5.11.x `interp_filter` selection),
//!   `force_integer_mv = 0` / `allow_high_precision_mv = 0`; r413
//!   adds 7-bit order hints (true ยง5.9.2 `ref_order_hint[]`
//!   surfacing), ยง5.9.22 skip-mode from `p_index = 2` on, and
//!   optional ยง5.9.14 `SEG_LVL_ALT_Q` spatial segmentation
//!   ([`encode_gop_yuv420_with_q_seg`]); `TxMode = ONLY_4X4` on the
//!   `CodedLossless` arm (`base_q_idx == 0`) or `TX_MODE_SELECT`
//!   otherwise.
//! * Per-node RD search (leaf vs HORZ vs VERT vs split, `BLOCK_64X64`
//!   down to `BLOCK_8X8` โ€” inter frames stop above the sub-8ร—8 chroma
//!   `someUseIntra` stitching): every square node trials one INTER
//!   leaf (per-reference LAST/GOLDEN integer motion search +
//!   half/quarter-pel refinement through the real ยง7.11.3.4 kernel,
//!   ยง5.11.24 mode selection over NEWMV / NEARESTMV / NEARMV /
//!   GLOBALMV via the r412 driver-side ยง7.10.2 mirror) against one
//!   INTRA leaf (the ยง5.11.22 arm with the KEY driver's 13-mode +
//!   ยง5.11.15 tx_depth pickers), the ยง5.11.4 PARTITION_HORZ /
//!   PARTITION_VERT pairs of rectangular inter halves, and the
//!   recursive split. Inter leaves additionally RD-select their
//!   ยง5.11.17 uniform `txfm_split` depth (`Max_Tx_Size_Rect` down to
//!   two `Split_Tx_Size` steps), coding the recursion's TUs in
//!   ยง5.11.36 transform-tree order.
//! * `skip = 1` on leaves whose every TU quantises to zero.
//!
//! ## Why the reconstruction loop is exact
//!
//! Inter prediction runs through the DECODER'S OWN ยง7.11.3 driver
//! ([`crate::inter_pred::reconstruct_inter_leaf_at`]) over grid state
//! stamped exactly like the ยง5.11.5 walker's (`MiSizes` / `IsInters` /
//! `RefFrames` / `Mvs` / `InterpFilters` / `MotionModes` / `YModes`),
//! reading the previous frame's reconstruction as the ยง7.20
//! `FrameStore`. The residual chain is the KEY driver's
//! ([`super::key_frame::residual_tx`] โ€” the decoder's dequant +
//! inverse + `Clip1(pred + residual)` merge), so the encoder's recon
//! tracks the decoder's `CurrFrame` sample-for-sample by induction
//! along the dispatch order, frame over frame.
//!
//! Spec provenance: `docs/video/av1/av1-spec.txt` ยง5.9.2 (inter frame
//! header), ยง5.9.24 (global motion), ยง5.11.18-ยง5.11.31 (inter block
//! syntax), ยง7.10.2 (MV prediction), ยง7.11.3 (inter prediction),
//! ยง7.20 (reference frame update).

use crate::cdf::{
    get_tx_size, inter_tx_type_set, tx_size_sqr_index, FindMvStackResult, PartitionWalker,
    QuantizerParams, TileCdfContext, TileGeometry, BLOCK_4X4, BLOCK_64X64, BLOCK_8X8, DCT_DCT,
    EIGHTTAP, GM_TYPE_IDENTITY, MAX_TX_SIZE_RECT, MAX_VARTX_DEPTH, MODE_GLOBALMV,
    MODE_GLOBAL_GLOBALMV, MODE_NEARESTMV, MODE_NEAREST_NEARESTMV, MODE_NEARMV, MODE_NEAR_NEARMV,
    MODE_NEWMV, MODE_NEW_NEWMV, MOTION_MODE_OBMC, MOTION_MODE_SIMPLE, MOTION_MODE_WARPED_CAUSAL,
    NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, PARTITION_HORZ, PARTITION_VERT, SPLIT_TX_SIZE,
    SWITCHABLE, TX_4X4, TX_HEIGHT, TX_SIZE_SQR_UP, TX_WIDTH,
};
use crate::encoder::block_mode_info::assign_mv_pred_mv;
use crate::encoder::ivf::{IvfWriter, FOURCC_AV01};
use crate::encoder::key_frame::{
    encode_leaf_sq, lambda_for, leaf_rate, region_distortion, region_distortion_wh, residual_tx,
    restore_region, save_region, save_region_wh, tu_bd_stamp, BlockDecodedMirror, ReconState,
    RegionSnapshot,
};
use crate::encoder::obu::{build_temporal_unit, ObuFrame};
use crate::encoder::partition_tree::{
    write_partition_tree_syntax, PartitionSyntaxWriter, SyntaxBlock, SyntaxFrameParams,
    SyntaxInterBlock, SyntaxInterFrameParams, SyntaxNode, VarTxSyntaxTree,
};
use crate::encoder::rate_twin::{score256, RateModel, RateTwin, TuCtx, TuFork};
use crate::encoder::symbol_writer::SymbolWriter;
use crate::encoder::tile_group_obu::{write_tile_group_obu, TileGroupObu, TilePayload};
use crate::encoder::yuv_frame::YuvFrame;
use crate::encoder::yuv_frame::{
    build_intra_only_yuv420_8bit_fh_with_q, sb_grid_origins, Yuv420Frame,
};
use crate::frame_header::{
    FrameHeader, FrameType, InterFrameRefs, ALL_FRAMES_PUB, PRIMARY_REF_NONE,
};
use crate::inter_pred::{
    reconstruct_inter_leaf_at, InterModeInfoGrid, PlaneReconContext, RefFrameStoreEntry,
};
use crate::obu::ObuType;
use crate::sequence_header::SequenceHeader;
use crate::uncompressed_header_tail::{
    FilmGrainParams, InterpolationFilter, TxMode, REFS_PER_FRAME, TOTAL_REFS_PER_FRAME,
};
use crate::uncompressed_header_tail::{GOLDEN_FRAME, LAST_FRAME};
use crate::Error;

/// One frame's reconstructed planes (row-major; U/V at
/// `(width/2) ร— (height/2)`).
#[derive(Debug, Clone)]
pub struct GopFrameRecon {
    /// Luma plane.
    pub y: Vec<u8>,
    /// Cb plane.
    pub u: Vec<u8>,
    /// Cr plane.
    pub v: Vec<u8>,
}

/// r427 โ€” general-format sibling of [`GopFrameRecon`]: `u16` planes
/// at the stream's bit depth, chroma at the subsampled extent (empty
/// on the monochrome arm).
#[derive(Debug, Clone)]
pub struct GopFrameReconYuv {
    /// Luma plane.
    pub y: Vec<u16>,
    /// Cb plane.
    pub u: Vec<u16>,
    /// Cr plane.
    pub v: Vec<u16>,
}

/// r427 โ€” result of [`encode_gop_yuv_with_q`]: the general-format
/// sibling of [`EncodedGop`].
#[derive(Debug, Clone)]
pub struct EncodedGopYuv {
    /// Complete IVF v0 file (header + one record per frame).
    pub ivf_bytes: Vec<u8>,
    /// The bare ยง7.5 temporal units, one per frame.
    pub temporal_units: Vec<Vec<u8>>,
    /// Per-frame encoder reconstruction โ€” the decoded output equals
    /// these sample-for-sample (and the inputs too at `base_q_idx ==
    /// 0`).
    pub recon: Vec<GopFrameReconYuv>,
    /// The emitted sequence header descriptor.
    pub seq: SequenceHeader,
}

/// r427 (hidden) โ€” [`EncodedGopYuv`] plus the per-P-frame election
/// outcomes: the general-format sibling of [`TunedGop`].
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct TunedGopYuv {
    pub gop: EncodedGopYuv,
    pub seg_temporal_updates: Vec<bool>,
    pub p_segment_maps: Vec<Vec<i32>>,
    /// r428 โ€” each P-frame's elected ยง5.9.2 `allow_high_precision_mv`
    /// header flag (index 0 is the first P-frame).
    pub hp_mv_elections: Vec<bool>,
    /// r428 โ€” each P-frame's elected ยง5.9.17 `delta_q_present` header
    /// flag (index 0 is the first P-frame).
    pub delta_q_elections: Vec<bool>,
    /// r439 โ€” each P-frame's elected ยง5.9.12 `using_qmatrix` header
    /// flag (index 0 is the first P-frame).
    pub qm_elections: Vec<bool>,
    /// r428 โ€” each P-frame's frame-level ยง5.9.19 CDEF election
    /// (index 0 is the first P-frame).
    pub cdef_elections: Vec<bool>,
    /// r429 โ€” each P-frame's ยง5.9.20 loop-restoration election
    /// (index 0 is the first P-frame).
    pub lr_elections: Vec<bool>,
    /// r436 โ€” each P-frame's ยง6.8.14 donor election: `Some(t)` when
    /// the frame elected tile `t != 0` of its PRIMARY frame as the
    /// CDF donor (the primary frame's `context_update_tile_id` was
    /// patched to `t` on the wire); `None` when the tile-0 donation
    /// stood (index 0 is the first P-frame).
    pub ctx_donor_elections: Vec<Option<u32>>,
    /// r441 โ€” whether the ยง5.9.30 film-grain arm won the GOP-level
    /// election (the `recon` planes then carry the ยง7.18.3 synthesis,
    /// exactly the decoder's output).
    pub film_grain_elected: bool,
    /// r456 โ€” each P-frame's ยง5.9.8 INTER superres election:
    /// `Some(SuperresDenom)` when the frame coded at the downscaled
    /// width against its upscaled-extent references, `None` on the
    /// flat shape (index 0 is the first P-frame).
    pub superres_inter_elections: Vec<Option<u32>>,
}

/// Result of [`encode_gop_yuv420_with_q`].
#[derive(Debug, Clone)]
pub struct EncodedGop {
    /// Complete IVF v0 file (header + one record per frame).
    pub ivf_bytes: Vec<u8>,
    /// The bare ยง7.5 temporal units, one per frame (the KEY frame's
    /// carries TD + SH + `OBU_FRAME`; P-frames carry TD +
    /// `OBU_FRAME`).
    pub temporal_units: Vec<Vec<u8>>,
    /// Per-frame encoder reconstruction โ€” the decoded output equals
    /// these byte-for-byte (and the inputs too at `base_q_idx == 0`).
    pub recon: Vec<GopFrameRecon>,
    /// The emitted sequence header descriptor.
    pub seq: SequenceHeader,
}

/// r423 (hidden) โ€” [`EncodedGop`] plus the per-P-frame ยง5.9.14
/// `segmentation_temporal_update` election outcomes (index 0 is the
/// first P-frame; empty on unsegmented GOPs). Returned by the
/// tuned measurement entry point only โ€” [`EncodedGop`] itself stays
/// field-stable for the public constructors.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct TunedGop {
    pub gop: EncodedGop,
    pub seg_temporal_updates: Vec<bool>,
    /// r426 โ€” each P-frame's committed ยง5.11.20 `SegmentIds[]` grid
    /// (row-major `mi_rows ร— mi_cols`; index 0 is the first P-frame;
    /// empty on unsegmented GOPs). Lets the measurement harnesses
    /// locate the per-segment-lossless blocks without re-deriving the
    /// election.
    pub p_segment_maps: Vec<Vec<i32>>,
    /// r428 โ€” each P-frame's elected ยง5.9.2 `allow_high_precision_mv`
    /// header flag (index 0 is the first P-frame).
    pub hp_mv_elections: Vec<bool>,
    /// r428 โ€” each P-frame's elected ยง5.9.17 `delta_q_present` header
    /// flag (index 0 is the first P-frame).
    pub delta_q_elections: Vec<bool>,
    /// r439 โ€” each P-frame's elected ยง5.9.12 `using_qmatrix` header
    /// flag (index 0 is the first P-frame).
    pub qm_elections: Vec<bool>,
    /// r428 โ€” each P-frame's frame-level ยง5.9.19 CDEF election
    /// (index 0 is the first P-frame).
    pub cdef_elections: Vec<bool>,
    /// r429 โ€” each P-frame's ยง5.9.20 loop-restoration election
    /// (index 0 is the first P-frame).
    pub lr_elections: Vec<bool>,
    /// r436 โ€” each P-frame's ยง6.8.14 donor election: `Some(t)` when
    /// the frame elected tile `t != 0` of its PRIMARY frame as the
    /// CDF donor (the primary frame's `context_update_tile_id` was
    /// patched to `t` on the wire); `None` when the tile-0 donation
    /// stood (index 0 is the first P-frame).
    pub ctx_donor_elections: Vec<Option<u32>>,
    /// r441 โ€” whether the ยง5.9.30 film-grain arm won (see
    /// [`TunedGopYuv::film_grain_elected`]).
    pub film_grain_elected: bool,
    /// r456 โ€” each P-frame's ยง5.9.8 INTER superres election:
    /// `Some(SuperresDenom)` when the frame coded at the downscaled
    /// width against its upscaled-extent references, `None` on the
    /// flat shape (index 0 is the first P-frame).
    pub superres_inter_elections: Vec<Option<u32>>,
}

/// GOP length bound (KEY + P-frames).
pub const GOP_MAX_FRAMES: usize = 64;

/// r427 โ€” narrow a general-format GOP result back to the 8-bit
/// [`EncodedGop`] shape (caller guarantees an 8-bit stream โ€” the
/// legacy 4:2:0 entry points).
pub(crate) fn narrow_gop_8bit(g: EncodedGopYuv) -> EncodedGop {
    let narrow = |p: Vec<u16>| p.into_iter().map(|s| s as u8).collect::<Vec<u8>>();
    EncodedGop {
        ivf_bytes: g.ivf_bytes,
        temporal_units: g.temporal_units,
        recon: g
            .recon
            .into_iter()
            .map(|r| GopFrameRecon {
                y: narrow(r.y),
                u: narrow(r.u),
                v: narrow(r.v),
            })
            .collect(),
        seq: g.seq,
    }
}

/// r413 โ€” one ยง7.20 slot's stored motion-field payload on the encode
/// side (the ยง7.19 `SavedMvs` / `SavedRefFrames` filter output plus
/// `SavedOrderHints`), mirroring the decode driver's per-slot store so
/// the ยง7.9 projection runs on identical inputs.
#[derive(Debug, Clone)]
pub(crate) struct SavedMotionField {
    mf_mvs: Vec<i16>,
    mf_ref_frames: Vec<i8>,
    saved_order_hints: [i32; 8],
    mi_rows: u32,
    mi_cols: u32,
    frame_is_intra: bool,
}

impl SavedMotionField {
    /// The KEY frame's slot payload (`FrameIsIntra = 1` โ€” ยง7.9.2
    /// skips intra sources, so the grids stay empty).
    pub(crate) fn intra(mi_rows: u32, mi_cols: u32) -> Self {
        SavedMotionField {
            mf_mvs: Vec::new(),
            mf_ref_frames: Vec::new(),
            saved_order_hints: [0; 8],
            mi_rows,
            mi_cols,
            frame_is_intra: true,
        }
    }
}

/// r423 โ€” one ยง7.20 slot's stored cross-frame decode state on the
/// encode side, mirroring the ยง5.9.2 primary-reference loads field by
/// field:
///
/// * `cdfs` โ€” the ยง8.4 frame-end CDF table `save_cdfs( i )` deposits
///   (the `context_update_tile_id` tile's adapted state;
///   `disable_frame_end_update_cdf = 0` on every header this encoder
///   emits). A frame electing this slot as its primary reference
///   starts from a clone with the per-row symbol counts zeroed
///   (ยง6.8.21 `load_cdfs`).
/// * `segment_ids` โ€” `SavedSegmentIds[ i ][ row ][ col ]` (row-major
///   over `mi_rows ร— mi_cols`), the ยง5.9.2
///   `load_previous_segment_ids()` source feeding the ยง5.11.21
///   `get_segment_id()` prediction.
/// * `gm_params` โ€” `SavedGmParams[ i ]`, the ยง7.21 `load_previous()`
///   `PrevGmParams` source the ยง5.9.24 subexp recentering codes
///   against.
#[derive(Debug, Clone)]
pub(crate) struct RefSlotCarry {
    pub(crate) cdfs: Box<TileCdfContext>,
    pub(crate) segment_ids: Vec<i32>,
    pub(crate) mi_rows: u32,
    pub(crate) mi_cols: u32,
    pub(crate) gm_params: [[i32; 6]; crate::uncompressed_header_tail::TOTAL_REFS_PER_FRAME],
    /// r436 โ€” ยง6.8.14 DONOR CANDIDATES: every tile's frame-end
    /// adapted CDF state, in tile order (`donor_cdfs[ t ]` = tile
    /// `t`'s state; `donor_cdfs[ 0 ] == cdfs` โ€” the header was
    /// emitted with `context_update_tile_id = 0`). Populated only
    /// when the frame was encoded with
    /// [`InterFrameConfig::collect_donor_cdfs`] on a multi-tile
    /// layout; EMPTY otherwise, and cleared by the driver once a
    /// consumer frame's election commits the donor (later consumers
    /// of the same slot must load the COMMITTED donation, not
    /// re-elect).
    pub(crate) donor_cdfs: Vec<Box<TileCdfContext>>,
    /// r436 โ€” the position of this frame's ยง5.9.15
    /// `context_update_tile_id` field on the wire: `(bit offset from
    /// the start of the frame-header payload, field width in bits)`.
    /// `Some` exactly when the layout codes the field
    /// (`TileColsLog2 + TileRowsLog2 > 0`); the driver patches the already-emitted
    /// frame in place when a later consumer's election lands (the
    /// field is fixed-width `f(n)` and nothing after it depends on
    /// its value, so the patch is length- and meaning-preserving for
    /// every other syntax element).
    pub(crate) ctx_update_span: Option<(u32, u32)>,
}

/// r424 โ€” one INTER frame's auxiliary election outcomes, returned by
/// [`encode_inter_frame_generic`] alongside the OBU: the ยง5.9.14
/// `segmentation_temporal_update` arm the exact-bits election kept
/// (r423) and the ยง5.9.2 `primary_ref_frame` ordinal the exact-bytes
/// election committed (r424; equals the config's ordinal when no
/// [`InterFrameConfig::alt_primaries`] were offered).
#[derive(Debug, Clone, Copy)]
pub(crate) struct InterFrameAux {
    pub(crate) seg_temporal: bool,
    pub(crate) primary_ref: u8,
    /// r428 โ€” the elected ยง5.9.2 `allow_high_precision_mv` header
    /// flag (the eighth-pel search arm may still be flipped back to
    /// quarter-pel by the exact-bytes replay election).
    pub(crate) hp_mv: bool,
    /// r428 โ€” the elected ยง5.9.17 `delta_q_present` header flag (the
    /// per-superblock delta-q arm won the frame-level joint-objective
    /// election over the single-quantiser arm).
    pub(crate) delta_q: bool,
    /// r439 โ€” the elected ยง5.9.12 `using_qmatrix` header flag (the
    /// quantizer-matrix arm won the frame-level joint-objective
    /// election over the flat-quantiser arm).
    pub(crate) qm: bool,
    /// r428 โ€” the elected frame-level ยง5.9.19 CDEF strengths (`true`
    /// when a non-zero strength set beat the unfiltered frame and
    /// landed in the header + reconstruction).
    pub(crate) cdef: bool,
    /// r429 โ€” the elected ยง5.9.20 loop-restoration plan (`true` when
    /// a per-unit Wiener/self-guided plan won the exact-bytes
    /// settlement and landed in the header + reconstruction).
    pub(crate) lr: bool,
    /// r436 โ€” the ยง6.8.14 donor election outcome: `Some(t)` when the
    /// exact-bytes replay election found that starting THIS frame's
    /// ยง8.3.1 CDF chain from the PRIMARY frame's tile-`t` frame-end
    /// state (`t != 0`) realizes a smaller frame than the committed
    /// tile-0 donation. The caller must then patch the primary
    /// frame's already-emitted `context_update_tile_id` field to `t`
    /// (via its carry's [`RefSlotCarry::ctx_update_span`]) and fix
    /// the stored carry so `cdfs` is the elected tile's state.
    pub(crate) donor_elected: Option<u32>,
}

/// Integer-pel motion-search radius (luma samples per axis).
const SEARCH_RANGE: i32 = 16;

/// r428 โ€” ยง5.9.17 `delta_q_res` this encoder codes on delta-q-elected
/// frames: reduced units scale by `1 << 3 = 8` quantiser-index steps,
/// keeping the per-superblock ยง5.11.13 symbols in the cheap
/// `|reduced| <= 2` literal range while covering a ยฑ16 index swing.
pub(crate) const DELTA_Q_RES: u8 = 3;

/// r439 โ€” the ยง5.9.12 quantizer-matrix level candidate for a frame
/// quantiser. ยง9.5.3 levels run 0..=14 (0 = steepest deviation from
/// the flat quantiser, 14 nearly flat; 15 is the ยง7.12.3 no-QM
/// short-circuit). Coarser base quantisers take steeper matrices โ€”
/// at low q the flat quantiser is already near the joint optimum and
/// only a gentle reshape can win; at high q the high-frequency
/// coefficients' rate dominates and a steeper reshape pays. The map
/// was settled by measurement on the `qm_ab` harness; the per-frame
/// election only KEEPS the arm where it wins, so the map needs to be
/// good, not perfect.
pub(crate) fn qm_level_for_q(base_q_idx: u8) -> u8 {
    match base_q_idx {
        0..=80 => 10,
        81..=160 => 8,
        _ => 6,
    }
}

/// r441 โ€” the multi-level QM LADDER: the quantiser-keyed level plus
/// its LIGHTER ยง9.5.3 neighbour two steps up (levels rise toward the
/// flat lattice at 15). The keyed banding is a coarse fit โ€” near a
/// band edge, or on content whose spectrum sits between the bands'
/// design points, the neighbour reshapes better; the election settles
/// each candidate by the same exact-realized-bytes joint objective,
/// so the ladder can only improve the elected stream. Two candidates
/// keep the extra full searches inside the tiered-CI budget (an
/// election-scoping choice).
pub(crate) fn qm_ladder_for_q(base_q_idx: u8) -> Vec<u8> {
    let keyed = qm_level_for_q(base_q_idx);
    let lighter = (keyed + 2).min(12);
    if lighter == keyed {
        vec![keyed]
    } else {
        vec![keyed, lighter]
    }
}

/// r441 โ€” the ladder's REFINEMENT discipline: candidates past the
/// first run only when the keyed level already beat the flat arm.
/// Measured on the committed matrix, the lighter neighbour refines
/// wins but never overturns a loss โ€” so the extra full search is
/// spent only on frames already paying for the tool (the r440
/// CI-budget lesson applied up front).
pub(crate) const QM_LADDER_REFINES_ONLY: bool = true;

/// r439 โ€” the QM arm's ARMING WINDOW: the measured win regime. The
/// `qm_ab` matrix showed the joint objective electing the arm in the
/// MID-RATE band (level-8 territory โ€” e.g. โˆ’14.85% bytes at
/// โˆ’0.067 dB at q100, โˆ’5.39% at +0.20 dB at q140) while at fine
/// quantisers the election trades bytes for distortion the flat
/// lattice already serves (q60: +4.7..+20% bytes) and at very coarse
/// ones it essentially never fires (q180+: โ‰ค ยฑ3%, mostly inert).
/// Tiny frames' fixed header cost dominates any reshape. So the
/// second full search is only spent where the tool measurably pays:
/// `base_q_idx` in `88..=176` and a luma extent of at least 96ร—80.
/// An encoder election-scoping choice, not a conformance constraint
/// (the decode side handles every ยง5.9.12 configuration).
pub(crate) fn qm_arm_allowed(base_q_idx: u8, width: usize, height: usize) -> bool {
    (88..=176).contains(&base_q_idx) && width * height >= 96 * 80
}

/// r439 โ€” the QM arm's content gate: mean absolute horizontal +
/// vertical luma second difference, in 1/16ths of an 8-bit-normalized
/// sample step. Smooth content (flat fills, gradients) has
/// essentially no high-frequency energy for a ยง9.5.3 matrix to
/// reshape โ€” the arm cannot win there, and skipping the second full
/// search keeps smooth-content streams bit-identical to the
/// baseline.
pub(crate) fn qm_probe(input: &YuvFrame) -> bool {
    let (w, h) = (input.width as usize, input.height as usize);
    let mut sum = 0u64;
    let mut count = 0u64;
    for r in 0..h {
        for c in 1..w.saturating_sub(1) {
            let m = i64::from(input.y[r * w + c]);
            sum += (2 * m - i64::from(input.y[r * w + c - 1]) - i64::from(input.y[r * w + c + 1]))
                .unsigned_abs();
            count += 1;
        }
    }
    for r in 1..h.saturating_sub(1) {
        for c in 0..w {
            let m = i64::from(input.y[r * w + c]);
            sum +=
                (2 * m - i64::from(input.y[(r - 1) * w + c]) - i64::from(input.y[(r + 1) * w + c]))
                    .unsigned_abs();
            count += 1;
        }
    }
    if count == 0 {
        return false;
    }
    let mean16 = (sum * 16) / count / (1u64 << (input.bit_depth - 8));
    mean16 >= 8
}

/// r428 โ€” the ยง5.9.17 complexity probe: map per-superblock source
/// luma activity (variance over the superblock's samples) to reduced
/// ยง5.11.13 delta units. Textured superblocks (activity well above
/// the frame median) coarsen (`+units` โ€” masking hides the extra
/// quantisation), flat superblocks (well below) refine (`-units` โ€”
/// banding shows first where nothing masks it); the mapping is
/// `round( ln2( activity / median ) / 2 )` clamped to `[-2, 2]`.
/// Returns `None` when every superblock lands on zero (flat spread โ€”
/// the delta arm would only add wire cost). Encoder heuristic, free
/// choice: the plan is simply what the frame-level exact election
/// scores against the single-quantiser arm.
pub(crate) fn delta_q_plan_units(input: &YuvFrame, mi_rows: u32, mi_cols: u32) -> Option<Vec<i32>> {
    let w = input.width as usize;
    let h = input.height as usize;
    let sbs = sb_grid_origins(mi_rows, mi_cols);
    let mut acts: Vec<f64> = Vec::with_capacity(sbs.len());
    for &(sb_r, sb_c) in &sbs {
        let y0 = (sb_r as usize) * 4;
        let x0 = (sb_c as usize) * 4;
        let y1 = (y0 + 64).min(h);
        let x1 = (x0 + 64).min(w);
        let n = ((y1 - y0) * (x1 - x0)) as u64;
        let mut sum = 0u64;
        let mut sum2 = 0u128;
        for r in y0..y1 {
            for c in x0..x1 {
                let v = u64::from(input.y[r * w + c]);
                sum += v;
                sum2 += u128::from(v * v);
            }
        }
        let mean = sum as f64 / n as f64;
        let var = (sum2 as f64 / n as f64) - mean * mean;
        acts.push(var.max(0.0));
    }
    // Geometric-mean reference: activity spread maps SYMMETRICALLY
    // (textured superblocks coarsen and pay for the flats'
    // refinement, keeping the armed frame's rate near the baseline).
    let log_mean = acts.iter().map(|&a| a.max(1.0).log2()).sum::<f64>() / acts.len() as f64;
    let units: Vec<i32> = acts
        .iter()
        .map(|&a| (((a.max(1.0).log2() - log_mean) * 0.5).round() as i32).clamp(-2, 2))
        .collect();
    units.iter().any(|&u| u != 0).then_some(units)
}

/// r415 โ€” one leaf's committed ยง5.11.29 compound selection for the
/// prediction driver ([`PSearchCtx::predict_leaf`] stamps it into the
/// ยง5.11.5 side-data grids the decoder's leaf driver reads).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CompoundSel {
    ctype: u8,
    wedge_index: u8,
    wedge_sign: u8,
    mask_type: u8,
}

impl CompoundSel {
    /// The ยง5.11.29 line-1/2 pre-set shape (every single-reference
    /// leaf and every compound leaf whose masked arms lost or are
    /// gated shut).
    const AVERAGE: CompoundSel = CompoundSel {
        ctype: crate::inter_pred::COMPOUND_AVERAGE,
        wedge_index: 0,
        wedge_sign: 0,
        mask_type: 0,
    };
}

/// r419 โ€” one leaf's committed ยง5.11.27 motion-mode selection for the
/// prediction driver ([`PSearchCtx::predict_leaf`] stamps the ordinal
/// into the `MotionModes[]` grid and โ€” on the warp arm โ€” the
/// ยง7.11.3.8 fit into the per-cell `LocalWarpParams` slice the
/// decoder's leaf driver reads).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MotionSel {
    /// ยง5.11.27 `SIMPLE` โ€” the translational ยง7.11.3.1 path.
    Simple,
    /// ยง5.11.27 `OBMC` โ€” the leaf's own prediction plus the
    /// ยง7.11.3.9-10 above/left overlap blend, resolved by the leaf
    /// driver from the committed neighbour grids.
    Obmc,
    /// ยง5.11.27 `WARPED_CAUSAL` โ€” the ยง7.11.3.5 warp with the carried
    /// ยง7.11.3.8 least-squares fit (already `setup_shear`-validated
    /// by the caller; an invalid fit is never committed).
    Warp([i32; 6]),
}

impl MotionSel {
    /// The committed ยง5.11.27 ordinal.
    fn ordinal(self) -> u8 {
        match self {
            MotionSel::Simple => MOTION_MODE_SIMPLE,
            MotionSel::Obmc => MOTION_MODE_OBMC,
            MotionSel::Warp(_) => MOTION_MODE_WARPED_CAUSAL,
        }
    }
}

/// r419 โ€” one driver-grid cell's saved state (see
/// [`PSearchCtx::snapshot_grids_rect`]).
#[derive(Debug, Clone, Copy)]
struct DriverGridCell {
    mi_size: usize,
    is_inter: u8,
    ref_frames: [i8; 2],
    mvs: [i16; 4],
    interp_filters: [u8; 2],
    motion_mode: u8,
    y_mode: u8,
    compound_type: u8,
    wedge_index: u8,
    wedge_sign: u8,
    mask_type: u8,
    interintra_mode: u8,
    wedge_interintra: u8,
    interintra_wedge_index: u8,
    local_warp: [i32; 6],
    local_warp_valid: u8,
}

/// r419 โ€” a rect snapshot of the ยง5.11.5 driver grids (row-major
/// cells over `[mi_row, r1) ร— [mi_col, c1)`).
struct DriverGridSnapshot {
    mi_row: u32,
    mi_col: u32,
    r1: u32,
    c1: u32,
    cells: Vec<DriverGridCell>,
}

/// r417 โ€” one ยง5.11.28 inter-intra selection for
/// [`PSearchCtx::predict_leaf`]: the ยง7.11.5-translated intra half is
/// predicted into the search scratch (reading reconstructed
/// neighbours from `neigh` through the decode walker's own ยง7.11.2
/// core), then the decoder's ยง7.11.3.14 mask blend combines it with
/// the single-reference inter prediction.
#[derive(Clone, Copy)]
struct InterIntraTrial<'a> {
    /// ยง6.10.27 `interintra_mode` ordinal
    /// (`II_DC_PRED..=II_SMOOTH_PRED`).
    mode: u8,
    /// `Some(wedge_index)` selects the `wedge_interintra == 1` sub-arm
    /// (ยง7.11.3.11 luma-grid wedge mask, sign fixed `0` per ยง5.11.28);
    /// `None` the ยง7.11.3.13 smooth intra-variant mask.
    wedge: Option<u8>,
    /// The committed running reconstruction โ€” the ยง7.11.2 neighbour
    /// source (the decode walker's intra half reads its own
    /// `CurrFrame[ plane ]`, whose encoder twin is this recon state,
    /// sample-exact by the module's induction argument).
    neigh: &'a ReconState,
}

/// Lossless (`base_q_idx = 0`) GOP encode โ€” see
/// [`encode_gop_yuv420_with_q`].
pub fn encode_gop_yuv420(frames: &[Yuv420Frame]) -> Result<EncodedGop, Error> {
    encode_gop_yuv420_with_q(frames, 0)
}

/// Encode a KEY + P GOP of 8-bit 4:2:0 frames at `base_q_idx` into a
/// spec-conformant IVF stream (see the module docs for the exact
/// scope and the reconstruction-exactness argument).
///
/// ## Errors
///
/// * Empty input, more than [`GOP_MAX_FRAMES`] frames, mismatched
///   dimensions across frames, or dimensions outside the KEY-frame
///   rules โ€” [`Error::PartitionWalkOutOfRange`].
pub fn encode_gop_yuv420_with_q(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
) -> Result<EncodedGop, Error> {
    encode_gop_yuv420_with_q_seg(frames, base_q_idx, &[])
}

/// r413 โ€” GOP encode with ยง5.9.14 `SEG_LVL_ALT_Q` segmentation on the
/// P-frames: `alt_q[ s ]` is segment `s`'s signed quantiser delta
/// (`get_qindex( s ) = Clip3( 0, 255, base_q_idx + alt_q[ s ] )`).
/// The encoder assigns segments per leaf by luma activity (flat
/// blocks take the higher-index segments), codes the spatial
/// ยง5.11.19/ยง5.11.20 segment map (skip leaves inherit the ยง5.11.20
/// `pred` cascade with no bits, per spec), and quantises each leaf's
/// residual at its segment's q-index. An empty `alt_q` disables
/// segmentation (the pre-r413 configuration). The KEY frame stays
/// unsegmented (its `segmentation_enabled = 0` header is unchanged;
/// every P-frame header re-codes the full feature table under the
/// `PRIMARY_REF_NONE` forced `update_data = 1`).
///
/// r426 โ€” **per-segment lossless mixing**: a segment whose ยง5.9.14
/// `get_qindex( s ) = Clip3( 0, 255, base_q_idx + alt_q[ s ] )`
/// reaches 0 takes the full ยง5.9.2 `LosslessArray[ s ]` leaf
/// semantics inside the otherwise-lossy frame โ€” its blocks code the
/// `TX_4X4`-only ยง5.11.34 row-major TU grid through the ยง7.13.2.10
/// WHT chain (bit-exact residual round-trip), read no ยง5.11.15 /
/// ยง5.11.16 tx-size symbols and no ยง5.11.47 tx-type symbol, exactly
/// as the decode side derives per block from
/// `Lossless = LosslessArray[ segment_id ]`. Blocks in the other
/// segments stay on the lossy ladder. `CodedLossless` stays 0 (the
/// frame still codes `TX_MODE_SELECT`, and segment 0 rides
/// `base_q_idx > 0`), so the mix is purely per-block.
///
/// ## Errors
///
/// [`Error::PartitionWalkOutOfRange`] on the
/// [`encode_gop_yuv420_with_q`] conditions, plus:
///
/// * `alt_q.len() > MAX_SEGMENTS = 8` or `alt_q.len() == 1`;
/// * `alt_q[ 0 ] != 0` (intra leaves code segment 0 at the frame
///   quantiser โ€” the residual chain requires the identity delta);
/// * `base_q_idx == 0` with a non-empty `alt_q` (a `base_q_idx = 0`
///   GOP is the `CodedLossless` configuration โ€” segment deltas would
///   make segment 0 the only lossless segment while the header
///   builder still derives the ONLY_4X4 frame shape);
/// * any `alt_q[ s ]` outside the ยง5.9.14 `su(1+8)` range
///   `-255..=255`, or any segment's `base_q_idx + alt_q[ s ] > 255`
///   (the ยง7.12.2 clamp makes over-255 deltas unreachable dead
///   weight; deltas that clamp BELOW zero are the per-segment
///   lossless election and are accepted).
pub fn encode_gop_yuv420_with_q_seg(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    alt_q: &[i16],
) -> Result<EncodedGop, Error> {
    encode_gop_yuv420_with_q_seg_rate_model(frames, base_q_idx, alt_q, RateModel::Twin)
}

/// r421 โ€” [`encode_gop_yuv420_with_q_seg`] with an explicit
/// [`RateModel`], kept public (hidden) so the sweep harnesses can A/B
/// the twin-priced elections against the pre-r421 heuristic baseline.
#[doc(hidden)]
pub fn encode_gop_yuv420_with_q_seg_rate_model(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    alt_q: &[i16],
    model: RateModel,
) -> Result<EncodedGop, Error> {
    encode_gop_yuv420_with_q_seg_rate_model_gm(frames, base_q_idx, alt_q, model, true)
}

/// r422 โ€” [`encode_gop_yuv420_with_q_seg_rate_model`] with an explicit
/// global-motion switch, kept public (hidden) so the measurement
/// harness can A/B the ยง5.9.24 election against the identity-only
/// baseline on identical inputs. Production entry points always
/// enable it.
#[doc(hidden)]
pub fn encode_gop_yuv420_with_q_seg_rate_model_gm(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    alt_q: &[i16],
    model: RateModel,
    global_motion: bool,
) -> Result<EncodedGop, Error> {
    encode_gop_yuv420_with_q_seg_tuned(
        frames,
        base_q_idx,
        alt_q,
        GopTuning {
            model,
            global_motion,
            ..GopTuning::default()
        },
    )
    .map(|t| t.gop)
}

/// r423 โ€” the P-GOP encoder's tuning switches, kept public (hidden)
/// so the measurement harnesses can A/B each cross-frame feature
/// against its baseline on identical inputs. Production entry points
/// always use [`GopTuning::default`] (everything on).
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct GopTuning {
    /// RD-election rate model (r421).
    pub model: RateModel,
    /// ยง5.9.24 global-motion election (r422).
    pub global_motion: bool,
    /// r423 โ€” ยง5.9.2 `primary_ref_frame` election: P-frames inherit
    /// the previous frame's frame-end CDFs (ยง6.8.21 `load_cdfs`),
    /// segment map (`load_previous_segment_ids`) and gm reference
    /// state (`load_previous`) instead of per-frame defaults.
    pub primary_ref: bool,
    /// r423 โ€” ยง5.9.14 / ยง5.11.19 temporal segment-map coding: allow
    /// the per-frame exact-bits election between the temporal
    /// (`seg_id_predicted`) and spatial segment-id arms. `false`
    /// forces spatial coding on every frame (the A/B baseline).
    /// Inert while `primary_ref` is off (the temporal arm requires
    /// real `PrevSegmentIds` state).
    pub temporal_seg: bool,
    /// r428 โ€” ยง5.9.2 `allow_high_precision_mv` arm: eighth-pel MV
    /// search + wire precision, with the per-frame exact-bytes
    /// replay election back to the quarter-pel arm. `false` keeps
    /// the pre-r428 quarter-pel shape on every frame (the A/B
    /// baseline).
    pub high_precision_mv: bool,
    /// r428 โ€” ยง5.9.17 per-superblock delta-q election on unsegmented
    /// lossy frames (complexity-probe plan + frame-level exact-bytes
    /// arm election). `false` keeps the single-quantiser shape on
    /// every frame (the A/B baseline).
    pub delta_q: bool,
    /// r439 โ€” ยง5.9.12 quantizer-matrix election on unsegmented lossy
    /// frames (KEY + inter): a second full search under
    /// `using_qmatrix = 1` at the [`qm_level_for_q`] ยง9.5.3 level,
    /// elected per frame by the joint objective over exact realized
    /// bytes; the [`qm_probe`] high-frequency gate skips the arm on
    /// smooth content (bit-identical to the baseline there). `false`
    /// keeps the flat-quantiser shape on every frame (the A/B
    /// baseline).
    pub qm: bool,
    /// r428 โ€” frame-level ยง5.9.19/ยง7.15 CDEF election on lossy
    /// frames (KEY + inter): decoder-mirror filtering on the recon
    /// path, source-scored strength search, zero tile bits. `false`
    /// keeps the all-zero-strength shape on every frame (the A/B
    /// baseline).
    pub cdef: bool,
    /// r429 โ€” per-64ร—64 ยง5.11.56 CDEF strength ids: allow the
    /// election to propose `cdef_bits > 0` (up to 8 ยง5.9.19 strength
    /// sets, one id literal per unit, tile re-emitted with the exact
    /// `L(cdef_bits)` bits priced against ฮป). `false` caps the
    /// election at the r428 frame-level arm (the A/B baseline).
    /// Inert while [`Self::cdef`] is off.
    pub cdef_units: bool,
    /// r429 โ€” ยง5.9.20/ยง7.17 loop-restoration election on lossy
    /// frames: per-64ร—64-unit Wiener / self-guided filters fitted on
    /// the encoder recon path, ยง5.11.57 unit payloads in the tile,
    /// exact-realized-bytes settlement. `false` keeps the
    /// all-RESTORE_NONE shape on every frame (the A/B baseline).
    pub lr: bool,
    /// r431 โ€” the ยง5.9.15 uniform tile layout `(TileColsLog2,
    /// TileRowsLog2)` coded on EVERY frame of the GOP (KEY + inter).
    /// `(0, 0)` is the single-tile pre-r431 shape (bit-identical).
    /// Must sit inside the ยง5.9.15 legal window for the frame size.
    pub tiles: (u32, u32),
    /// r433 โ€” ยง5.11.1 tile-group packaging on EVERY frame of the GOP:
    /// split each frame's tiles across this many `OBU_TILE_GROUP`
    /// OBUs (standalone `OBU_FRAME_HEADER` + contiguous
    /// `tg_start ..= tg_end` slices, `tile_start_and_end_present_flag
    /// = 1`) instead of the single ยง5.10 `OBU_FRAME`. `0` / `1` keep
    /// the historical one-OBU shape (bit-identical); clamps to each
    /// frame's realized tile count. Entropy payloads are
    /// byte-identical either way โ€” only the OBU framing changes.
    pub tile_groups: u32,
    /// r436 โ€” ยง6.8.14 `context_update_tile_id` election on
    /// multi-tile GOPs: each P-frame replays its committed trees
    /// from every tile-donor CDF state of its PRIMARY frame and
    /// keeps the smallest realized body; a win patches the primary
    /// frame's already-emitted (fixed-width) field in place โ€” no
    /// other bit of the stream moves. `false` keeps the tile-0
    /// donation on every frame (the A/B baseline; bit-identical to
    /// the pre-r436 streams). Inert on single-tile layouts or with
    /// [`Self::primary_ref`] off.
    pub ctx_update_elect: bool,
    /// r441 โ€” ยง5.9.8 SUPERRES election on the KEY frame of a
    /// single-tile GOP inside the measured win regime: each candidate
    /// denominator codes the KEY at the ยง5.9.8 downscaled width, the
    /// reconstruction upscales through the decoder's own ยง7.16
    /// driver (the P chain predicts from the upscaled reference,
    /// exactly the decoder's ยง7.20 store), and the joint objective
    /// over original-extent SSE + exact realized bytes keeps the
    /// winner. r444 โ€” SEGMENTED GOPs ride the election too: the KEY
    /// of a plain segmented GOP is itself unsegmented, and a
    /// segmented P-frame's ยง5.11.19 temporal prediction over the
    /// KEY's mi-grid-mismatched `SavedSegmentIds` takes the
    /// ยง5.9.2 `load_previous_segment_ids()` all-zero arm both twins
    /// already mirror. `false` keeps the flat-width shape on every
    /// frame (the A/B baseline; bit-identical outside an elected
    /// win).
    pub superres: bool,
    /// r441 โ€” ยง5.9.30 FILM-GRAIN election on unsegmented lossy GOPs
    /// whose content passes the noise probe (energy + spatial
    /// whiteness + temporal decorrelation): the grain arm codes the
    /// DENOISED frames with full ยง5.9.30 parameters on every header
    /// and publishes ยง7.18.3-synthesized output planes, elected under
    /// the documented perceptually-neutral-rate objective. `false`
    /// keeps the no-grain shape on every frame (the A/B baseline;
    /// probe-failing content is bit-identical either way).
    pub film_grain: bool,
    /// r447 โ€” ยง5.9.2 SWITCH-frame cadence: every `s_frame_period`-th
    /// inter frame (display positions `s_frame_period,
    /// 2ยทs_frame_period, โ€ฆ`) codes `frame_type = SWITCH_FRAME` โ€” the
    /// spec's chunk-boundary frame (ยง "Switch Frame" definition):
    /// error-resilient (inferred `error_resilient_mode = 1`, no bit),
    /// all eight ยง7.20 slots overwritten (inferred
    /// `refresh_frame_flags = allFrames`, no bits), explicit frame
    /// size (inferred `frame_size_override_flag = 1`), per-frame
    /// default CDFs (inferred `primary_ref_frame = PRIMARY_REF_NONE`)
    /// and `use_ref_frame_mvs = 0` โ€” so every cross-frame decode
    /// dependency except the reference SAMPLES re-anchors at the
    /// switch point, and a same-geometry stream may splice its
    /// temporal units in at that boundary. `0` keeps the all-P shape
    /// (bit-identical).
    pub s_frame_period: u32,
    /// r450 โ€” ยง5.9.2 CODED error-resilient cadence: every
    /// `error_resilient_period`-th inter frame (display positions
    /// `error_resilient_period, 2ยทerror_resilient_period, โ€ฆ`;
    /// S-frame positions keep the SWITCH shape โ€” the flag is
    /// inferred there) codes `error_resilient_mode = 1` on the wire
    /// while staying a plain INTER frame: normal
    /// `refresh_frame_flags`, references predicting across the
    /// boundary, every frame-level election still riding โ€” but every
    /// cross-frame DECODE dependency (CDFs, motion fields, segment
    /// ids, loop-filter deltas, gm carry) re-anchors at per-frame
    /// defaults, the ยง5.9.2 `ref_order_hint[]` block goes on the
    /// wire, and `use_ref_frame_mvs = allow_warped_motion = 0` per
    /// the parse-side inferences. `0` = never (the default).
    pub error_resilient_period: u32,
    /// r450 โ€” ยง5.11.1 EXPLICIT tile spans: on multi-tile frames the
    /// single tile group codes `tile_start_and_end_present_flag = 1`
    /// with its full `tg_start = 0 ..= tg_end = NumTiles โˆ’ 1` span,
    /// packaged as `OBU_FRAME_HEADER` + `OBU_TILE_GROUP` (the ยง5.10
    /// `OBU_FRAME` packing requires the flag to be 0). The per-tile
    /// entropy payloads are byte-identical to the flag-0 shape โ€”
    /// only the OBU framing and the group prologue change. Inert on
    /// single-tile frames and when `tile_groups > 1` already splits
    /// the frame (each split group codes the flag anyway).
    pub tile_spans: bool,
    /// r452 โ€” ยง5.9.2 `frame_refs_short_signaling = 1` on plain INTER
    /// frames: the header codes only `last_frame_idx` /
    /// `gold_frame_idx` (3 bits each) and the DECODER derives the
    /// whole seven-entry `ref_frame_idx[]` through ยง7.8
    /// `set_frame_refs()` from its stored `RefOrderHint[]` state โ€”
    /// 7 wire bits replace 22. The encoder ADOPTS the ยง7.8
    /// derivation as its own reference map (the same slots land on
    /// the LAST / GOLDEN ordinals the RD ladder actually codes โ€”
    /// ยง7.8 seeds them from the two explicit indices โ€” while the
    /// unsearched ordinals move to the spec-derived slots, which
    /// feeds every downstream twin: ยง7.8 sign bias, ยง5.9.22 skip
    /// mode, ยง7.9 motion-field projection), so the write side and
    /// the parse side run the identical algorithm in lockstep.
    /// SWITCH-cadence and coded-error-resilient positions keep the
    /// explicit shape (their re-anchoring semantics are the point of
    /// those frames). `false` keeps the explicit 22-bit shape on
    /// every frame (the A/B baseline; bit-identical).
    pub short_ref_signaling: bool,
}

impl Default for GopTuning {
    fn default() -> Self {
        GopTuning {
            model: RateModel::Twin,
            global_motion: true,
            primary_ref: true,
            temporal_seg: true,
            high_precision_mv: true,
            delta_q: true,
            qm: true,
            cdef: true,
            cdef_units: true,
            lr: true,
            tiles: (0, 0),
            tile_groups: 1,
            ctx_update_elect: true,
            superres: true,
            film_grain: true,
            s_frame_period: 0,
            error_resilient_period: 0,
            tile_spans: false,
            short_ref_signaling: false,
        }
    }
}

/// r426 โ€” one caller-supplied exactness-demand rectangle in LUMA
/// pixel coordinates (top-left `(x, y)`, `width ร— height`; clipped to
/// the frame). Every block overlapping the rectangle is coded on the
/// lossless segment (ยง5.9.14 `SEG_LVL_ALT_Q` to qindex 0 โ€” the
/// ยง5.9.2 `LosslessArray[]` TX_4X4/WHT leaf semantics), so the
/// decoded region equals the input pixel-for-pixel on every frame
/// the encoder segments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LosslessRegion {
    /// Left edge (luma samples).
    pub x: u32,
    /// Top edge (luma samples).
    pub y: u32,
    /// Width (luma samples; > 0).
    pub width: u32,
    /// Height (luma samples; > 0).
    pub height: u32,
}

/// r426 โ€” build the row-major mi-cell exactness mask for the demand
/// rectangles: a 4ร—4 luma cell is demanded when it intersects any
/// (frame-clipped) rectangle, then the demand dilates to the full
/// 2ร—2-mi group so a sub-8ร—8 group's single ยง5.11.34 `HasChroma`
/// coder (the SE cell's leaf) and the 4:2:0 chroma cositing are
/// covered by the same lossless segment.
fn build_exact_mask(
    regions: &[LosslessRegion],
    width: u32,
    height: u32,
    mi_rows: u32,
    mi_cols: u32,
) -> Vec<bool> {
    let mut mask = vec![false; (mi_rows as usize) * (mi_cols as usize)];
    for reg in regions {
        let x0 = reg.x.min(width);
        let y0 = reg.y.min(height);
        let x1 = reg.x.saturating_add(reg.width).min(width);
        let y1 = reg.y.saturating_add(reg.height).min(height);
        if x0 >= x1 || y0 >= y1 {
            continue;
        }
        let (c0, r0) = (x0 / 4, y0 / 4);
        let (c1, r1) = (x1.div_ceil(4).min(mi_cols), y1.div_ceil(4).min(mi_rows));
        for r in r0..r1 {
            for c in c0..c1 {
                mask[(r * mi_cols + c) as usize] = true;
            }
        }
    }
    // 2ร—2-mi group dilation.
    let mut out = mask.clone();
    for r in 0..mi_rows {
        for c in 0..mi_cols {
            if mask[(r * mi_cols + c) as usize] {
                let (gr, gc) = (r & !1, c & !1);
                for rr in gr..(gr + 2).min(mi_rows) {
                    for cc in gc..(gc + 2).min(mi_cols) {
                        out[(rr * mi_cols + cc) as usize] = true;
                    }
                }
            }
        }
    }
    out
}

/// r426 โ€” the pixel-exact-region GOP entry point: encode at
/// `base_q_idx` with the demand `regions` coded PIXEL-EXACT through
/// the per-segment lossless machinery (`alt_q = [ 0, -base_q_idx ]`
/// โ€” segment 1's ยง7.12.2 qindex is exactly 0), optionally electing
/// additional synthetic leaves onto the lossless segment by twin
/// bits + distortion (`auto_detect`). The KEY frame is unsegmented
/// (r413 shape) โ€” the exactness contract covers the P-frames; a
/// segmented-KEY arm is the follow-up.
pub fn encode_gop_yuv420_with_q_lossless_regions(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    regions: &[LosslessRegion],
    auto_detect: bool,
) -> Result<EncodedGop, Error> {
    if base_q_idx == 0 {
        // Already CodedLossless everywhere โ€” the demand is vacuous.
        return encode_gop_yuv420_with_q(frames, 0);
    }
    let alt_q = [0i16, -i16::from(base_q_idx)];
    encode_gop_yuv420_with_q_seg_lossless_tuned(
        frames,
        base_q_idx,
        &alt_q,
        regions,
        auto_detect,
        GopTuning::default(),
    )
    .map(|t| t.gop)
}

/// r423 โ€” [`encode_gop_yuv420_with_q_seg`] with explicit
/// [`GopTuning`] switches (the measurement-harness entry point).
#[doc(hidden)]
pub fn encode_gop_yuv420_with_q_seg_tuned(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    alt_q: &[i16],
    tuning: GopTuning,
) -> Result<TunedGop, Error> {
    encode_gop_yuv420_with_q_seg_lossless_tuned(frames, base_q_idx, alt_q, &[], false, tuning)
}

/// r426 โ€” the full-surface GOP entry: segmentation deltas, exactness
/// demand rectangles, the auto-lossless election switch and the
/// [`GopTuning`] measurement switches. `regions`/`auto_detect`
/// require an `alt_q` table carrying a lossless segment (a delta
/// clamping the ยง7.12.2 qindex to 0).
#[doc(hidden)]
pub fn encode_gop_yuv420_with_q_seg_lossless_tuned(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    alt_q: &[i16],
    regions: &[LosslessRegion],
    auto_detect: bool,
    tuning: GopTuning,
) -> Result<TunedGop, Error> {
    encode_gop_yuv420_with_q_seg_extras_tuned(
        frames,
        base_q_idx,
        alt_q,
        regions,
        auto_detect,
        None,
        tuning,
    )
}

/// r426 โ€” the full-surface GOP entry (ladder items 6 + 8):
/// segmentation deltas, exactness-demand rectangles, the
/// auto-lossless election, the three ยง5.9.14 inter-override features
/// and the [`GopTuning`] measurement switches. `extras` requires a
/// non-empty `alt_q` (the segmentation carrier), a feature-free
/// segment 0 (the encoder's intra/skip-mode fallback segment), no
/// SEG_LVL_SKIP on a lossless segment (a skip block codes no
/// residual โ€” it cannot honour a qindex-0 exactness contract), and
/// SEG_LVL_REF_FRAME data within the P-GOP reference ladder.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn encode_gop_yuv420_with_q_seg_extras_tuned(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    alt_q: &[i16],
    regions: &[LosslessRegion],
    auto_detect: bool,
    extras: Option<&SegExtras>,
    tuning: GopTuning,
) -> Result<TunedGop, Error> {
    let wide: Vec<YuvFrame> = frames.iter().map(YuvFrame::from_yuv420_8bit).collect();
    let t = encode_gop_yuv_seg_extras_tuned(
        &wide,
        base_q_idx,
        alt_q,
        regions,
        auto_detect,
        extras,
        tuning,
    )?;
    Ok(TunedGop {
        gop: narrow_gop_8bit(t.gop),
        seg_temporal_updates: t.seg_temporal_updates,
        p_segment_maps: t.p_segment_maps,
        hp_mv_elections: t.hp_mv_elections,
        delta_q_elections: t.delta_q_elections,
        qm_elections: t.qm_elections,
        cdef_elections: t.cdef_elections,
        lr_elections: t.lr_elections,
        ctx_donor_elections: t.ctx_donor_elections,
        film_grain_elected: t.film_grain_elected,
        superres_inter_elections: t.superres_inter_elections,
    })
}

/// r427 โ€” general-format lossless GOP encode: see
/// [`encode_gop_yuv_with_q`].
pub fn encode_gop_yuv(frames: &[YuvFrame]) -> Result<EncodedGopYuv, Error> {
    encode_gop_yuv_with_q(frames, 0)
}

/// r427 โ€” encode a KEY + P GOP at any conformant (bit depth, chroma
/// format) pairing: the general-format sibling of
/// [`encode_gop_yuv420_with_q`] (whose 8-bit 4:2:0 arm now routes
/// through this driver). Every frame must carry the same dimensions,
/// bit depth and chroma format.
///
/// ## Errors
///
/// Same conditions as [`encode_gop_yuv420_with_q`] plus per-frame
/// [`YuvFrame::validate`] failures and cross-frame format mismatches
/// โ€” [`Error::PartitionWalkOutOfRange`].
pub fn encode_gop_yuv_with_q(frames: &[YuvFrame], base_q_idx: u8) -> Result<EncodedGopYuv, Error> {
    encode_gop_yuv_seg_extras_tuned(
        frames,
        base_q_idx,
        &[],
        &[],
        false,
        None,
        GopTuning::default(),
    )
    .map(|t| t.gop)
}

/// r433 โ€” KEY + P GOP with an explicitly configured ยง5.9.15
/// **NON-UNIFORM** tile layout on every frame
/// (`uniform_tile_spacing_flag = 0`): `widths_sb` / `heights_sb` in
/// superblock units per [`crate::tile_info::TileInfo::explicit_layout`].
///
/// ## Errors
///
/// * The layout is outside the ยง5.9.15 legal window, plus every
///   [`encode_gop_yuv_with_q`] reject โ€”
///   [`Error::PartitionWalkOutOfRange`].
pub fn encode_gop_yuv_with_q_tile_layout(
    frames: &[YuvFrame],
    base_q_idx: u8,
    widths_sb: &[u32],
    heights_sb: &[u32],
) -> Result<EncodedGopYuv, Error> {
    encode_gop_yuv_seg_extras_tuned_layout(
        frames,
        base_q_idx,
        &[],
        &[],
        false,
        None,
        GopTuning::default(),
        Some((widths_sb, heights_sb)),
    )
    .map(|t| t.gop)
}

/// 8-bit 4:2:0 sibling of [`encode_gop_yuv_with_q_tile_layout`].
pub fn encode_gop_yuv420_with_q_tile_layout(
    frames: &[Yuv420Frame],
    base_q_idx: u8,
    widths_sb: &[u32],
    heights_sb: &[u32],
) -> Result<EncodedGop, Error> {
    let wide: Vec<YuvFrame> = frames.iter().map(YuvFrame::from_yuv420_8bit).collect();
    encode_gop_yuv_with_q_tile_layout(&wide, base_q_idx, widths_sb, heights_sb).map(narrow_gop_8bit)
}

/// r427 โ€” the general-format GOP core: every entry point above
/// funnels here (through the r433 `_layout` sibling below, which
/// additionally threads a ยง5.9.15 non-uniform tile layout).
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn encode_gop_yuv_seg_extras_tuned(
    frames: &[YuvFrame],
    base_q_idx: u8,
    alt_q: &[i16],
    regions: &[LosslessRegion],
    auto_detect: bool,
    extras: Option<&SegExtras>,
    tuning: GopTuning,
) -> Result<TunedGopYuv, Error> {
    encode_gop_yuv_seg_extras_tuned_layout(
        frames,
        base_q_idx,
        alt_q,
        regions,
        auto_detect,
        extras,
        tuning,
        None,
    )
}

/// r433 โ€” [`encode_gop_yuv_seg_extras_tuned`] with an optional
/// ยง5.9.15 NON-UNIFORM tile layout (`(widths_sb, heights_sb)` in
/// superblock units, `uniform_tile_spacing_flag = 0` on every frame's
/// wire) overriding [`GopTuning::tiles`].
///
/// r441 โ€” this wrapper additionally owns the ยง5.9.30 FILM-GRAIN
/// election, under the documented "perceptually-neutral rate"
/// objective (grain is OUTPUT-ONLY and its noise field is by design
/// not sample-matched, so the grain arm's distortion is STRUCTURE
/// fidelity โ€” its pre-grain reconstruction against the DENOISED
/// source โ€” plus a per-frame noise-AMPLITUDE mismatch penalty
/// `luma_samples ยท (ฯƒ_src โˆ’ ฯƒ_syn)ยฒ`, while the plain arm keeps the
/// ordinary source-matched SSE; rate is exact realized IVF bytes on
/// both arms). The arm is spent only when the
/// [`crate::encoder::film_grain_elect::film_grain_probe`] content
/// gate fires (real noise energy, spatially white, temporally
/// decorrelated); probe-failing content stays bit-identical to the
/// baseline. On a win the published `recon` planes carry the ยง7.18.3
/// synthesis (the decoder's own driver โ€” byte-identical to its
/// output) while the reference chain inside the encode stayed
/// pre-grain, exactly the decoder's ยง7.20 store.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn encode_gop_yuv_seg_extras_tuned_layout(
    frames: &[YuvFrame],
    base_q_idx: u8,
    alt_q: &[i16],
    regions: &[LosslessRegion],
    auto_detect: bool,
    extras: Option<&SegExtras>,
    tuning: GopTuning,
    explicit_tiles: Option<(&[u32], &[u32])>,
) -> Result<TunedGopYuv, Error> {
    let plain = encode_gop_yuv_core_fg(
        frames,
        base_q_idx,
        alt_q,
        regions,
        auto_detect,
        extras,
        tuning,
        explicit_tiles,
        None,
    )?;
    // r441 โ€” ยง5.9.30 film-grain election gates: lossy twin-model
    // GOPs of at least two frames (the probe needs a
    // temporal-decorrelation witness). r450 lifts the unsegmented
    // gate for the plain SEG_LVL_ALT_Q ladder: the grain arm codes
    // the DENOISED frames under the same ยง5.9.14 table (the KEY of a
    // segmented GOP is itself unsegmented, so the grain block and
    // the feature table ride together only on the P headers). r456
    // lifts the two remaining table gates: FEATURE-EXTRA
    // segmentation (SEG_LVL_REF_FRAME / SKIP / GLOBALMV โ€” the arm
    // re-runs the r426 twin-priced feature trials over the denoised
    // frames under the same table) and tables carrying a LOSSLESS
    // segment (a `-base_q_idx`-clamped SEG_LVL_ALT_Q entry is a
    // quantiser choice, not a pixel contract โ€” the pre-grain ยง7.20
    // reference stays WHT-exact for the blocks the ladder puts
    // there, and ยง7.18.3 synthesis is output-only). Exactness-demand
    // regions and the auto-lossless election stay out: grain
    // synthesis on a demanded region would break the pixel contract.
    if !(tuning.film_grain
        && base_q_idx > 0
        && regions.is_empty()
        && !auto_detect
        && tuning.model == RateModel::Twin
        && frames.len() >= 2)
    {
        return Ok(plain);
    }
    let elected = elect_film_grain(
        frames,
        base_q_idx,
        plain.gop.seq.color_config.matrix_coefficients,
        plain.gop.ivf_bytes.len(),
        &plain.gop.recon,
        |denoised, fg| {
            encode_gop_yuv_core_fg(
                denoised,
                base_q_idx,
                alt_q,
                regions,
                auto_detect,
                extras,
                tuning,
                explicit_tiles,
                Some(fg),
            )
        },
        |c: &TunedGopYuv| (c.gop.ivf_bytes.len(), c.gop.recon.as_slice()),
    )?;
    match elected {
        Some((cand, grained)) => {
            let mut out = cand;
            out.gop.recon = grained;
            out.film_grain_elected = true;
            Ok(out)
        }
        None => Ok(plain),
    }
}

/// r452 โ€” the ยง5.9.30 film-grain ELECTION, driver-agnostic: the r441
/// probe, the r444/r447 parameter-set candidate ladder and the
/// perceptually-neutral-rate settlement (see
/// [`encode_gop_yuv_seg_extras_tuned_layout`]) over any driver that
/// can re-encode the DENOISED frames with an armed parameter set.
/// `encode(denoised, params)` runs the driver under the arm;
/// `view(&t)` exposes its realized IVF byte count and DISPLAY-order
/// pre-grain reconstructions. Returns the winning arm plus its
/// ยง7.18.3-synthesized output planes, or `None` when the plain arm
/// stands (probe failure, no candidate strictly under the plain
/// bytes, or no score win). `plain_bytes` / `plain_recon` describe
/// the caller's already-encoded plain arm; `mc` is the sequence's
/// `matrix_coefficients`.
pub(crate) fn elect_film_grain<T, F, V>(
    frames: &[YuvFrame],
    base_q_idx: u8,
    mc: u8,
    plain_bytes: usize,
    plain_recon: &[GopFrameReconYuv],
    mut encode: F,
    view: V,
) -> Result<Option<(T, Vec<GopFrameReconYuv>)>, Error>
where
    F: FnMut(&[YuvFrame], &FilmGrainParams) -> Result<T, Error>,
    V: Fn(&T) -> (usize, &[GopFrameReconYuv]),
{
    if frames.len() < 2 {
        return Ok(None);
    }
    use crate::encoder::film_grain_elect as fge;
    let dn01: Vec<YuvFrame> = frames[..2].iter().map(fge::denoise_frame).collect();
    if !fge::film_grain_probe(&frames[..2], &dn01) {
        return Ok(None);
    }
    let mut denoised = dn01;
    denoised.extend(frames[2..].iter().map(fge::denoise_frame));
    let est = fge::noise_estimate(&frames[0], &denoised[0]);
    let bit_depth = frames[0].bit_depth;
    let (width, height) = (frames[0].width, frames[0].height);
    let format = frames[0].format;
    let (ssx, ssy) = format.subsampling();
    let num_planes = format.num_planes();
    // r444 โ€” the parameter-set CANDIDATE ladder. Candidate 0 is the
    // r441 shape (white luma-only grain โ€” bit-identical params on
    // identical input); when the residual carries structure the spec
    // can model, further sets add fitted ยง5.9.30 AR taps (lag 1 and
    // lag 2 โ€” each ring costs real parameter bytes on EVERY frame
    // header, so the depth choice belongs to the score settlement,
    // never to a fit statistic alone) and/or per-plane chroma
    // scaling points (the chroma gate mirrors the luma probe at the
    // chroma extent: energy + spatial modelability + temporal
    // decorrelation, so moving chroma texture never masquerades as
    // grain).
    let mut chroma_cb =
        num_planes > 1 && fge::chroma_noise_gate(&frames[..2], &denoised[..2], 1, est.cb_sigma16);
    let mut chroma_cr =
        num_planes > 1 && fge::chroma_noise_gate(&frames[..2], &denoised[..2], 2, est.cr_sigma16);
    // ยง5.9.30 bitstream conformance: with 4:2:0 subsampling, film
    // grain is applied to BOTH chroma components or to NEITHER
    // (`num_cb_points == 0` โ‡” `num_cr_points == 0`) โ€” couple the
    // gates so a single-plane pass never puts a non-conformant
    // header on the wire.
    if ssx == 1 && ssy == 1 && !(chroma_cb && chroma_cr) {
        chroma_cb = false;
        chroma_cr = false;
    }
    if std::env::var_os("OXIDEAV_AV1_FG_DEBUG").is_some() {
        eprintln!(
            "fg-elect gates: cb {} cr {} (sigma16 y {} cb {} cr {})",
            chroma_cb, chroma_cr, est.sigma16, est.cb_sigma16, est.cr_sigma16
        );
    }
    let fit1 = fge::fit_ar_lag(&frames[0], &denoised[0], 1);
    let fit2 = fge::fit_ar_lag(&frames[0], &denoised[0], 2);
    // r456 โ€” the `ar_coeff_lag = 3` ring joins the ladder, GATED on
    // the residual actually carrying distance-3 horizontal structure
    // (|ฯ(3)| >= 0.2 on the first frame โ€” the r452 measurement showed
    // the 24-tap header never pays where the deeper lags are flat,
    // and each candidate is a full re-encode). The correlation-match
    // term below scores lags 1..=3, so the ring is scored on exactly
    // the structure it models.
    let fit3 = {
        let (w, h) = (width as usize, height as usize);
        (fge::lag_h_rho(&frames[0].y, &denoised[0].y, w, h, 3).abs() >= 0.2)
            .then(|| fge::fit_ar_lag(&frames[0], &denoised[0], 3))
            .flatten()
    };
    let mut cand_params: Vec<FilmGrainParams> = vec![fge::build_grain_params(
        &est, bit_depth, ssx, ssy, mc, None, false, false, false,
    )];
    // r447 โ€” the `chroma_scaling_from_luma` shape needs the chroma AR
    // lists on the wire too, so the white-grain csfl candidate rides
    // the lag-0 correlation-tap fit exactly like the points arm.
    let csfl_ok = chroma_cb && chroma_cr;
    let chroma_only: Option<fge::ArFit> = ((chroma_cb || chroma_cr) && fit1.is_none())
        .then(|| fge::fit_chroma_corr(&frames[0], &denoised[0]));
    for fit in [
        fit1.as_ref(),
        fit2.as_ref(),
        fit3.as_ref(),
        chroma_only.as_ref(),
    ]
    .into_iter()
    .flatten()
    {
        cand_params.push(fge::build_grain_params(
            &est,
            bit_depth,
            ssx,
            ssy,
            mc,
            Some(fit),
            chroma_cb,
            chroma_cr,
            false,
        ));
        // r447 โ€” the csfl twin of each fitted shape: chroma rides the
        // LUMA scaling function (ยง7.18.3.4 reads the luma points for
        // every plane, the ยง7.18.3.5 blend indexes it at the
        // co-located average luma), `num_cb_points = num_cr_points =
        // 0` and no mult/offset fields โ€” the whole per-plane point
        // surface is saved where the chroma noise amplitude tracks
        // luma. Offered only when BOTH chroma gates fire (csfl
        // synthesizes grain on both planes) and settled by the same
        // score + strictly-fewer-bytes mandate as every candidate.
        if csfl_ok {
            cand_params.push(fge::build_grain_params(
                &est,
                bit_depth,
                ssx,
                ssy,
                mc,
                Some(fit),
                false,
                false,
                true,
            ));
        }
    }
    // Perceptually-neutral-rate scoring (see the doc comment above;
    // r444 adds the chroma amplitude terms and a luma
    // CORRELATION-match term โ€” `samples ยท (ฯ_src โˆ’ ฯ_syn)ยฒ ยท ฯƒ_srcยฒ`
    // โ€” so an AR candidate wins exactly where the white one leaves
    // spatial structure unmodelled).
    let sse_pair = |a: &GopFrameReconYuv, f: &YuvFrame| -> u64 {
        let mut d = 0u64;
        for (x, y) in
            a.y.iter()
                .zip(&f.y)
                .chain(a.u.iter().zip(&f.u))
                .chain(a.v.iter().zip(&f.v))
        {
            let diff = i64::from(*x) - i64::from(*y);
            d += (diff * diff) as u64;
        }
        d
    };
    let d_plain: u64 = plain_recon
        .iter()
        .zip(frames)
        .map(|(rc, f)| sse_pair(rc, f))
        .sum();
    let lambda = lambda_for(&QuantizerParams::neutral(base_q_idx, bit_depth));
    let score_plain = score256(d_plain, lambda, (plain_bytes as u64) * 8 * 256);
    let shift = u32::from(bit_depth - 8);
    let mut best: Option<(T, Vec<GopFrameReconYuv>, u64)> = None;
    for fg_base in &cand_params {
        let cand = encode(&denoised, fg_base)?;
        let (cand_bytes, cand_recon) = view(&cand);
        // The published output planes: the ยง7.18.3 synthesis through
        // the decoder's own driver, per-frame seeds from the shared
        // schedule.
        let grained: Vec<GopFrameReconYuv> = cand_recon
            .iter()
            .enumerate()
            .map(|(k, rc)| {
                let mut fg = fg_base.clone();
                fg.grain_seed = fge::grain_seed_for(k as u32);
                let (gy, gu, gv) = fge::apply_grain_to_recon(
                    &fg, &rc.y, &rc.u, &rc.v, width, height, bit_depth, ssx, ssy, num_planes, mc,
                );
                GopFrameReconYuv {
                    y: gy,
                    u: gu,
                    v: gv,
                }
            })
            .collect();
        let mut d_grain: u64 = cand_recon
            .iter()
            .zip(&denoised)
            .map(|(rc, f)| sse_pair(rc, f))
            .sum();
        for k in 0..frames.len() {
            // Luma + chroma amplitude terms: (ฯƒ16 difference)ยฒ / 256
            // = ฯƒยฒ in 8-bit sampleยฒ units; scale back to the
            // stream's raw sampleยฒ scale.
            type PlaneRefs<'p> = (&'p [u16], &'p [u16], &'p [u16], &'p [u16], usize);
            let planes: [PlaneRefs<'_>; 3] = [
                (
                    &frames[k].y,
                    &denoised[k].y,
                    &grained[k].y,
                    &cand_recon[k].y,
                    frames[k].y.len(),
                ),
                (
                    &frames[k].u,
                    &denoised[k].u,
                    &grained[k].u,
                    &cand_recon[k].u,
                    frames[k].u.len(),
                ),
                (
                    &frames[k].v,
                    &denoised[k].v,
                    &grained[k].v,
                    &cand_recon[k].v,
                    frames[k].v.len(),
                ),
            ];
            for (src, den, syn, pre, samples) in planes {
                if samples == 0 {
                    continue;
                }
                let sig_src = fge::plane_sigma16(src, den, bit_depth);
                let sig_syn = fge::plane_sigma16(syn, pre, bit_depth);
                let diff = sig_src.abs_diff(sig_syn);
                d_grain += (samples as u64) * diff * diff * (1u64 << (2 * shift)) / 256;
            }
            // Correlation-match term (luma): unmodelled spatial
            // structure counts as noise energy times the squared
            // correlation gap โ€” r456: summed over lags 1..=3 (white
            // and lag-1 content leave the deeper gaps at ~0, so the
            // r444 settlement is unchanged there; distance-3
            // structure now reaches the score).
            let w = width as usize;
            let h = height as usize;
            let sig_src = fge::plane_sigma16(&frames[k].y, &denoised[k].y, bit_depth);
            let mut gap2 = 0.0f64;
            for lag in 1..=3usize {
                let rho_src = fge::lag_h_rho(&frames[k].y, &denoised[k].y, w, h, lag);
                let rho_syn = fge::lag_h_rho(&grained[k].y, &cand_recon[k].y, w, h, lag);
                let gap = rho_src - rho_syn;
                gap2 += gap * gap;
            }
            let term = (frames[k].y.len() as f64) * gap2 * ((sig_src * sig_src) as f64) / 256.0
                * f64::from(1u32 << (2 * shift));
            d_grain += term.round() as u64;
        }
        let score = score256(d_grain, lambda, (cand_bytes as u64) * 8 * 256);
        if std::env::var_os("OXIDEAV_AV1_FG_DEBUG").is_some() {
            eprintln!(
                "fg-elect cand: lag {} cb {} cr {} csfl {} bytes {} d_grain {} score {} | plain bytes {} d {} score {}",
                fg_base.ar_coeff_lag,
                fg_base.num_cb_points,
                fg_base.num_cr_points,
                fg_base.chroma_scaling_from_luma,
                cand_bytes,
                d_grain,
                score,
                plain_bytes,
                d_plain,
                score_plain
            );
        }
        // The tool's mandate is RATE at perceptually-neutral quality:
        // a candidate that scores better only through the
        // structure-side distortion asymmetry but realizes MORE bytes
        // than the plain arm is not a win โ€” eligibility demands
        // strictly fewer bytes PER CANDIDATE (r444: a deeper
        // parameter set may outscore the white one on the neutrality
        // terms yet forfeit the rate mandate; the white candidate
        // stays eligible on its own bytes).
        if cand_bytes < plain_bytes && best.as_ref().map(|(_, _, s)| score < *s).unwrap_or(true) {
            best = Some((cand, grained, score));
        }
    }
    match best {
        Some((cand, grained, score_grain)) if score_grain < score_plain => {
            Ok(Some((cand, grained)))
        }
        _ => Ok(None),
    }
}

/// The GOP core behind [`encode_gop_yuv_seg_extras_tuned_layout`]:
/// one complete KEY + P encode, with an optional armed ยง5.9.30
/// film-grain parameter set riding every frame header (per-frame
/// seeds from [`crate::encoder::film_grain_elect::grain_seed_for`];
/// reconstructions stay PRE-grain).
#[allow(clippy::too_many_arguments)]
fn encode_gop_yuv_core_fg(
    frames: &[YuvFrame],
    base_q_idx: u8,
    alt_q: &[i16],
    regions: &[LosslessRegion],
    auto_detect: bool,
    extras: Option<&SegExtras>,
    tuning: GopTuning,
    explicit_tiles: Option<(&[u32], &[u32])>,
    film_grain: Option<&FilmGrainParams>,
) -> Result<TunedGopYuv, Error> {
    if let Some(x) = extras {
        let ll = seg_lossless_array(base_q_idx, alt_q);
        if alt_q.is_empty()
            || x.ref_frame[0].is_some()
            || x.skip[0]
            || x.globalmv[0]
            || x.ref_frame.iter().flatten().any(|rf| !(1..=7).contains(rf))
            || (0..crate::uncompressed_header_tail::MAX_SEGMENTS).any(|s| x.skip[s] && ll[s])
        {
            return Err(Error::PartitionWalkOutOfRange);
        }
    }
    let model = tuning.model;
    let global_motion = tuning.global_motion;
    if frames.is_empty() || frames.len() > GOP_MAX_FRAMES {
        return Err(Error::PartitionWalkOutOfRange);
    }
    if !alt_q.is_empty() {
        if alt_q.len() == 1
            || alt_q.len() > crate::uncompressed_header_tail::MAX_SEGMENTS
            || alt_q[0] != 0
            || base_q_idx == 0
        {
            return Err(Error::PartitionWalkOutOfRange);
        }
        for &d in alt_q {
            // ยง5.9.14 su(1+8) representability; ยง7.12.2 clamps the
            // derived qindex at 0 (the r426 per-segment lossless
            // election) but over-255 sums are rejected as dead weight.
            if !(-255..=255).contains(&d) || i32::from(base_q_idx) + i32::from(d) > 255 {
                return Err(Error::PartitionWalkOutOfRange);
            }
        }
    }
    let (width, height) = (frames[0].width, frames[0].height);
    let (bit_depth, format) = (frames[0].bit_depth, frames[0].format);
    if frames.iter().any(|f| {
        f.width != width || f.height != height || f.bit_depth != bit_depth || f.format != format
    }) {
        return Err(Error::PartitionWalkOutOfRange);
    }

    // Frame 0: the r410 conformance-grade KEY-frame encoder (which
    // also validates the dimension rules). r423: also take the KEY
    // frame's ยง7.20 slot payload โ€” its `allFrames` refresh seeds
    // every slot of the carry store below. r426: with demand
    // rectangles the KEY frame is SEGMENTED too (same delta table,
    // ยง5.11.8 per-block segment ids) so the demanded region is
    // pixel-exact from frame 0, not just on the P-frames.
    let key_mask: Option<Vec<bool>> = (!regions.is_empty()).then(|| {
        // ยง5.9.5: dimensions are validated multiples of 8, so
        // `MiCols = width / 4` / `MiRows = height / 4` exactly (the
        // same grid the fh builder below derives).
        build_exact_mask(regions, width, height, height / 4, width / 4)
    });
    // r436 โ€” arm the ยง6.8.14 donor election: multi-tile layouts
    // with a primary-reference chain (single-tile frames have no
    // `context_update_tile_id` field; without a primary chain
    // nobody consumes the donation).
    let donor_armed = tuning.ctx_update_elect
        && tuning.primary_ref
        && (tuning.tiles != (0, 0) || explicit_tiles.is_some());
    // r441 โ€” the KEY's per-frame ยง5.9.30 seed rides the shared
    // schedule at display position 0.
    let key_fg: Option<FilmGrainParams> = film_grain.map(|base| {
        let mut f = base.clone();
        f.grain_seed = crate::encoder::film_grain_elect::grain_seed_for(0);
        f
    });
    // r456 โ€” the mid-GOP ยง5.9.8 INTER superres election arms under the
    // KEY arm's own regime (quantiser window, extent, the horizontal
    // smoothness probe on at least one P-frame's source) on plain
    // GOPs โ€” no segmentation table (the ยง5.11.19 map inherits across
    // an mi-grid mismatch), no exactness demand, twin pricing; an
    // explicit tile layout remaps its column widths per candidate.
    // Arming opens the sequence gate for the WHOLE GOP
    // (every frame header then carries its `use_superres` bit, the
    // KEY included); content failing the probe on every frame stays
    // bit-identical to the pre-r456 shape.
    let sr_inter_armed = tuning.superres
        && base_q_idx > 0
        && alt_q.is_empty()
        && regions.is_empty()
        && !auto_detect
        && model == RateModel::Twin
        && crate::encoder::superres_elect::superres_arm_allowed(
            base_q_idx,
            width as usize,
            height as usize,
        )
        && frames
            .iter()
            .skip(1)
            .any(crate::encoder::superres_elect::superres_probe);
    let (key, key_carry) = crate::encoder::key_frame::encode_key_frame_yuv_full(
        &frames[0],
        base_q_idx,
        model,
        if key_mask.is_some() { alt_q } else { &[] },
        key_mask.as_deref(),
        // r436 โ€” CDEF is armed on segmented GOPs too (the r428
        // scope gate is lifted; the KEY of a plain segmented GOP is
        // itself unsegmented โ€” it takes the table only under
        // exactness-demand masks, where the encoder-side
        // `exact_mask` gate closes CDEF anyway).
        tuning.cdef,
        tuning.cdef_units,
        // r436 โ€” LR joins CDEF on segmented GOPs (the KEY of a
        // plain segmented GOP is itself unsegmented; under
        // exactness-demand masks the encoder-side gate closes LR).
        tuning.lr,
        &crate::encoder::key_frame::KeyExtras {
            // r431 โ€” the GOP-wide ยง5.9.15 tile layout (r433: the
            // explicit non-uniform override rides beside it), r433 โ€”
            // the GOP-wide ยง5.11.1 tile-group packaging.
            tiles: tuning.tiles,
            tile_groups: tuning.tile_groups,
            tile_spans: tuning.tile_spans,
            explicit_tiles,
            // r431 โ€” the KEY frame rides the same ยง5.9.17 delta-q
            // switch as the P-frames; r439 โ€” and the ยง5.9.12 QM
            // switch.
            delta_q: tuning.delta_q,
            qm: tuning.qm,
            // r441 โ€” ยง5.9.8 superres on the KEY. r444: segmented
            // GOPs too โ€” the KEY of a plain segmented GOP is itself
            // unsegmented, and the P-frames' ยง5.11.19 temporal
            // prediction over the KEY's mi-grid-mismatched
            // SavedSegmentIds takes the spec's all-zero
            // `load_previous_segment_ids()` arm, which BOTH the
            // decode driver and the write mirror already derive
            // (extent-checked carry).
            superres_elect: tuning.superres,
            // r441 โ€” the armed ยง5.9.30 parameter set (opens the
            // sequence gate for the whole GOP).
            film_grain: key_fg.as_ref(),
            // r436 โ€” the KEY donates too: collect its per-tile end
            // CDFs.
            collect_donor_cdfs: donor_armed,
            // r456 โ€” the mid-GOP inter election's sequence gate.
            superres_gate: sr_inter_armed,
            ..crate::encoder::key_frame::KeyExtras::default()
        },
    )?;
    let seq = key.seq.clone();
    // r456 โ€” the KEY-elected ยง5.9.8 denominator seeds the inter
    // candidate set (see `inter_candidate_denoms`).
    let key_sr_denom: Option<u32> = key
        .fh
        .frame_size
        .as_ref()
        .and_then(|fs| fs.use_superres.then_some(fs.superres_denom));
    let sr_lambda =
        crate::encoder::key_frame::lambda_for(&QuantizerParams::neutral(base_q_idx, bit_depth));
    let mut temporal_units = vec![key.temporal_unit_bytes.clone()];
    let mut recon = vec![GopFrameReconYuv {
        y: key.recon_y,
        u: key.recon_u,
        v: key.recon_v,
    }];

    // r413 โ€” encoder-side ยง7.20 motion-field store: the KEY frame's
    // `allFrames` refresh fills every slot with an intra payload;
    // each P-frame then refreshes its rotation slot with the ยง7.19
    // filter of its committed Mvs[] / RefFrames[] grids.
    let key_mi = {
        let fh0 = build_intra_only_yuv420_8bit_fh_with_q(&seq, width, height, base_q_idx);
        let fs0 = fh0.frame_size.expect("KEY builder always sizes");
        (fs0.mi_rows, fs0.mi_cols)
    };
    // r426 โ€” exactness-demand mask + auto-lossless election arming:
    // both require a lossless segment in the table.
    if (!regions.is_empty() || auto_detect)
        && !seg_lossless_array(base_q_idx, alt_q)[..alt_q.len()]
            .iter()
            .any(|&l| l)
    {
        return Err(Error::PartitionWalkOutOfRange);
    }
    let exact_mask: Option<Vec<bool>> =
        (!regions.is_empty()).then(|| build_exact_mask(regions, width, height, key_mi.0, key_mi.1));
    let mut mf_store: [SavedMotionField; 8] =
        core::array::from_fn(|_| SavedMotionField::intra(key_mi.0, key_mi.1));
    // r423 โ€” encoder-side ยง7.20 cross-frame carry store (CDFs /
    // segment map / gm params per slot). The KEY frame's `allFrames`
    // refresh fills every slot with its payload; each P-frame then
    // refreshes its rotation slot, exactly like `mf_store`.
    let key_carry = std::rc::Rc::new(key_carry);
    let mut carry_store: [std::rc::Rc<RefSlotCarry>; 8] =
        core::array::from_fn(|_| key_carry.clone());
    // r436 โ€” which temporal unit each slot's carried frame lives in
    // (the donor patch rewrites that unit's header field in place).
    let mut carry_tu: [usize; 8] = [0; 8];
    let mut seg_temporal_updates: Vec<bool> = Vec::new();
    let mut p_segment_maps: Vec<Vec<i32>> = Vec::new();
    let mut hp_mv_elections: Vec<bool> = Vec::new();
    let mut delta_q_elections: Vec<bool> = Vec::new();
    let mut qm_elections: Vec<bool> = Vec::new();
    let mut cdef_elections: Vec<bool> = Vec::new();
    let mut lr_elections: Vec<bool> = Vec::new();
    let mut ctx_donor_elections: Vec<Option<u32>> = Vec::new();
    let mut superres_inter_elections: Vec<Option<u32>> = Vec::new();

    // r447 โ€” the all-slot-refresh FLOOR: the most recent frame that
    // overwrote every ยง7.20 slot (the KEY at 0; each SWITCH frame
    // advances it). Slots outside the two-slot rotation hold the
    // floor frame โ€” its hint, its motion field, its carry.
    let mut floor: u32 = 0;
    for (k, input) in frames[1..].iter().enumerate() {
        let p_index = (k + 1) as u32;
        // r447 โ€” the ยง5.9.2 SWITCH-frame cadence (see
        // [`GopTuning::s_frame_period`]).
        let is_s = tuning.s_frame_period > 0 && p_index % tuning.s_frame_period == 0;
        // r450 โ€” the CODED error-resilient cadence (see
        // [`GopTuning::error_resilient_period`]); an S-frame position
        // keeps the SWITCH shape (the flag is inferred there).
        let is_er = !is_s
            && tuning.error_resilient_period > 0
            && p_index % tuning.error_resilient_period == 0;
        let prev = recon.last().expect("at least the KEY recon");
        // GOLDEN's slot holds frame `max(floor, p_index - 2)` (the
        // rotation refresher, unless the floor frame overwrote every
        // slot more recently).
        let prevprev = &recon[p_index.saturating_sub(2).max(floor) as usize];
        // r423 โ€” the primary reference is LAST (ordinal 0): slot
        // `p_index & 1`, holding frame `p_index - 1`. r447 โ€” a
        // SWITCH frame is error-resilient: PRIMARY_REF_NONE by
        // ยง5.9.2 inference, so no carry is consumed.
        let primary = if tuning.primary_ref && !is_s && !is_er {
            Some(carry_store[(p_index & 1) as usize].clone())
        } else {
            None
        };
        // r441 โ€” the P-frame's per-frame ยง5.9.30 seed rides the
        // shared schedule at its display position.
        let p_fg: Option<FilmGrainParams> = film_grain.map(|base| {
            let mut f = base.clone();
            f.grain_seed = crate::encoder::film_grain_elect::grain_seed_for(p_index);
            f
        });
        let encode_arm = |arm_input: &YuvFrame, superres: Option<(u32, u32)>| {
            encode_p_frame_yuv(
                arm_input,
                prev,
                prevprev,
                &seq,
                base_q_idx,
                p_index,
                alt_q,
                &mf_store,
                model,
                global_motion,
                primary.as_deref(),
                tuning.temporal_seg,
                exact_mask.as_deref(),
                auto_detect,
                extras,
                tuning.high_precision_mv,
                tuning.delta_q,
                tuning.qm,
                tuning.cdef,
                tuning.cdef_units,
                tuning.lr,
                tuning.tiles,
                tuning.tile_groups,
                tuning.tile_spans,
                explicit_tiles,
                donor_armed,
                p_fg.as_ref(),
                floor,
                &recon[floor as usize],
                is_s,
                is_er,
                tuning.short_ref_signaling,
                superres,
                superres.is_some().then_some(input),
            )
        };
        let mut best = encode_arm(input, None)?;
        let mut sr_elected: Option<u32> = None;
        // r456 โ€” the mid-GOP ยง5.9.8 INTER election: on probe-passing
        // P-frames each bounded candidate denominator codes the
        // DOWNSCALED source against the upscaled-extent references
        // (the ยง7.11.3.3 scaled path), the reconstruction comes back
        // ยง7.16-upscaled, and the joint objective over ORIGINAL-extent
        // SSE + exact realized temporal-unit bytes keeps the winner โ€”
        // the same settlement the KEY arm uses. SWITCH / coded
        // error-resilient positions keep the flat shape.
        if sr_inter_armed
            && !is_s
            && !is_er
            && crate::encoder::superres_elect::superres_probe(input)
        {
            let sr_score = |tu: &[u8], rc: &GopFrameReconYuv| -> u64 {
                let mut d = 0u64;
                for (a, b) in
                    rc.y.iter()
                        .zip(&input.y)
                        .chain(rc.u.iter().zip(&input.u))
                        .chain(rc.v.iter().zip(&input.v))
                {
                    let diff = i64::from(*a) - i64::from(*b);
                    d += (diff * diff) as u64;
                }
                score256(d, sr_lambda, (tu.len() as u64) * 8 * 256)
            };
            let mut best_score = sr_score(&best.0, &best.1);
            for denom in crate::encoder::superres_elect::inter_candidate_denoms(
                width,
                height,
                tuning.tiles,
                explicit_tiles,
                key_sr_denom,
            ) {
                let wd = crate::encoder::superres_elect::superres_coded_width(width, denom);
                let down = crate::encoder::superres_elect::downscale_width(input, wd);
                let cand = encode_arm(&down, Some((width, denom)))?;
                let sc = sr_score(&cand.0, &cand.1);
                if sc < best_score {
                    best_score = sc;
                    best = cand;
                    sr_elected = Some(denom);
                }
            }
        }
        superres_inter_elections.push(sr_elected);
        let (tu, rc, saved_mf, carry, aux) = best;
        temporal_units.push(tu);
        recon.push(rc);
        // r436 โ€” a ยง6.8.14 donor win: patch the PRIMARY frame's
        // already-emitted `context_update_tile_id` to the elected
        // tile and fix every slot holding that frame's carry so its
        // `cdfs` is the elected donation (the donor set is cleared โ€”
        // the election is committed once; ยง7.20 slots sharing the
        // same frame all point at the same fixed carry).
        if let Some(t) = aux.donor_elected {
            let src_slot = (p_index & 1) as usize;
            let elected_from = carry_store[src_slot].clone();
            let span = elected_from
                .ctx_update_span
                .expect("donor election only fires on multi-tile primaries");
            patch_ctx_update_in_tu(&mut temporal_units[carry_tu[src_slot]], span, t);
            let fixed = std::rc::Rc::new(RefSlotCarry {
                cdfs: elected_from.donor_cdfs[t as usize].clone(),
                segment_ids: elected_from.segment_ids.clone(),
                mi_rows: elected_from.mi_rows,
                mi_cols: elected_from.mi_cols,
                gm_params: elected_from.gm_params,
                donor_cdfs: Vec::new(),
                ctx_update_span: None,
            });
            for slot in carry_store.iter_mut() {
                if std::rc::Rc::ptr_eq(slot, &elected_from) {
                    *slot = fixed.clone();
                }
            }
        }
        seg_temporal_updates.push(aux.seg_temporal);
        hp_mv_elections.push(aux.hp_mv);
        delta_q_elections.push(aux.delta_q);
        qm_elections.push(aux.qm);
        cdef_elections.push(aux.cdef);
        lr_elections.push(aux.lr);
        ctx_donor_elections.push(aux.donor_elected);
        if !alt_q.is_empty() {
            p_segment_maps.push(carry.segment_ids.clone());
        }
        // ยง7.20: a plain P-frame refreshed slot `(p_index - 1) & 1`;
        // r447 โ€” a SWITCH frame refreshed EVERY slot
        // (`refresh_frame_flags = allFrames`): its motion field,
        // carry and temporal-unit ordinal land in all eight, and the
        // floor advances to it.
        if is_s {
            floor = p_index;
            let carry_rc = std::rc::Rc::new(carry);
            for slot in 0..8usize {
                mf_store[slot] = saved_mf.clone();
                carry_store[slot] = carry_rc.clone();
                carry_tu[slot] = p_index as usize;
            }
        } else {
            mf_store[((p_index - 1) & 1) as usize] = saved_mf;
            carry_store[((p_index - 1) & 1) as usize] = std::rc::Rc::new(carry);
            carry_tu[((p_index - 1) & 1) as usize] = p_index as usize;
        }
    }

    // IVF v0 wrap.
    let mut ivf_bytes: Vec<u8> = Vec::new();
    {
        let cursor = std::io::Cursor::new(&mut ivf_bytes);
        let mut iw = IvfWriter::new(cursor, FOURCC_AV01, width as u16, height as u16, 25, 1)
            .map_err(|_| Error::PartitionWalkOutOfRange)?;
        for (idx, tu) in temporal_units.iter().enumerate() {
            iw.write_frame(tu, idx as u64)
                .map_err(|_| Error::PartitionWalkOutOfRange)?;
        }
        iw.patch_frame_count()
            .map_err(|_| Error::PartitionWalkOutOfRange)?;
    }

    Ok(TunedGopYuv {
        gop: EncodedGopYuv {
            ivf_bytes,
            temporal_units,
            recon,
            seq,
        },
        seg_temporal_updates,
        p_segment_maps,
        hp_mv_elections,
        delta_q_elections,
        qm_elections,
        cdef_elections,
        lr_elections,
        ctx_donor_elections,
        film_grain_elected: false,
        superres_inter_elections,
    })
}

/// ยง5.9.2 INTER P-frame header for the r412 GOP configuration โ€”
/// derived from the KEY builder with the inter-path fields set (see
/// the module docs for the exact configuration).
///
/// r412 two-slot reference rotation (`p_index` is the 1-based
/// P-frame index): frame `k` refreshes slot `(k - 1) & 1`, reads
/// LAST (and every other reference except GOLDEN) from slot `k & 1`
/// โ€” the slot holding frame `k - 1` โ€” and GOLDEN from slot
/// `(k - 1) & 1`, which still holds frame `k - 2` when the header is
/// read (ยง7.20 updates the store AFTER decoding; for `k <= 2` both
/// slots reach back to the KEY frame, which every slot holds after
/// the KEY's `allFrames` refresh).
/// Output order hints of the two rotated references at P-frame
/// `p_index = k` (1-based): LAST holds frame `k - 1`, GOLDEN frame
/// `k - 2`, clamped at the KEY frame (hint 0).
#[cfg(test)]
fn gop_ref_hints(p_index: u32) -> (u32, u32) {
    gop_ref_hints_floor(p_index, 0)
}

/// r447 โ€” [`gop_ref_hints`] under an all-slot-refresh FLOOR: the
/// most recent frame that overwrote every ยง7.20 slot (the KEY at 0,
/// or the latest SWITCH frame). LAST always holds frame
/// `p_index - 1`; GOLDEN's slot was last refreshed by the rotation
/// at `p_index - 2` OR by the floor frame, whichever came later.
fn gop_ref_hints_floor(p_index: u32, floor: u32) -> (u32, u32) {
    (p_index - 1, p_index.saturating_sub(2).max(floor))
}

/// ยง5.9.2-derived [`FrameInterOrderHints`] for P-frame `p_index` โ€”
/// `OrderHints[ ref ]` per raw `RefFrame` value (`LAST_FRAME..=
/// ALTREF_FRAME` read the LAST slot except `GOLDEN_FRAME`).
#[cfg(test)]
fn gop_order_hints(p_index: u32, order_hint_bits: u8) -> crate::cdf::FrameInterOrderHints {
    let (last_hint, golden_hint) = gop_ref_hints(p_index);
    let mut by_ref = [0i32; crate::uncompressed_header_tail::ALTREF_FRAME + 1];
    for (r, hint) in by_ref.iter_mut().enumerate().skip(1) {
        // GOLDEN_FRAME = 4; every other reference maps to the LAST slot.
        *hint = if r == 4 {
            golden_hint as i32
        } else {
            last_hint as i32
        };
    }
    crate::cdf::FrameInterOrderHints {
        order_hint_bits: u32::from(order_hint_bits),
        current_order_hint: p_index as i32,
        order_hints_by_ref: by_ref,
    }
}

/// r415 โ€” one INTER frame's reference/role configuration for the
/// generic frame encoder ([`encode_inter_frame_generic`]): the ยง5.9.2
/// header fields that vary per pyramid role, the ยง7.20 slot state,
/// and the RD ladder.
pub(crate) struct InterFrameConfig<'a> {
    /// ยง5.9.2 `order_hint` โ€” the frame's DISPLAY position.
    pub order_hint: u32,
    /// ยง5.9.2 `show_frame` (`false` = decoded-not-shown; a later
    /// `show_existing_frame` header displays it).
    pub show_frame: bool,
    /// ยง5.9.2 `refresh_frame_flags`.
    pub refresh_frame_flags: u8,
    /// ยง5.9.2 `ref_frame_idx[ 0..7 ]` โ€” per-reference ยง7.20 slot.
    pub ref_frame_idx: [u8; 7],
    /// r452 โ€” code the header with `frame_refs_short_signaling = 1`
    /// (ยง5.9.2): `ref_frame_idx` above must already BE the ยง7.8
    /// `set_frame_refs()` derivation for this frame's
    /// `last_frame_idx = ref_frame_idx[ 0 ]` / `gold_frame_idx =
    /// ref_frame_idx[ 3 ]` over `slot_hints` (the caller adopts the
    /// derivation โ€” see [`GopTuning::short_ref_signaling`]).
    pub short_ref_signaling: bool,
    /// The TRUE per-slot stored `RefOrderHint[ i ]` state at this
    /// frame's header (drives the ยง5.9.22 twin + ยง7.8 sign bias).
    pub slot_hints: [u32; 8],
    /// RD ladder โ€” see [`PSearchCtx::single_refs`] /
    /// [`PSearchCtx::compound_pairs`].
    pub single_refs: Vec<i8>,
    pub compound_pairs: Vec<[i8; 2]>,
    /// The distinct reference reconstructions + the ยง7.20 slot map
    /// onto them โ€” see [`PSearchCtx::slot_to_plane`].
    pub refs: Vec<&'a GopFrameReconYuv>,
    pub slot_to_plane: [usize; 8],
    /// r423 โ€” ยง5.9.2 `primary_ref_frame`: the ordinal into
    /// `ref_frame_idx[]` whose slot's saved state (CDFs, segment map,
    /// gm params) this frame inherits, or [`PRIMARY_REF_NONE`] for
    /// per-frame default state.
    pub primary_ref_frame: u8,
    /// r423 โ€” the ยง7.20 stored state of
    /// `ref_frame_idx[ primary_ref_frame ]`. MUST be `Some` whenever
    /// `primary_ref_frame != PRIMARY_REF_NONE`.
    pub primary_carry: Option<&'a RefSlotCarry>,
    /// r423 โ€” allow the ยง5.9.14 `temporal_update` election on this
    /// frame (see [`GopTuning::temporal_seg`]). Only consulted on
    /// segmented frames with a primary reference.
    pub allow_temporal_seg: bool,
    /// r424 โ€” alternative ยง5.9.2 `primary_ref_frame` candidates for
    /// the exact-bytes election: after the main pass (searched and
    /// written under `primary_ref_frame` / `primary_carry` above),
    /// the committed trees are replayed bit-exactly from each
    /// candidate's ยง8.3.1 frame-start CDF state and the smallest
    /// total frame (header + tile) wins. `(PRIMARY_REF_NONE, None)`
    /// is the per-frame-defaults candidate. All candidates decode to
    /// the identical reconstruction (the trees carry every mode /
    /// coefficient value; only the adaptive-coding bits and the
    /// ยง5.9.24 gm recentering differ), so the election is purely
    /// rate. Incompatible with the segmented temporal-update election
    /// (caller bug โ€” the pyramid drivers that use this never
    /// segment).
    pub alt_primaries: Vec<(u8, Option<&'a RefSlotCarry>)>,
    /// r426 โ€” exactness-demand mask (row-major `mi_rows ร— mi_cols`
    /// cells; `None` = no demand). Requires a lossless segment in the
    /// frame's `alt_q` table. Leaves overlapping demanded cells are
    /// forced onto the lossless segment on every arm, making the
    /// demanded region reconstruct pixel-exact.
    pub exact_mask: Option<&'a [bool]>,
    /// r426 โ€” content-driven per-segment-lossless election for
    /// leaves OUTSIDE the demand mask (see
    /// [`GopTuning`]-level docs on the twin-priced trial).
    pub auto_lossless: bool,
    /// r426 โ€” the three ยง5.9.14 inter-override features (ladder item
    /// 8): SEG_LVL_REF_FRAME / SEG_LVL_SKIP / SEG_LVL_GLOBALMV per
    /// segment. `Some` requires a non-empty `alt_q` table (the
    /// segmentation-enabled carrier) and flips `SegIdPreSkip` to 1.
    pub seg_extras: Option<&'a SegExtras>,
    /// r428 โ€” ยง5.9.2 `allow_high_precision_mv` arm: `true` searches
    /// and writes under eighth-pel MV precision (the sub-pel
    /// refinement adds a ยฑ1-in-1/8-units pass and every ยง5.11.32 MV
    /// difference codes the `mv_hp` cascade), then the per-frame
    /// exact-bytes election below may still flip the header flag to
    /// the quarter-pel arm when the identical committed trees replay
    /// smaller. `false` keeps the pre-r428 quarter-pel search + wire
    /// shape unconditionally (the A/B baseline).
    pub high_precision_mv: bool,
    /// r428 โ€” ยง5.9.17 per-superblock delta-q arm: when the complexity
    /// probe finds real activity spread on an UNSEGMENTED lossy
    /// frame, a second full search runs under a per-superblock
    /// `CurrentQIndex` plan (ยง5.11.13 deltas on the wire) and the
    /// frame-level exact-realized-bytes election keeps whichever arm
    /// scores better under `D + ฮปยทR`. `false` keeps the pre-r428
    /// single-quantiser shape unconditionally (the A/B baseline).
    pub delta_q: bool,
    /// r439 โ€” ยง5.9.12 quantizer-matrix arm: on an UNSEGMENTED lossy
    /// frame whose luma carries real high-frequency energy (the
    /// [`qm_probe`] gate), a second full search runs under
    /// `using_qmatrix = 1` with the ยง9.5.3 level from
    /// [`qm_level_for_q`] on all three planes (the ยง7.12.3 QM-scaled
    /// `q2` on every quantise/dequantise step), and a frame-level
    /// joint-objective election over exact realized (header + tile)
    /// bytes keeps the better arm. `false` keeps the flat-quantiser
    /// shape unconditionally (the A/B baseline).
    pub qm: bool,
    /// r428 โ€” frame-level ยง5.9.19/ยง7.15 CDEF arm: after the tile is
    /// committed the reconstruction is filtered through the decoder's
    /// own ยง7.15 driver over the write mirror's grids, a bounded
    /// strength search scores candidates against the SOURCE, and the
    /// winner (when it beats the unfiltered frame) lands in the
    /// header and in the reference-store reconstruction. ZERO tile
    /// bits at `cdef_bits = 0` โ€” the election is pure distortion.
    /// `false` keeps the all-zero-strength header shape (the A/B
    /// baseline).
    pub cdef: bool,
    /// r429 โ€” allow `cdef_bits > 0` (per-64ร—64 ยง5.11.56 strength
    /// ids; tile re-emitted with the exact literals). `false` caps
    /// the election at the frame-level arm. Inert while
    /// [`Self::cdef`] is off.
    pub cdef_units: bool,
    /// r429 โ€” ยง5.9.20/ยง7.17 loop-restoration election (see
    /// [`GopTuning::lr`]).
    pub lr: bool,
    /// r430 โ€” freeze the CDF state: code the frame with
    /// `disable_cdf_update = 1` AND `disable_frame_end_update_cdf =
    /// 1` (the ยง7.3 large-scale-tile camera-frame shape โ€” every
    /// symbol prices against the frame-start CDFs and the frame
    /// donates no adapted state). `false` keeps the adaptive shape
    /// every other driver uses.
    pub freeze_cdfs: bool,
    /// r431 โ€” the ยง5.9.15 uniform tile layout: `(TileColsLog2,
    /// TileRowsLog2)`. `(0, 0)` is the single-tile shape every
    /// pre-r431 driver codes (bit-identical). A multi-tile layout
    /// walks/searches/emits per tile (fresh ยง8.2 partition + ยง8.3.1
    /// frame-start CDFs per tile) and every post-tile replay election
    /// re-emits ALL tiles; the layout must sit inside the ยง5.9.15
    /// legal window for the frame size (see
    /// [`crate::tile_info::TileInfo::uniform_layout`]).
    pub tiles: (u32, u32),
    /// r433 โ€” ยง5.11.1 tile-group packaging: split the frame's tiles
    /// across this many `OBU_TILE_GROUP` OBUs (standalone
    /// `OBU_FRAME_HEADER` + contiguous `tg_start ..= tg_end` slices)
    /// instead of the single ยง5.10 `OBU_FRAME`. `0` / `1` keep the
    /// historical one-OBU shape; clamps to the realized tile count.
    /// The per-tile entropy payloads are byte-identical either way.
    pub tile_groups: u32,
    /// r436 โ€” collect every tile's frame-end adapted CDF state into
    /// the returned carry ([`RefSlotCarry::donor_cdfs`]) so a LATER
    /// frame chaining its ยง8.3.1 primary reference off this frame's
    /// slot can run the ยง6.8.14 donor election. Inert on single-tile
    /// layouts.
    pub collect_donor_cdfs: bool,
    /// r436 โ€” ยง6.8.14 `context_update_tile_id` ELECTION: when the
    /// primary carry offers donor candidates
    /// ([`RefSlotCarry::donor_cdfs`]) and the main primary reference
    /// survives the r424 ordinal election, replay the committed trees
    /// from EACH candidate tile's frame-end CDF state and keep the
    /// start state realizing the smallest assembled tile body (the
    /// header is donor-invariant โ€” the election is exact realized
    /// bytes, and every candidate decodes to the identical
    /// reconstruction). A win is reported via
    /// [`InterFrameAux::donor_elected`]; the caller patches the
    /// primary frame's `context_update_tile_id` on the wire.
    pub elect_donor: bool,
    /// r433 โ€” ยง5.9.15 NON-UNIFORM (explicit) tile layout: per-column
    /// widths and per-row heights in superblock units
    /// (`uniform_tile_spacing_flag = 0`). Overrides
    /// [`InterFrameConfig::tiles`] when `Some`; must satisfy the
    /// ยง5.9.15 legal window (see
    /// [`crate::tile_info::TileInfo::explicit_layout`]).
    pub explicit_tiles: Option<(&'a [u32], &'a [u32])>,
    /// r441 โ€” the armed ยง5.9.30 film-grain parameter set for THIS
    /// frame (`apply_grain = 1`, full parameters, `update_grain = 1`,
    /// per-frame `grain_seed`). OUTPUT-ONLY: the reconstruction /
    /// ยง7.20 reference payload stays pre-grain; the GOP-level
    /// election applies the ยง7.18.3 synthesis to the published
    /// output planes. `None` keeps the pre-r441 header shape (the
    /// sequence gate is closed unless the KEY armed it).
    pub film_grain: Option<&'a FilmGrainParams>,
    /// r447 โ€” code this frame as a ยง5.9.2 SWITCH_FRAME: the header
    /// rides the four inferred (bit-free) fields โ€”
    /// `error_resilient_mode = 1`, `frame_size_override_flag = 1`
    /// (the frame size codes EXPLICITLY on the ยง5.9.5 arm; the
    /// `frame_size_with_refs` branch is bypassed under error
    /// resilience), `refresh_frame_flags = allFrames` and
    /// `primary_ref_frame = PRIMARY_REF_NONE` โ€” plus the derived
    /// `use_ref_frame_mvs = 0` (no ยง7.9 projection on either twin)
    /// and the coded ยง5.9.2 `ref_order_hint[]` block over the TRUE
    /// [`Self::slot_hints`]. Requires `refresh_frame_flags = 0xff`,
    /// `primary_ref_frame = PRIMARY_REF_NONE`, no `primary_carry`
    /// and no `alt_primaries` (caller bug otherwise).
    pub s_frame: bool,
    /// r450 โ€” code this frame as a regular INTER frame with the
    /// ยง5.9.2 `error_resilient_mode` f(1) CODED as 1 (unlike a
    /// SWITCH frame, where the flag is inferred bit-free): the
    /// parse-side inferences follow โ€” `primary_ref_frame =
    /// PRIMARY_REF_NONE` (the f(3) is not coded; per-frame default
    /// CDFs + `setup_past_independence`), `use_ref_frame_mvs = 0`
    /// and `allow_warped_motion = 0` (neither f(1) coded), the
    /// ยง5.9.2 `ref_order_hint[]` block fires over the TRUE
    /// [`Self::slot_hints`], and the writer's `frame_size_with_refs`
    /// branch is bypassed. Everything else keeps the plain INTER
    /// shape: `frame_type = INTER`, the ordinary
    /// `refresh_frame_flags`, the reference SAMPLES still predicting
    /// across the boundary, and every frame-level election (hp-mv /
    /// delta-q / QM / CDEF / LR, tiles, film grain) still riding.
    /// Implied by [`Self::s_frame`]. Requires `primary_ref_frame =
    /// PRIMARY_REF_NONE`, no `primary_carry` and no `alt_primaries`
    /// (caller bug otherwise).
    pub error_resilient: bool,
    /// r450 โ€” see [`GopTuning::tile_spans`]: single-group multi-tile
    /// frames code `tile_start_and_end_present_flag = 1` under the
    /// split (`OBU_FRAME_HEADER` + `OBU_TILE_GROUP`) framing.
    pub tile_spans: bool,
    /// r456 โ€” ยง5.9.8 SUPERRES on an INTER frame: `Some((UpscaledWidth,
    /// SuperresDenom))` codes `input` (the DOWNSCALED frame, exactly
    /// `superres_coded_width(UpscaledWidth, SuperresDenom)` wide)
    /// against references held at the UPSCALED extent โ€” every
    /// reference is `is_scaled()` per ยง5.11.27 (the ยง7.11.3.3 scaled
    /// sampling path on both sides), LOCALWARP / global warps fall
    /// silent, the reconstruction is ยง7.16-upscaled between the CDEF
    /// and LR stages, and the returned reconstruction (the ยง7.20
    /// payload) lives at the upscaled extent. `None` keeps the flat
    /// shape.
    pub superres: Option<(u32, u32)>,
    /// r456 โ€” the ORIGINAL (upscaled-extent) source frame on a
    /// [`Self::superres`] arm: the ยง7.17 election fits and scores
    /// against it. `None` unless `superres` is set.
    pub superres_source: Option<&'a YuvFrame>,
    /// r456 โ€” per-[`Self::refs`] LUMA extents `(RefUpscaledWidth,
    /// RefFrameHeight)` for references whose size differs from the
    /// coded frame's (spatial-SVC INTER-LAYER prediction: a lower
    /// layer's reconstruction predicting an enhancement frame through
    /// the ยง7.11.3.3 scaled path in BOTH axes). Empty = every
    /// reference at the frame's extent (or the superres upscaled
    /// extent). Each reference must satisfy the ยง6.8.2 bounds.
    pub ref_dims: Vec<(u32, u32)>,
}

/// r415 generic ยง5.9.2 INTER frame header โ€” every pyramid role
/// (P / ALT / MID / B) shares this shape: non-error-resilient,
/// `PRIMARY_REF_NONE` (per-frame default CDFs), identity global
/// motion, SWITCHABLE frame filter, quarter-pel MVs,
/// `use_ref_frame_mvs = 1`, order hints on, and the ยง5.9.22
/// `skip_mode_present` derived from the true slot state via the
/// write twin.
fn build_inter_frame_fh(
    seq: &SequenceHeader,
    width: u32,
    height: u32,
    base_q_idx: u8,
    cfg: &InterFrameConfig<'_>,
    alt_q: &[i16],
) -> FrameHeader {
    let mut fh = build_intra_only_yuv420_8bit_fh_with_q(seq, width, height, base_q_idx);
    fh.frame_type = FrameType::Inter;
    fh.frame_is_intra = false;
    // r431 โ€” ยง5.9.5: under a shared (layered-stream) sequence header
    // a smaller frame codes its dimensions explicitly; the ยง5.9.7
    // write arm then emits the no-found-ref fallback (7 zero
    // `found_ref` bits + the explicit size). Frames at the sequence
    // maximum keep the implicit arm โ€” bit-identical to pre-r431.
    fh.frame_size_override_flag =
        width != seq.max_frame_width_minus_1 + 1 || height != seq.max_frame_height_minus_1 + 1;
    // ยง5.9.2: `showable_frame = frame_type != KEY_FRAME` on the
    // `show_frame == 1` arm (derived, no bit); on the `show_frame == 0`
    // arm it is CODED โ€” a not-shown pyramid frame must be showable for
    // its later `show_existing_frame` display.
    fh.show_frame = cfg.show_frame;
    fh.showable_frame = true;
    // r413: error resilience OFF โ€” ยง5.9.2 codes primary_ref_frame and
    // opens the use_ref_frame_mvs f(1). r423: the config elects the
    // primary reference (forward CDF inheritance via ยง6.8.21
    // `load_cdfs` + the ยง7.21 `load_previous()` /
    // `load_previous_segment_ids()` state) โ€” PRIMARY_REF_NONE keeps
    // the per-frame default state.
    fh.error_resilient_mode = false;
    fh.force_integer_mv = false;
    // r430 โ€” the ยง7.3 camera-frame shape freezes both CDF flags; every
    // other driver keeps the adaptive defaults (false / false).
    fh.disable_cdf_update = cfg.freeze_cdfs;
    fh.disable_frame_end_update_cdf = cfg.freeze_cdfs;
    fh.primary_ref_frame = cfg.primary_ref_frame;
    fh.refresh_frame_flags = cfg.refresh_frame_flags;
    // ยง5.9.2 `order_hint` โ€” the DISPLAY order (KEY = 0), `<
    // GOP_MAX_FRAMES = 64` so the 7-bit modulus never wraps in-GOP.
    fh.order_hint = cfg.order_hint & ((1 << u32::from(seq.order_hint_bits)) - 1);
    // The true stored per-slot hints โ€” with error resilience off the
    // ยง5.9.2 ref_order_hint block is not coded, but the writer needs
    // them as session state for the ยง5.9.22 skipModeAllowed twin.
    fh.ref_order_hints = Some(cfg.slot_hints);
    // r441 โ€” the armed ยง5.9.30 film-grain block for this frame (see
    // [`InterFrameConfig::film_grain`]); the sequence gate must have
    // been opened by the KEY's arm.
    if let Some(fg) = cfg.film_grain {
        fh.film_grain_params = Some(fg.clone());
    }
    // ยง5.9.21: ONLY_4X4 rides the CodedLossless arm; the lossy arm
    // codes TX_MODE_SELECT โ€” intra leaves carry the ยง5.11.15
    // `tx_depth` choice and inter leaves the ยง5.11.17 `txfm_split`
    // recursion.
    fh.tx_mode = Some(if base_q_idx == 0 {
        TxMode::Only4x4
    } else {
        TxMode::TxModeSelect
    });
    // ยง5.9.23: per-block single/compound choice whenever the ladder
    // carries a compound pair.
    let reference_select = !cfg.compound_pairs.is_empty();
    fh.reference_select = Some(reference_select);
    // ยง5.9.22 `skip_mode_present = 1` whenever skipModeAllowed (the
    // full forward/backward derivation twin over the true slot state;
    // `reference_select` and `enable_order_hint` gate the read).
    let (skip_allowed, _) = crate::encoder::frame_obu::skip_mode_params_twin(
        &cfg.slot_hints,
        &cfg.ref_frame_idx,
        fh.order_hint,
        seq.order_hint_bits,
    );
    fh.skip_mode_present = Some(skip_allowed && reference_select && seq.enable_order_hint);
    // r419: `allow_warped_motion = 1` whenever the sequence gate is
    // open (the f(1) is coded under `!error_resilient_mode &&
    // enable_warped_motion`) โ€” ยง5.11.27 arm B becomes reachable and
    // the RD ladder may commit WARPED_CAUSAL leaves.
    fh.allow_warped_motion = Some(seq.enable_warped_motion);
    fh.inter_refs = Some(InterFrameRefs {
        // r452 โ€” the ยง7.8 short-signaling twin: the config's
        // `ref_frame_idx` IS the `set_frame_refs()` derivation over
        // the two explicit indices (see
        // [`InterFrameConfig::short_ref_signaling`]), so the wire
        // carries only `last_frame_idx` / `gold_frame_idx`.
        frame_refs_short_signaling: cfg.short_ref_signaling,
        last_frame_idx: cfg.short_ref_signaling.then_some(cfg.ref_frame_idx[0]),
        gold_frame_idx: cfg
            .short_ref_signaling
            .then_some(cfg.ref_frame_idx[GOLDEN_FRAME - LAST_FRAME]),
        ref_frame_idx: cfg.ref_frame_idx,
        // r428 โ€” the eighth-pel arm (ยง5.9.2; force_integer_mv is 0 on
        // every header this builder emits, so the f(1) is always
        // coded). The per-frame exact-bytes election may flip this
        // back to 0 after the tile is priced.
        allow_high_precision_mv: cfg.high_precision_mv,
        interpolation_filter: InterpolationFilter::Switchable,
        // r419: ยง5.9.2 `is_motion_mode_switchable = 1` โ€” every
        // ยง5.11.27-eligible leaf codes the `use_obmc` /
        // `motion_mode` S(), and the RD ladder may commit OBMC /
        // WARPED_CAUSAL winners.
        is_motion_mode_switchable: true,
        // r413: ยง7.9 temporal MV prediction on every inter frame (the
        // first P-frame's projections are empty โ€” every slot still
        // holds the intra KEY โ€” which both sides derive identically).
        // r430: derived from the sequence gates โ€” an order-hint-free
        // sequence (the ยง7.3 camera-frame shape) infers 0 on the
        // parse side, so the writer twin must agree.
        // r447: ยง5.9.2 forces `use_ref_frame_mvs = 0` under error
        // resilience (the f(1) is not even coded) โ€” the SWITCH-frame
        // arm below flips `error_resilient_mode` on, so mirror the
        // parse-side inference here.
        use_ref_frame_mvs: seq.enable_order_hint
            && seq.enable_ref_frame_mvs
            && !cfg.error_resilient,
    });
    // r450 โ€” the CODED error-resilient arm (see
    // [`InterFrameConfig::error_resilient`]): the ยง5.9.2 f(1) goes on
    // the wire as 1 and the parse-side inferences mirror โ€”
    // `primary_ref_frame = PRIMARY_REF_NONE` (f(3) not coded) and
    // `allow_warped_motion = 0` (f(1) not coded). The frame stays a
    // plain INTER frame otherwise (type, refresh, explicit-size
    // handling untouched โ€” the SWITCH arm below adds its own shape).
    if cfg.error_resilient {
        fh.error_resilient_mode = true;
        fh.primary_ref_frame = PRIMARY_REF_NONE;
        fh.allow_warped_motion = Some(false);
    }
    // r447 โ€” the ยง5.9.2 SWITCH_FRAME shape: the four inferred fields
    // plus the error-resilient derivations (see
    // [`InterFrameConfig::s_frame`]). `frame_size_override_flag = 1`
    // makes the ยง5.9.5 frame size EXPLICIT on the wire (the writer's
    // `frame_size_with_refs` bypass takes the plain arm under error
    // resilience), and the ยง5.9.2 `ref_order_hint[]` block fires โ€”
    // `fh.ref_order_hints` already carries the true slot state.
    if cfg.s_frame {
        fh.frame_type = FrameType::Switch;
        fh.error_resilient_mode = true;
        fh.frame_size_override_flag = true;
        fh.refresh_frame_flags = ALL_FRAMES_PUB;
        fh.primary_ref_frame = PRIMARY_REF_NONE;
        // ยง5.9.2: `allow_warped_motion = 0` under error resilience
        // (the f(1) is not coded) โ€” the search ladder must not offer
        // the WARPED_CAUSAL arm and every eligible leaf's ยง5.11.27
        // `motion_mode` collapses to the two-way `use_obmc` S().
        fh.allow_warped_motion = Some(false);
    }
    // r413: ยง5.9.14 SEG_LVL_ALT_Q segmentation โ€” under
    // `PRIMARY_REF_NONE` the parser forces `update_map = 1`,
    // `temporal_update = 0`, `update_data = 1` (no bits for the three
    // flags); under a primary reference (r423) the three flags are
    // CODED and this builder emits the same configuration explicitly
    // (`update_map = 1`, `update_data = 1` โ€” the feature table is
    // re-coded every frame; `temporal_update` starts at 0, the
    // per-frame election may flip it after the tile is priced). The
    // feature table codes one active ALT_Q slot per segment
    // (`su(1+8)` each). `SegIdPreSkip = 0` (no feature at `j >=
    // SEG_LVL_REF_FRAME`); `LastActiveSegId = alt_q.len() - 1`.
    if !alt_q.is_empty() {
        fh.segmentation_params = Some(match cfg.seg_extras {
            Some(x) => segmentation_params_for_plan(alt_q, x),
            None => segmentation_params_for(alt_q),
        });
    }
    fh
}

/// The ยง5.9.14 feature table this encoder codes for a SEG_LVL_ALT_Q
/// delta ladder: one active ALT_Q slot per segment (`su(1+8)` each),
/// `update_map = update_data = 1`, `temporal_update` starting at 0
/// (the r423 per-frame election may flip it after the tile is
/// priced), `SegIdPreSkip = 0`, `LastActiveSegId = alt_q.len() - 1`.
pub(crate) fn segmentation_params_for(
    alt_q: &[i16],
) -> crate::uncompressed_header_tail::SegmentationParams {
    segmentation_params_for_plan(alt_q, &SegExtras::default())
}

/// r426 โ€” the three ยง5.9.14 inter-override features per segment
/// (ladder item 8): `ref_frame[ s ] = Some(data)` activates
/// SEG_LVL_REF_FRAME with `FeatureData = data` (a raw `RefFrame`
/// ordinal, `LAST_FRAME = 1 ..= ALTREF_FRAME = 7`); `skip[ s ]` /
/// `globalmv[ s ]` activate SEG_LVL_SKIP / SEG_LVL_GLOBALMV
/// (bits = 0 features โ€” no data). Any active slot flips the ยง5.9.14
/// `SegIdPreSkip` derivation to 1 (segment ids code BEFORE skip on
/// every block).
#[doc(hidden)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SegExtras {
    pub ref_frame: [Option<i8>; crate::uncompressed_header_tail::MAX_SEGMENTS],
    pub skip: [bool; crate::uncompressed_header_tail::MAX_SEGMENTS],
    pub globalmv: [bool; crate::uncompressed_header_tail::MAX_SEGMENTS],
}

impl SegExtras {
    /// Any feature slot active (โ‡’ ยง5.9.14 `SegIdPreSkip = 1`).
    pub(crate) fn any(&self) -> bool {
        self.ref_frame.iter().any(|r| r.is_some())
            || self.skip.iter().any(|&b| b)
            || self.globalmv.iter().any(|&b| b)
    }

    /// Highest segment index carrying any feature slot.
    pub(crate) fn top_segment(&self) -> usize {
        (0..crate::uncompressed_header_tail::MAX_SEGMENTS)
            .rev()
            .find(|&s| self.ref_frame[s].is_some() || self.skip[s] || self.globalmv[s])
            .unwrap_or(0)
    }
}

/// [`segmentation_params_for`] plus the r426 inter-override features:
/// SEG_LVL_REF_FRAME data is the ยง5.9.14 3-bit unsigned field,
/// SEG_LVL_SKIP / SEG_LVL_GLOBALMV are `bits = 0` active flags. The
/// ยง5.9.14 `SegIdPreSkip` / `LastActiveSegId` derivations follow the
/// combined table.
pub(crate) fn segmentation_params_for_plan(
    alt_q: &[i16],
    extras: &SegExtras,
) -> crate::uncompressed_header_tail::SegmentationParams {
    use crate::uncompressed_header_tail::{
        SegmentationParams, SEG_LVL_ALT_Q, SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP,
    };
    let mut sp = SegmentationParams::disabled();
    sp.enabled = true;
    sp.update_map = true;
    sp.temporal_update = false;
    sp.update_data = true;
    for (seg, &d) in alt_q.iter().enumerate() {
        sp.segment_feature_active[seg][SEG_LVL_ALT_Q] = true;
        sp.segment_feature_data[seg][SEG_LVL_ALT_Q] = d;
    }
    for (seg, rf) in extras.ref_frame.iter().enumerate() {
        if let Some(data) = rf {
            sp.segment_feature_active[seg][SEG_LVL_REF_FRAME] = true;
            sp.segment_feature_data[seg][SEG_LVL_REF_FRAME] = i16::from(*data);
        }
    }
    for (seg, &on) in extras.skip.iter().enumerate() {
        sp.segment_feature_active[seg][SEG_LVL_SKIP] = on;
    }
    for (seg, &on) in extras.globalmv.iter().enumerate() {
        sp.segment_feature_active[seg][SEG_LVL_GLOBALMV] = on;
    }
    // ยง5.9.14 derivations over the combined table.
    sp.seg_id_pre_skip = extras.any();
    sp.last_active_seg_id = alt_q.len().saturating_sub(1).max(if extras.any() {
        extras.top_segment()
    } else {
        0
    }) as u8;
    sp
}

/// r426 โ€” the ยง5.9.2 `LosslessArray[]` this encoder's headers derive:
/// `LosslessArray[ s ] = get_qindex( 1, s ) == 0` (every `DeltaQ??`
/// side value is zero on every header this encoder emits, so the
/// ยง5.9.2 conjunction collapses to the qindex test). Segments at or
/// past `alt_q.len()` carry no active `SEG_LVL_ALT_Q` feature โ€”
/// ยง7.12.2 returns `base_q_idx` for them.
pub(crate) fn seg_lossless_array(
    base_q_idx: u8,
    alt_q: &[i16],
) -> [bool; crate::uncompressed_header_tail::MAX_SEGMENTS] {
    core::array::from_fn(|s| {
        let q = match alt_q.get(s) {
            Some(&d) => (i32::from(base_q_idx) + i32::from(d)).clamp(0, 255),
            None => i32::from(base_q_idx),
        };
        q == 0
    })
}

/// r453 โ€” the EXACT ยง7.12.2 delta-q ceiling over a SEG_LVL_ALT_Q
/// table: the largest upward plan unit (in `1 << DELTA_Q_RES` steps
/// above `base_q_idx`) such that every LOSSLESS segment's block still
/// dequantizes at `get_qindex( 0, segmentId ) = Clip3( 0, 255,
/// CurrentQIndex + data ) == 0`, i.e. `CurrentQIndex <= -data`.
/// `2` (the probe's full span) when the table carries no lossless
/// segment or every lossless `data` sits far enough below
/// `-base_q_idx` (the spec note's `-255` always does); `0` when a
/// lossless `data` sits exactly at `-base_q_idx` (only the downward,
/// refining swings survive). Never negative: lossless means
/// `base_q_idx + data <= 0`.
#[must_use]
pub(crate) fn delta_q_lossless_up_cap(base_q_idx: u8, alt_q: &[i16]) -> i32 {
    let ll = seg_lossless_array(base_q_idx, alt_q);
    let step = 1i32 << DELTA_Q_RES;
    alt_q
        .iter()
        .enumerate()
        .filter(|&(sid, _)| ll[sid])
        .map(|(_, &d)| ((-i32::from(d)) - i32::from(base_q_idx)) / step)
        .min()
        .unwrap_or(2)
        .clamp(0, 2)
}

/// The r412/r413 two-slot P-frame [`InterFrameConfig`] for P-frame
/// `p_index` (see [`gop_ref_hints`] for the rotation).
#[cfg(test)]
fn p_frame_config<'a>(
    prev: &'a GopFrameReconYuv,
    prevprev: &'a GopFrameReconYuv,
    p_index: u32,
) -> InterFrameConfig<'a> {
    p_frame_config_primary(prev, prevprev, p_index, None, 0, false)
}

/// r423 โ€” [`p_frame_config`] with the primary-reference election:
/// `primary_carry = Some` elects `primary_ref_frame = 0` (LAST โ€” the
/// ordinal reading slot `p_index & 1`, which holds frame
/// `p_index - 1`, the ยง7.20 slot the caller's carry store tracks);
/// `None` keeps `PRIMARY_REF_NONE` (the pre-r423 shape, and the A/B
/// baseline).
fn p_frame_config_primary<'a>(
    prev: &'a GopFrameReconYuv,
    prevprev: &'a GopFrameReconYuv,
    p_index: u32,
    primary_carry: Option<&'a RefSlotCarry>,
    floor: u32,
    s_frame: bool,
) -> InterFrameConfig<'a> {
    let last_slot = (p_index & 1) as usize;
    let golden_slot = ((p_index - 1) & 1) as usize;
    let (last_hint, golden_hint) = gop_ref_hints_floor(p_index, floor);
    // r447 โ€” the TRUE per-slot ยง7.20 hint state: every slot outside
    // the two-slot rotation still holds the last all-refresh frame
    // (the KEY, hint 0, or the latest SWITCH frame โ€” the floor). A
    // SWITCH frame codes this whole array on the wire (ยง5.9.2
    // `ref_order_hint[ i ]` must equal the decoder's stored
    // `RefOrderHint[ i ]`, else the slot is marked invalid).
    let mut slot_hints = [floor; 8];
    slot_hints[last_slot] = last_hint;
    slot_hints[golden_slot] = golden_hint;
    let mut ref_frame_idx = [last_slot as u8; REFS_PER_FRAME];
    // GOLDEN_FRAME = 4 โ†’ ref_frame_idx[ GOLDEN_FRAME - LAST_FRAME = 3 ].
    ref_frame_idx[3] = golden_slot as u8;
    let mut slot_to_plane = [0usize; 8];
    slot_to_plane[golden_slot] = 1;
    InterFrameConfig {
        order_hint: p_index,
        show_frame: true,
        refresh_frame_flags: if s_frame {
            ALL_FRAMES_PUB
        } else {
            1 << ((p_index - 1) & 1)
        },
        ref_frame_idx,
        short_ref_signaling: false,
        slot_hints,
        single_refs: vec![1, 4],
        compound_pairs: vec![[1, 4]],
        refs: vec![prev, prevprev],
        slot_to_plane,
        primary_ref_frame: if primary_carry.is_some() && !s_frame {
            0 // LAST_FRAME ordinal โ€” ref_frame_idx[ 0 ] = last_slot.
        } else {
            PRIMARY_REF_NONE
        },
        primary_carry: if s_frame { None } else { primary_carry },
        allow_temporal_seg: true,
        alt_primaries: Vec::new(),
        exact_mask: None,
        auto_lossless: false,
        seg_extras: None,
        film_grain: None,
        high_precision_mv: true,
        delta_q: true,
        qm: true,
        cdef: true,
        cdef_units: true,
        lr: true,
        freeze_cdfs: false,
        tiles: (0, 0),
        tile_groups: 1,
        collect_donor_cdfs: false,
        elect_donor: false,
        explicit_tiles: None,
        s_frame,
        error_resilient: s_frame,
        tile_spans: false,
        superres: None,
        superres_source: None,
        ref_dims: Vec::new(),
    }
}

#[cfg(test)]
fn build_p_frame_yuv420_8bit_fh_with_q(
    seq: &SequenceHeader,
    width: u32,
    height: u32,
    base_q_idx: u8,
    p_index: u32,
    alt_q: &[i16],
) -> FrameHeader {
    // The refs are irrelevant to the header โ€” reuse a dummy pair.
    let dummy = GopFrameReconYuv {
        y: Vec::new(),
        u: Vec::new(),
        v: Vec::new(),
    };
    let cfg = p_frame_config(&dummy, &dummy, p_index);
    build_inter_frame_fh(seq, width, height, base_q_idx, &cfg, alt_q)
}

/// Encode one INTER P-frame against `prev` (the previous frame's
/// reconstruction, LAST_FRAME) and `prevprev` (the frame before it,
/// GOLDEN_FRAME โ€” the KEY recon again for the first two P-frames).
/// Returns the ยง7.5 temporal unit (TD + `OBU_FRAME`) and this frame's
/// reconstruction.
/// r436 โ€” patch an already-emitted ยง7.5 temporal unit's frame-header
/// `context_update_tile_id` field in place: locate the unit's first
/// frame-carrying OBU (`OBU_FRAME`, or the standalone
/// `OBU_FRAME_HEADER` on the split packaging โ€” the header bits start
/// at payload offset 0 in both), then overwrite the fixed-width
/// `f(n)` field at `span = (bit offset, n)` with `id`. Nothing else
/// moves: the field is fixed-width and no later syntax element
/// depends on its value (ยง5.9.15), so tile payloads, OBU sizes and
/// every other header bit are untouched.
pub(crate) fn patch_ctx_update_in_tu(tu: &mut [u8], span: (u32, u32), id: u32) {
    patch_ctx_update_in_tu_frame(tu, 0, span, id);
}

/// r439 โ€” multi-frame-unit sibling of [`patch_ctx_update_in_tu`]:
/// the out-of-order (pyramid) and layered (SVC) drivers pack SEVERAL
/// frames into one ยง7.5 temporal unit, so the patch target is the
/// `frame_ord`-th frame-carrying OBU (`OBU_FRAME` /
/// `OBU_FRAME_HEADER`) of the unit, counting in emission order
/// (`show_existing_frame` short headers ride `OBU_FRAME_HEADER` too
/// but always FOLLOW the coded frames of their unit, so coded-frame
/// ordinals are stable). Extension-carrying OBU headers (ยง5.3.3) walk
/// through the ordinary `ObuIter`, so layered units patch the same
/// way.
pub(crate) fn patch_ctx_update_in_tu_frame(
    tu: &mut [u8],
    frame_ord: usize,
    span: (u32, u32),
    id: u32,
) {
    let payload_off = {
        let base = tu.as_ptr() as usize;
        let mut found: Option<usize> = None;
        let mut seen = 0usize;
        for desc in crate::obu::ObuIter::new(tu) {
            let desc = desc.expect("own temporal unit walks");
            if matches!(
                desc.obu_type,
                crate::obu::ObuType::Frame | crate::obu::ObuType::FrameHeader
            ) {
                if seen == frame_ord {
                    found = Some(desc.payload.as_ptr() as usize - base);
                    break;
                }
                seen += 1;
            }
        }
        found.expect("temporal unit carries the addressed frame OBU")
    };
    patch_bits_at(tu, payload_off, span, id);
}

/// r439 โ€” overwrite the fixed-width `f(n)` field at `span = (bit
/// offset from `payload_off * 8`, n)` with `id`. Shared by the
/// temporal-unit patchers above and the pyramid driver's
/// pending-OBU patch (where the frame-header payload IS the buffer,
/// `payload_off = 0`).
pub(crate) fn patch_bits_at(buf: &mut [u8], payload_off: usize, span: (u32, u32), id: u32) {
    let (start, n) = span;
    for i in 0..n {
        let bitpos = payload_off * 8 + (start + i) as usize;
        let byte = bitpos / 8;
        let mask = 1u8 << (7 - (bitpos % 8));
        if (id >> (n - 1 - i)) & 1 == 1 {
            buf[byte] |= mask;
        } else {
            buf[byte] &= !mask;
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn encode_p_frame_yuv(
    input: &YuvFrame,
    prev: &GopFrameReconYuv,
    prevprev: &GopFrameReconYuv,
    seq: &SequenceHeader,
    base_q_idx: u8,
    p_index: u32,
    alt_q: &[i16],
    mf_store: &[SavedMotionField; 8],
    model: RateModel,
    global_motion: bool,
    primary_carry: Option<&RefSlotCarry>,
    allow_temporal_seg: bool,
    exact_mask: Option<&[bool]>,
    auto_lossless: bool,
    seg_extras: Option<&SegExtras>,
    high_precision_mv: bool,
    delta_q: bool,
    qm: bool,
    cdef: bool,
    cdef_units: bool,
    lr: bool,
    tiles: (u32, u32),
    tile_groups: u32,
    tile_spans: bool,
    explicit_tiles: Option<(&[u32], &[u32])>,
    donor_armed: bool,
    film_grain: Option<&FilmGrainParams>,
    floor: u32,
    floor_recon: &GopFrameReconYuv,
    s_frame: bool,
    error_resilient: bool,
    short_ref_signaling: bool,
    superres: Option<(u32, u32)>,
    superres_source: Option<&YuvFrame>,
) -> Result<
    (
        Vec<u8>,
        GopFrameReconYuv,
        SavedMotionField,
        RefSlotCarry,
        InterFrameAux,
    ),
    Error,
> {
    // r447 โ€” a SWITCH frame starts from per-frame default state
    // (ยง5.9.2 infers PRIMARY_REF_NONE under error resilience);
    // r450 โ€” so does a CODED error-resilient INTER frame.
    let error_resilient = error_resilient || s_frame;
    let primary_carry = if error_resilient { None } else { primary_carry };
    let mut cfg = p_frame_config_primary(prev, prevprev, p_index, primary_carry, floor, s_frame);
    cfg.error_resilient = error_resilient;
    // r452 โ€” ยง5.9.2 `frame_refs_short_signaling` (see
    // [`GopTuning::short_ref_signaling`]): on a plain INTER frame the
    // encoder adopts the ยง7.8 `set_frame_refs()` derivation over the
    // LAST / GOLDEN slots and the TRUE stored hints as its reference
    // map, so the decoder's derivation reproduces it in lockstep.
    // The f(1) is only coded under `enable_order_hint` (ยง5.9.2).
    if short_ref_signaling && !error_resilient && seq.enable_order_hint {
        cfg.ref_frame_idx = crate::frame_header::set_frame_refs(
            cfg.ref_frame_idx[0],
            cfg.ref_frame_idx[GOLDEN_FRAME - LAST_FRAME],
            cfg.order_hint,
            seq.order_hint_bits,
            seq.enable_order_hint,
            &cfg.slot_hints,
        );
        cfg.short_ref_signaling = true;
        // The derived map may name slots OUTSIDE the two-slot
        // rotation (every one holds the all-refresh FLOOR frame โ€” the
        // KEY or the latest SWITCH frame), and the ยง5.9.22 skip-mode
        // twin resolves its second forward reference by ORDINAL order
        // over equal hints, so such a slot can be predicted from:
        // give it the floor reconstruction, exactly what the decoder's
        // ยง7.20 store holds there.
        cfg.refs.push(floor_recon);
        let floor_plane = cfg.refs.len() - 1;
        let last_slot = cfg.ref_frame_idx[0] as usize;
        let gold_slot = cfg.ref_frame_idx[GOLDEN_FRAME - LAST_FRAME] as usize;
        for (slot, plane) in cfg.slot_to_plane.iter_mut().enumerate() {
            if slot != last_slot && slot != gold_slot {
                *plane = floor_plane;
            }
        }
    }
    // r441 โ€” the armed ยง5.9.30 film-grain block for this frame.
    cfg.film_grain = film_grain;
    cfg.allow_temporal_seg = allow_temporal_seg;
    cfg.exact_mask = exact_mask;
    cfg.auto_lossless = auto_lossless;
    cfg.seg_extras = seg_extras;
    cfg.high_precision_mv = high_precision_mv;
    cfg.delta_q = delta_q;
    cfg.qm = qm;
    cfg.cdef = cdef;
    cfg.cdef_units = cdef_units;
    cfg.lr = lr;
    cfg.tiles = tiles;
    cfg.tile_groups = tile_groups;
    cfg.tile_spans = tile_spans;
    cfg.explicit_tiles = explicit_tiles;
    // r436 โ€” the ยง6.8.14 donor election arms both directions: this
    // frame ELECTS over its primary's donor set, and COLLECTS its
    // own per-tile end CDFs for the next frame's election. r447 โ€” a
    // SWITCH frame has no primary to elect over (it still collects:
    // the frames chaining off its slots elect on ITS donor set).
    cfg.collect_donor_cdfs = donor_armed;
    // A SWITCH or coded error-resilient frame has no primary to
    // elect over (it still collects: the frames chaining off its
    // slots elect on ITS donor set).
    cfg.elect_donor = donor_armed && !error_resilient;
    cfg.superres = superres;
    cfg.superres_source = superres_source;
    let (obus, recon, saved, carry, aux) = encode_inter_frame_generic_gm(
        input,
        seq,
        base_q_idx,
        &cfg,
        alt_q,
        mf_store,
        model,
        global_motion,
    )?;
    // ยง7.5 temporal unit: TD + the frame's OBUs (one `OBU_FRAME`, or
    // r433's `OBU_FRAME_HEADER` + tile groups; the SH rode the KEY
    // frame's unit โ€” ยง7.5 requires it once per coded video sequence).
    // Every P-frame is shown, so the unit satisfies the "exactly one
    // shown frame per temporal unit" bitstream conformance rule.
    Ok((build_temporal_unit(None, &obus), recon, saved, carry, aux))
}

/// r415 โ€” the shared INTER frame encoder every pyramid role (P / ALT /
/// MID / B) runs: builds the ยง5.9.2 header from an
/// [`InterFrameConfig`], derives order hints / ยง7.8 sign bias /
/// ยง5.9.22 skip mode / ยง7.9 temporal MVs from the config's true slot
/// state, runs the r411-r413 RD search over the config's reference
/// ladder, and writes the ยง5.10 `OBU_FRAME`. Returns
/// `(frame OBU, reconstruction, ยง7.19 motion-field payload)` โ€” the
/// caller packs OBUs into ยง7.5 temporal units (each unit must carry
/// exactly ONE shown frame, so pyramid drivers bundle
/// decoded-not-shown frames with the next shown one).
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode_inter_frame_generic(
    input: &YuvFrame,
    seq: &SequenceHeader,
    base_q_idx: u8,
    cfg: &InterFrameConfig<'_>,
    alt_q: &[i16],
    mf_store: &[SavedMotionField; 8],
    model: RateModel,
) -> Result<
    (
        Vec<ObuFrame>,
        GopFrameReconYuv,
        SavedMotionField,
        RefSlotCarry,
        InterFrameAux,
    ),
    Error,
> {
    encode_inter_frame_generic_gm(input, seq, base_q_idx, cfg, alt_q, mf_store, model, true)
}

/// r422 โ€” [`encode_inter_frame_generic`] with the global-motion
/// election switch (`false` = identity-only headers, the pre-r422
/// baseline the measurement harness A/Bs against).
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode_inter_frame_generic_gm(
    input: &YuvFrame,
    seq: &SequenceHeader,
    base_q_idx: u8,
    cfg: &InterFrameConfig<'_>,
    alt_q: &[i16],
    mf_store: &[SavedMotionField; 8],
    model: RateModel,
    global_motion: bool,
) -> Result<
    (
        Vec<ObuFrame>,
        GopFrameReconYuv,
        SavedMotionField,
        RefSlotCarry,
        InterFrameAux,
    ),
    Error,
> {
    input.validate()?;
    // r423 โ€” a primary-reference election requires the ยง7.20 carry of
    // the elected slot and a valid ordinal (`0..7`).
    if cfg.primary_ref_frame != PRIMARY_REF_NONE
        && (usize::from(cfg.primary_ref_frame) >= REFS_PER_FRAME || cfg.primary_carry.is_none())
    {
        return Err(Error::PartitionWalkOutOfRange);
    }
    // r447 โ€” a SWITCH frame is error-resilient by ยง5.9.2 inference:
    // it must refresh every slot, start from per-frame default state
    // (no primary carry โ€” the ordinal is not even coded) and offer no
    // replay candidates (the ยง5.9.24 recentering baseline is the
    // setup_past_independence default, unique).
    if cfg.s_frame && (cfg.refresh_frame_flags != ALL_FRAMES_PUB || !cfg.error_resilient) {
        return Err(Error::PartitionWalkOutOfRange);
    }
    // r450 โ€” every error-resilient frame (SWITCH or coded) starts
    // from per-frame default state: ยง5.9.2 infers PRIMARY_REF_NONE
    // (the ordinal is not even coded) and no replay candidate can
    // exist (the ยง5.9.24 recentering baseline is the
    // setup_past_independence default, unique).
    if cfg.error_resilient
        && (cfg.primary_ref_frame != PRIMARY_REF_NONE
            || cfg.primary_carry.is_some()
            || !cfg.alt_primaries.is_empty())
    {
        return Err(Error::PartitionWalkOutOfRange);
    }
    let bit_depth = input.bit_depth;
    let (ssx, ssy) = input.format.subsampling();
    let mono = input.format == crate::encoder::yuv_frame::ChromaFormat::Monochrome;
    let num_planes = input.format.num_planes();
    let width = input.width as usize;
    let height = input.height as usize;
    let chroma_w = input.chroma_width() as usize;
    let chroma_h = input.chroma_height() as usize;
    // r456 โ€” the ยง5.9.8 inter arm: `input` is the DOWNSCALED frame,
    // every reference sits at the UPSCALED extent (`ref_w`), and the
    // pair must satisfy the ยง5.9.8 width derivation, the sequence
    // gate, the sequence budget and the ยง6.8.2 reference-size bounds
    // (`2 * FrameWidth >= RefUpscaledWidth` โ€” the ladder's strongest
    // ratio lands exactly on it).
    let ref_w: usize = match cfg.superres {
        Some((up_w, denom)) => {
            if !(crate::frame_header::SUPERRES_DENOM_MIN..=16).contains(&denom)
                || crate::encoder::superres_elect::superres_coded_width(up_w, denom) != input.width
                || up_w <= input.width
                || !seq.enable_superres
                || up_w > seq.max_frame_width_minus_1 + 1
                || 2 * input.width < up_w
                || cfg.exact_mask.is_some()
                || cfg.auto_lossless
            {
                return Err(Error::PartitionWalkOutOfRange);
            }
            match cfg.superres_source {
                Some(src)
                    if src.width == up_w
                        && src.height == input.height
                        && src.bit_depth == bit_depth
                        && src.format == input.format => {}
                _ => return Err(Error::PartitionWalkOutOfRange),
            }
            up_w as usize
        }
        None => width,
    };
    // r456 โ€” per-reference LUMA extents: the caller's `ref_dims`
    // (inter-layer prediction) or the shared extent; every reference
    // plane must match its extent and satisfy the ยง6.8.2 bounds
    // (`2 * FrameWidth >= RefUpscaledWidth`, `2 * FrameHeight >=
    // RefFrameHeight`, `FrameWidth <= 16 * RefUpscaledWidth`,
    // `FrameHeight <= 16 * RefFrameHeight`).
    let ref_dims: Vec<(u32, u32)> = if cfg.ref_dims.is_empty() {
        vec![(ref_w as u32, height as u32); cfg.refs.len()]
    } else {
        cfg.ref_dims.clone()
    };
    if ref_dims.len() != cfg.refs.len() {
        return Err(Error::PartitionWalkOutOfRange);
    }
    for (reference, &(rw, rh)) in cfg.refs.iter().zip(&ref_dims) {
        let (rw, rh) = (rw as usize, rh as usize);
        // Monochrome references carry EMPTY chroma planes (the frame's
        // own `chroma_width()` / `chroma_height()` are 0 there).
        let (rcw, rch) = if mono {
            (0, 0)
        } else {
            (
                (rw + usize::from(ssx)) >> ssx,
                (rh + usize::from(ssy)) >> ssy,
            )
        };
        if rw == 0
            || rh == 0
            || reference.y.len() != rw * rh
            || reference.u.len() != rcw * rch
            || reference.v.len() != rcw * rch
            || 2 * width < rw
            || 2 * height < rh
            || width > 16 * rw
            || height > 16 * rh
        {
            return Err(Error::PartitionWalkOutOfRange);
        }
    }
    // ยง5.11.27 `is_scaled( refFrame )` per reference ordinal (through
    // the slot map to the reference's extent).
    let mut scaled_per_ref = [false; 7];
    for (r, flag) in scaled_per_ref.iter_mut().enumerate() {
        let (rw, rh) = ref_dims[cfg.slot_to_plane[cfg.ref_frame_idx[r] as usize]];
        *flag = crate::encoder::superres_elect::is_scaled(rw, rh, width as u32, height as u32);
    }
    let any_scaled = scaled_per_ref.iter().any(|&f| f);

    let mut fh = build_inter_frame_fh(seq, input.width, input.height, base_q_idx, cfg, alt_q);
    // r427 โ€” the ยง5.11.46 palette election inside inter frames stays
    // 8-bit-4:2:0-scoped, like the KEY driver.
    fh.allow_screen_content_tools = fh.allow_screen_content_tools
        && bit_depth == 8
        && input.format == crate::encoder::yuv_frame::ChromaFormat::Yuv420;
    // r456 โ€” patch the ยง5.9.8 fields: the wire codes the UPSCALED
    // width (through the sequence maximum on the implicit arm, or the
    // ยง5.9.5 override fields) plus `use_superres = 1` / `coded_denom`;
    // `FrameWidth` and the mi grid stay at the coded (downscaled)
    // extent the builder derived from `input`. The ยง5.9.5 override
    // decision compares the DISPLAY width (a SWITCH frame keeps its
    // forced explicit shape).
    if let Some((up_w, denom)) = cfg.superres {
        let fs = fh
            .frame_size
            .as_mut()
            .ok_or(Error::PartitionWalkOutOfRange)?;
        fs.upscaled_width = up_w;
        fs.render_width = up_w;
        fs.use_superres = true;
        fs.superres_denom = denom;
        fs.coded_denom = (denom - crate::frame_header::SUPERRES_DENOM_MIN) as u8;
        if !cfg.s_frame {
            fh.frame_size_override_flag = up_w != seq.max_frame_width_minus_1 + 1
                || input.height != seq.max_frame_height_minus_1 + 1;
        }
    }
    let fs = fh
        .frame_size
        .as_ref()
        .ok_or(Error::PartitionWalkOutOfRange)?;
    let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
    // r431 โ€” the ยง5.9.15 uniform tile layout (single-tile unless the
    // config asked for columns/rows). The whole driver โ€” search arms,
    // every post-tile replay election, the ยง5.11.1 assembly โ€” walks
    // the same tile plan.
    // r456 โ€” on the superres inter arm an explicit column layout is
    // remapped onto the downscaled superblock grid (column count
    // preserved โ€” the primary frame's per-tile donor CDFs keep
    // lining up; Annex A superres tile-width rule enforced).
    let remapped_widths: Option<Vec<u32>> = match (cfg.superres, cfg.explicit_tiles) {
        (Some((up_w, denom)), Some((ws, hs))) => Some(
            crate::encoder::superres_elect::denom_explicit_ok(up_w, input.height, denom, ws, hs)
                .ok_or(Error::PartitionWalkOutOfRange)?,
        ),
        _ => None,
    };
    let explicit_tiles: Option<(&[u32], &[u32])> =
        match (remapped_widths.as_deref(), cfg.explicit_tiles) {
            (Some(r), Some((_, hs))) => Some((r, hs)),
            _ => cfg.explicit_tiles,
        };
    let mut ti = match explicit_tiles {
        // r433 โ€” ยง5.9.15 non-uniform (explicit) layout.
        Some((widths_sb, heights_sb)) => crate::tile_info::TileInfo::explicit_layout(
            mi_cols,
            mi_rows,
            seq.use_128x128_superblock,
            widths_sb,
            heights_sb,
        ),
        None => crate::tile_info::TileInfo::uniform_layout(
            mi_cols,
            mi_rows,
            seq.use_128x128_superblock,
            cfg.tiles.0,
            cfg.tiles.1,
        ),
    }
    .ok_or(Error::PartitionWalkOutOfRange)?;
    fh.tile_info = Some(ti.clone());
    let num_tiles = ti.tile_cols * ti.tile_rows;
    let tile_plan: Vec<(TileGeometry, Vec<(u32, u32)>)> = (0..num_tiles)
        .map(|t| {
            let g = ti.tile_geometry(t).expect("tile_num < NumTiles");
            let mut origins: Vec<(u32, u32)> = Vec::new();
            let mut r = g.mi_row_start;
            while r < g.mi_row_end {
                let mut c = g.mi_col_start;
                while c < g.mi_col_end {
                    origins.push((r, c));
                    c += 16;
                }
                r += 16;
            }
            (g, origins)
        })
        .collect();
    // The superblock origins in TILE-SCAN order โ€” the order every
    // arm's `trees` vector rides (equals the frame raster on the
    // single-tile layout).
    let flat_sb: Vec<(u32, u32)> = tile_plan
        .iter()
        .flat_map(|(_, o)| o.iter().copied())
        .collect();
    let (layout_cols_log2, layout_rows_log2, ctx_update_id) = (
        ti.tile_cols_log2,
        ti.tile_rows_log2,
        ti.context_update_tile_id,
    );
    // ยง5.11.1 assembled tile-group body (single tile: the payload
    // itself, byte for byte).
    let assemble = move |payloads: &[Vec<u8>]| -> Result<Vec<u8>, Error> {
        let tsb = crate::encoder::key_frame::min_tile_size_bytes(payloads);
        write_tile_group_obu(&TileGroupObu::whole_frame(
            num_tiles,
            layout_cols_log2,
            layout_rows_log2,
            tsb,
            payloads.iter().cloned().map(TilePayload::new).collect(),
        ))
    };
    let lossless = base_q_idx == 0;
    let mut qp = QuantizerParams::neutral(base_q_idx, bit_depth);
    if !alt_q.is_empty() {
        // ยง7.12.2 get_qindex inputs โ€” the write-side ยง5.11.47 guard
        // and the ยง5.11.39 quantiser chain both key off these.
        qp.segmentation_enabled = true;
        for (seg, &d) in alt_q.iter().enumerate() {
            qp.seg_alt_q_active[seg] = true;
            qp.seg_alt_q_data[seg] = d;
        }
    }

    // ONE ยง5.9 inter-frame parameter bundle shared verbatim by the
    // driver-side ยง7.10.2 mirror and the write pass โ€” the two
    // `find_mv_stack` runs at each leaf must see identical inputs.
    let mut ip = SyntaxInterFrameParams::single_ref_baseline(
        mi_rows, mi_cols, /* force_integer_mv = */ false,
    );
    // r428 โ€” ยง5.9.2 `allow_high_precision_mv`: the search mirror, the
    // ยง7.10.2 stack derivations (`lower_mv_precision` becomes a
    // no-op) and the ยง5.11.32 `mv_hp` write cascade all key off this.
    ip.allow_high_precision_mv = cfg.high_precision_mv;
    // r456 โ€” ยง5.11.27 `is_scaled( refFrame )` per reference: on the
    // ยง5.9.8 inter arm the scale test fires for all seven (the
    // `motion_mode` read collapses to the `use_obmc` arm; the syntax
    // twin prices exactly that cascade).
    ip.is_scaled_per_ref = scaled_per_ref;
    // r412: SWITCHABLE frame filter โ€” each inter leaf RD-selects its
    // own ยง5.11.x interp_filter (the header writer emits
    // `is_filter_switchable = 1`).
    ip.interpolation_filter = SWITCHABLE;
    // r412: per-block single/compound reference choice (ยง5.9.23) โ€”
    // open exactly when the ladder carries a compound pair (matches
    // the header).
    ip.reference_select = !cfg.compound_pairs.is_empty();
    // r415: ยง5.5.2 masked compound โ€” compound leaves code the
    // ยง5.11.29 comp_group_idx cascade and may commit COMPOUND_WEDGE /
    // COMPOUND_DIFFWTD (the RD ladder trials both against the
    // AVERAGE baseline).
    ip.enable_masked_compound = seq.enable_masked_compound;
    // r417: ยง5.5.2 inter-intra compound โ€” single-reference 8x8..32x32
    // leaves code the ยง5.11.28 cascade and may commit smooth / wedge
    // inter-intra blends (the RD ladder trials all four II modes and
    // the 16 wedge masks against the plain leaf).
    ip.enable_interintra_compound = seq.enable_interintra_compound;
    // r416: ยง5.5.2 jnt-comp โ€” compound leaves code the ยง5.11.29
    // `compound_idx` S() and may commit COMPOUND_DISTANCE (the RD
    // ladder trials the ยง7.11.3.15 distance-weighted blend against
    // the AVERAGE baseline).
    ip.enable_jnt_comp = seq.enable_jnt_comp;
    // r419: ยง5.9.2 motion-mode switchability + warped motion โ€” the
    // write pass codes ยง5.11.27 `motion_mode` on eligible leaves and
    // the RD ladder trials OBMC (and, with the warp gates open,
    // WARPED_CAUSAL) against SIMPLE. `allow_warped_motion` mirrors
    // the header derivation: coded only when the sequence gate is
    // open (the header writer emits the f(1) under the same gate).
    ip.is_motion_mode_switchable = true;
    // r447: ยง5.9.2 infers `allow_warped_motion = 0` under error
    // resilience (the SWITCH-frame shape) โ€” mirror the parse-side
    // derivation exactly as the header writer's bit gate does.
    ip.allow_warped_motion = seq.enable_warped_motion && !fh.error_resilient_mode;
    // ยง5.9.2 order hints โ€” `OrderHints[ ref ]` =
    // `RefOrderHint[ ref_frame_idx[ ref - LAST_FRAME ] ]` over the
    // config's slot state.
    ip.order_hints = crate::cdf::FrameInterOrderHints {
        order_hint_bits: u32::from(seq.order_hint_bits),
        current_order_hint: fh.order_hint as i32,
        order_hints_by_ref: {
            let mut by_ref = [0i32; crate::uncompressed_header_tail::ALTREF_FRAME + 1];
            for (i, hint) in by_ref.iter_mut().enumerate().skip(1) {
                *hint = cfg.slot_hints[cfg.ref_frame_idx[i - 1] as usize] as i32;
            }
            by_ref
        },
    };
    // ยง7.8 `RefFrameSignBias[ ref ]` = `get_relative_dist(
    // OrderHints[ ref ], OrderHint ) > 0` โ€” backward references (the
    // pyramid's BWDREF/ALTREF roles) flip the bias.
    for r in 1..=7usize {
        ip.ref_frame_sign_bias[r] = i32::from(
            crate::inter_pred::get_relative_dist(
                ip.order_hints.order_hints_by_ref[r],
                fh.order_hint as i32,
                u32::from(seq.order_hint_bits),
            ) > 0,
        );
    }
    // ยง5.9.22 skip mode โ€” the SAME write-twin derivation the header
    // builder ran (presence AND the `SkipModeFrame[]` pair).
    {
        let (allowed, pair) = crate::encoder::frame_obu::skip_mode_params_twin(
            &cfg.slot_hints,
            &cfg.ref_frame_idx,
            fh.order_hint,
            seq.order_hint_bits,
        );
        ip.skip_mode_present = fh.skip_mode_present == Some(true) && allowed;
        ip.skip_mode_frame = pair;
    }
    // r413: segmentation map update (spatial coding; the r423
    // frame-level election may flip the temporal arm on after the
    // tile is priced). r423: `load_previous_segment_ids()` โ€” with a
    // primary reference whose stored extent matches, `PrevSegmentIds`
    // is that slot's ยง7.20 `SavedSegmentIds`; otherwise all-zero
    // (also the setup_past_independence state for PRIMARY_REF_NONE),
    // exactly mirroring the decode driver's derivation.
    if !alt_q.is_empty() {
        ip.segmentation_update_map = true;
        // r423 โ€” the main pass always searches and emits under the
        // SPATIAL arm: the search (and therefore the committed trees)
        // is bit-identical to the temporal-disabled baseline, and the
        // exact-bits election below replays those trees under the
        // ยง5.11.19 temporal arm โ€” so the elected stream can only be
        // smaller-or-equal, PER FRAME, than the spatial-only encode
        // of the same input. (An early variant searched under the
        // temporal arm and elected the spatial replay as fallback;
        // measurement showed the temporal-biased trees sometimes lose
        // to a spatial-native search outright, which the flipped
        // election excludes by construction.)
        ip.segmentation_temporal_update = false;
        let cells = (mi_rows as usize) * (mi_cols as usize);
        let prev_ids = match cfg.primary_carry {
            Some(c)
                if cfg.primary_ref_frame != PRIMARY_REF_NONE
                    && c.mi_rows == mi_rows
                    && c.mi_cols == mi_cols
                    && c.segment_ids.len() == cells =>
            {
                c.segment_ids.clone()
            }
            _ => vec![0i32; cells],
        };
        ip.prev_segment_ids = Some(std::sync::Arc::new(prev_ids));
    }
    // r413: ยง7.9 motion-field estimation over the encoder-side ยง7.20
    // store โ€” the SAME shared core the decode driver runs, so the
    // ยง7.10.2.5 temporal scan sees identical `MotionFieldMvs` at
    // search time, at write time and at decode time.
    // r430: mirrors the header derivation โ€” an order-hint-free
    // sequence codes (and infers) `use_ref_frame_mvs = 0`, so the
    // ยง7.9 projection must not run (the walker keeps the invalid
    // motion-field default on both sides). r447: the ยง5.9.2
    // error-resilient inference (`use_ref_frame_mvs = 0`, no bit) is
    // mirrored too โ€” the SWITCH-frame arm rides it.
    ip.use_ref_frame_mvs =
        seq.enable_order_hint && seq.enable_ref_frame_mvs && !fh.error_resilient_mode;
    if ip.use_ref_frame_mvs {
        use crate::inter_pred::{motion_field_estimation_core, MotionFieldSlot};
        let ref_frame_idx = cfg.ref_frame_idx;
        let mut order_hints = [0i32; 8];
        order_hints.copy_from_slice(&ip.order_hints.order_hints_by_ref);
        let mut slots: [Option<MotionFieldSlot<'_>>; 8] = [None; 8];
        for (i, slot) in mf_store.iter().enumerate() {
            slots[i] = Some(MotionFieldSlot {
                mf_mvs: &slot.mf_mvs,
                mf_ref_frames: &slot.mf_ref_frames,
                saved_order_hints: slot.saved_order_hints,
                mi_rows: slot.mi_rows,
                mi_cols: slot.mi_cols,
                frame_is_intra: slot.frame_is_intra,
            });
        }
        ip.motion_field_mvs = motion_field_estimation_core(
            &slots,
            &ref_frame_idx,
            &order_hints,
            fh.order_hint as i32,
            u32::from(seq.order_hint_bits),
            mi_rows,
            mi_cols,
        );
    }

    // r422 โ€” frame-level global-motion election (ยง5.9.24): one coarse
    // motion pre-pass per DISTINCT reference reconstruction, then the
    // least-squares model fits + ยง5.9.25 grid quantization +
    // ยง7.11.3.6 validation of [`crate::encoder::global_motion`]. The
    // elected `(GmType, gm_params)` pairs are stamped into the shared
    // inter bundle (feeding the ยง7.10.2.1 `GlobalMvs` derivation and
    // the ยง7.11.3 global-warp arm of BOTH the search mirror and the
    // write pass) and into the frame header (feeding the ยง5.9.24
    // write arm) โ€” one source of truth on every side, so the stream
    // and the search can never disagree about the model.
    // r456 โ€” ยง7.11.3.1 step 7 never selects a global warp against a
    // scaled reference (`is_scaled( refFrame ) == 0` is required) and
    // the estimator's sample collection assumes equal extents: the
    // superres inter arm keeps identity models.
    if global_motion && !any_scaled {
        let hp = fh
            .inter_refs
            .as_ref()
            .map(|ir| ir.allow_high_precision_mv)
            .unwrap_or(false);
        // Estimate once per distinct reference plane, then fan the
        // result out to every RefFrame ordinal mapped onto it.
        let mut per_plane: Vec<Option<(crate::uncompressed_header_tail::WarpModelType, [i32; 6])>> =
            vec![None; cfg.refs.len()];
        for &rf in &cfg.single_refs {
            let plane = cfg.slot_to_plane[cfg.ref_frame_idx[(rf - 1) as usize] as usize];
            let (t, p) = match per_plane[plane] {
                Some(tp) => tp,
                None => {
                    let samples = crate::encoder::global_motion::collect_motion_samples(
                        &input.y,
                        &cfg.refs[plane].y,
                        width,
                        height,
                    );
                    let tp = crate::encoder::global_motion::estimate_global_motion(&samples, hp);
                    per_plane[plane] = Some(tp);
                    tp
                }
            };
            ip.gm_type[rf as usize] = i32::from(t.as_u8());
            ip.gm_params[rf as usize] = p;
        }
        // Header twin of the elected models.
        let mut gmp = crate::uncompressed_header_tail::GlobalMotionParams::identity();
        gmp.short_circuited = false;
        for r in 1..=7usize {
            gmp.gm_type[r] = match ip.gm_type[r] {
                1 => crate::uncompressed_header_tail::WarpModelType::Translation,
                2 => crate::uncompressed_header_tail::WarpModelType::RotZoom,
                3 => crate::uncompressed_header_tail::WarpModelType::Affine,
                _ => crate::uncompressed_header_tail::WarpModelType::Identity,
            };
            gmp.gm_params[r] = ip.gm_params[r];
        }
        fh.global_motion_params = Some(gmp);
    }

    // r426 โ€” the ยง5.9.14 inter-override feature tables + derivations
    // (SegIdPreSkip / LastActiveSegId over the combined table).
    let x = cfg.seg_extras.copied().unwrap_or_default();
    let seg_id_pre_skip = x.any();
    let last_active_seg_id =
        alt_q
            .len()
            .saturating_sub(1)
            .max(if x.any() { x.top_segment() } else { 0 }) as u8;
    let mut params = SyntaxFrameParams {
        subsampling_x: ssx,
        subsampling_y: ssy,
        num_planes,
        seg_id_pre_skip,
        segmentation_enabled: !alt_q.is_empty(),
        seg_ref_frame: x.ref_frame,
        seg_skip: x.skip,
        seg_globalmv: x.globalmv,
        last_active_seg_id,
        // r426 โ€” per-segment ยง5.9.2 `LosslessArray[]`: a segment whose
        // ยง7.12.2 qindex clamps to 0 flips the full lossless leaf
        // semantics for its blocks while the frame stays lossy.
        lossless_array: seg_lossless_array(base_q_idx, alt_q),
        coded_lossless: lossless,
        enable_cdef: seq.enable_cdef,
        allow_intrabc: false,
        cdef_bits: 0,
        read_deltas: false,
        use_128x128_superblock: seq.use_128x128_superblock,
        delta_q_res: 0,
        delta_lf_present: false,
        delta_lf_multi: false,
        mono_chrome: mono,
        delta_lf_res: 0,
        allow_screen_content_tools: fh.allow_screen_content_tools,
        enable_filter_intra: seq.enable_filter_intra,
        bit_depth,
        tx_mode_select: !lossless,
        quant: qp,
        reduced_tx_set: fh.reduced_tx_set.unwrap_or(false),
        inter: Some(ip.clone()),
    };

    // ยง8.3.1 frame-start CDF state (mirroring the decode driver):
    // with a primary reference, ยง6.8.21 `load_cdfs( ref_frame_idx[
    // primary_ref_frame ] )` โ€” the slot's ยง7.20-saved frame-end state
    // (coefficient CDFs included) with the per-row symbol counts
    // zeroed; otherwise `init_non_coeff_cdfs()` (the ยง9.4 defaults)
    // plus the q-context-selected `init_coeff_cdfs( base_q_idx )`.
    let frame_start_cdfs: Box<TileCdfContext> = match cfg.primary_carry {
        Some(carry) if cfg.primary_ref_frame != PRIMARY_REF_NONE => {
            let mut loaded = carry.cdfs.clone();
            loaded.zero_counts();
            loaded
        }
        _ => {
            let mut c = TileCdfContext::new_from_defaults();
            c.init_coeff_cdfs(base_q_idx);
            Box::new(c)
        }
    };

    // r428 โ€” ยง5.9.17 delta-q plan: on an UNSEGMENTED lossy frame with
    // the config arm open, the complexity probe maps per-superblock
    // source-luma activity to reduced ยง5.11.13 delta units (`None`
    // when the spread is flat โ€” the single-quantiser arm is then the
    // only arm searched).
    // r436 โ€” ยง5.9.17 ร— ยง5.9.14: the delta-q arm runs on SEGMENTED
    // frames too. ยง7.12.2 `get_qindex` composes the segment's
    // SEG_LVL_ALT_Q data on top of the running ยง5.11.13
    // `CurrentQIndex` (both the search twin and the decoder ride the
    // same shared derivation), so the plan and the segment map are
    // orthogonal on the wire.
    // r453 โ€” the lossless-segment guard is EXACT per ยง7.12.2 (it
    // replaced the conservative r436 "any lossless segment โ‡’ single
    // quantiser" rule): `LosslessArray[]` is derived with
    // `ignoreDeltaQ = 1` (`base_q_idx + data`) while a block
    // dequantizes at `get_qindex( 0, segmentId ) = Clip3( 0, 255,
    // CurrentQIndex + data )`, so a lossless segment stays lossless
    // under delta-q exactly when EVERY realized `CurrentQIndex`
    // satisfies `CurrentQIndex + data <= 0` (the spec's note reaches
    // the same place with `data = -255`). The plan is absolute
    // (`base_q_idx + units << delta_q_res`), so its UPWARD units are
    // capped by [`delta_q_lossless_up_cap`] and the arm keeps the
    // refining swings (`CodedLossless` frames stay excluded by
    // `!lossless` and the ยง5.9.17 `base_q_idx > 0` read gate).
    let ll_up_cap = delta_q_lossless_up_cap(base_q_idx, alt_q);
    let delta_plan: Option<Vec<i32>> = if cfg.delta_q && !lossless {
        delta_q_plan_units(input, mi_rows, mi_cols).and_then(|mut units| {
            if ll_up_cap < 2 {
                for u in units.iter_mut() {
                    *u = (*u).min(ll_up_cap);
                }
            }
            units.iter().any(|&u| u != 0).then_some(units)
        })
    } else {
        None
    };

    /// One frame-search arm's complete artifact set (everything the
    /// OBU assembly + the post-tile exact-bytes elections consume).
    struct FrameArm {
        /// Per-tile ยง8.2 payloads in tile-scan order (r431).
        payloads: Vec<Vec<u8>>,
        /// The assembled ยง5.11.1 tile-group body (equals the lone
        /// payload on the single-tile layout) โ€” what the elections
        /// price.
        tile: Vec<u8>,
        // Boxed: `TileCdfContext` (and the search context) are far
        // too large for by-value moves through closure returns on a
        // 2 MiB test-thread stack (debug builds memcpy every move).
        // r436 โ€” EVERY tile's frame-end adapted state, in tile order
        // (`all_cdfs[ context_update_tile_id ]` is the ยง8.4
        // donation; the donor election needs the full set).
        all_cdfs: Vec<Box<TileCdfContext>>,
        state: PartitionSyntaxWriter,
        trees: Vec<SyntaxNode>,
        recon: Box<ReconState>,
        ictx: Box<PSearchCtx>,
    }

    // One full search + tile write under `arm_params` (and, when
    // `plan` is set, the per-superblock ยง5.11.13 `CurrentQIndex`
    // walk). Each arm builds its own reconstruction / search context
    // / writer state from the shared frame-start snapshot, so arms
    // are exactly comparable and the winner's artifacts flow into the
    // unchanged post-tile pipeline.
    // r439 โ€” the two header fields the arm runner reads, captured by
    // VALUE so the closure does not borrow `fh` (the QM election
    // assigns `fh` between two `run_arm` calls; both fields are
    // arm-invariant).
    let fh_sct = fh.allow_screen_content_tools;
    let fh_disable_cdf_update = fh.disable_cdf_update;
    let run_arm =
        |arm_params: &SyntaxFrameParams, plan: Option<&[i32]>| -> Result<FrameArm, Error> {
            let mut recon = Box::new(ReconState {
                y: vec![0u16; width * height],
                u: vec![0u16; chroma_w * chroma_h],
                v: vec![0u16; chroma_w * chroma_h],
                width,
                height,
                chroma_w,
                chroma_h,
                bit_depth,
                subsampling_x: ssx,
                subsampling_y: ssy,
                num_planes,
                mi_rows,
                mi_cols,
                lossless,
                allow_screen_content_tools: fh_sct,
                // ยง5.9.20: intra-block-copy is intra-frame-only.
                allow_intrabc: false,
                qp: arm_params.quant,
                search: crate::encoder::key_frame::SearchLimits::default(),
                bd: BlockDecodedMirror::new(ssx, ssy, num_planes),
                dv_hash: Default::default(),
            });
            let mut ictx = Box::new(PSearchCtx::with_refs(
                &cfg.refs,
                cfg.slot_to_plane,
                cfg.ref_frame_idx,
                cfg.single_refs.clone(),
                cfg.compound_pairs.clone(),
                mi_rows,
                mi_cols,
                width,
                height,
                &ref_dims,
                ip.clone(),
                base_q_idx,
                alt_q,
                bit_depth,
                ssx,
                ssy,
                num_planes,
            )?);
            // r426 โ€” arm the ยง5.9.14 inter-override features (ladder item
            // 8): requires the segmentation carrier (non-empty alt_q), raw
            // RefFrame data within the ladder, and flips SegIdPreSkip.
            if let Some(x) = cfg.seg_extras {
                if alt_q.is_empty()
                    || x.ref_frame
                        .iter()
                        .flatten()
                        .any(|rf| !cfg.single_refs.contains(rf))
                {
                    return Err(Error::PartitionWalkOutOfRange);
                }
                ictx.extras = Some(*x);
                ictx.seg_id_pre_skip = x.any();
            }
            // r426 โ€” arm the exactness-demand / auto-lossless election.
            // Both require a lossless segment in the table, and the mask
            // must cover the mi grid exactly.
            if cfg.exact_mask.is_some() || cfg.auto_lossless {
                if ictx.lossless_seg.is_none() {
                    return Err(Error::PartitionWalkOutOfRange);
                }
                if let Some(mask) = cfg.exact_mask {
                    if mask.len() != (mi_rows as usize) * (mi_cols as usize) {
                        return Err(Error::PartitionWalkOutOfRange);
                    }
                    ictx.exact_mask = Some(mask.to_vec());
                }
                ictx.auto_lossless = cfg.auto_lossless;
            }

            let mut state = PartitionSyntaxWriter::new(
                mi_rows,
                mi_cols,
                TileGeometry {
                    mi_row_start: 0,
                    mi_row_end: mi_rows,
                    mi_col_start: 0,
                    mi_col_end: mi_cols,
                },
            )
            .ok_or(Error::PartitionWalkOutOfRange)?;

            // r423 โ€” the committed per-superblock syntax trees are
            // retained: the post-tile elections replay them bit-exactly
            // under alternative header arms. r431: tile-scan order (the
            // frame raster on the single-tile layout).
            let mut trees: Vec<SyntaxNode> = Vec::new();
            let mut payloads: Vec<Vec<u8>> = Vec::with_capacity(num_tiles as usize);
            let mut all_cdfs: Vec<Box<TileCdfContext>> = Vec::with_capacity(num_tiles as usize);
            let sb_cols_frame = mi_cols.div_ceil(16);
            for (geo, origins) in tile_plan.iter() {
                // ยง5.11.2 per-tile re-scope on BOTH mirrors (the write
                // driver and the search context โ€” ยง7.10.2 walker plus its
                // precomputed availability grids), plus the pixel path's
                // tile registry.
                if !state.begin_tile(*geo) {
                    return Err(Error::PartitionWalkOutOfRange);
                }
                ictx.begin_tile(*geo);
                recon.bd.set_tile(*geo);
                let mut writer = SymbolWriter::new(fh_disable_cdf_update);
                // ยง8.3.1: every tile starts from the frame-start CDF
                // state (ยง6.8.21 `load_cdfs` under a primary reference,
                // the q-selected defaults otherwise).
                let mut cdfs: Box<TileCdfContext> = frame_start_cdfs.clone();
                // ยง5.11.1 per-tile prologue: `CurrentQIndex = base_q_idx`
                // at every tile entry.
                recon.qp.current_q_index = base_q_idx;
                for &(sb_r, sb_c) in origins {
                    recon.bd.clear_for_sb(sb_r, sb_c, mi_rows, mi_cols);
                    // r428 โ€” ยง5.11.13 `CurrentQIndex` walk: apply the plan
                    // step BEFORE the superblock's search so every trial
                    // quantises (and the twin prices the first block's
                    // delta symbol) at the target index.
                    let prev_q = recon.qp.current_q_index;
                    if let Some(p) = plan {
                        // The plan is ABSOLUTE (offset from `base_q_idx`,
                        // FRAME-raster indexed); the ยง5.11.13 symbol codes
                        // the RELATIVE step from the running index. Units
                        // are computed so the ยง7.12.2 `Clip3( 1, 255, _ )`
                        // never truncates โ€” encoder and decoder land on
                        // the identical index.
                        let k = ((sb_r / 16) * sb_cols_frame + (sb_c / 16)) as usize;
                        let step = 1i32 << arm_params.delta_q_res;
                        let want = (i32::from(base_q_idx) + p[k] * step).clamp(1, 255);
                        let units = (want - i32::from(prev_q)) / step;
                        recon.qp.current_q_index = (i32::from(prev_q) + units * step) as u8;
                        ictx.delta_q_units = units;
                    }
                    // r421 โ€” arm the ยง5.11.2 delta lifecycle on the live
                    // state AND the rate twin's fork, so both enter the
                    // superblock identically.
                    state.arm_read_deltas();
                    let mut twin = RateTwin::snapshot(&cdfs, &state, &writer);
                    twin.arm_read_deltas();
                    let (tree, _cost) = build_p_search_tree(
                        sb_r,
                        sb_c,
                        BLOCK_64X64,
                        input,
                        &mut recon,
                        &mut ictx,
                        &mut twin,
                        arm_params,
                        model,
                    )?;
                    write_partition_tree_syntax(
                        &mut writer,
                        &mut cdfs,
                        &mut state,
                        &tree,
                        sb_r,
                        sb_c,
                        BLOCK_64X64,
                        arm_params,
                    )?;
                    // r421 anti-desync invariant: the search committed
                    // EXACTLY the symbols the writer just emitted.
                    debug_assert!(
                        twin.matches(&cdfs, &writer),
                        "rate twin desynced from the writer after superblock ({sb_r},{sb_c})"
                    );
                    // r428 โ€” realized `CurrentQIndex`: a full-superblock
                    // skip leaf takes the ยง5.11.13 short-circuit arm (no
                    // delta on the wire), so the decoder's running index
                    // never moves โ€” mirror that for the next superblock's
                    // step.
                    if plan.is_some() {
                        if let SyntaxNode::Leaf(b) = &tree {
                            if b.skip == 1 {
                                recon.qp.current_q_index = prev_q;
                            }
                        }
                    }
                    trees.push(tree);
                }
                payloads.push(writer.finish());
                all_cdfs.push(cdfs);
            }
            let body = assemble(&payloads)?;
            Ok(FrameArm {
                payloads,
                tile: body,
                all_cdfs,
                state,
                trees,
                recon,
                ictx,
            })
        };

    // r428 โ€” ยง5.9.17 delta-q election by EXACT realized bytes +
    // masking-weighted distortion: both arms are complete frame
    // encodes (their trees decode to different reconstructions โ€”
    // replays cannot compare them), so the election runs the
    // encoder's frame-level adaptive-quantisation objective
    // `Dwยท256 + ฮปยทR_bits256` over realized (header + tile) bytes.
    // `Dw` weights each superblock's squared error by `2^-units`
    // from the SAME probe plan on both arms (a flat superblock's
    // error counts up to 4ร—: banding shows first where nothing masks
    // it; a textured superblock's counts down to ยผ: masking hides
    // it). Under UNWEIGHTED SSE a per-superblock quantiser deviation
    // can essentially never win at fixed ฮป (convexity of the R(D)
    // curve โ€” the frame quantiser IS the ฮป-matched point), so the
    // weighted objective is what makes delta-q a real tool; the A/B
    // harness reports the resulting plain-PSNR/bytes trade honestly.
    let mut arm = run_arm(&params, None)?;

    // r439 โ€” ยง5.9.12 quantizer-matrix election by EXACT realized
    // bytes + distortion: on a lossy frame with real high-frequency
    // luma energy (the `qm_probe` gate โ€” the arm cannot win on
    // smooth content, and skipping it keeps those streams
    // bit-identical), a second full search runs under
    // `using_qmatrix = 1` at the `qm_level_for_q` ยง9.5.3 level on
    // all three planes: every quantise/dequantise step rides the
    // ยง7.12.3 `q2 = Round2( q * Quantizer_Matrix[ .. ], 5 )` scaling
    // through the SAME `SegQMLevel[ plane ][ segment_id ]` row the
    // decoder derives per ยง5.9.2. Both arms are complete frame
    // encodes with different reconstructions, so the election runs
    // the plain joint objective `Dยท256 + ฮปยทR_bits256` over realized
    // (header + tile) bytes โ€” the QM arm typically trades a small
    // SSE increase in the high frequencies for an outsized rate
    // saving on textured content; the winner's params flow into the
    // delta-q election below (the arms compose โ€” a delta-q plan
    // quantises at the running index with the SAME QM scaling on
    // both sides).
    //
    // r441 โ€” the SEGMENTED-frame gate is lifted: the arm's per-
    // segment `SegQMLevel` rows follow the ยง5.9.2 derivation (a
    // lossless segment takes the no-QM sentinel 15, every other
    // segment the coded level), the per-segment quantiser bundle
    // (`seg_qp`) carries each block's own row through the residual
    // chain, and the SEG_LVL feature trials price their QM-quantised
    // chains through the same bundles.
    let qm_arm_levels: Vec<u8> = if cfg.qm
        && !lossless
        && cfg.exact_mask.is_none()
        && !cfg.auto_lossless
        && qm_arm_allowed(base_q_idx, width, height)
        && qm_probe(input)
    {
        // r441 โ€” the multi-level ladder (see [`qm_ladder_for_q`]).
        qm_ladder_for_q(base_q_idx)
    } else {
        Vec::new()
    };
    let mut qm_elected = false;
    if !qm_arm_levels.is_empty() {
        let seg_ll = seg_lossless_array(base_q_idx, alt_q);
        let lambda = lambda_for(&qp);
        let prev_gm_score: Option<[[i32; 6]; TOTAL_REFS_PER_FRAME]> =
            if fh.primary_ref_frame != PRIMARY_REF_NONE {
                cfg.primary_carry.map(|c| c.gm_params)
            } else {
                None
            };
        let header_len = |fh_arm: &FrameHeader| -> usize {
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
                &mut bw,
                fh_arm,
                seq,
                prev_gm_score.as_ref(),
            );
            bw.byte_align();
            bw.finish().len()
        };
        let plain_sse = |rc: &ReconState| -> u64 {
            let mut d = 0u64;
            for (a, b) in rc.y.iter().zip(&input.y) {
                let diff = i64::from(*a) - i64::from(*b);
                d += (diff * diff) as u64;
            }
            if num_planes > 1 {
                for (a, b) in rc.u.iter().zip(&input.u).chain(rc.v.iter().zip(&input.v)) {
                    let diff = i64::from(*a) - i64::from(*b);
                    d += (diff * diff) as u64;
                }
            }
            d
        };
        let mut best_score = score256(
            plain_sse(&arm.recon),
            lambda,
            ((header_len(&fh) + arm.tile.len()) as u64) * 8 * 256,
        );
        for &lvl in &qm_arm_levels {
            let mut qp_m = qp;
            qp_m.using_qmatrix = true;
            for plane in 0..3 {
                for (seg, &ll) in seg_ll.iter().enumerate() {
                    // ยง5.9.2: a lossless segment's `SegQMLevel` is the
                    // no-QM sentinel 15; every other segment carries
                    // the coded `qm_y` / `qm_u` / `qm_v`.
                    qp_m.seg_qm_level[plane][seg] = if ll { 15 } else { lvl };
                }
            }
            let mut params_m = params.clone();
            params_m.quant = qp_m;
            let cand = run_arm(&params_m, None)?;
            let mut fh_m = fh.clone();
            if let Some(q) = fh_m.quantization_params.as_mut() {
                q.using_qmatrix = true;
                q.qm_y = lvl;
                q.qm_u = lvl;
                q.qm_v = lvl;
            }
            let score_qm = score256(
                plain_sse(&cand.recon),
                lambda,
                ((header_len(&fh_m) + cand.tile.len()) as u64) * 8 * 256,
            );
            if std::env::var_os("OXIDEAV_AV1_QM_DEBUG").is_some() {
                eprintln!(
                    "qm-frame oh={} lvl={} qm: tile {} B sse {} score {} | best so far {}",
                    cfg.order_hint,
                    lvl,
                    cand.tile.len(),
                    plain_sse(&cand.recon),
                    score_qm,
                    best_score,
                );
            }
            if score_qm < best_score {
                best_score = score_qm;
                qm_elected = true;
                arm = cand;
                fh = fh_m;
                params = params_m;
                qp = qp_m;
            }
            // Refinement discipline: only a winning keyed level earns
            // the neighbour's extra full search.
            if QM_LADDER_REFINES_ONLY && !qm_elected {
                break;
            }
        }
    }

    let mut delta_q_elected = false;
    if let Some(plan) = &delta_plan {
        let mut qp_d = qp;
        qp_d.delta_q_present = true;
        qp_d.current_q_index = base_q_idx;
        let mut params_d = params.clone();
        params_d.read_deltas = true;
        params_d.delta_q_res = DELTA_Q_RES;
        params_d.quant = qp_d;
        let cand = run_arm(&params_d, Some(plan))?;
        let mut fh_d = fh.clone();
        fh_d.delta_q_params = Some(crate::uncompressed_header_tail::DeltaQParams {
            delta_q_present: true,
            delta_q_res: DELTA_Q_RES,
        });
        let lambda = lambda_for(&qp);
        let prev_gm_score: Option<[[i32; 6]; TOTAL_REFS_PER_FRAME]> =
            if fh.primary_ref_frame != PRIMARY_REF_NONE {
                cfg.primary_carry.map(|c| c.gm_params)
            } else {
                None
            };
        let header_len = |fh_arm: &FrameHeader| -> usize {
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
                &mut bw,
                fh_arm,
                seq,
                prev_gm_score.as_ref(),
            );
            bw.byte_align();
            bw.finish().len()
        };
        // Plan-derived masking weights, applied identically to both
        // arms: per superblock, `sse << -units` (flat, `units < 0`)
        // or `sse >> units` (textured, `units > 0`).
        let weighted_sse = |rc: &ReconState| -> u64 {
            let mut d = 0u64;
            for (sb_index, &(sb_r, sb_c)) in sb_grid_origins(mi_rows, mi_cols).iter().enumerate() {
                let units = plan[sb_index];
                let y0 = (sb_r as usize) * 4;
                let x0 = (sb_c as usize) * 4;
                let y1 = (y0 + 64).min(height);
                let x1 = (x0 + 64).min(width);
                let mut sse = 0u64;
                for r in y0..y1 {
                    for c in x0..x1 {
                        let diff =
                            i64::from(rc.y[r * width + c]) - i64::from(input.y[r * width + c]);
                        sse += (diff * diff) as u64;
                    }
                }
                if num_planes > 1 {
                    let (cy0, cx0) = (y0 >> ssy, x0 >> ssx);
                    let (cy1, cx1) = (
                        (y1 + usize::from(ssy)) >> ssy,
                        (x1 + usize::from(ssx)) >> ssx,
                    );
                    for r in cy0..cy1.min(chroma_h) {
                        for c in cx0..cx1.min(chroma_w) {
                            let du = i64::from(rc.u[r * chroma_w + c])
                                - i64::from(input.u[r * chroma_w + c]);
                            let dv = i64::from(rc.v[r * chroma_w + c])
                                - i64::from(input.v[r * chroma_w + c]);
                            sse += (du * du + dv * dv) as u64;
                        }
                    }
                }
                // Variance-normalising weight `~ ref_activity /
                // activity == 2^(-2ยทunits)` (units โ‰ˆ ยฝยทlog2 of the
                // activity ratio): each superblock's error counts
                // relative to what its own content masks โ€” the
                // classic adaptive-quantisation objective.
                d += if units >= 0 {
                    sse >> (2 * units)
                } else {
                    sse << (-2 * units)
                };
            }
            d
        };
        let score_base = score256(
            weighted_sse(&arm.recon),
            lambda,
            ((header_len(&fh) + arm.tile.len()) as u64) * 8 * 256,
        );
        let score_delta = score256(
            weighted_sse(&cand.recon),
            lambda,
            ((header_len(&fh_d) + cand.tile.len()) as u64) * 8 * 256,
        );
        if std::env::var_os("OXIDEAV_AV1_DQ_DEBUG").is_some() {
            eprintln!(
                "dq-frame oh={} plan={:?} base: tile {} B Dw {} score {} | delta: tile {} B Dw {} score {}",
                cfg.order_hint,
                plan,
                arm.tile.len(),
                weighted_sse(&arm.recon),
                score_base,
                cand.tile.len(),
                weighted_sse(&cand.recon),
                score_delta,
            );
        }
        if score_delta < score_base {
            delta_q_elected = true;
            arm = cand;
            fh = fh_d;
            params = params_d;
        }
    }
    let FrameArm {
        payloads: mut tile_payloads,
        tile: mut tile_bytes,
        mut all_cdfs,
        mut state,
        mut trees,
        mut recon,
        ictx,
    } = arm;

    // r431 โ€” replay the committed trees across the tile plan under
    // `emit_params`: per tile a fresh ยง8.2 writer, the frame-start
    // CDF state from `start_cdfs()` (per-candidate for the
    // primary-ref election), the optional ยง5.11.57 `write_lr`
    // interleave, on a fresh frame-scope driver re-scoped tile by
    // tile. `Err` when any tile cannot reproduce a committed leaf
    // (the hp election's self-validation arm) or an LR window
    // rejects. Every post-tile election below re-emits ALL tiles and
    // prices the ASSEMBLED ยง5.11.1 body.
    let disable_cdf_update = fh.disable_cdf_update;
    type EmitOut = (
        Vec<Vec<u8>>,
        Vec<Box<TileCdfContext>>,
        PartitionSyntaxWriter,
    );
    let emit_tiles = |trees: &[SyntaxNode],
                      emit_params: &SyntaxFrameParams,
                      start_cdfs: &dyn Fn() -> Box<TileCdfContext>,
                      lr_plan: Option<&crate::encoder::lr_elect::LrPlan>|
     -> Result<EmitOut, Error> {
        let mut re_state = PartitionSyntaxWriter::new(
            mi_rows,
            mi_cols,
            TileGeometry {
                mi_row_start: 0,
                mi_row_end: mi_rows,
                mi_col_start: 0,
                mi_col_end: mi_cols,
            },
        )
        .ok_or(Error::PartitionWalkOutOfRange)?;
        let mut payloads: Vec<Vec<u8>> = Vec::with_capacity(num_tiles as usize);
        let mut all: Vec<Box<TileCdfContext>> = Vec::with_capacity(num_tiles as usize);
        let mut tree_idx = 0usize;
        for (geo, origins) in tile_plan.iter() {
            if !re_state.begin_tile(*geo) {
                return Err(Error::PartitionWalkOutOfRange);
            }
            let mut re_writer = SymbolWriter::new(disable_cdf_update);
            let mut re_cdfs: Box<TileCdfContext> = start_cdfs();
            let mut lr_write_state = crate::encoder::loop_restoration_write::LrWriteState::new();
            for &(sb_r, sb_c) in origins {
                re_state.arm_read_deltas();
                if let Some(plan) = lr_plan {
                    crate::encoder::loop_restoration_write::write_lr(
                        &mut re_writer,
                        &mut re_cdfs,
                        &mut lr_write_state,
                        sb_r,
                        sb_c,
                        BLOCK_64X64,
                        &plan.write_params,
                        &plan.units,
                    )?;
                }
                write_partition_tree_syntax(
                    &mut re_writer,
                    &mut re_cdfs,
                    &mut re_state,
                    &trees[tree_idx],
                    sb_r,
                    sb_c,
                    BLOCK_64X64,
                    emit_params,
                )?;
                tree_idx += 1;
            }
            payloads.push(re_writer.finish());
            all.push(re_cdfs);
        }
        Ok((payloads, all, re_state))
    };

    // r428 โ€” ยง5.9.2 `allow_high_precision_mv` election by EXACT
    // realized bits: the main pass searched and wrote under the
    // eighth-pel arm; replay the identical committed trees under the
    // quarter-pel arm from the same ยง8.3.1 frame-start CDF state and
    // keep whichever tile is smaller. The replay self-validates: the
    // write pass re-derives every ยง7.10.2 stack under the coarser
    // arm's ยง7.10.2.10 `lower_mv_precision`, and any committed leaf
    // the quarter-pel arm cannot reproduce bit-exactly (an odd
    // component in a ยง5.11.32 difference, a NEAREST/NEAR/GLOBAL
    // derivation that rounds away from the committed vector) errors
    // the replay writer out โ€” the frame then keeps the eighth-pel
    // arm. A successful replay decodes to the SAME reconstruction
    // (the trees carry every mode / vector / coefficient), so the
    // election is purely rate; the header cost is arm-invariant (one
    // f(1) either way). Frames carrying a non-IDENTITY ยง5.9.24 model
    // skip the replay: a TRANSLATION model's ยง5.9.24 grid
    // quantization is precision-dependent (the coarser header could
    // not code the elected parameters verbatim), and the
    // ROTZOOM/AFFINE ยง7.10.2.1 GlobalMvs derivation rounds
    // differently across the arms โ€” the elected models were fitted
    // and validated on the eighth-pel arm.
    let mut hp_elected = cfg.high_precision_mv;
    let gm_all_identity = params
        .inter
        .as_ref()
        .is_some_and(|i| (1..=7).all(|r| i.gm_type[r] == 0));
    if cfg.high_precision_mv && gm_all_identity {
        let mut alt_ip = params.inter.clone().ok_or(Error::PartitionWalkOutOfRange)?;
        alt_ip.allow_high_precision_mv = false;
        let mut alt_params = params.clone();
        alt_params.inter = Some(alt_ip);
        let replay = emit_tiles(&trees, &alt_params, &|| frame_start_cdfs.clone(), None)
            .and_then(|(p, c, s)| Ok((assemble(&p)?, p, c, s)));
        if let Ok((alt_body, alt_payloads, alt_cdfs, alt_state)) = replay {
            // `<=`: on an exact byte tie (no `mv_hp` cascade was ever
            // coded and every derivation matched) prefer the
            // quarter-pel arm โ€” the conservative wire shape, and the
            // bit-identical-to-baseline outcome the A/B control
            // expects.
            if alt_body.len() <= tile_bytes.len() {
                hp_elected = false;
                tile_payloads = alt_payloads;
                tile_bytes = alt_body;
                all_cdfs = alt_cdfs;
                state = alt_state;
                // The later elections (temporal segment arm, primary
                // reference) replay under the ELECTED precision arm,
                // and the header codes it.
                params.inter = alt_params.inter;
                if let Some(ir) = fh.inter_refs.as_mut() {
                    ir.allow_high_precision_mv = false;
                }
            }
        }
    }

    // r423 โ€” ยง5.9.14 `segmentation_temporal_update` election by EXACT
    // realized bits: the main pass searched and wrote under the
    // spatial arm; when the frame can code the temporal arm (a
    // primary reference exists and the config allows it), replay the
    // identical committed trees under the ยง5.11.19 temporal arm from
    // the same ยง8.3.1 frame-start CDF state and keep whichever tile
    // is smaller. Both arms decode to the same reconstruction (the
    // segment ids, modes and coefficients are the trees'; only the
    // ยง5.11.19 id-coding bits differ), so the election is purely
    // rate. Header cost is arm-invariant (each ยง5.9.14 flag is one
    // f(1) either way).
    let main_ip = params
        .inter
        .as_ref()
        .ok_or(Error::PartitionWalkOutOfRange)?;
    let mut seg_temporal_elected = false;
    let temporal_codable =
        !alt_q.is_empty() && cfg.primary_ref_frame != PRIMARY_REF_NONE && cfg.allow_temporal_seg;
    if temporal_codable {
        let mut alt_ip = main_ip.clone();
        alt_ip.segmentation_temporal_update = true;
        let mut alt_params = params.clone();
        alt_params.inter = Some(alt_ip);
        let (alt_payloads, alt_cdfs, alt_state) =
            emit_tiles(&trees, &alt_params, &|| frame_start_cdfs.clone(), None)?;
        let alt_body = assemble(&alt_payloads)?;
        if alt_body.len() < tile_bytes.len() {
            seg_temporal_elected = true;
            tile_payloads = alt_payloads;
            tile_bytes = alt_body;
            all_cdfs = alt_cdfs;
            state = alt_state;
        }
    }
    // The header codes the elected arm (`update_map`/`update_data`
    // are already 1 on every segmented frame).
    if let Some(sp) = fh.segmentation_params.as_mut() {
        sp.temporal_update = seg_temporal_elected;
    }

    // r424 โ€” ยง5.9.2 `primary_ref_frame` election by EXACT realized
    // bytes: the main pass searched and wrote under the config's
    // primary reference; each alternative candidate replays the
    // identical committed trees from its own ยง8.3.1 frame-start CDF
    // state (ยง6.8.21 `load_cdfs` of the candidate's carried slot, or
    // the per-frame defaults for the `PRIMARY_REF_NONE` candidate)
    // and re-prices the header (the 3-bit ordinal is constant; the
    // ยง5.9.24 subexp recentering against the candidate's
    // `PrevGmParams` is not). Every candidate decodes to the SAME
    // reconstruction โ€” the trees carry all modes and coefficients โ€”
    // so the election is purely rate, and the smallest header + tile
    // total wins.
    let mut prev_gm_for_header: Option<[[i32; 6]; TOTAL_REFS_PER_FRAME]> =
        if fh.primary_ref_frame != PRIMARY_REF_NONE {
            cfg.primary_carry.map(|c| c.gm_params)
        } else {
            None
        };
    if !cfg.alt_primaries.is_empty() {
        // The segmented temporal-update election above and this
        // election both swap the tile โ€” combining them would need a
        // per-candidate seg replay matrix nobody codes yet (the
        // pyramid drivers that offer alternatives never segment).
        if temporal_codable {
            return Err(Error::PartitionWalkOutOfRange);
        }
        let header_len = |ord: u8, prev: Option<&[[i32; 6]; TOTAL_REFS_PER_FRAME]>| -> usize {
            let mut fh_c = fh.clone();
            fh_c.primary_ref_frame = ord;
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
                &mut bw, &fh_c, seq, prev,
            );
            bw.byte_align();
            bw.finish().len()
        };
        let mut best_total =
            header_len(fh.primary_ref_frame, prev_gm_for_header.as_ref()) + tile_bytes.len();
        #[allow(clippy::type_complexity)]
        let mut best: Option<(
            u8,
            Vec<Vec<u8>>,
            Vec<u8>,
            Vec<Box<TileCdfContext>>,
            PartitionSyntaxWriter,
            Option<[[i32; 6]; TOTAL_REFS_PER_FRAME]>,
        )> = None;
        for (ord, carry_opt) in &cfg.alt_primaries {
            if *ord != PRIMARY_REF_NONE
                && (usize::from(*ord) >= REFS_PER_FRAME || carry_opt.is_none())
            {
                return Err(Error::PartitionWalkOutOfRange);
            }
            let cand_start = || -> Box<TileCdfContext> {
                match carry_opt {
                    Some(carry) if *ord != PRIMARY_REF_NONE => {
                        let mut loaded = carry.cdfs.clone();
                        loaded.zero_counts();
                        loaded
                    }
                    _ => {
                        let mut c = Box::new(TileCdfContext::new_from_defaults());
                        c.init_coeff_cdfs(base_q_idx);
                        c
                    }
                }
            };
            let (cand_payloads, cand_cdfs, cand_state) =
                emit_tiles(&trees, &params, &cand_start, None)?;
            let cand_body = assemble(&cand_payloads)?;
            let cand_prev = if *ord != PRIMARY_REF_NONE {
                carry_opt.map(|c| c.gm_params)
            } else {
                None
            };
            let total = header_len(*ord, cand_prev.as_ref()) + cand_body.len();
            if total < best_total {
                best_total = total;
                best = Some((
                    *ord,
                    cand_payloads,
                    cand_body,
                    cand_cdfs,
                    cand_state,
                    cand_prev,
                ));
            }
        }
        if let Some((ord, e_payloads, e_body, e_cdfs, e_state, e_prev)) = best {
            fh.primary_ref_frame = ord;
            tile_payloads = e_payloads;
            tile_bytes = e_body;
            all_cdfs = e_cdfs;
            state = e_state;
            prev_gm_for_header = e_prev;
        }
    }

    // r436 โ€” ยง6.8.14 `context_update_tile_id` DONOR election by
    // EXACT realized bytes: the PRIMARY frame's header names which of
    // its tiles donates the ยง8.4 frame-end CDF state this frame's
    // ยง8.3.1 chain loads (ยง6.8.21 `load_cdfs`). The main pass
    // searched and wrote under the committed tile-0 donation
    // (`primary_carry.cdfs`); when the carry offers the full donor
    // set and the main primary reference survived the r424 ordinal
    // election, replay the identical committed trees from EACH other
    // tile's frame-end state and keep the start state realizing the
    // smallest assembled ยง5.11.1 body. THIS frame's header is
    // donor-invariant (the field lives in the PRIMARY frame's
    // header, fixed-width `f(n)` โ€” even its byte length cannot
    // move), and every candidate decodes to the identical
    // reconstruction, so the election is purely rate; the caller
    // patches the primary frame's already-emitted field to the
    // elected id and fixes the stored carry.
    // r439 โ€” the donor election follows the ELECTED primary: when the
    // r424 ordinal election committed an ALT candidate (the pyramid's
    // nearest-backward anchor), that carry's donor set is the one
    // this frame's ยง8.3.1 chain loads from, so the replay candidates
    // come from IT (the caller patches THAT frame's field). The
    // GOP / ladder / SVC drivers only ever offer `PRIMARY_REF_NONE`
    // as the alternative, so their arm is unchanged.
    let donor_src: Option<&RefSlotCarry> = if fh.primary_ref_frame == PRIMARY_REF_NONE {
        None
    } else if fh.primary_ref_frame == cfg.primary_ref_frame {
        cfg.primary_carry
    } else {
        cfg.alt_primaries
            .iter()
            .find(|(o, _)| *o == fh.primary_ref_frame)
            .and_then(|(_, c)| *c)
    };
    let mut donor_elected: Option<u32> = None;
    if cfg.elect_donor {
        if let Some(pc) = donor_src {
            if pc.donor_cdfs.len() > 1 {
                // Replay under the ELECTED params (hp updated
                // `params.inter` in place; the temporal-seg arm
                // swapped the tile without touching `params`, so
                // mirror its flag here โ€” same doctrine as the CDEF
                // re-emission below).
                let mut d_params = params.clone();
                if let Some(ip) = d_params.inter.as_mut() {
                    ip.segmentation_temporal_update = seg_temporal_elected;
                }
                for (tid, cand) in pc.donor_cdfs.iter().enumerate().skip(1) {
                    let cand_start = || -> Box<TileCdfContext> {
                        let mut loaded = cand.clone();
                        loaded.zero_counts();
                        loaded
                    };
                    let (cand_payloads, cand_all, cand_state) =
                        emit_tiles(&trees, &d_params, &cand_start, None)?;
                    let cand_body = assemble(&cand_payloads)?;
                    if cand_body.len() < tile_bytes.len() {
                        donor_elected = Some(tid as u32);
                        tile_payloads = cand_payloads;
                        tile_bytes = cand_body;
                        all_cdfs = cand_all;
                        state = cand_state;
                    }
                }
            }
        }
    }

    // r428/r429 โ€” ยง5.9.19/ยง7.15 CDEF election: the committed
    // reconstruction (deblock levels are 0 on every header this
    // encoder emits, so it IS the ยง7.15 input) is filtered through
    // the decoder's own driver over the write mirror's committed
    // `cdef_idx[]` / `Skips[]` grids, a bounded strength search
    // scores each candidate against the SOURCE, and a winner that
    // beats the unfiltered frame under `D + ฮปยทR` lands in the header
    // and in the reconstruction โ€” the ยง7.20 reference store the
    // decoder will hold.
    // r429 extends the r428 frame-level arm (`cdef_bits = 0`, zero
    // tile bits) to per-64ร—64 strength ids: when the per-unit arm
    // wins, the tile is RE-EMITTED from the committed trees with the
    // ยง5.11.56 `L(cdef_bits)` literals stamped โ€” from the ELECTED
    // frame-start CDF state (hp / temporal-seg / primary-ref
    // elections above all replay from it) and the ELECTED params, so
    // only the equiprobable literals move the coder.
    // HARD gate on exactness-demand / auto-lossless frames: ยง7.15
    // filters every non-skip 8ร—8 block regardless of its segment, so
    // an elected strength would break the demanded regions'
    // pixel-exactness contract even when the frame-total SSD improves.
    // r436 โ€” SEGMENTED frames join the arm (the r428 scope gate is
    // lifted): ยง7.15 is segment-agnostic apart from the Skips grid,
    // the r423 temporal segment-map election replays the committed
    // trees (segment ids are carried state, not pixels โ€” a filtered
    // reference cannot desync it), and the whole pairing is pinned
    // bit-exact against independent decoders.
    // r429 โ€” the elected frame-start CDF state, rebuilt on demand for
    // the CDEF / LR tile re-emissions: the primary-ref election may
    // have swapped the ordinal โ€” reproduce its ยง8.3.1 start state
    // exactly as the candidate loop did (ยง6.8.21 `load_cdfs` of the
    // carried slot, or the per-frame defaults).
    let start_cdfs_for = |ord: u8| -> Box<TileCdfContext> {
        // r436 โ€” a donor election supersedes the main start state
        // (r439: it fires on the ELECTED primary's carry โ€” main or
        // alt โ€” so the donation is read from `donor_src`).
        if let (Some(t), Some(pc)) = (donor_elected, donor_src) {
            let mut loaded = pc.donor_cdfs[t as usize].clone();
            loaded.zero_counts();
            return loaded;
        }
        if ord == cfg.primary_ref_frame {
            frame_start_cdfs.clone()
        } else {
            match cfg
                .alt_primaries
                .iter()
                .find(|(o, _)| *o == ord)
                .and_then(|(_, c)| *c)
            {
                Some(carry) => {
                    let mut loaded = carry.cdfs.clone();
                    loaded.zero_counts();
                    loaded
                }
                None => {
                    let mut c = Box::new(TileCdfContext::new_from_defaults());
                    c.init_coeff_cdfs(base_q_idx);
                    c
                }
            }
        }
    };
    // r429 โ€” loop restoration needs the PRE-CDEF reconstruction
    // (ยง7.17 reads `CurrFrame` at stripe boundaries): snapshot before
    // the CDEF election below overwrites it.
    // r436 โ€” SEGMENTED frames join this arm too (the last in-loop
    // pairing): ยง7.17 is segment-agnostic, the unit fits run on the
    // committed reconstruction, and the tile re-emission replays the
    // committed trees (segment ids included) with the ยง5.11.57
    // interleave โ€” the pairing is pinned bit-exact against
    // independent decoders alongside the CDEF one.
    let lr_armed = cfg.lr
        && !lossless
        && seq.enable_restoration
        && cfg.exact_mask.is_none()
        && !cfg.auto_lossless;
    let pre_cdef: Option<(Vec<u16>, Vec<u16>, Vec<u16>)> =
        lr_armed.then(|| (recon.y.clone(), recon.u.clone(), recon.v.clone()));
    let mut committed_cdef_bits: u32 = 0;
    let mut cdef_elected = false;
    if cfg.cdef && !lossless && seq.enable_cdef && cfg.exact_mask.is_none() && !cfg.auto_lossless {
        if let Some(election) =
            crate::encoder::cdef_elect::elect_cdef(&crate::encoder::cdef_elect::CdefElectInput {
                mirror: state.mirror(),
                input,
                recon_y: &recon.y,
                recon_u: &recon.u,
                recon_v: &recon.v,
                width,
                height,
                chroma_w,
                chroma_h,
                bit_depth,
                subsampling_x: ssx,
                subsampling_y: ssy,
                num_planes,
                lambda: crate::encoder::key_frame::lambda_for(&recon.qp),
                max_bits: if cfg.cdef_units { 3 } else { 0 },
                fast: None,
                threads: 1,
            })
        {
            let lambda = crate::encoder::key_frame::lambda_for(&recon.qp);
            let cdef_header_len = |cdef_params: &crate::uncompressed_header_tail::CdefParams| {
                let mut fh_c = fh.clone();
                fh_c.cdef_params = Some(*cdef_params);
                let mut bw = crate::encoder::bitwriter::BitWriter::new();
                crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
                    &mut bw,
                    &fh_c,
                    seq,
                    prev_gm_for_header.as_ref(),
                );
                bw.byte_align();
                bw.finish().len()
            };
            let adopted: Option<crate::encoder::cdef_elect::CdefPlan>;
            if election.best.params.cdef_bits > 0 {
                let plan = &election.best;
                let elected_ord = fh.primary_ref_frame;
                // The elected params: hp updated `params.inter` in
                // place; the temporal-seg arm swapped the tile without
                // touching `params`, so mirror its flag here.
                let mut re_params = params.clone();
                if let Some(ip) = re_params.inter.as_mut() {
                    ip.segmentation_temporal_update = seg_temporal_elected;
                }
                re_params.cdef_bits = u32::from(plan.params.cdef_bits);
                // r431 โ€” `plan.unit_idx` is frame-raster per 64ร—64
                // unit; the trees ride tile-scan order โ€” map through
                // each tree's superblock origin.
                let sb_cols_frame = mi_cols.div_ceil(16);
                for (tree, &(sb_r, sb_c)) in trees.iter_mut().zip(flat_sb.iter()) {
                    let k = ((sb_r / 16) * sb_cols_frame + (sb_c / 16)) as usize;
                    tree.stamp_cdef_idx(plan.unit_idx[k].max(0));
                }
                let (re_payloads, re_cdfs, re_state) =
                    emit_tiles(&trees, &re_params, &|| start_cdfs_for(elected_ord), None)?;
                let re_body = assemble(&re_payloads)?;
                // Exact-bytes settlement: per-unit vs the fallback arm
                // (frame-level when it beats unfiltered, else the
                // unfiltered default header) on the SAME `D + ฮปยทR`
                // scale the leaf ladders use.
                let unit_score = plan.d * 256
                    + lambda * 8 * 256 * ((cdef_header_len(&plan.params) + re_body.len()) as u64);
                let (fb_d, fb_hdr) = match &election.frame_level {
                    Some(p) => (p.d, cdef_header_len(&p.params)),
                    None => (
                        election.base_d,
                        cdef_header_len(
                            fh.cdef_params
                                .as_ref()
                                .expect("lossy inter header carries cdef params"),
                        ),
                    ),
                };
                let fb_score = fb_d * 256 + lambda * 8 * 256 * ((fb_hdr + tile_bytes.len()) as u64);
                if unit_score < fb_score {
                    tile_payloads = re_payloads;
                    tile_bytes = re_body;
                    all_cdfs = re_cdfs;
                    state = re_state;
                    committed_cdef_bits = u32::from(plan.params.cdef_bits);
                    debug_assert!(
                        {
                            let grid = state.mirror().cdef_idx();
                            let sb_cols_dbg = mi_cols.div_ceil(16);
                            plan.unit_idx.iter().enumerate().all(|(k, &idx)| {
                                let (ur, uc) = (k as u32 / sb_cols_dbg, k as u32 % sb_cols_dbg);
                                grid[((ur * 16) * mi_cols + uc * 16) as usize] == idx
                            })
                        },
                        "re-emitted cdef_idx grid diverged from the elected plan"
                    );
                    adopted = Some(election.best);
                } else {
                    // The per-unit arm lost the settlement: the
                    // original tile stands. Re-stamp the trees to id
                    // 0 โ€” a later re-emission (the LR election)
                    // replays them at `cdef_bits = 0`, whose ยง5.11.56
                    // range check rejects any stamped id > 0.
                    for tree in trees.iter_mut() {
                        tree.stamp_cdef_idx(0);
                    }
                    adopted = election.frame_level;
                }
            } else {
                adopted = Some(election.best);
            }
            if let Some(plan) = adopted {
                crate::encoder::cdef_elect::apply_cdef_plan(
                    state.mirror(),
                    &plan,
                    input,
                    &mut recon.y,
                    &mut recon.u,
                    &mut recon.v,
                    width,
                    height,
                    chroma_w,
                    chroma_h,
                    bit_depth,
                    ssx,
                    ssy,
                    num_planes,
                    1,
                );
                fh.cdef_params = Some(plan.params);
                cdef_elected = true;
            }
        }
    }

    // r429 โ€” ยง5.9.20/ยง5.11.57/ยง7.17 loop-restoration election: the
    // LAST in-loop stage runs on the post-CDEF reconstruction. The
    // election fits per-64ร—64-unit Wiener / self-guided candidates
    // through the decoder's own ยง7.17 kernels, then the tile is
    // RE-EMITTED with the ยง5.11.57 `write_lr` interleave (one window
    // per superblock, under the ELECTED frame-start CDF state, params
    // and ยง5.11.56 CDEF literals of the committed tile) and LR-on vs
    // LR-off settles on EXACT realized bytes. On adoption the plan is
    // applied through the ยง7.17 frame driver โ€” the ยง7.20 reference
    // store the following frames predict from is the RESTORED frame,
    // exactly like the decoder's.
    // r456 โ€” ยง7.4 steps 3-4 / ยง7.16 on the superres inter arm: upscale
    // the post-CDEF reconstruction (and the pre-CDEF snapshot ยง7.17
    // reads across stripe boundaries) to the upscaled extent through
    // the decoder's OWN driver, BETWEEN the CDEF and LR elections โ€”
    // exactly the KEY arm's order. From here on the recon planes (the
    // ยง7.20 reference payload) live at the upscaled extent.
    let mut pre_cdef = pre_cdef;
    let (lr_w, lr_chroma_w, lr_src): (usize, usize, &YuvFrame) =
        if let Some((up_w, _)) = cfg.superres {
            let np = usize::from(num_planes);
            let upscale = |y: &[u16], u: &[u16], v: &[u16]| {
                crate::encoder::superres_elect::upscale_recon(
                    [y, u, v],
                    width as u32,
                    height as u32,
                    up_w,
                    mi_cols,
                    bit_depth,
                    ssx,
                    ssy,
                    np,
                )
            };
            let (uy, uu, uv) = upscale(&recon.y, &recon.u, &recon.v)?;
            recon.y = uy;
            recon.u = uu;
            recon.v = uv;
            if let Some(pc) = pre_cdef.as_mut() {
                let (py, pu, pv) = upscale(&pc.0, &pc.1, &pc.2)?;
                *pc = (py, pu, pv);
            }
            let src = cfg.superres_source.ok_or(Error::PartitionWalkOutOfRange)?;
            (
                up_w as usize,
                ((up_w + u32::from(ssx)) >> ssx) as usize,
                src,
            )
        } else {
            (width, chroma_w, input)
        };
    let mut lr_elected = false;
    if let Some((pcy, pcu, pcv)) = pre_cdef.as_ref() {
        let price_cdfs = start_cdfs_for(fh.primary_ref_frame);
        let lambda = crate::encoder::key_frame::lambda_for(&recon.qp);
        let lr_header_len = |lrp: &crate::uncompressed_header_tail::LrParams| {
            let mut fh_c = fh.clone();
            fh_c.lr_params = Some(*lrp);
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
                &mut bw,
                &fh_c,
                seq,
                prev_gm_for_header.as_ref(),
            );
            bw.byte_align();
            bw.finish().len()
        };
        let off_hdr = lr_header_len(
            fh.lr_params
                .as_ref()
                .expect("lossy inter header carries lr_params"),
        );
        // r460 โ€” the ยง5.9.20 unit-size ladder (64 / 128 / 256-sample
        // units; see the KEY driver): every rung a complete election
        // + re-emission, the frame keeping the best exact score
        // against the unfiltered arm.
        type LrCand = (
            crate::encoder::lr_elect::LrPlan,
            Vec<Vec<u8>>,
            Vec<u8>,
            Vec<Box<TileCdfContext>>,
            PartitionSyntaxWriter,
            u64,
        );
        let mut best_lr: Option<LrCand> = None;
        let mut off_score: Option<u64> = None;
        let min_shift: u8 = if seq.use_128x128_superblock { 1 } else { 0 };
        for unit_shift in min_shift..=2u8 {
            let Some(plan) =
                crate::encoder::lr_elect::elect_lr(&crate::encoder::lr_elect::LrElectInput {
                    input: lr_src,
                    curr_y: crate::encoder::lr_elect::LrCurr::Full(pcy),
                    curr_u: crate::encoder::lr_elect::LrCurr::Full(pcu),
                    curr_v: crate::encoder::lr_elect::LrCurr::Full(pcv),
                    cdef_y: &recon.y,
                    cdef_u: &recon.u,
                    cdef_v: &recon.v,
                    width: lr_w,
                    height,
                    chroma_w: lr_chroma_w,
                    chroma_h,
                    bit_depth,
                    subsampling_x: ssx,
                    subsampling_y: ssy,
                    num_planes,
                    mi_rows,
                    mi_cols,
                    lambda,
                    price_cdfs: &price_cdfs,
                    disable_cdf_update: fh.disable_cdf_update,
                    frame_width: lr_w,
                    frame_height: height,
                    sgr_step: 1,
                    unit_shift,
                    use_superres: cfg.superres.is_some(),
                    superres_denom: cfg
                        .superres
                        .map_or(crate::frame_header::SUPERRES_NUM, |(_, d)| d),
                    threads: 1,
                    wiener_rounds: 2,
                })
            else {
                continue;
            };
            let mut re_params = params.clone();
            if let Some(ip) = re_params.inter.as_mut() {
                ip.segmentation_temporal_update = seg_temporal_elected;
            }
            re_params.cdef_bits = committed_cdef_bits;
            let elected_ord = fh.primary_ref_frame;
            let re_out = emit_tiles(
                &trees,
                &re_params,
                &|| start_cdfs_for(elected_ord),
                Some(&plan),
            );
            let Ok((re_payloads, re_cdfs, re_state)) = re_out else {
                continue;
            };
            let re_body = assemble(&re_payloads)?;
            let on_score = plan.d * 256
                + lambda * 8 * 256 * ((lr_header_len(&plan.header) + re_body.len()) as u64);
            let off = *off_score.get_or_insert(
                plan.d_pre * 256 + lambda * 8 * 256 * ((off_hdr + tile_bytes.len()) as u64),
            );
            if on_score < off && best_lr.as_ref().map_or(true, |b| on_score < b.5) {
                best_lr = Some((plan, re_payloads, re_body, re_cdfs, re_state, on_score));
            }
        }
        if let Some((plan, re_payloads, re_body, re_cdfs, re_state, _)) = best_lr {
            tile_payloads = re_payloads;
            tile_bytes = re_body;
            all_cdfs = re_cdfs;
            state = re_state;
            let applied_d = crate::encoder::lr_elect::apply_lr_plan(
                &plan,
                lr_src,
                crate::encoder::lr_elect::LrCurr::Full(pcy),
                crate::encoder::lr_elect::LrCurr::Full(pcu),
                crate::encoder::lr_elect::LrCurr::Full(pcv),
                &mut recon.y,
                &mut recon.u,
                &mut recon.v,
                lr_w,
                height,
                lr_chroma_w,
                chroma_h,
                bit_depth,
                ssx,
                ssy,
                num_planes,
                mi_rows,
                mi_cols,
                lr_w,
                height,
            );
            debug_assert_eq!(
                applied_d, plan.d,
                "applied ยง7.17 SSD diverged from the elected plan"
            );
            fh.lr_params = Some(plan.header);
            lr_elected = true;
        }
    }

    // ยง5.11.1 tile-group body โ€” the winning arms' assembly
    // (`tile_bytes`); stamp the REALIZED ยง6.8.14 `TileSizeBytes` into
    // the header descriptor so the coded `tile_size_bytes_minus_1`
    // matches (the header BIT LENGTH is invariant โ€” a fixed `f(2)` โ€”
    // so the election prices above stay exact).
    ti.tile_size_bytes = crate::encoder::key_frame::min_tile_size_bytes(&tile_payloads) as u8;
    fh.tile_info = Some(ti.clone());
    let tile_group_body = tile_bytes;

    // r436 โ€” locate the ยง5.9.15 `context_update_tile_id` field on
    // the wire for the caller's deferred donor patch: write the
    // header twice (field = 0 vs 1 โ€” legal on every multi-tile
    // layout) and the single differing bit is the field's LSB (the
    // field is fixed-width `f(n)` and no later syntax element
    // depends on its value, so the two writes differ in exactly
    // that bit).
    let ctx_update_span: Option<(u32, u32)> = if ti.tile_cols_log2 + ti.tile_rows_log2 > 0 {
        let write_with = |ctx: u32| -> Vec<u8> {
            let mut fh_c = fh.clone();
            if let Some(t) = fh_c.tile_info.as_mut() {
                t.context_update_tile_id = ctx;
            }
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
                &mut bw,
                &fh_c,
                seq,
                prev_gm_for_header.as_ref(),
            );
            bw.byte_align();
            bw.finish()
        };
        let a = write_with(0);
        let b = write_with(1);
        debug_assert_eq!(a.len(), b.len(), "f(n) field cannot move the header length");
        let n = ti.tile_cols_log2 + ti.tile_rows_log2;
        let mut lsb: Option<u32> = None;
        for (i, (&x, &y)) in a.iter().zip(b.iter()).enumerate() {
            let d = x ^ y;
            if d != 0 {
                debug_assert!(
                    d.count_ones() == 1 && lsb.is_none(),
                    "exactly one bit distinguishes ctx ids 0 and 1"
                );
                lsb = Some((i as u32) * 8 + (7 - d.trailing_zeros()));
            }
        }
        let lsb = lsb.ok_or(Error::PartitionWalkOutOfRange)?;
        Some((lsb + 1 - n, n))
    } else {
        None
    };

    // Frame packaging. r423: with a primary reference the ยง5.9.24
    // subexp recentering codes against the carried `SavedGmParams`
    // (ยง7.21 `load_previous()`), not the setup_past_independence
    // defaults. r433 โ€” two packagings of the SAME header bits + tile
    // payloads: the ยง5.10 `OBU_FRAME` (header + `byte_alignment()` +
    // tile group), or โ€” when `cfg.tile_groups > 1` โ€” a standalone
    // `OBU_FRAME_HEADER` (ยง5.3.4 trailing_bits) followed by that many
    // `OBU_TILE_GROUP` OBUs re-framing the whole-frame body into
    // contiguous `tg_start ..= tg_end` slices (ยง6.10.1).
    let write_fh_bits = |bw: &mut crate::encoder::bitwriter::BitWriter| {
        crate::encoder::frame_obu::encode_uncompressed_header_with_prev_gm(
            bw,
            &fh,
            seq,
            prev_gm_for_header.as_ref(),
        );
    };
    let effective_groups = cfg.tile_groups.clamp(1, num_tiles);
    // r450 โ€” `cfg.tile_spans` forces the split framing on a
    // single-group multi-tile frame so the group can CODE its span
    // (`tile_start_and_end_present_flag = 1`; the ยง5.10 `OBU_FRAME`
    // packing requires the flag to be 0).
    let spans_split = cfg.tile_spans && effective_groups == 1 && num_tiles > 1;
    let frame_obus: Vec<ObuFrame> = if effective_groups > 1 || spans_split {
        let fh_payload = {
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            write_fh_bits(&mut bw);
            bw.trailing_bits_to_alignment();
            bw.finish()
        };
        let tg_bodies = if spans_split {
            vec![crate::encoder::tile_group_obu::single_group_with_spans(
                &tile_group_body,
                num_tiles,
                ti.tile_cols_log2,
                ti.tile_rows_log2,
                u32::from(ti.tile_size_bytes),
            )?]
        } else {
            crate::encoder::tile_group_obu::split_whole_frame_body(
                &tile_group_body,
                num_tiles,
                ti.tile_cols_log2,
                ti.tile_rows_log2,
                u32::from(ti.tile_size_bytes),
                effective_groups,
            )?
        };
        let mut obus = vec![ObuFrame::new(ObuType::FrameHeader, fh_payload)];
        obus.extend(
            tg_bodies
                .into_iter()
                .map(|b| ObuFrame::new(ObuType::TileGroup, b)),
        );
        obus
    } else {
        let frame_body = {
            let mut bw = crate::encoder::bitwriter::BitWriter::new();
            write_fh_bits(&mut bw);
            bw.byte_align();
            let mut body = bw.finish();
            body.extend_from_slice(&tile_group_body);
            body
        };
        vec![ObuFrame::new(ObuType::Frame, frame_body)]
    };

    // r413 โ€” ยง7.19 motion field motion vector storage: filter the
    // committed Mvs[] / RefFrames[] mirror grids down to the ยง7.20
    // per-slot payload (per cell, the LAST candidate list whose
    // reference lies in the past and whose components sit within
    // REFMVS_LIMIT), exactly like the decode driver does after
    // decoding this frame.
    const REFMVS_LIMIT: i16 = (1 << 12) - 1;
    let cells = (mi_rows as usize) * (mi_cols as usize);
    let mut mf_ref_frames: Vec<i8> = vec![-1; cells];
    let mut mf_mvs: Vec<i16> = vec![0; cells * 2];
    {
        let raw_refs = ictx.mirror.ref_frames();
        let raw_mvs = ictx.mirror.mvs();
        let hint_bits = u32::from(seq.order_hint_bits);
        let by_ref = ictx.ip.order_hints.order_hints_by_ref;
        for cell in 0..cells {
            for list in 0..2usize {
                let r = raw_refs[cell * 2 + list];
                if r > 0 {
                    let dist = crate::inter_pred::get_relative_dist(
                        by_ref[r as usize],
                        fh.order_hint as i32,
                        hint_bits,
                    );
                    if dist < 0 {
                        let mv_row = raw_mvs[(cell * 2 + list) * 2];
                        let mv_col = raw_mvs[(cell * 2 + list) * 2 + 1];
                        if mv_row.abs() <= REFMVS_LIMIT && mv_col.abs() <= REFMVS_LIMIT {
                            mf_ref_frames[cell] = r;
                            mf_mvs[cell * 2] = mv_row;
                            mf_mvs[cell * 2 + 1] = mv_col;
                        }
                    }
                }
            }
        }
    }
    let saved_mf = SavedMotionField {
        mf_mvs,
        mf_ref_frames,
        saved_order_hints: ictx.ip.order_hints.order_hints_by_ref,
        mi_rows,
        mi_cols,
        frame_is_intra: false,
    };

    // r423 โ€” this frame's own ยง7.20 slot payload for the caller's
    // carry store: the tile's adapted frame-end CDFs (ยง8.4
    // `save_cdfs` โ€” single tile, `context_update_tile_id = 0`,
    // `disable_frame_end_update_cdf = 0`), the committed
    // `SavedSegmentIds` grid (the write mirror's stamps โ€” identical
    // to the decode walker's by the lockstep argument), and
    // `SavedGmParams` (this frame's decoded GmParams table; identity
    // rows where no model was coded).
    // r436 โ€” the donation is `all_cdfs[ context_update_tile_id ]`
    // (id 0 as emitted; a LATER consumer's donor election may patch
    // the field, in which case the caller swaps `cdfs` for the
    // elected entry of `donor_cdfs`).
    let (cdfs, donor_cdfs) = if cfg.collect_donor_cdfs && all_cdfs.len() > 1 {
        (all_cdfs[ctx_update_id as usize].clone(), all_cdfs)
    } else {
        (all_cdfs.swap_remove(ctx_update_id as usize), Vec::new())
    };
    let carry = RefSlotCarry {
        cdfs,
        segment_ids: state.mirror().segment_ids().to_vec(),
        mi_rows,
        mi_cols,
        gm_params: fh
            .global_motion_params
            .as_ref()
            .map(|g| g.gm_params)
            .unwrap_or_else(crate::uncompressed_header_tail::prev_gm_params_default),
        donor_cdfs,
        ctx_update_span,
    };

    Ok((
        frame_obus,
        GopFrameReconYuv {
            y: recon.y,
            u: recon.u,
            v: recon.v,
        },
        saved_mf,
        carry,
        InterFrameAux {
            seg_temporal: seg_temporal_elected,
            primary_ref: fh.primary_ref_frame,
            hp_mv: hp_elected,
            delta_q: delta_q_elected,
            qm: qm_elected,
            cdef: cdef_elected,
            lr: lr_elected,
            donor_elected,
        },
    ))
}

// ---------------------------------------------------------------------
// ยง7.11.3 encoder-side prediction context.
// ---------------------------------------------------------------------

/// Driver-side ยง5.11.5 grid state + reference pixels: the exact inputs
/// [`reconstruct_inter_leaf_at`] (the decode walker's own ยง5.11.33
/// leaf driver) consumes, so the encoder's prediction is
/// bit-identical to the decoder's by construction.
///
/// Only the current leaf's own footprint is ever read back on the
/// r411 configuration (no OBMC / warp / compound neighbour reads and
/// no sub-8ร—8 inter leaves), so trial rollbacks need not restore the
/// grids โ€” the winning candidate re-stamps its footprint before
/// predicting.
///
/// r412 adds [`PSearchCtx::mirror`]: a full [`PartitionWalker`] the
/// RD search stamps with each COMMITTED leaf (via
/// [`PSearchCtx::stamp_leaf`], the same
/// `stamp_encoder_block_syntax` values the write pass stamps) so the
/// ยง7.10.2 `find_mv_stack` scan can run at SEARCH time with exactly
/// the state the write-pass mirror will hold at that leaf โ€” the
/// NEARESTMV / NEARMV / drl mode selection depends on it. Trials are
/// rolled back with the rect snapshot pair
/// ([`PartitionWalker::snapshot_encoder_stamp_rect`] /
/// [`PartitionWalker::restore_encoder_stamp_rect`]), mirroring the
/// pixel-plane `save_region` / `restore_region` discipline.
struct PSearchCtx {
    mi_rows: u32,
    mi_cols: u32,
    luma_w: u32,
    luma_h: u32,
    /// r456 โ€” per-[`Self::ref_planes`] LUMA extents
    /// (`RefUpscaledWidth` / `RefFrameHeight` per ยง7.11.3.3); equal to
    /// `(luma_w, luma_h)` off the scaled arms (superres inter frames,
    /// spatial-SVC inter-layer prediction).
    ref_dims: Vec<(u32, u32)>,
    /// r456 โ€” integer-pel SEARCH planes at the CODED extent for
    /// scaled references (`Some` per reference whose extent differs
    /// from the frame's: its luma resampled to the frame's extent):
    /// the coarse SSD walk reads them where it reads
    /// `ref_planes[..][0]` on flat references. A selection aid only โ€”
    /// every candidate that matters is scored through the decoder's
    /// own ยง7.11.3.3 / ยง7.11.3.4 kernels.
    search_planes: Vec<Option<Vec<u16>>>,
    /// r427 โ€” stream ยง5.5.2 `BitDepth` (threads the ยง7.11.2 /
    /// ยง7.11.3 clip + rounding parameters of the decoder kernels the
    /// search predicts through).
    bit_depth: u8,
    /// ยง5.5.2 `subsampling_x` (0 or 1).
    subsampling_x: u8,
    /// ยง5.5.2 `subsampling_y`.
    subsampling_y: u8,
    /// ยง5.5.2 `NumPlanes` (1 or 3).
    num_planes: u8,
    /// r415 โ€” the DISTINCT reference reconstructions this frame reads,
    /// widened to the ยง7.11.3.4 sample type (one entry per distinct
    /// coded frame; [`Self::slot_to_plane`] maps ยง7.20 slots onto
    /// them).
    ref_planes: Vec<[Vec<u16>; 3]>,
    /// r415 โ€” ยง7.20 slot โ†’ [`Self::ref_planes`] index. Slots never
    /// resolved through `ref_frame_idx` may point anywhere (their
    /// content is immaterial but must be sized like a real plane).
    slot_to_plane: [usize; 8],
    /// ยง5.9.2 `ref_frame_idx[ 0..7 ]` โ€” the header's slot map, fed
    /// verbatim to the decoder's leaf driver.
    ref_frame_idx: [u8; 7],
    /// r415 โ€” the single-reference ladder: each entry is a raw
    /// `RefFrame` ordinal (`LAST_FRAME = 1 ..= ALTREF_FRAME = 7`) the
    /// per-leaf ยง5.11.24 search trials with its own motion search.
    single_refs: Vec<i8>,
    /// r415 โ€” the compound ladder: `[ fwd, bwd-or-second ]` pairs the
    /// ยง5.11.25 cascade can code (slot 0 must be the ยง6.10.24 lower
    /// ordinal); both members must appear in [`Self::single_refs`]
    /// (NEW_NEWMV reuses their searched vectors).
    compound_pairs: Vec<[i8; 2]>,
    // ยง5.11.5 grids (per mi cell).
    mi_sizes: Vec<usize>,
    is_inters: Vec<u8>,
    ref_frames: Vec<i8>,
    mvs: Vec<i16>,
    interp_filters: Vec<u8>,
    motion_modes: Vec<u8>,
    y_modes: Vec<u8>,
    /// r419 โ€” ยง5.11.18 per-cell `AvailU` / `AvailL` grids for the
    /// ยง7.11.3.9 OBMC pass gates and every search-side neighbour
    /// scalar. r431: tile-scoped (`is_inside` of the CURRENT tile
    /// geometry) โ€” rebuilt by [`Self::begin_tile`]; the whole-frame
    /// construction values (`AvailU = MiRow > 0`, `AvailL = MiCol >
    /// 0`) are the single-tile layout's.
    avail_us: Vec<u8>,
    avail_ls: Vec<u8>,
    /// r415 โ€” the ยง5.11.5 `CompoundTypes[ .. ]` grid (COMPOUND_AVERAGE
    /// initial fill; [`Self::predict_leaf`] stamps each trial's
    /// committed ยง5.11.29 selection over its footprint); read at
    /// compound leaf origins by the decoder's leaf driver.
    compound_types: Vec<u8>,
    /// r415 โ€” the ยง5.11.5 wedge / diffwtd side-data grids
    /// (`wedge_index` / `wedge_sign` / `mask_type`), stamped alongside
    /// [`Self::compound_types`].
    wedge_indices: Vec<u8>,
    wedge_signs: Vec<u8>,
    mask_types: Vec<u8>,
    /// r417 โ€” the ยง5.11.28 inter-intra side-data grids the decoder's
    /// leaf driver reads at an inter-intra origin (`RefFrames[.. ][1]
    /// == INTRA_FRAME`): decoded-twin `InterIntraModes[]` /
    /// `WedgeInterIntras[]` / interintra `WedgeIndices[]` (all-zero
    /// pre-fill; [`Self::predict_leaf`] stamps each trial's committed
    /// selection over its footprint).
    interintra_modes: Vec<u8>,
    wedge_interintras: Vec<u8>,
    interintra_wedge_indices: Vec<u8>,
    /// ยง7.11.3.8 per-cell `LocalWarpParams[ 0..6 ]` slice
    /// ([`crate::GridWarpContext`] contract; r419 โ€”
    /// [`Self::predict_leaf`] stamps a `Warp` trial's fit at the leaf
    /// origin, the only cell the leaf driver reads).
    local_warp: Vec<i32>,
    /// r419 โ€” ยง7.11.3.8 `LocalValid` bit per cell (twin of the decode
    /// walker's grid; stamped alongside [`Self::local_warp`]).
    local_warp_valid: Vec<u8>,
    /// Full-plane prediction scratch (`reconstruct_inter_leaf_at`
    /// writes at absolute plane coordinates).
    scratch: [Vec<u16>; 3],
    gm_types: [u8; 8],
    gm_flat: [i32; 48],
    /// r413 โ€” `OrderHints[ ref ]` per raw `RefFrame` value (feeds the
    /// ยง7.11.3.15 order-hint context of the decoder's leaf driver;
    /// only the DISTANCE compound arm reads it, but the values track
    /// the real frame hints so the mirror stays derivation-exact).
    ref_hints: [i32; 8],
    /// r413 โ€” `OrderHintBits` / current-frame `OrderHint` twins of
    /// [`Self::ref_hints`] for the leaf driver's order-hint context.
    hint_bits: u32,
    current_hint: i32,
    no_scaled: [bool; 8],
    /// r413 โ€” ยง5.9.14 SEG_LVL_ALT_Q deltas per segment (empty =
    /// segmentation disabled). Drives the per-leaf segment policy,
    /// the per-segment residual quantiser, and the ยง5.11.20 `pred`
    /// inheritance on skip leaves.
    seg_alt_q: Vec<i16>,
    /// ยง5.9.12 `base_q_idx` (the segment-0 quantiser).
    base_q_idx: u8,
    /// r426 โ€” the exactness-demand mask (row-major mi-cell grid;
    /// `None` = no demand). A leaf overlapping a demanded cell is
    /// FORCED onto the lossless segment ([`Self::lossless_seg`]) on
    /// every arm โ€” inter residual, intra fallback, and the skip-mode
    /// admissibility guard โ€” so the demanded region reconstructs
    /// pixel-exact by the WHT chain's bit-exactness.
    exact_mask: Option<Vec<bool>>,
    /// r426 โ€” content-driven election: when `true`, synthetic leaves
    /// OUTSIDE the demand mask additionally trial the lossless
    /// segment against the lossy depth ladder on twin bits +
    /// distortion.
    auto_lossless: bool,
    /// r426 โ€” the lowest segment whose ยง7.12.2 qindex clamps to 0
    /// (`None` when the table has no lossless segment; the mask and
    /// auto arms are inert then).
    lossless_seg: Option<u8>,
    /// r426 โ€” the three ยง5.9.14 inter-override features (ladder item
    /// 8); `None` = no feature segments (the pre-r426 shape).
    extras: Option<SegExtras>,
    /// r426 โ€” ยง5.9.14 `SegIdPreSkip` (1 whenever any override feature
    /// is active): segment ids code BEFORE skip, so skip leaves keep
    /// their own committed segment instead of the ยง5.11.9 pred.
    seg_id_pre_skip: bool,
    /// r412 โ€” driver-side write-mirror twin for ยง7.10.2 MV prediction
    /// (see the struct docs).
    mirror: PartitionWalker,
    /// The ยง5.9 inter bundle shared with the write pass โ€” the
    /// `find_mv_stack` argument set.
    ip: SyntaxInterFrameParams,
    /// r428 โ€” the CURRENT superblock's ยง5.11.13 delta-q plan value in
    /// reduced units (`0` = delta-q off or a no-delta superblock).
    /// Every committed leaf carries it in `reduced_delta_q_index`
    /// (the ยง5.11.2 lifecycle codes only the FIRST block's value;
    /// full-superblock skip leaves carry 0 โ€” the ยง5.11.13
    /// short-circuit arm never codes a delta).
    delta_q_units: i32,
}

impl PSearchCtx {
    /// r412 two-slot P-frame configuration: LAST = `prev`, GOLDEN =
    /// `prevprev`, ladder `{ LAST, GOLDEN }` singles + the one
    /// unidirectional compound pair.
    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    fn new(
        prev: &GopFrameReconYuv,
        prevprev: &GopFrameReconYuv,
        mi_rows: u32,
        mi_cols: u32,
        width: usize,
        height: usize,
        ip: SyntaxInterFrameParams,
        p_index: u32,
        base_q_idx: u8,
        seg_alt_q: &[i16],
    ) -> Result<Self, Error> {
        let last_slot = (p_index & 1) as usize;
        let golden_slot = ((p_index - 1) & 1) as usize;
        let mut slot_to_plane = [0usize; 8];
        slot_to_plane[golden_slot] = 1;
        let mut ref_frame_idx = [last_slot as u8; 7];
        ref_frame_idx[3] = golden_slot as u8;
        Self::with_refs(
            &[prev, prevprev],
            slot_to_plane,
            ref_frame_idx,
            vec![1, 4],
            vec![[1, 4]],
            mi_rows,
            mi_cols,
            width,
            height,
            &[(width as u32, height as u32); 2],
            ip,
            base_q_idx,
            seg_alt_q,
            8,
            1,
            1,
            3,
        )
    }

    /// r415 โ€” the general reference configuration: `refs` are the
    /// distinct reference reconstructions, `slot_to_plane` the ยง7.20
    /// slot map onto them, `ref_frame_idx` the ยง5.9.2 header slot map,
    /// and `single_refs` / `compound_pairs` the RD ladder (see the
    /// field docs).
    #[allow(clippy::too_many_arguments)]
    fn with_refs(
        refs: &[&GopFrameReconYuv],
        slot_to_plane: [usize; 8],
        ref_frame_idx: [u8; 7],
        single_refs: Vec<i8>,
        compound_pairs: Vec<[i8; 2]>,
        mi_rows: u32,
        mi_cols: u32,
        width: usize,
        height: usize,
        ref_dims: &[(u32, u32)],
        ip: SyntaxInterFrameParams,
        base_q_idx: u8,
        seg_alt_q: &[i16],
        bit_depth: u8,
        subsampling_x: u8,
        subsampling_y: u8,
        num_planes: u8,
    ) -> Result<Self, Error> {
        if refs.is_empty()
            || slot_to_plane.iter().any(|&p| p >= refs.len())
            || single_refs.iter().any(|&r| !(1..=7).contains(&r))
            || compound_pairs.iter().any(|pr| {
                !single_refs.contains(&pr[0]) || !single_refs.contains(&pr[1]) || pr[0] >= pr[1]
            })
        {
            return Err(Error::PartitionWalkOutOfRange);
        }
        let cells = (mi_rows as usize) * (mi_cols as usize);
        // r422 โ€” the ยง5.9.24 model state comes from the shared inter
        // bundle (identity unless the frame-level election committed
        // a model), so the ยง7.11.3 warp context of `predict_leaf`
        // sees EXACTLY what the write pass and the decoder see.
        let mut gm_flat = [0i32; 48];
        let mut gm_types_u8 = [GM_TYPE_IDENTITY as u8; 8];
        for r in 0..8 {
            gm_flat[r * 6..r * 6 + 6].copy_from_slice(&ip.gm_params[r]);
            gm_types_u8[r] = ip.gm_type[r] as u8;
        }
        let mut ref_frames = vec![0i8; cells * 2];
        for cell in 0..cells {
            ref_frames[cell * 2] = 0; // INTRA_FRAME pre-fill
            ref_frames[cell * 2 + 1] = -1; // NONE
        }
        let mirror = PartitionWalker::new(
            mi_rows,
            mi_cols,
            TileGeometry {
                mi_row_start: 0,
                mi_row_end: mi_rows,
                mi_col_start: 0,
                mi_col_end: mi_cols,
            },
        )
        .ok_or(Error::PartitionWalkOutOfRange)?;
        if ref_dims.len() != refs.len() {
            return Err(Error::PartitionWalkOutOfRange);
        }
        let scaled_of = |plane: usize| -> bool {
            let (rw, rh) = ref_dims[plane];
            crate::encoder::superres_elect::is_scaled(rw, rh, width as u32, height as u32)
        };
        let search_planes: Vec<Option<Vec<u16>>> = refs
            .iter()
            .enumerate()
            .map(|(plane, r)| {
                scaled_of(plane).then(|| {
                    let (rw, rh) = ref_dims[plane];
                    crate::encoder::superres_elect::resample_plane_bilinear(
                        &r.y,
                        rw as usize,
                        rh as usize,
                        width,
                        height,
                    )
                })
            })
            .collect();
        let mut no_scaled = [false; 8];
        for (slot, flag) in no_scaled.iter_mut().enumerate() {
            *flag = scaled_of(slot_to_plane[slot]);
        }
        Ok(PSearchCtx {
            mi_rows,
            mi_cols,
            luma_w: width as u32,
            luma_h: height as u32,
            ref_dims: ref_dims.to_vec(),
            search_planes,
            bit_depth,
            subsampling_x,
            subsampling_y,
            num_planes,
            ref_planes: refs
                .iter()
                .map(|r| [r.y.clone(), r.u.clone(), r.v.clone()])
                .collect(),
            slot_to_plane,
            ref_frame_idx,
            single_refs,
            compound_pairs,
            mi_sizes: vec![BLOCK_4X4; cells],
            is_inters: vec![0u8; cells],
            ref_frames,
            mvs: vec![0i16; cells * 4],
            interp_filters: vec![EIGHTTAP; cells * 2],
            motion_modes: vec![MOTION_MODE_SIMPLE; cells],
            y_modes: vec![0u8; cells],
            avail_us: {
                let mut v = vec![1u8; cells];
                v[..mi_cols as usize].fill(0);
                v
            },
            avail_ls: {
                let mut v = vec![1u8; cells];
                for r in 0..mi_rows as usize {
                    v[r * mi_cols as usize] = 0;
                }
                v
            },
            compound_types: vec![crate::cdf::COMPOUND_AVERAGE; cells],
            wedge_indices: vec![0u8; cells],
            wedge_signs: vec![0u8; cells],
            mask_types: vec![0u8; cells],
            interintra_modes: vec![0u8; cells],
            wedge_interintras: vec![0u8; cells],
            interintra_wedge_indices: vec![0u8; cells],
            local_warp: vec![0i32; cells * 6],
            local_warp_valid: vec![0u8; cells],
            scratch: {
                let (cw, ch) = if num_planes > 1 {
                    (width >> subsampling_x, height >> subsampling_y)
                } else {
                    (0, 0)
                };
                [
                    vec![0u16; width * height],
                    vec![0u16; cw * ch],
                    vec![0u16; cw * ch],
                ]
            },
            gm_types: gm_types_u8,
            gm_flat,
            ref_hints: {
                let mut h = [0i32; 8];
                h.copy_from_slice(&ip.order_hints.order_hints_by_ref);
                h
            },
            hint_bits: ip.order_hints.order_hint_bits,
            current_hint: ip.order_hints.current_order_hint,
            seg_alt_q: seg_alt_q.to_vec(),
            base_q_idx,
            exact_mask: None,
            auto_lossless: false,
            extras: None,
            seg_id_pre_skip: false,
            lossless_seg: {
                let ll = seg_lossless_array(base_q_idx, seg_alt_q);
                (0..seg_alt_q.len()).find(|&s| ll[s]).map(|s| s as u8)
            },
            no_scaled,
            mirror,
            ip,
            delta_q_units: 0,
        })
    }

    /// r413 โ€” per-leaf segment policy: map the input block's luma
    /// mean-absolute-deviation to a segment index (flat blocks take
    /// segment 0, increasingly textured blocks the higher segments).
    /// Any deterministic rule is conformant โ€” the map is simply what
    /// the encoder codes; this one makes every segment reachable on
    /// textured content.
    fn segment_for_block(&self, input: &YuvFrame, mi_row: u32, mi_col: u32, b_size: usize) -> u8 {
        if self.seg_alt_q.is_empty() {
            return 0;
        }
        // r426 โ€” exactness-demand override: a leaf overlapping the
        // demand mask is FORCED onto the lossless segment (the
        // caller validated the table carries one).
        if let Some(ll) = self.lossless_seg {
            if self.demands_exact(mi_row, mi_col, b_size) {
                return ll;
            }
            if self.exact_mask.is_some() || self.auto_lossless {
                // Region/auto configuration: the activity policy maps
                // non-demanded leaves onto the LOSSY prefix only โ€”
                // lossless coding outside the demand is the r426
                // twin-priced election's call, never the policy's.
                let cap = u64::from(ll.saturating_sub(1));
                let act = self.block_activity(input, mi_row, mi_col, b_size);
                return (act / 6).min(cap) as u8;
            }
        }
        let act = self.block_activity(input, mi_row, mi_col, b_size);
        let mut top = (self.seg_alt_q.len() - 1) as u64;
        // r426 โ€” inter-override feature segments (ladder item 8) are
        // TRIAL-elected, never activity-assigned: their blocks carry
        // forced ยง5.11.10/ยง5.11.11/ยง5.11.23/ยง5.11.25 derivations the
        // plain residual ladder does not honour. The activity policy
        // maps onto the feature-free prefix only.
        if let Some(x) = self.extras.as_ref() {
            let first_feature = (0..self.seg_alt_q.len())
                .find(|&s| x.ref_frame[s].is_some() || x.skip[s] || x.globalmv[s])
                .unwrap_or(self.seg_alt_q.len());
            top = top.min(first_feature.saturating_sub(1) as u64);
        }
        (act / 6).min(top) as u8
    }

    /// r413 โ€” the activity metric behind [`Self::segment_for_block`]:
    /// the input block's luma mean-absolute-deviation.
    fn block_activity(&self, input: &YuvFrame, mi_row: u32, mi_col: u32, b_size: usize) -> u64 {
        let (bw, bh) = (
            NUM_4X4_BLOCKS_WIDE[b_size] * 4,
            NUM_4X4_BLOCKS_HIGH[b_size] * 4,
        );
        let (row0, col0) = ((mi_row as usize) * 4, (mi_col as usize) * 4);
        let w = input.width as usize;
        let mut sum = 0u64;
        for i in 0..bh {
            for j in 0..bw {
                sum += u64::from(input.y[(row0 + i) * w + (col0 + j)]);
            }
        }
        let n = (bw * bh) as u64;
        let mean = sum / n;
        let mut mad = 0u64;
        for i in 0..bh {
            for j in 0..bw {
                let v = u64::from(input.y[(row0 + i) * w + (col0 + j)]);
                mad += v.abs_diff(mean);
            }
        }
        mad / n
    }

    /// r413 โ€” the quantiser bundle for one segment: ยง7.12.2
    /// `get_qindex( seg ) = Clip3( 0, 255, base_q_idx + alt_q[ seg ] )`
    /// with the frame's zero per-plane deltas (the encode-side
    /// residual chain quantises at exactly the q-index the ยง5.11.39
    /// reader will dequantise with).
    ///
    /// r429 BUG FIX โ€” the bundle carries the FRAME's ยง6.4.1
    /// `BitDepth`, not a hardcoded 8: the ยง7.12.2 `dc_q` / `ac_q`
    /// lookups, the residual chain's `(1 << BitDepth) - 1` clip and
    /// the [`lambda_for`] `4^(BitDepth-8)` distortion scale are all
    /// depth-keyed, so an 8-bit bundle mis-quantised every non-zero
    /// segment of a 10/12-bit GOP (encoder recon diverged from the
    /// decoder's ยง7.12.3 dequantisation of the very coefficients it
    /// wrote).
    /// r436 โ€” ยง5.9.17 pairing: on a delta-q-armed frame the ยง7.12.2
    /// step-3 branch composes the segment's data on top of the
    /// RUNNING `CurrentQIndex` (the ยง5.11.13 walk), not `base_q_idx`
    /// โ€” the caller's `frame_qp` carries the superblock's live index,
    /// and the decoder's `get_qindex( 0, segment_id )` will resolve
    /// to exactly this value (baking `base_q_idx + data` here
    /// mis-quantised every non-zero segment of a delta-stepped
    /// superblock: encoder recon diverged from the ยง7.12.3
    /// dequantisation of the very coefficients it wrote).
    /// r441 โ€” ยง5.9.12 pairing: the bundle carries the frame's
    /// `using_qmatrix` and THIS segment's ยง5.9.2 `SegQMLevel[ plane ][
    /// segment_id ]` row (the residual chain reads the bundle's slot
    /// 0, so the segment's own triple is installed uniformly). A
    /// neutral bundle dropped the QM state, so on a QM-elected
    /// segmented frame every non-zero segment quantised through the
    /// flat lattice while the decoder dequantised through the ยง9.5.3
    /// matrix.
    fn seg_qp(&self, frame_qp: &QuantizerParams, segment_id: u8) -> QuantizerParams {
        if self.seg_alt_q.is_empty() || segment_id == 0 {
            return *frame_qp;
        }
        let base = if frame_qp.delta_q_present {
            i32::from(frame_qp.current_q_index)
        } else {
            i32::from(self.base_q_idx)
        };
        let q = (base + i32::from(self.seg_alt_q[segment_id as usize])).clamp(0, 255) as u8;
        let mut qp = QuantizerParams::neutral(q, frame_qp.bit_depth);
        if frame_qp.using_qmatrix {
            qp.using_qmatrix = true;
            let row = frame_qp.seg_qm_level_for(segment_id);
            for (plane, &lvl) in row.iter().enumerate() {
                qp.seg_qm_level[plane] = [lvl; crate::uncompressed_header_tail::MAX_SEGMENTS];
            }
        }
        qp
    }

    /// r426 โ€” `LosslessArray[ segment_id ]` for this GOP's frames
    /// (see [`seg_lossless_array`]): `true` exactly when the block's
    /// ยง7.12.2 qindex clamps to 0, flipping the ยง5.11.15 `TX_4X4` /
    /// ยง7.13.2.10 WHT leaf semantics for that block.
    fn seg_lossless(&self, segment_id: u8) -> bool {
        let s = segment_id as usize;
        let q = if self.seg_alt_q.is_empty() || s >= self.seg_alt_q.len() {
            i32::from(self.base_q_idx)
        } else {
            (i32::from(self.base_q_idx) + i32::from(self.seg_alt_q[s])).clamp(0, 255)
        };
        q == 0
    }

    /// r426 โ€” synthetic-content detector for the auto-lossless
    /// election: `true` when the input block's luma alphabet is small
    /// (`<= 16` distinct values โ€” flat fills, text glyphs, UI edges,
    /// lightly antialiased text). The bound deliberately exceeds the
    /// ยง5.11.46 `PALETTE_COLORS = 8` ceiling: at `<= 8` the
    /// screen-content palette already codes the block exactly, so the
    /// lossless segment's unique territory starts where the palette
    /// alphabet ends. Pure gate: it only bounds which leaves PAY for
    /// the extra lossless trial; the election itself is twin bits +
    /// distortion.
    fn synthetic_leaf(&self, input: &YuvFrame, mi_row: u32, mi_col: u32, b_size: usize) -> bool {
        let (bw, bh) = (
            NUM_4X4_BLOCKS_WIDE[b_size] * 4,
            NUM_4X4_BLOCKS_HIGH[b_size] * 4,
        );
        let (row0, col0) = ((mi_row as usize) * 4, (mi_col as usize) * 4);
        let w = input.width as usize;
        let mut seen = [false; 256];
        let mut distinct = 0usize;
        for i in 0..bh {
            for j in 0..bw {
                let v = input.y[(row0 + i) * w + (col0 + j)] as usize;
                if !seen[v] {
                    seen[v] = true;
                    distinct += 1;
                    if distinct > 16 {
                        return false;
                    }
                }
            }
        }
        true
    }

    /// r426 โ€” `true` iff the leaf at `(mi_row, mi_col, b_size)`
    /// overlaps a demanded cell of the exactness mask. Demanded
    /// leaves are forced onto the lossless segment on every arm.
    fn demands_exact(&self, mi_row: u32, mi_col: u32, b_size: usize) -> bool {
        let Some(mask) = self.exact_mask.as_ref() else {
            return false;
        };
        let bh4 = NUM_4X4_BLOCKS_HIGH[b_size] as u32;
        let bw4 = NUM_4X4_BLOCKS_WIDE[b_size] as u32;
        let r1 = (mi_row + bh4).min(self.mi_rows);
        let c1 = (mi_col + bw4).min(self.mi_cols);
        (mi_row..r1).any(|r| (mi_col..c1).any(|c| mask[(r * self.mi_cols + c) as usize]))
    }

    /// r431 โ€” ยง5.11.2 per-tile re-scope of the WHOLE search context:
    /// the ยง7.10.2 driver mirror (its own `begin_tile` clears the
    /// above contexts and rebuilds the walk-availability grids) plus
    /// this context's precomputed `AvailU` / `AvailL` grids. Must run
    /// at every tile entry, in lockstep with the write driver's
    /// [`PartitionSyntaxWriter::begin_tile`].
    fn begin_tile(&mut self, geometry: TileGeometry) {
        self.mirror.begin_tile(geometry);
        for r in 0..self.mi_rows {
            for c in 0..self.mi_cols {
                let i = (r * self.mi_cols + c) as usize;
                self.avail_us[i] = u8::from(geometry.is_inside(r as i32 - 1, c as i32));
                self.avail_ls[i] = u8::from(geometry.is_inside(r as i32, c as i32 - 1));
            }
        }
    }

    /// r413 โ€” the ยง5.11.20 `pred` cascade over the mirror's
    /// `SegmentIds[]` (the value a `skip == 1` leaf inherits with no
    /// bits; must be derived at SEARCH time from exactly the state
    /// the write pass will hold). r431: `AvailU` / `AvailL` are
    /// tile-scoped, like the write side's
    /// [`PartitionSyntaxWriter::segment_pred_ctx`].
    fn segment_pred(&self, mi_row: u32, mi_col: u32) -> u8 {
        let at = |r: i64, c: i64| -> i32 {
            if r < 0 || c < 0 || r >= i64::from(self.mi_rows) || c >= i64::from(self.mi_cols) {
                return -1;
            }
            self.mirror.segment_ids()[(r as u32 * self.mi_cols + c as u32) as usize]
        };
        let cell = (mi_row * self.mi_cols + mi_col) as usize;
        let (avail_u, avail_l) = (self.avail_us[cell] != 0, self.avail_ls[cell] != 0);
        let (r, c) = (i64::from(mi_row), i64::from(mi_col));
        let prev_ul = if avail_u && avail_l {
            at(r - 1, c - 1)
        } else {
            -1
        };
        let prev_u = if avail_u { at(r - 1, c) } else { -1 };
        let prev_l = if avail_l { at(r, c - 1) } else { -1 };
        #[allow(clippy::if_same_then_else)]
        let pred: i32 = if prev_u == -1 {
            if prev_l == -1 {
                0
            } else {
                prev_l
            }
        } else if prev_l == -1 {
            prev_u
        } else if prev_ul == prev_u {
            prev_u
        } else {
            prev_l
        };
        pred as u8
    }

    /// r415 โ€” resolve a raw `RefFrame` ordinal to its
    /// [`Self::ref_planes`] index through the header slot map.
    /// r456 โ€” the luma plane the integer-pel SSD walk reads for
    /// reference plane `plane`: the reference itself on flat frames,
    /// its coded-extent resample on the superres inter arm.
    fn search_luma(&self, plane: usize) -> &[u16] {
        self.search_planes[plane]
            .as_deref()
            .unwrap_or(&self.ref_planes[plane][0])
    }

    fn plane_of_ref(&self, rf: i8) -> usize {
        self.slot_to_plane[self.ref_frame_idx[(rf - 1) as usize] as usize]
    }

    /// ยง7.10.2 `find_mv_stack( 0 )` against the driver mirror for the
    /// single-reference LAST_FRAME leaf at `(mi_row, mi_col)` โ€” the
    /// argument set is character-for-character the write arm's
    /// (`write_block_syntax_inter_frame` threads the same
    /// [`SyntaxInterFrameParams`] fields), so both scans agree by
    /// construction whenever the two mirrors hold the same grids.
    fn find_stack(
        &self,
        mi_row: u32,
        mi_col: u32,
        b_size: usize,
        ref_frame: [i8; 2],
    ) -> Result<FindMvStackResult, Error> {
        self.mirror.find_mv_stack(
            mi_row,
            mi_col,
            b_size,
            [i32::from(ref_frame[0]), i32::from(ref_frame[1])],
            /* is_compound = */ ref_frame[1] > 0,
            self.ip.use_ref_frame_mvs,
            self.ip.gm_type,
            self.ip.gm_params,
            self.ip.ref_frame_sign_bias,
            self.ip.allow_high_precision_mv,
            self.ip.force_integer_mv,
            &self.ip.motion_field_mvs,
        )
    }

    /// r419 โ€” rect snapshot of every ยง5.11.5 driver grid (the slices
    /// [`Self::predict_leaf`] / [`Self::stamp_intra_leaf_grids`]
    /// stamp and the decoder's leaf driver reads). The r419 OBMC
    /// neighbour scan reads committed ABOVE/LEFT cells through these
    /// grids, so โ€” like the mirror โ€” losing trials must roll back:
    /// [`build_p_search_tree`] pairs every mirror snapshot/restore
    /// with a driver-grid one.
    fn snapshot_grids_rect(&self, mi_row: u32, mi_col: u32, n4: u32) -> DriverGridSnapshot {
        let r1 = (mi_row + n4).min(self.mi_rows);
        let c1 = (mi_col + n4).min(self.mi_cols);
        let mut cells = Vec::with_capacity(((r1 - mi_row) * (c1 - mi_col)) as usize);
        for rr in mi_row..r1 {
            for cc in mi_col..c1 {
                let cell = (rr * self.mi_cols + cc) as usize;
                cells.push(DriverGridCell {
                    mi_size: self.mi_sizes[cell],
                    is_inter: self.is_inters[cell],
                    ref_frames: [self.ref_frames[cell * 2], self.ref_frames[cell * 2 + 1]],
                    mvs: [
                        self.mvs[cell * 4],
                        self.mvs[cell * 4 + 1],
                        self.mvs[cell * 4 + 2],
                        self.mvs[cell * 4 + 3],
                    ],
                    interp_filters: [
                        self.interp_filters[cell * 2],
                        self.interp_filters[cell * 2 + 1],
                    ],
                    motion_mode: self.motion_modes[cell],
                    y_mode: self.y_modes[cell],
                    compound_type: self.compound_types[cell],
                    wedge_index: self.wedge_indices[cell],
                    wedge_sign: self.wedge_signs[cell],
                    mask_type: self.mask_types[cell],
                    interintra_mode: self.interintra_modes[cell],
                    wedge_interintra: self.wedge_interintras[cell],
                    interintra_wedge_index: self.interintra_wedge_indices[cell],
                    local_warp: {
                        let mut w = [0i32; 6];
                        w.copy_from_slice(&self.local_warp[cell * 6..cell * 6 + 6]);
                        w
                    },
                    local_warp_valid: self.local_warp_valid[cell],
                });
            }
        }
        DriverGridSnapshot {
            mi_row,
            mi_col,
            r1,
            c1,
            cells,
        }
    }

    /// Restore a [`Self::snapshot_grids_rect`] snapshot.
    fn restore_grids_rect(&mut self, snap: &DriverGridSnapshot) {
        let mut it = snap.cells.iter();
        for rr in snap.mi_row..snap.r1 {
            for cc in snap.mi_col..snap.c1 {
                let cell = (rr * self.mi_cols + cc) as usize;
                let s = it.next().expect("snapshot covers the rect");
                self.mi_sizes[cell] = s.mi_size;
                self.is_inters[cell] = s.is_inter;
                self.ref_frames[cell * 2] = s.ref_frames[0];
                self.ref_frames[cell * 2 + 1] = s.ref_frames[1];
                self.mvs[cell * 4..cell * 4 + 4].copy_from_slice(&s.mvs);
                self.interp_filters[cell * 2] = s.interp_filters[0];
                self.interp_filters[cell * 2 + 1] = s.interp_filters[1];
                self.motion_modes[cell] = s.motion_mode;
                self.y_modes[cell] = s.y_mode;
                self.compound_types[cell] = s.compound_type;
                self.wedge_indices[cell] = s.wedge_index;
                self.wedge_signs[cell] = s.wedge_sign;
                self.mask_types[cell] = s.mask_type;
                self.interintra_modes[cell] = s.interintra_mode;
                self.wedge_interintras[cell] = s.wedge_interintra;
                self.interintra_wedge_indices[cell] = s.interintra_wedge_index;
                self.local_warp[cell * 6..cell * 6 + 6].copy_from_slice(&s.local_warp);
                self.local_warp_valid[cell] = s.local_warp_valid;
            }
        }
    }

    /// r419 โ€” the ยง5.11.27 WARPED_CAUSAL fit for one leaf: the
    /// ยง7.10.4 `find_warp_samples` scan against the driver mirror
    /// (the identical scan the write pass validates `NumSamples`
    /// with and the decode walker re-runs at its in-walk
    /// `compute_prediction( )` position), the ยง7.11.3.8
    /// `warp_estimation` least squares, and the ยง7.11.3.6
    /// `setup_shear` validity check. `Some(params)` iff the scan
    /// found samples AND the fit is shear-valid โ€” the only
    /// configuration where committing `WARPED_CAUSAL` changes the
    /// ยง7.11.3.1 step-7 prediction.
    fn warp_fit(
        &self,
        mi_row: u32,
        mi_col: u32,
        b_size: usize,
        ref0: i8,
        mv: [[i32; 2]; 2],
    ) -> Option<[i32; 6]> {
        let mut cands: Vec<crate::inter_pred::WarpSampleCand> = Vec::new();
        let ns = self.mirror.find_warp_samples_list(
            mi_row,
            mi_col,
            b_size,
            i32::from(ref0),
            mv,
            &mut cands,
        );
        if ns == 0 {
            return None;
        }
        let lw = crate::inter_pred::warp_estimation(
            &cands,
            mi_row as i32,
            mi_col as i32,
            NUM_4X4_BLOCKS_WIDE[b_size] as i32,
            NUM_4X4_BLOCKS_HIGH[b_size] as i32,
            [mv[0][0] as i16, mv[0][1] as i16],
        );
        if !lw.local_valid {
            return None;
        }
        match crate::inter_pred::setup_shear(lw.local_warp_params) {
            Some(s) if s.warp_valid => Some(lw.local_warp_params),
            _ => None,
        }
    }

    /// r421 โ€” `NumSamples` from the same ยง7.10.4 `find_warp_samples`
    /// scan [`Self::warp_fit`] runs, without the fit: the ยง5.11.27
    /// arm-A/arm-B dispatch operand (`num_samples == 0` selects the
    /// `use_obmc` arm even when warp is enabled), needed to price the
    /// motion-mode symbol through the writer's own arm derivation.
    fn warp_num_samples(
        &self,
        mi_row: u32,
        mi_col: u32,
        b_size: usize,
        ref0: i8,
        mv: [[i32; 2]; 2],
    ) -> u32 {
        let mut cands: Vec<crate::inter_pred::WarpSampleCand> = Vec::new();
        self.mirror
            .find_warp_samples_list(mi_row, mi_col, b_size, i32::from(ref0), mv, &mut cands)
    }

    /// Stamp a COMMITTED leaf into the driver mirror with the same
    /// `stamp_encoder_block_syntax` values the write pass stamps for
    /// this leaf (`cdef: None` per the
    /// [`PartitionWalker::snapshot_encoder_stamp_rect`] contract โ€”
    /// the ยง5.11.56 anchor can land outside the trial rect, and no
    /// ยง7.10.2 / ยง8.3.2 read the search performs consults it).
    fn stamp_leaf(
        &mut self,
        block: &SyntaxBlock,
        mi_row: u32,
        mi_col: u32,
        b_size: usize,
        lossless: bool,
    ) {
        use crate::cdf::EncoderBlockSyntaxStamp;
        let tx_pre = if lossless {
            TX_4X4 as u8
        } else {
            MAX_TX_SIZE_RECT[b_size] as u8
        };
        let stamp = match block.inter.as_ref() {
            Some(ib) => EncoderBlockSyntaxStamp {
                mi_row,
                mi_col,
                sub_size: b_size,
                skip: block.skip,
                skip_mode: ib.skip_mode,
                segment_id: block.segment_id,
                is_inter: 1,
                y_mode: ib.y_mode,
                // r417 โ€” the ยง5.11.28 imperative override the decode
                // walker (and the write pass) stamp: `RefFrame[ 1 ] =
                // INTRA_FRAME` on the `interintra == 1` arm.
                ref_frame: if ib.interintra_mode.is_some() {
                    [
                        ib.ref_frame[0],
                        crate::uncompressed_header_tail::INTRA_FRAME as i8,
                    ]
                } else {
                    ib.ref_frame
                },
                mv: ib.mv[0],
                mv2: ib.mv[1],
                interp_filter: ib.interp_filter,
                // r419 โ€” the committed ยง5.11.27 ordinal (the write
                // pass stamps the identical value).
                motion_mode: ib.motion_mode,
                palette_size_y: 0,
                palette_colors_y: &[],
                palette_size_uv: 0,
                palette_colors_u: &[],
                palette_colors_v: &[],
                cdef: None,
                tx_size: tx_pre,
                // r415 โ€” the SAME ยง5.11.29 stamp values the write
                // pass commits for this leaf (search mirror and write
                // mirror must observe identical neighbour grids).
                // r416: only the MASKED ordinals set
                // `comp_group_idx = 1`; COMPOUND_DISTANCE stays on
                // the `comp_group_idx = 0` arm with `compound_idx = 0`.
                comp_group_idx: u8::from(
                    ib.ref_frame[1] > 0
                        && ib.skip_mode == 0
                        && matches!(
                            ib.compound_type,
                            crate::inter_pred::COMPOUND_WEDGE | crate::inter_pred::COMPOUND_DIFFWTD
                        ),
                ),
                compound_idx: u8::from(
                    !(ib.ref_frame[1] > 0
                        && ib.skip_mode == 0
                        && ib.compound_type == crate::inter_pred::COMPOUND_DISTANCE),
                ),
                compound_type: if ib.interintra_mode.is_some()
                    || (ib.ref_frame[1] > 0 && ib.skip_mode == 0)
                {
                    // r417 โ€” inter-intra leaves carry the ยง5.11.29
                    // bit-silent derivation in `ib.compound_type`
                    // (the write pass validates the exact value).
                    ib.compound_type
                } else {
                    crate::inter_pred::COMPOUND_AVERAGE
                },
                wedge_index: ib.wedge_index,
                wedge_sign: ib.wedge_sign,
                mask_type: ib.mask_type,
                // r417 โ€” ยง5.11.28 side-data stamps (decode-walker
                // grid-fill twins).
                interintra_mode: ib.interintra_mode.unwrap_or(0),
                wedge_interintra: u8::from(
                    ib.interintra_mode.is_some() && ib.wedge_interintra == 1,
                ),
                interintra_wedge_index: ib.interintra_wedge_index,
            },
            None => EncoderBlockSyntaxStamp {
                mi_row,
                mi_col,
                sub_size: b_size,
                skip: block.skip,
                skip_mode: 0,
                segment_id: block.segment_id,
                is_inter: 0,
                y_mode: block.y_mode,
                ref_frame: [0, -1],
                mv: [0, 0],
                mv2: [0, 0],
                interp_filter: [0, 0],
                motion_mode: MOTION_MODE_SIMPLE,
                palette_size_y: block.palette.size_y,
                palette_colors_y: &block.palette.colors_y,
                palette_size_uv: block.palette.size_uv,
                palette_colors_u: &block.palette.colors_u,
                palette_colors_v: &block.palette.colors_v,
                cdef: None,
                tx_size: tx_pre,
                // r415 ยง5.11.29 compound defaults (AVERAGE, pre-set
                // comp_group_idx/compound_idx, no side data).
                comp_group_idx: 0,
                compound_idx: 1,
                compound_type: crate::inter_pred::COMPOUND_AVERAGE,
                wedge_index: 0,
                wedge_sign: 0,
                mask_type: 0,
                interintra_mode: 0,
                wedge_interintra: 0,
                interintra_wedge_index: 0,
            },
        };
        self.mirror.stamp_encoder_block_syntax(&stamp);
    }

    /// r417 โ€” driver-grid stamps for a committed ยง5.11.22 INTRA leaf
    /// (the decode walker's intra grid-fill twins). `predict_leaf`
    /// stamps only inter trials, so an intra winner must overwrite
    /// the losing trial's stamps: the ยง5.11.33 `someUseIntra` scan
    /// reads `RefFrames[ .. ][ 0 ] == INTRA_FRAME` at the
    /// neighbouring 2ร—2-group cells through THESE grids when a later
    /// sub-8 inter leaf predicts its group chroma.
    fn stamp_intra_leaf_grids(&mut self, mi_row: u32, mi_col: u32, b_size: usize, y_mode: u8) {
        let bw4 = NUM_4X4_BLOCKS_WIDE[b_size] as u32;
        let bh4 = NUM_4X4_BLOCKS_HIGH[b_size] as u32;
        for dr in 0..bh4 {
            let rr = mi_row + dr;
            if rr >= self.mi_rows {
                break;
            }
            for dc in 0..bw4 {
                let cc = mi_col + dc;
                if cc >= self.mi_cols {
                    break;
                }
                let cell = (rr * self.mi_cols + cc) as usize;
                self.mi_sizes[cell] = b_size;
                self.is_inters[cell] = 0;
                // ยง5.11.22: `RefFrame[ 0 ] = INTRA_FRAME`,
                // `RefFrame[ 1 ] = NONE`.
                self.ref_frames[cell * 2] = 0;
                self.ref_frames[cell * 2 + 1] = -1;
                self.mvs[cell * 4] = 0;
                self.mvs[cell * 4 + 1] = 0;
                self.mvs[cell * 4 + 2] = 0;
                self.mvs[cell * 4 + 3] = 0;
                self.interp_filters[cell * 2] = EIGHTTAP;
                self.interp_filters[cell * 2 + 1] = EIGHTTAP;
                self.motion_modes[cell] = MOTION_MODE_SIMPLE;
                self.y_modes[cell] = y_mode;
                self.compound_types[cell] = crate::inter_pred::COMPOUND_AVERAGE;
                self.wedge_indices[cell] = 0;
                self.wedge_signs[cell] = 0;
                self.mask_types[cell] = 0;
                self.interintra_modes[cell] = 0;
                self.wedge_interintras[cell] = 0;
                self.interintra_wedge_indices[cell] = 0;
            }
        }
    }

    /// Stamp the leaf's ยง5.11.5 grid footprint (the same values the
    /// write mirror / decode walker stamp), then run the decoder's
    /// ยง5.11.33 leaf driver into the scratch planes.
    ///
    /// r417 โ€” `ii: Some(_)` selects the ยง5.11.28 inter-intra arm: the
    /// stamps mirror the decode walker's ยง5.11.28 imperative override
    /// (`RefFrame[ 1 ] = INTRA_FRAME`, the ยง5.11.29 bit-silent
    /// `compound_type` derivation, the inter-intra side-data grids),
    /// the ยง7.11.5-translated intra half is predicted into the
    /// scratch planes FIRST (the ยง5.11.33 order: `predict_intra`
    /// before `predict_inter`), and the leaf driver's ยง7.11.3.14
    /// blend consumes it in place. `ref_frame[ 1 ]` must be `-1`
    /// (the ยง5.11.28 gate requires a single-reference leaf).
    #[allow(clippy::too_many_arguments)]
    fn predict_leaf(
        &mut self,
        mi_row: u32,
        mi_col: u32,
        b_size: usize,
        ref_frame: [i8; 2],
        y_mode: u8,
        mv: [[i32; 2]; 2],
        filter: u8,
        comp: CompoundSel,
        ii: Option<InterIntraTrial<'_>>,
        motion: MotionSel,
    ) -> Result<(), Error> {
        if ii.is_some() && ref_frame[1] != -1 {
            return Err(Error::PartitionWalkOutOfRange);
        }
        // r419 โ€” ยง5.11.27: a non-SIMPLE motion mode exists only on a
        // single-reference non-inter-intra leaf.
        if motion != MotionSel::Simple && (ref_frame[1] != -1 || ii.is_some()) {
            return Err(Error::PartitionWalkOutOfRange);
        }
        let bw4 = NUM_4X4_BLOCKS_WIDE[b_size] as u32;
        let bh4 = NUM_4X4_BLOCKS_HIGH[b_size] as u32;
        // ยง5.11.28 imperative overrides the decode walker stamps on
        // the `interintra == 1` arm: `RefFrame[ 1 ] = INTRA_FRAME`
        // plus the ยง5.11.29 bit-silent `compound_type` derivation
        // (`wedge_interintra ? COMPOUND_WEDGE : COMPOUND_INTRA`).
        let stamp_rf1: i8 = if ii.is_some() {
            crate::uncompressed_header_tail::INTRA_FRAME as i8
        } else {
            ref_frame[1]
        };
        let stamp_ctype: u8 = match &ii {
            Some(t) if t.wedge.is_some() => crate::inter_pred::COMPOUND_WEDGE,
            Some(_) => crate::inter_pred::COMPOUND_INTRA,
            None => comp.ctype,
        };
        for dr in 0..bh4 {
            let rr = mi_row + dr;
            if rr >= self.mi_rows {
                break;
            }
            for dc in 0..bw4 {
                let cc = mi_col + dc;
                if cc >= self.mi_cols {
                    break;
                }
                let cell = (rr * self.mi_cols + cc) as usize;
                self.mi_sizes[cell] = b_size;
                self.is_inters[cell] = 1;
                self.ref_frames[cell * 2] = ref_frame[0];
                self.ref_frames[cell * 2 + 1] = stamp_rf1;
                self.mvs[cell * 4] = mv[0][0] as i16;
                self.mvs[cell * 4 + 1] = mv[0][1] as i16;
                self.mvs[cell * 4 + 2] = mv[1][0] as i16;
                self.mvs[cell * 4 + 3] = mv[1][1] as i16;
                self.interp_filters[cell * 2] = filter;
                self.interp_filters[cell * 2 + 1] = filter;
                // r419 โ€” the committed ยง5.11.27 ordinal over the
                // footprint (the decode walker's grid-fill twin).
                self.motion_modes[cell] = motion.ordinal();
                self.y_modes[cell] = y_mode;
                // r415 โ€” ยง5.11.29 side-data stamps (the decoder's leaf
                // driver dispatches WEDGE / DIFFWTD masks from these).
                self.compound_types[cell] = stamp_ctype;
                self.wedge_indices[cell] = comp.wedge_index;
                self.wedge_signs[cell] = comp.wedge_sign;
                self.mask_types[cell] = comp.mask_type;
                // r417 โ€” ยง5.11.28 inter-intra side-data stamps (the
                // decode-walker grid-fill twins; all-zero outside the
                // inter-intra arm).
                self.interintra_modes[cell] = ii.as_ref().map_or(0, |t| t.mode);
                self.wedge_interintras[cell] =
                    u8::from(ii.as_ref().is_some_and(|t| t.wedge.is_some()));
                self.interintra_wedge_indices[cell] =
                    ii.as_ref().and_then(|t| t.wedge).unwrap_or(0);
            }
        }

        // r419 โ€” ยง7.11.3.8 per-cell warp-fit stamps at the leaf
        // origin (the only cell the leaf driver's warp context
        // reads), mirroring the decode walker's in-walk
        // `compute_prediction( )` stamp.
        {
            let origin = (mi_row * self.mi_cols + mi_col) as usize;
            if let MotionSel::Warp(p) = motion {
                self.local_warp[origin * 6..origin * 6 + 6].copy_from_slice(&p);
                self.local_warp_valid[origin] = 1;
            } else {
                self.local_warp[origin * 6..origin * 6 + 6].fill(0);
                self.local_warp_valid[origin] = 0;
            }
        }

        // r417 โ€” ยง5.11.33 `IsInterIntra` arm, intra half FIRST: run
        // the ยง7.11.5-translated `predict_intra` into the scratch
        // planes over the whole per-plane block region (av1-spec
        // ยง5.11.33 line 5146: one call at `(baseX, baseY, log2W,
        // log2H)`), reading reconstructed neighbours from the
        // committed recon โ€” the decode walker's `CurrFrame[ plane ]`
        // twin. The ยง7.11.3.14 blend below reads it back as `pred1`.
        if let Some(t) = &ii {
            // ยง5.11.33 `interintra_mode โ†’ mode` translation
            // (av1-spec p.82 lines 5142-5145).
            let mode = match t.mode {
                crate::cdf::II_V_PRED => crate::cdf::V_PRED,
                crate::cdf::II_H_PRED => crate::cdf::H_PRED,
                crate::cdf::II_DC_PRED => crate::cdf::DC_PRED,
                _ => crate::cdf::SMOOTH_PRED,
            };
            // ยง5.11.5 availability (r431: tile-scoped through the
            // precomputed grids); the chroma pair equals the luma
            // pair on every ยง5.11.28-eligible block (`bw4 >= 2 &&
            // bh4 >= 2` skips the ยง5.11.5 sub-8 chroma fix-ups).
            let cell = (mi_row * self.mi_cols + mi_col) as usize;
            let avail_u = self.avail_us[cell] != 0;
            let avail_l = self.avail_ls[cell] != 0;
            for plane in 0..usize::from(self.num_planes) {
                let (sub_x, sub_y): (u8, u8) = if plane > 0 {
                    (self.subsampling_x, self.subsampling_y)
                } else {
                    (0, 0)
                };
                let plane_sz =
                    crate::cdf::get_plane_residual_size(b_size, plane as u8, sub_x, sub_y)
                        .ok_or(Error::PartitionWalkOutOfRange)?;
                let w = NUM_4X4_BLOCKS_WIDE[plane_sz] * 4;
                let h = NUM_4X4_BLOCKS_HIGH[plane_sz] * 4;
                let tx_sz = crate::cdf::find_tx_size(w, h).ok_or(Error::PartitionWalkOutOfRange)?;
                let base_x = ((mi_col >> sub_x) * 4) as usize;
                let base_y = ((mi_row >> sub_y) * 4) as usize;
                // ยง5.11.33 `BlockDecoded[ ]` above-right / below-left
                // reads against the encoder's own ยง5.11.3 mirror.
                // Provably inert for the four ยง6.10.27 II modes (DC /
                // V@0 / H@0 / SMOOTH never read the extended
                // neighbour segments), threaded for ยง7.11.2 fidelity.
                let (have_ar, have_bl) =
                    super::key_frame::tu_corner_avail(&t.neigh.bd, plane, base_x, base_y, w, h);
                let (buf, pw, ph) = t.neigh.plane(plane);
                let read = |yy: u32, xx: u32| -> u16 { buf[(yy as usize) * pw + (xx as usize)] };
                let out = &mut self.scratch[plane];
                // ยง7.11.2.4 step-4 pre-pass inputs: inert on the II
                // mode set (no directional D-mode reachable โ€” V/H ride
                // the exact-90ยฐ/180ยฐ copies at `angle_delta == 0`), so
                // the neutral pair matches the decode walker's output
                // sample-for-sample regardless of the sequence's
                // `enable_intra_edge_filter`.
                PartitionWalker::predict_intra_into_u16_plane(
                    &read,
                    out,
                    pw,
                    (pw - 1) as u32,
                    (ph - 1) as u32,
                    base_x as u32,
                    base_y as u32,
                    tx_sz,
                    mode,
                    /* angle_delta = */ 0,
                    self.bit_depth,
                    avail_u,
                    avail_l,
                    have_ar,
                    have_bl,
                    /* enable_intra_edge_filter = */ false,
                    /* filter_type = */ 0,
                    /* filter_intra_mode = */ None,
                );
            }
        }

        // Field-split borrows: the grid views borrow the mode-info
        // vectors immutably while the plane contexts borrow the
        // scratch planes mutably.
        let (luma_w, luma_h) = (self.luma_w, self.luma_h);
        let (mi_rows, mi_cols) = (self.mi_rows, self.mi_cols);
        let slot_to_plane = self.slot_to_plane;
        let ref_frame_idx = self.ref_frame_idx;
        // r427 โ€” format scalars (copied out before the field split).
        let bit_depth = self.bit_depth;
        let (ssx, ssy) = (self.subsampling_x, self.subsampling_y);
        let num_planes = usize::from(self.num_planes);
        let PSearchCtx {
            ref_planes,
            compound_types,
            wedge_indices,
            wedge_signs,
            mask_types,
            interintra_modes,
            wedge_interintras,
            interintra_wedge_indices,
            mi_sizes,
            is_inters,
            ref_frames,
            mvs,
            interp_filters,
            motion_modes,
            y_modes,
            avail_us,
            avail_ls,
            local_warp,
            local_warp_valid,
            scratch,
            gm_types,
            gm_flat,
            ref_hints,
            hint_bits,
            current_hint,
            no_scaled,
            ref_dims,
            ..
        } = &mut *self;

        // ยง7.20 `FrameStore` views โ€” r415: each slot resolves through
        // `slot_to_plane` to its distinct reference reconstruction
        // (slots outside the mapped roles point at plane 0, never
        // resolved through `ref_frame_idx`). Dimensions are LUMA
        // extents per the r405 contract; strides are plane samples.
        // r456 โ€” the store carries the REFERENCE extents (ยง7.11.3.3
        // `RefUpscaledWidth` / `RefFrameHeight`); strides are the
        // reference's own plane widths. Off the superres inter arm
        // they coincide with the frame's.
        let store_y = make_store(ref_planes, ref_dims, &slot_to_plane, 0, 0);
        let store_u = make_store(ref_planes, ref_dims, &slot_to_plane, 1, ssx);
        let store_v = make_store(ref_planes, ref_dims, &slot_to_plane, 2, ssx);

        let grid = InterModeInfoGrid {
            mi_sizes,
            is_inters,
            ref_frames,
            mvs,
            interp_filters,
            compound_types,
            wedge_indices,
            wedge_signs,
            mask_types,
            interintra_modes,
            wedge_interintras,
            interintra_wedge_indices,
            order_hint_bits: *hint_bits,
            current_order_hint: *current_hint,
            order_hints_by_ref: ref_hints,
            mi_rows,
            mi_cols,
            bit_depth,
            // ยง7.11.3.1 step-7 warp context โ€” identity global motion;
            // r419: a `WARPED_CAUSAL` trial carries its ยง7.11.3.8 fit
            // in the per-cell slices stamped above (SIMPLE / OBMC
            // leaves keep `useWarp = 0`).
            warp: Some(crate::GridWarpContext {
                motion_modes,
                local_warp_params: local_warp,
                local_warp_valid,
                y_modes,
                gm_types,
                gm_params: gm_flat,
                force_integer_mv: false,
                is_scaled: no_scaled,
            }),
            // r419 โ€” ยง7.11.3.9 OBMC context: an `OBMC` trial routes
            // through the decoder's own neighbour-scan dispatch over
            // the committed grids (the decode frame walk threads the
            // identical trio).
            obmc: Some(crate::GridObmcContext {
                motion_modes,
                avail_u: avail_us,
                avail_l: avail_ls,
            }),
        };
        let [s0, s1, s2] = scratch;
        let mut planes = [
            PlaneReconContext {
                plane: 0,
                subsampling_x: 0,
                subsampling_y: 0,
                frame_store: &store_y,
                frame_width: luma_w,
                frame_height: luma_h,
                curr: s0,
                curr_stride: luma_w as usize,
            },
            PlaneReconContext {
                plane: 1,
                subsampling_x: ssx,
                subsampling_y: ssy,
                frame_store: &store_u,
                frame_width: luma_w,
                frame_height: luma_h,
                curr: s1,
                curr_stride: (luma_w as usize) >> ssx,
            },
            PlaneReconContext {
                plane: 2,
                subsampling_x: ssx,
                subsampling_y: ssy,
                frame_store: &store_v,
                frame_width: luma_w,
                frame_height: luma_h,
                curr: s2,
                curr_stride: (luma_w as usize) >> ssx,
            },
        ];
        reconstruct_inter_leaf_at(
            &grid,
            &ref_frame_idx,
            &mut planes[..num_planes],
            mi_row as usize,
            mi_col as usize,
        )
    }
}

/// One plane's ยง7.20 `FrameStore` view (r415 general form): slot `s`
/// resolves to `ref_planes[ slot_to_plane[ s ] ][ plane ]` (extents in
/// LUMA samples per the r405 contract, stride in this plane's own
/// samples). Slots outside the frame's mapped roles are never resolved
/// through `ref_frame_idx`, so their content is immaterial.
fn make_store<'a>(
    ref_planes: &'a [[Vec<u16>; 3]],
    ref_dims: &[(u32, u32)],
    slot_to_plane: &[usize; 8],
    plane: usize,
    ssx: u8,
) -> [RefFrameStoreEntry<'a>; 8] {
    core::array::from_fn(|slot| {
        let idx = slot_to_plane[slot];
        let (rw, rh) = ref_dims[idx];
        RefFrameStoreEntry {
            plane: &ref_planes[idx][plane],
            // r456 โ€” the reference's OWN plane stride and extents
            // (ยง7.11.3.3 `RefUpscaledWidth` / `RefFrameHeight`).
            stride: ((rw + u32::from(ssx)) >> ssx) as usize,
            upscaled_width: rw,
            width: rw,
            height: rh,
        }
    })
}

// ---------------------------------------------------------------------
// Motion search + inter leaf encoder.
// ---------------------------------------------------------------------

/// Integer-pel luma motion search: coarse step-4 grid over
/// `ยฑSEARCH_RANGE` then a full `ยฑ3` refinement, SSD against the
/// edge-clamped reference (exactly the ยง7.11.3.4 phase-0 sample
/// fetch), with a small magnitude bias so near-zero vectors win ties.
/// Returns the best vector in 1/8-luma units (a multiple of 8).
/// `bw ร— bh` are the (possibly rectangular) luma block dimensions.
#[allow(clippy::too_many_arguments)]
fn motion_search_luma(
    input: &YuvFrame,
    ref_y: &[u16],
    width: usize,
    height: usize,
    row0: usize,
    col0: usize,
    bw: usize,
    bh: usize,
) -> [i32; 2] {
    let n = bw.max(bh) as u64;
    let cost_at = |dy: i32, dx: i32| -> u64 {
        let mut ssd = 0u64;
        for i in 0..bh {
            let sy = ((row0 + i) as i32 + dy).clamp(0, height as i32 - 1) as usize;
            for j in 0..bw {
                let sx = ((col0 + j) as i32 + dx).clamp(0, width as i32 - 1) as usize;
                let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                    - i64::from(ref_y[sy * width + sx]);
                ssd += (d * d) as u64;
            }
        }
        ssd + (dy.unsigned_abs() as u64 + dx.unsigned_abs() as u64) * n
    };
    let mut best = (cost_at(0, 0), [0i32, 0]);
    let mut dy = -SEARCH_RANGE;
    while dy <= SEARCH_RANGE {
        let mut dx = -SEARCH_RANGE;
        while dx <= SEARCH_RANGE {
            if !(dy == 0 && dx == 0) {
                let c = cost_at(dy, dx);
                if c < best.0 {
                    best = (c, [dy, dx]);
                }
            }
            dx += 4;
        }
        dy += 4;
    }
    let center = best.1;
    for dy in center[0] - 3..=center[0] + 3 {
        for dx in center[1] - 3..=center[1] + 3 {
            if dy == center[0] && dx == center[1] {
                continue;
            }
            let c = cost_at(dy, dx);
            if c < best.0 {
                best = (c, [dy, dx]);
            }
        }
    }
    [best.1[0] * 8, best.1[1] * 8]
}

/// Sub-pel MV refinement through the decoder's ยง7.11.3 leaf driver:
/// a half-pel pass (ยฑ4 in 1/8 units) then a quarter-pel pass (ยฑ2)
/// around the running best โ€” plus, on the r428
/// `allow_high_precision_mv` arm, an eighth-pel pass (ยฑ1) โ€” scoring
/// each candidate by luma SSD over the kernel's actual prediction
/// plus a small magnitude bias.
#[allow(clippy::too_many_arguments)]
fn refine_mv_subpel(
    input: &YuvFrame,
    ictx: &mut PSearchCtx,
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    ref_frame: i8,
    row0: usize,
    col0: usize,
    bw: usize,
    bh: usize,
    width: usize,
    mv_int: [i32; 2],
) -> Result<[i32; 2], Error> {
    let score = |ictx: &mut PSearchCtx, mv: [i32; 2]| -> Result<u64, Error> {
        ictx.predict_leaf(
            mi_r,
            mi_c,
            b_size,
            [ref_frame, -1],
            MODE_NEWMV,
            [mv, [0, 0]],
            EIGHTTAP,
            CompoundSel::AVERAGE,
            None,
            MotionSel::Simple,
        )?;
        let mut ssd = 0u64;
        for i in 0..bh {
            for j in 0..bw {
                let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                    - i64::from(ictx.scratch[0][(row0 + i) * width + col0 + j]);
                ssd += (d * d) as u64;
            }
        }
        Ok(ssd + ((mv[0].unsigned_abs() + mv[1].unsigned_abs()) as u64) * (bw.max(bh) as u64) / 8)
    };
    let mut best = (score(ictx, mv_int)?, mv_int);
    // ยง5.9.2: quarter-pel components are multiples of 2 in 1/8-luma
    // units; the eighth-pel pass is reachable only under
    // `allow_high_precision_mv = 1`.
    let steps: &[i32] = if ictx.ip.allow_high_precision_mv {
        &[4, 2, 1]
    } else {
        &[4, 2]
    };
    for &step in steps {
        let center = best.1;
        for dy in [-step, 0, step] {
            for dx in [-step, 0, step] {
                if dy == 0 && dx == 0 {
                    continue;
                }
                let cand = [center[0] + dy, center[1] + dx];
                let c = score(ictx, cand)?;
                if c < best.0 {
                    best = (c, cand);
                }
            }
        }
    }
    Ok(best.1)
}

/// Encode one in-frame INTER leaf at `b_size` (`BLOCK_8X8` โ€ฆ
/// `BLOCK_64X64`, plus the r412 rectangular HORZ/VERT halves โ€”
/// `BLOCK_16X8` and larger): motion search, ยง7.11.3 prediction
/// through the decoder's leaf driver, residual per TU (one
/// `Max_Tx_Size_Rect` luma TU on the lossy arm / the `TX_4X4` grid on
/// the lossless arm; chroma at the ยง5.11.38 size), `skip = 1` when
/// every TU quantises to zero.
#[allow(clippy::too_many_arguments)]
fn encode_inter_leaf(
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &mut PSearchCtx,
    // r421 โ€” `Some((twin, params))` prices the leaf-level elections
    // (tx-depth ladder, ยง5.11.10 skip-mode trial) with exact twin
    // bits; `None` keeps the pre-r421 heuristics.
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
) -> Result<SyntaxBlock, Error> {
    let leaf = encode_inter_leaf_base(mi_r, mi_c, b_size, input, recon, ictx, pricing)?;
    // r426 โ€” ladder item 8: the ยง5.9.14 inter-override feature-segment
    // trials (SEG_LVL_SKIP / SEG_LVL_GLOBALMV / SEG_LVL_REF_FRAME)
    // against the fully-searched winner, on >= 8x8 leaves.
    let mut leaf = if ictx.extras.is_some()
        && crate::cdf::block_width(b_size) >= 8
        && crate::cdf::block_height(b_size) >= 8
    {
        seg_extras_trials(mi_r, mi_c, b_size, input, recon, ictx, pricing, leaf)?
    } else {
        leaf
    };
    stamp_delta_q(&mut leaf, b_size, ictx, pricing);
    Ok(leaf)
}

/// r428 โ€” stamp the current superblock's ยง5.11.13 delta-q plan value
/// into a committed leaf. Only the block the ยง5.11.2 lifecycle still
/// has PENDING codes the value (the twin fork the leaf is built
/// against carries the authoritative bit โ€” the same fork the block
/// is committed into, so build-time state == write-time state), and
/// a full-superblock skip leaf takes the ยง5.11.13 short-circuit arm
/// (zero bits โ€” the writer validates the field is 0 there).
fn stamp_delta_q(
    leaf: &mut SyntaxBlock,
    b_size: usize,
    ictx: &PSearchCtx,
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
) {
    if ictx.delta_q_units == 0 {
        return;
    }
    let pending = pricing.is_some_and(|(twin, _)| twin.deltas_pending());
    leaf.reduced_delta_q_index = if pending && !(b_size == BLOCK_64X64 && leaf.skip == 1) {
        ictx.delta_q_units
    } else {
        0
    };
}

/// The pre-r426 [`encode_inter_leaf`] body: the fully-searched leaf
/// plus the ยง5.11.10 skip-mode trial.
#[allow(clippy::too_many_arguments)]
fn encode_inter_leaf_base(
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &mut PSearchCtx,
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
) -> Result<SyntaxBlock, Error> {
    let leaf = encode_inter_leaf_modes(mi_r, mi_c, b_size, input, recon, ictx, pricing)?;

    // r413 โ€” ยง5.11.10 skip-mode trial: on a skip-mode frame, every
    // >= 8ร—8 leaf additionally trials the pure-derivation skip-mode
    // block (COMPOUND_AVERAGE over SkipModeFrame[] = { LAST, GOLDEN }
    // at the compound-stack NEARESTMV pair, EIGHTTAP, `skip = 1`, no
    // residual โ€” ONE ยง5.11.10 S() total) against the fully-searched
    // leaf. The comparison is exact on both sides: the normal leaf's
    // residual-coded reconstruction vs the skip-mode leaf's bare
    // prediction, each scored `D + ฮปยทR` over all three planes.
    if !ictx.ip.skip_mode_present
        || crate::cdf::block_width(b_size) < 8
        || crate::cdf::block_height(b_size) < 8
    {
        return Ok(leaf);
    }
    let sm_ref: [i8; 2] = ictx.ip.skip_mode_frame;
    let stack = ictx.find_stack(mi_r, mi_c, b_size, sm_ref)?;
    let sm_mv = [stack.ref_stack_mv[0][0], stack.ref_stack_mv[0][1]];
    if sm_mv
        .iter()
        .any(|m| m[0].unsigned_abs() >= (1 << 14) || m[1].unsigned_abs() >= (1 << 14))
    {
        return Ok(leaf);
    }
    let bw4 = NUM_4X4_BLOCKS_WIDE[b_size];
    let bh4 = NUM_4X4_BLOCKS_HIGH[b_size];
    let lambda = lambda_for(&recon.qp);
    // r421 โ€” twin-priced or heuristic, one scale per call (heuristic
    // rates scaled by 256 so both run the same comparison with
    // decisions identical to the pre-r421 integer scores).
    let rate_of = |blk: &SyntaxBlock| -> Result<u64, Error> {
        match pricing {
            Some((twin, params)) => twin.price_block(blk, mi_r, mi_c, b_size, params),
            None => Ok(p_leaf_rate(blk) * 256),
        }
    };
    let d_normal = region_distortion_wh(recon, input, mi_r, mi_c, bw4, bh4);
    let score_normal = score256(d_normal, lambda, rate_of(&leaf)?);
    let after_normal = save_region_wh(recon, mi_r, mi_c, bw4, bh4);

    // Predict the skip-mode leaf (re-stamps the grid footprint) and
    // stitch the bare prediction into the recon.
    ictx.predict_leaf(
        mi_r,
        mi_c,
        b_size,
        sm_ref,
        MODE_NEAREST_NEARESTMV,
        sm_mv,
        EIGHTTAP,
        CompoundSel::AVERAGE,
        None,
        MotionSel::Simple,
    )?;
    let (bw, bh) = (bw4 * 4, bh4 * 4);
    let (row0, col0) = ((mi_r as usize) * 4, (mi_c as usize) * 4);
    // r427 โ€” subsampling-derived chroma stitch footprint (empty on
    // the monochrome arm).
    let (crow0, ccol0) = recon.chroma_origin(mi_r, mi_c);
    let (cbw, cbh) = if recon.num_planes > 1 {
        (bw >> recon.subsampling_x, bh >> recon.subsampling_y)
    } else {
        (0, 0)
    };
    let width = recon.width;
    let cw = recon.chroma_w;
    for i in 0..bh {
        for j in 0..bw {
            recon.y[(row0 + i) * width + (col0 + j)] =
                ictx.scratch[0][(row0 + i) * width + (col0 + j)];
        }
    }
    for i in 0..cbh {
        for j in 0..cbw {
            recon.u[(crow0 + i) * cw + (ccol0 + j)] =
                ictx.scratch[1][(crow0 + i) * cw + (ccol0 + j)];
            recon.v[(crow0 + i) * cw + (ccol0 + j)] =
                ictx.scratch[2][(crow0 + i) * cw + (ccol0 + j)];
        }
    }
    tu_bd_stamp(&mut recon.bd, 0, col0, row0, bw, bh);
    if recon.num_planes > 1 {
        tu_bd_stamp(&mut recon.bd, 1, ccol0, crow0, cbw, cbh);
        tu_bd_stamp(&mut recon.bd, 2, ccol0, crow0, cbw, cbh);
    }

    let mut sm_leaf = SyntaxBlock::skip_leaf(0, None);
    // ยง5.11.19/ยง5.11.20: skip leaves inherit the segment pred cascade
    // (r426: except under SegIdPreSkip, where the id codes pre-skip โ€”
    // skip-mode blocks then commit segment 0, whose feature slots are
    // empty by the entry validation, keeping ยง5.11.10 codable).
    sm_leaf.segment_id = if ictx.seg_id_pre_skip {
        0
    } else {
        ictx.segment_pred(mi_r, mi_c)
    };
    sm_leaf.inter = Some(SyntaxInterBlock {
        ref_frame: sm_ref,
        y_mode: MODE_NEAREST_NEARESTMV,
        mv: sm_mv,
        ref_mv_idx: 0,
        interp_filter: [EIGHTTAP; 2],
        skip_mode: 1,
        compound_type: crate::inter_pred::COMPOUND_AVERAGE,
        wedge_index: 0,
        wedge_sign: 0,
        mask_type: 0,
        interintra_mode: None,
        wedge_interintra: 0,
        interintra_wedge_index: 0,
        // ยง5.11.27 line 1: skip-mode forces SIMPLE with no bits.
        motion_mode: MOTION_MODE_SIMPLE,
    });
    let d_sm = region_distortion_wh(recon, input, mi_r, mi_c, bw4, bh4);
    let score_sm = score256(d_sm, lambda, rate_of(&sm_leaf)?);
    // On a lossless-segment leaf a skip-mode block (which can never
    // code a residual) is only admissible when its bare prediction is
    // already exact โ€” the q = 0 contract is reconstruction == input.
    // r426: the skip-mode leaf's segment is the ยง5.11.20 `pred`
    // cascade value, so ITS `LosslessArray[]` slot gates the check
    // (on CodedLossless frames every slot is lossless โ€” the pre-r426
    // frame-wide guard falls out as the uniform case); a leaf
    // overlapping the exactness-demand mask takes the same exactness
    // gate regardless of the pred segment.
    let must_be_exact =
        ictx.seg_lossless(sm_leaf.segment_id) || ictx.demands_exact(mi_r, mi_c, b_size);
    if score_sm < score_normal && (!must_be_exact || d_sm == 0) {
        return Ok(sm_leaf);
    }
    // Skip-mode loses: restore the residual-coded reconstruction and
    // re-stamp the winner's grid footprint (predict_leaf writes only
    // the scratch planes, never the recon).
    restore_region(recon, mi_r, mi_c, &after_normal);
    if let Some(ib) = leaf.inter.as_ref() {
        // r417 โ€” an inter-intra winner re-predicts through the same
        // arm (its committed compound_type is the ยง5.11.29 bit-silent
        // derivation, not a ยง5.11.29 side-data selection).
        let ii = ib.interintra_mode.map(|m| InterIntraTrial {
            mode: m,
            wedge: (ib.wedge_interintra == 1).then_some(ib.interintra_wedge_index),
            neigh: &*recon,
        });
        let sel = if ib.interintra_mode.is_some() {
            CompoundSel::AVERAGE
        } else {
            CompoundSel {
                ctype: ib.compound_type,
                wedge_index: ib.wedge_index,
                wedge_sign: ib.wedge_sign,
                mask_type: ib.mask_type,
            }
        };
        // r419 โ€” a WARPED_CAUSAL winner re-predicts through the same
        // arm: the ยง7.11.3.8 fit is a pure function of the mirror
        // state (unchanged since the trial โ€” `stamp_leaf` runs at the
        // caller), so the recomputation is bit-identical.
        let motion = match ib.motion_mode {
            MOTION_MODE_OBMC => MotionSel::Obmc,
            MOTION_MODE_WARPED_CAUSAL => MotionSel::Warp(
                ictx.warp_fit(mi_r, mi_c, b_size, ib.ref_frame[0], ib.mv)
                    .ok_or(Error::PartitionWalkOutOfRange)?,
            ),
            _ => MotionSel::Simple,
        };
        ictx.predict_leaf(
            mi_r,
            mi_c,
            b_size,
            ib.ref_frame,
            ib.y_mode,
            ib.mv,
            ib.interp_filter[0],
            sel,
            ii,
            motion,
        )?;
    }
    Ok(leaf)
}

/// r426 โ€” re-run the committed leaf's prediction arm so the driver
/// grids (and the prediction scratch) hold the WINNER's stamps โ€” the
/// same re-predict discipline as the skip-mode loser path.
fn repredict_leaf_arm(
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    recon: &ReconState,
    ictx: &mut PSearchCtx,
    leaf: &SyntaxBlock,
) -> Result<(), Error> {
    let Some(ib) = leaf.inter.as_ref() else {
        return Ok(());
    };
    let ii = ib.interintra_mode.map(|m| InterIntraTrial {
        mode: m,
        wedge: (ib.wedge_interintra == 1).then_some(ib.interintra_wedge_index),
        neigh: recon,
    });
    let sel = if ib.interintra_mode.is_some() {
        CompoundSel::AVERAGE
    } else {
        CompoundSel {
            ctype: ib.compound_type,
            wedge_index: ib.wedge_index,
            wedge_sign: ib.wedge_sign,
            mask_type: ib.mask_type,
        }
    };
    let motion = match ib.motion_mode {
        MOTION_MODE_OBMC => MotionSel::Obmc,
        MOTION_MODE_WARPED_CAUSAL => MotionSel::Warp(
            ictx.warp_fit(mi_r, mi_c, b_size, ib.ref_frame[0], ib.mv)
                .ok_or(Error::PartitionWalkOutOfRange)?,
        ),
        _ => MotionSel::Simple,
    };
    ictx.predict_leaf(
        mi_r,
        mi_c,
        b_size,
        ib.ref_frame,
        ib.y_mode,
        ib.mv,
        ib.interp_filter[0],
        sel,
        ii,
        motion,
    )
}

/// r426 โ€” ladder item 8: the ยง5.9.14 inter-override feature-segment
/// trials against the fully-searched winner, in three arms:
///
/// * **SEG_LVL_REF_FRAME** re-labelling: a single-reference winner
///   whose `RefFrame[ 0 ]` equals the feature data moves onto the
///   feature segment โ€” identical pixels, the ยง5.11.25 reference bits
///   and the ยง5.11.20 `is_inter` S() fall bit-silent (elected by
///   exact twin bits; requires the identical ยง7.12.2 quantiser).
/// * **SEG_LVL_SKIP**: a pure-derivation block (skip = 1 with NO
///   ยง5.11.11 bit, mode GLOBALMV, `RefFrame = [ LAST, NONE ]`, no
///   residual) โ€” the ยง5.9.14 static-region form; scored as bare
///   prediction against the winner like the ยง5.11.10 skip-mode
///   trial.
/// * **SEG_LVL_GLOBALMV**: mode/ref fall bit-silent, the residual
///   still codes at the segment's quantiser through the normal
///   ยง5.11.34 chain.
///
/// All trials run on `>= 8x8` leaves only and finish by re-running
/// the winner's prediction arm (grid-invariant discipline).
#[allow(clippy::too_many_arguments)]
fn seg_extras_trials(
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &mut PSearchCtx,
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
    mut best: SyntaxBlock,
) -> Result<SyntaxBlock, Error> {
    let x = ictx.extras.expect("caller gated on extras");
    let bw4 = NUM_4X4_BLOCKS_WIDE[b_size];
    let bh4 = NUM_4X4_BLOCKS_HIGH[b_size];
    let lambda = lambda_for(&recon.qp);
    let rate_of = |blk: &SyntaxBlock| -> Result<u64, Error> {
        match pricing {
            Some((twin, params)) => twin.price_block(blk, mi_r, mi_c, b_size, params),
            None => Ok(p_leaf_rate(blk) * 256),
        }
    };
    let d_now = region_distortion_wh(recon, input, mi_r, mi_c, bw4, bh4);
    let mut score_best = score256(d_now, lambda, rate_of(&best)?);

    // Arm 1 โ€” SEG_LVL_REF_FRAME re-labelling (no pixel change).
    for (s, rf) in x.ref_frame.iter().enumerate() {
        let Some(rf) = rf else { continue };
        if x.skip[s] || x.globalmv[s] {
            continue;
        }
        let Some(ib) = best.inter.as_ref() else {
            break;
        };
        if ib.skip_mode != 0
            || ib.ref_frame[0] != *rf
            || ib.ref_frame[1] > 0
            || best.segment_id as usize == s
        {
            continue;
        }
        // The residual was quantised at the winner's segment โ€” the
        // re-label is only valid on an identical ยง7.12.2 qindex.
        if ictx.seg_qp(&recon.qp, s as u8).base_q_idx
            != ictx.seg_qp(&recon.qp, best.segment_id).base_q_idx
        {
            continue;
        }
        let mut alt = best.clone();
        alt.segment_id = s as u8;
        let sc = score256(d_now, lambda, rate_of(&alt)?);
        if sc < score_best {
            score_best = sc;
            best = alt;
        }
    }

    // Arms 2/3 โ€” SEG_LVL_SKIP / SEG_LVL_GLOBALMV prediction trials.
    let mut after_best = save_region_wh(recon, mi_r, mi_c, bw4, bh4);
    for s in 0..crate::uncompressed_header_tail::MAX_SEGMENTS {
        let (is_skip_seg, is_gmv_seg) = (x.skip[s], x.globalmv[s]);
        if !is_skip_seg && !is_gmv_seg {
            continue;
        }
        // ยง5.11.25 arm 3: RefFrame = [ LAST_FRAME, NONE ]; ยง5.11.23
        // arm 2: YMode = GLOBALMV; Mv = GlobalMvs[ 0 ] (ยง7.10.2.1).
        let stack = ictx.find_stack(mi_r, mi_c, b_size, [1, -1])?;
        let gmv = [stack.global_mvs[0], [0, 0]];
        if gmv[0][0].unsigned_abs() >= (1 << 14) || gmv[0][1].unsigned_abs() >= (1 << 14) {
            continue;
        }
        ictx.predict_leaf(
            mi_r,
            mi_c,
            b_size,
            [1, -1],
            MODE_GLOBALMV,
            gmv,
            EIGHTTAP,
            CompoundSel::AVERAGE,
            None,
            MotionSel::Simple,
        )?;
        let trial: SyntaxBlock = if is_skip_seg {
            // Bare-prediction block (skip = 1, no residual) โ€” stitch
            // the scratch prediction into the recon planes.
            let (bw, bh) = (bw4 * 4, bh4 * 4);
            let (row0, col0) = ((mi_r as usize) * 4, (mi_c as usize) * 4);
            // r427 โ€” subsampling-derived chroma stitch footprint.
            let (crow0, ccol0) = recon.chroma_origin(mi_r, mi_c);
            let (cbw, cbh) = if recon.num_planes > 1 {
                (bw >> recon.subsampling_x, bh >> recon.subsampling_y)
            } else {
                (0, 0)
            };
            let width = recon.width;
            let cw = recon.chroma_w;
            for i in 0..bh {
                for j in 0..bw {
                    recon.y[(row0 + i) * width + (col0 + j)] =
                        ictx.scratch[0][(row0 + i) * width + (col0 + j)];
                }
            }
            for i in 0..cbh {
                for j in 0..cbw {
                    recon.u[(crow0 + i) * cw + (ccol0 + j)] =
                        ictx.scratch[1][(crow0 + i) * cw + (ccol0 + j)];
                    recon.v[(crow0 + i) * cw + (ccol0 + j)] =
                        ictx.scratch[2][(crow0 + i) * cw + (ccol0 + j)];
                }
            }
            tu_bd_stamp(&mut recon.bd, 0, col0, row0, bw, bh);
            if recon.num_planes > 1 {
                tu_bd_stamp(&mut recon.bd, 1, ccol0, crow0, cbw, cbh);
                tu_bd_stamp(&mut recon.bd, 2, ccol0, crow0, cbw, cbh);
            }
            let mut l = SyntaxBlock::skip_leaf(0, None);
            l.segment_id = s as u8;
            l.inter = Some(SyntaxInterBlock {
                ref_frame: [1, -1],
                y_mode: MODE_GLOBALMV,
                mv: gmv,
                ref_mv_idx: 0,
                interp_filter: [EIGHTTAP; 2],
                skip_mode: 0,
                compound_type: crate::inter_pred::COMPOUND_AVERAGE,
                wedge_index: 0,
                wedge_sign: 0,
                mask_type: 0,
                interintra_mode: None,
                wedge_interintra: 0,
                interintra_wedge_index: 0,
                motion_mode: MOTION_MODE_SIMPLE,
            });
            l
        } else {
            // SEG_LVL_GLOBALMV โ€” residual-coded at the segment's
            // quantiser, over the SAME ยง5.11.17 uniform-depth ladder
            // the normal leaf searched (a depth-0-only trial would
            // concede distortion the mode/ref bit savings cannot
            // recoup).
            let seg_qp = ictx.seg_qp(&recon.qp, s as u8);
            let mut max_depth = 0u32;
            let mut t = MAX_TX_SIZE_RECT[b_size];
            while max_depth < MAX_VARTX_DEPTH && t != TX_4X4 {
                t = SPLIT_TX_SIZE[t];
                max_depth += 1;
            }
            let before_trial = save_region_wh(recon, mi_r, mi_c, bw4, bh4);
            let mut inner: Option<(SyntaxBlock, RegionSnapshot, u64)> = None;
            for depth in 0..=max_depth {
                let cand = encode_inter_leaf_residual(
                    mi_r,
                    mi_c,
                    b_size,
                    input,
                    recon,
                    ictx,
                    [1, -1],
                    MODE_GLOBALMV,
                    gmv,
                    0,
                    EIGHTTAP,
                    CompoundSel::AVERAGE,
                    None,
                    MOTION_MODE_SIMPLE,
                    depth,
                    s as u8,
                    &seg_qp,
                    pricing,
                )?;
                let d = region_distortion_wh(recon, input, mi_r, mi_c, bw4, bh4);
                let sc = score256(d, lambda, rate_of(&cand)?);
                if inner.as_ref().map(|(_, _, s0)| sc < *s0).unwrap_or(true) {
                    inner = Some((cand, save_region_wh(recon, mi_r, mi_c, bw4, bh4), sc));
                }
                restore_region(recon, mi_r, mi_c, &before_trial);
            }
            let (cand, after_cand, _) = inner.expect("at least depth 0");
            restore_region(recon, mi_r, mi_c, &after_cand);
            cand
        };
        let d = region_distortion_wh(recon, input, mi_r, mi_c, bw4, bh4);
        let sc = score256(d, lambda, rate_of(&trial)?);
        if sc < score_best {
            score_best = sc;
            best = trial;
            after_best = save_region_wh(recon, mi_r, mi_c, bw4, bh4);
        } else {
            restore_region(recon, mi_r, mi_c, &after_best);
        }
    }
    // Grid-invariant finish: recon holds the winner; re-run its
    // prediction arm so the ยง5.11.5 driver grids match.
    restore_region(recon, mi_r, mi_c, &after_best);
    repredict_leaf_arm(mi_r, mi_c, b_size, recon, ictx, &best)?;
    Ok(best)
}

/// r411/r412 fully-searched inter leaf (mode + filter + residual RD);
/// the r413 [`encode_inter_leaf`] wrapper adds the skip-mode trial on
/// top.
#[allow(clippy::too_many_arguments)]
fn encode_inter_leaf_modes(
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &mut PSearchCtx,
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
) -> Result<SyntaxBlock, Error> {
    let bw4 = NUM_4X4_BLOCKS_WIDE[b_size];
    let bh4 = NUM_4X4_BLOCKS_HIGH[b_size];
    let (bw, bh) = (bw4 * 4, bh4 * 4);
    let row0 = (mi_r as usize) * 4;
    let col0 = (mi_c as usize) * 4;
    let width = recon.width;

    // r412 โ€” ยง5.11.24 single-pred mode + reference selection over the
    // full candidate set the syntax can express at this leaf. For
    // each codable reference (LAST_FRAME = the previous frame,
    // GOLDEN_FRAME = the frame before it โ€” the r412 two-slot
    // rotation) the ยง7.10.2 `find_mv_stack` scan runs against the
    // driver mirror (the same scan the write pass will re-derive),
    // then:
    //
    // * `NEWMV` at the searched vector, with the ยง5.11.23 `drl_mode`
    //   index chosen to minimise the ยง5.11.32 difference bits against
    //   the reachable `PredMv` slots (`{0}` for `NumMvFound <= 1`,
    //   `{0, 1}` at 2, `{0, 1, 2}` beyond โ€” the reader's loop bounds);
    // * `NEARESTMV` at `RefStackMv[ 0 ][ 0 ]` (no MV bits);
    // * `NEARMV` at every `RefStackMv[ idx ][ 0 ]` the drl loop can
    //   reach (`idx = 1` always โ€” the arm's silent start value โ€” plus
    //   `2` at `NumMvFound >= 3` and `3` at `NumMvFound >= 4`);
    // * `GLOBALMV` at the ยง7.10.2.1 derivation (identity warp โ‡’ the
    //   zero vector on this frame configuration).
    //
    // Each candidate's prediction runs through the decoder's own
    // ยง7.11.3 leaf driver; the winner minimises luma SSD + ฮป ยท a
    // small per-mode rate proxy (mode cascade + drl + MV-difference
    // bits + a one-bit ยง5.11.25 cascade surcharge on the non-LAST
    // reference), mirroring [`p_leaf_rate`]'s constants.
    struct ModeCand {
        ref_frame: [i8; 2],
        y_mode: u8,
        mv: [[i32; 2]; 2],
        ref_mv_idx: u32,
        rate: u64,
        /// r422 โ€” the EXACT ยง5.11.23 mode + MV prefix price
        /// (1/256-bit units) through the writer's own emission path
        /// against the twin's current adaptive CDFs; `None` under the
        /// heuristic rate model.
        bits256: Option<u64>,
    }
    let diff_bits = |mv: [i32; 2], pred: [i32; 2]| -> u64 {
        let b = |d: i32| u64::from(34 - d.unsigned_abs().leading_zeros());
        b(mv[0] - pred[0]) + b(mv[1] - pred[1])
    };
    // r422 โ€” exact candidate pricing under the twin model: the
    // ยง5.11.18 neighbour scalars the ยง5.11.25 cascade ctx walks read,
    // derived from the search mirror exactly as the write pass
    // derives them from ITS mirror at this leaf (both hold only prior
    // committed blocks here).
    // r431 โ€” tile-scoped availability through the search context's
    // precomputed grids (the write pass derives the same pair from
    // ITS tile geometry).
    let nbr_cell = (mi_r * ictx.mi_cols + mi_c) as usize;
    let (nbr_avail_u, nbr_avail_l) = (ictx.avail_us[nbr_cell] != 0, ictx.avail_ls[nbr_cell] != 0);
    let nbr_ref = |r: u32, c: u32| -> [i32; 2] {
        let cell = ((r * ictx.mi_cols + c) as usize) * 2;
        let rfg = ictx.mirror.ref_frames();
        [i32::from(rfg[cell]), i32::from(rfg[cell + 1])]
    };
    let above_ref_frame = if nbr_avail_u {
        nbr_ref(mi_r - 1, mi_c)
    } else {
        [0, -1]
    };
    let left_ref_frame = if nbr_avail_l {
        nbr_ref(mi_r, mi_c - 1)
    } else {
        [0, -1]
    };
    let (p_reference_select, p_fimv, p_hp) = (
        ictx.ip.reference_select,
        ictx.ip.force_integer_mv,
        ictx.ip.allow_high_precision_mv,
    );
    let price_mode = |cand_ref: [i8; 2],
                      y_mode: u8,
                      mv: [[i32; 2]; 2],
                      ref_mv_idx: u32,
                      stack: &crate::cdf::FindMvStackResult|
     -> Result<Option<u64>, Error> {
        match pricing {
            Some((twin, _)) => Ok(Some(twin.price_inter_mode(
                [i32::from(cand_ref[0]), i32::from(cand_ref[1])],
                y_mode,
                mv,
                ref_mv_idx,
                stack,
                b_size,
                p_reference_select,
                nbr_avail_u,
                nbr_avail_l,
                above_ref_frame,
                left_ref_frame,
                p_fimv,
                p_hp,
            )?)),
            None => Ok(None),
        }
    };
    let mut cands: Vec<ModeCand> = Vec::with_capacity(18);
    // r415 โ€” per-reference searched vectors, keyed by the raw
    // `RefFrame` ordinal (NEW_NEWMV compound candidates reuse them).
    let mut searched_mv: [[i32; 2]; 8] = [[0, 0]; 8];
    let single_refs = ictx.single_refs.clone();
    // r416 โ€” ยง5.11.25 `Min( bw4, bh4 ) >= 2`: sub-8ร—8 blocks cannot
    // code `comp_mode` (SINGLE_REFERENCE forced with no bit), so the
    // compound ladder is empty there. r421 โ€” the ยง5.11.25
    // `reference_select` frame gate joins: with `reference_select ==
    // 0` the reader never codes `comp_mode` (SINGLE_REFERENCE forced),
    // so a compound candidate would be uncodable โ€” the rate twin's
    // write-path validation surfaced configurations offering pairs the
    // header cannot express.
    let compound_pairs = if bw4.min(bh4) >= 2 && ictx.ip.reference_select {
        ictx.compound_pairs.clone()
    } else {
        Vec::new()
    };
    for (ref_ord, &rf) in single_refs.iter().enumerate() {
        let ref_bias = ref_ord as u64;
        let stack = ictx.find_stack(mi_r, mi_c, b_size, [rf, -1])?;
        let ref_plane = ictx.plane_of_ref(rf);
        let mv_int = motion_search_luma(
            input,
            ictx.search_luma(ref_plane),
            width,
            recon.height,
            row0,
            col0,
            bw,
            bh,
        );
        // r411 sub-pel refinement: half-pel then quarter-pel deltas
        // around the integer winner, each candidate evaluated through
        // the REAL ยง7.11.3.4 kernel (so the search cost IS the coding
        // cost). `allow_high_precision_mv = 0` restricts components
        // to quarter-pel (multiples of 2 in 1/8-luma units).
        let mv_new = refine_mv_subpel(
            input, ictx, mi_r, mi_c, b_size, rf, row0, col0, bw, bh, width, mv_int,
        )?;
        searched_mv[rf as usize] = mv_new;
        let nfound = stack.num_mv_found;
        {
            // NEWMV: pick the reachable drl slot with the cheapest
            // ยง5.11.32 difference โ€” exact twin bits when priced
            // (drl_mode + read_mv against the current adaptive CDFs),
            // else each extra slot costs one heuristic drl bit.
            let window: u32 = match nfound {
                0 | 1 => 0,
                2 => 1,
                _ => 2,
            };
            let mut best: Option<(u64, u32, u64, Option<u64>)> = None;
            for idx in 0..=window {
                let pred = assign_mv_pred_mv(&stack, MODE_NEWMV, 0, idx)?;
                let rate = 5 + ref_bias + u64::from(idx) + diff_bits(mv_new, pred);
                let exact = price_mode([rf, -1], MODE_NEWMV, [mv_new, [0, 0]], idx, &stack)?;
                let key = exact.unwrap_or(rate);
                if best.map_or(true, |(k, _, _, _)| key < k) {
                    best = Some((key, idx, rate, exact));
                }
            }
            let (_, idx, rate, bits256) = best.expect("slot 0 is always reachable");
            cands.push(ModeCand {
                ref_frame: [rf, -1],
                y_mode: MODE_NEWMV,
                mv: [mv_new, [0, 0]],
                ref_mv_idx: idx,
                rate,
                bits256,
            });
        }
        let nearest_mv = [stack.ref_stack_mv[0][0], [0, 0]];
        cands.push(ModeCand {
            ref_frame: [rf, -1],
            y_mode: MODE_NEARESTMV,
            mv: nearest_mv,
            ref_mv_idx: 0,
            rate: 3 + ref_bias,
            bits256: price_mode([rf, -1], MODE_NEARESTMV, nearest_mv, 0, &stack)?,
        });
        let near_top: u32 = match nfound {
            0..=2 => 1,
            3 => 2,
            _ => 3,
        };
        for idx in 1..=near_top {
            let near_mv = [stack.ref_stack_mv[idx as usize][0], [0, 0]];
            cands.push(ModeCand {
                ref_frame: [rf, -1],
                y_mode: MODE_NEARMV,
                mv: near_mv,
                ref_mv_idx: idx,
                rate: 4 + ref_bias + u64::from(idx - 1),
                bits256: price_mode([rf, -1], MODE_NEARMV, near_mv, idx, &stack)?,
            });
        }
        let global_mv = [stack.global_mvs[0], [0, 0]];
        cands.push(ModeCand {
            ref_frame: [rf, -1],
            y_mode: MODE_GLOBALMV,
            mv: global_mv,
            ref_mv_idx: 0,
            rate: 4 + ref_bias,
            bits256: price_mode([rf, -1], MODE_GLOBALMV, global_mv, 0, &stack)?,
        });
    }

    // r412 โ€” COMPOUND_AVERAGE candidates over each ladder pair
    // (ยง5.11.25 unidirectional or bidirectional compound; the
    // ยง5.11.29 tail is bit-silent on this configuration and derives
    // COMPOUND_AVERAGE): NEAREST_NEARESTMV / NEAR_NEARMV from the
    // compound ยง7.10.2 stack, GLOBAL_GLOBALMV at the identity
    // derivation, and NEW_NEWMV re-using the two per-reference
    // searched vectors.
    for &crf in &compound_pairs {
        let stack = ictx.find_stack(mi_r, mi_c, b_size, crf)?;
        let nfound = stack.num_mv_found;
        let nn_mv = [stack.ref_stack_mv[0][0], stack.ref_stack_mv[0][1]];
        cands.push(ModeCand {
            ref_frame: crf,
            y_mode: MODE_NEAREST_NEARESTMV,
            mv: nn_mv,
            ref_mv_idx: 0,
            rate: 6,
            bits256: price_mode(crf, MODE_NEAREST_NEARESTMV, nn_mv, 0, &stack)?,
        });
        let near_top: u32 = match nfound {
            0..=2 => 1,
            3 => 2,
            _ => 3,
        };
        for idx in 1..=near_top {
            let nn_mv = [
                stack.ref_stack_mv[idx as usize][0],
                stack.ref_stack_mv[idx as usize][1],
            ];
            cands.push(ModeCand {
                ref_frame: crf,
                y_mode: MODE_NEAR_NEARMV,
                mv: nn_mv,
                ref_mv_idx: idx,
                rate: 7 + u64::from(idx - 1),
                bits256: price_mode(crf, MODE_NEAR_NEARMV, nn_mv, idx, &stack)?,
            });
        }
        let gg_mv = [stack.global_mvs[0], stack.global_mvs[1]];
        cands.push(ModeCand {
            ref_frame: crf,
            y_mode: MODE_GLOBAL_GLOBALMV,
            mv: gg_mv,
            ref_mv_idx: 0,
            rate: 7,
            bits256: price_mode(crf, MODE_GLOBAL_GLOBALMV, gg_mv, 0, &stack)?,
        });
        {
            let window: u32 = match nfound {
                0 | 1 => 0,
                2 => 1,
                _ => 2,
            };
            let pair_mv = [searched_mv[crf[0] as usize], searched_mv[crf[1] as usize]];
            let mut best: Option<(u64, u32, u64, Option<u64>)> = None;
            for idx in 0..=window {
                let pred0 = assign_mv_pred_mv(&stack, MODE_NEW_NEWMV, 0, idx)?;
                let pred1 = assign_mv_pred_mv(&stack, MODE_NEW_NEWMV, 1, idx)?;
                let rate = 8
                    + u64::from(idx)
                    + diff_bits(pair_mv[0], pred0)
                    + diff_bits(pair_mv[1], pred1);
                let exact = price_mode(crf, MODE_NEW_NEWMV, pair_mv, idx, &stack)?;
                let key = exact.unwrap_or(rate);
                if best.map_or(true, |(k, _, _, _)| key < k) {
                    best = Some((key, idx, rate, exact));
                }
            }
            let (_, idx, rate, bits256) = best.expect("slot 0 is always reachable");
            cands.push(ModeCand {
                ref_frame: crf,
                y_mode: MODE_NEW_NEWMV,
                mv: pair_mv,
                ref_mv_idx: idx,
                rate,
                bits256,
            });
        }
    }
    // ยง6.10.27 conformance bound โ€” the writers reject any leaf beyond
    // it, so a (pathological) out-of-bound stack candidate is simply
    // not offered.
    cands.retain(|c| {
        c.mv.iter()
            .all(|m| m[0].unsigned_abs() < (1 << 14) && m[1].unsigned_abs() < (1 << 14))
    });

    let lambda = lambda_for(&recon.qp);
    let mut best: Option<(u64, usize)> = None;
    let mut best_compound: Option<(u64, usize)> = None;
    // r417 โ€” the best SINGLE-reference candidate (the ยง5.11.28
    // inter-intra trials blend on top of it).
    let mut best_single: Option<(u64, usize)> = None;
    for (ci, cand) in cands.iter().enumerate() {
        ictx.predict_leaf(
            mi_r,
            mi_c,
            b_size,
            cand.ref_frame,
            cand.y_mode,
            cand.mv,
            EIGHTTAP,
            CompoundSel::AVERAGE,
            None,
            MotionSel::Simple,
        )?;
        let mut ssd = 0u64;
        for i in 0..bh {
            for j in 0..bw {
                let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                    - i64::from(ictx.scratch[0][(row0 + i) * width + col0 + j]);
                ssd += (d * d) as u64;
            }
        }
        // r422 โ€” twin model: `Dยท256 + ฮปยทbits256` with the exact
        // ยง5.11.23 mode-prefix price; heuristic model keeps the
        // pre-r422 proxy scale. All candidates of one election carry
        // the same scale, so the comparison is well-formed.
        let score = match cand.bits256 {
            Some(b) => score256(ssd, lambda, b),
            None => ssd + lambda * cand.rate,
        };
        if best.map_or(true, |(s, _)| score < s) {
            best = Some((score, ci));
        }
        if cand.ref_frame[1] > 0 && best_compound.map_or(true, |(s, _)| score < s) {
            best_compound = Some((score, ci));
        }
        if cand.ref_frame[1] < 0 && best_single.map_or(true, |(s, _)| score < s) {
            best_single = Some((score, ci));
        }
    }
    let (mut best_score, mut best_ci) = best.ok_or(Error::PartitionWalkOutOfRange)?;

    // r415 โ€” ยง5.11.29 MASKED-compound trials on the best compound
    // candidate: every WEDGE (index, sign) pair where
    // `Wedge_Bits[ MiSize ] > 0` plus both DIFFWTD mask types, each
    // predicted through the decoder's own ยง7.11.3.11/ยง7.11.3.12 mask
    // blend and scored `D + ฮปยท(rate + side-data bits)` against the
    // running best (which keeps COMPOUND_AVERAGE when the masks lose).
    let mut comp = CompoundSel::AVERAGE;
    if ictx.ip.enable_masked_compound {
        if let Some((_, cci)) = best_compound {
            let (c_ref, c_mode, c_mv, c_rate, c_bits256) = {
                let c = &cands[cci];
                (c.ref_frame, c.y_mode, c.mv, c.rate, c.bits256)
            };
            let mut trials: Vec<(CompoundSel, u64)> = Vec::new();
            if crate::cdf::wedge_bits(b_size) > 0 {
                for wi in 0..16u8 {
                    for ws in 0..=1u8 {
                        trials.push((
                            CompoundSel {
                                ctype: crate::inter_pred::COMPOUND_WEDGE,
                                wedge_index: wi,
                                wedge_sign: ws,
                                mask_type: 0,
                            },
                            /* comp_group_idx + wedge_index S() + sign L(1) */ 6,
                        ));
                    }
                }
            }
            for mt in 0..=1u8 {
                trials.push((
                    CompoundSel {
                        ctype: crate::inter_pred::COMPOUND_DIFFWTD,
                        wedge_index: 0,
                        wedge_sign: 0,
                        mask_type: mt,
                    },
                    /* comp_group_idx (+ compound_type S()) + mask L(1) */ 3,
                ));
            }
            for (sel, extra) in trials {
                ictx.predict_leaf(
                    mi_r,
                    mi_c,
                    b_size,
                    c_ref,
                    c_mode,
                    c_mv,
                    EIGHTTAP,
                    sel,
                    None,
                    MotionSel::Simple,
                )?;
                let mut ssd = 0u64;
                for i in 0..bh {
                    for j in 0..bw {
                        let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                            - i64::from(ictx.scratch[0][(row0 + i) * width + col0 + j]);
                        ssd += (d * d) as u64;
                    }
                }
                // r422 โ€” twin scale: the exact mode-prefix bits plus
                // the side-symbol proxy promoted to 1/256 units.
                let score = match c_bits256 {
                    Some(b) => score256(ssd, lambda, b + extra * 256),
                    None => ssd + lambda * (c_rate + extra),
                };
                if score < best_score {
                    best_score = score;
                    best_ci = cci;
                    comp = sel;
                }
            }
        }
    }

    // r416 โ€” ยง5.11.29 jnt-comp trial on the best compound candidate:
    // the COMPOUND_DISTANCE leaf (`comp_group_idx = 0`,
    // `compound_idx = 0`) predicted through the decoder's own
    // ยง7.11.3.15 distance-weighted blend. Rate-neutral against the
    // coded AVERAGE arm (both code the same two ยง5.11.29 symbols), so
    // luma distortion alone decides; ties keep the running best.
    if ictx.ip.enable_jnt_comp {
        if let Some((_, cci)) = best_compound {
            let (c_ref, c_mode, c_mv, c_rate, c_bits256) = {
                let c = &cands[cci];
                (c.ref_frame, c.y_mode, c.mv, c.rate, c.bits256)
            };
            let sel = CompoundSel {
                ctype: crate::inter_pred::COMPOUND_DISTANCE,
                wedge_index: 0,
                wedge_sign: 0,
                mask_type: 0,
            };
            ictx.predict_leaf(
                mi_r,
                mi_c,
                b_size,
                c_ref,
                c_mode,
                c_mv,
                EIGHTTAP,
                sel,
                None,
                MotionSel::Simple,
            )?;
            let mut ssd = 0u64;
            for i in 0..bh {
                for j in 0..bw {
                    let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                        - i64::from(ictx.scratch[0][(row0 + i) * width + col0 + j]);
                    ssd += (d * d) as u64;
                }
            }
            let score = match c_bits256 {
                Some(b) => score256(ssd, lambda, b),
                None => ssd + lambda * c_rate,
            };
            if score < best_score {
                best_score = score;
                best_ci = cci;
                comp = sel;
            }
        }
    }

    // r417 โ€” ยง5.11.28 inter-intra trials on the best single-reference
    // candidate: each of the four ยง6.10.27 II modes through the
    // ยง7.11.3.13 smooth intra-variant mask (the intra half predicted
    // from the committed recon's neighbours), then โ€” where
    // `Wedge_Bits[ MiSize ] > 0` โ€” the 16 ยง7.11.3.11 wedge masks at
    // the best smooth mode, every trial through the decoder's own
    // ยง7.11.3.14 blend driver and scored `D + ฮปยท(rate + ยง5.11.28
    // bits)` against the running best (which keeps the plain leaf
    // when the blends lose).
    let mut ii_sel: Option<(u8, Option<u8>)> = None;
    if ictx.ip.enable_interintra_compound
        && (crate::cdf::BLOCK_8X8..=crate::cdf::BLOCK_32X32).contains(&b_size)
    {
        if let Some((_, sci)) = best_single {
            let (s_ref, s_mode, s_mv, s_rate, s_bits256) = {
                let c = &cands[sci];
                (c.ref_frame, c.y_mode, c.mv, c.rate, c.bits256)
            };
            let leaf_ssd = |ictx: &PSearchCtx| -> u64 {
                let mut ssd = 0u64;
                for i in 0..bh {
                    for j in 0..bw {
                        let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                            - i64::from(ictx.scratch[0][(row0 + i) * width + col0 + j]);
                        ssd += (d * d) as u64;
                    }
                }
                ssd
            };
            // Stage 1 โ€” the four smooth-mask II modes
            // (`interintra` S() + `interintra_mode` S() +
            // `wedge_interintra` S() โ‰ˆ 4 rate-proxy bits).
            let mut stage: Option<(u64, u8)> = None;
            for m in 0..crate::cdf::INTERINTRA_MODES as u8 {
                ictx.predict_leaf(
                    mi_r,
                    mi_c,
                    b_size,
                    s_ref,
                    s_mode,
                    s_mv,
                    EIGHTTAP,
                    CompoundSel::AVERAGE,
                    Some(InterIntraTrial {
                        mode: m,
                        wedge: None,
                        neigh: &*recon,
                    }),
                    MotionSel::Simple,
                )?;
                let ssd = leaf_ssd(ictx);
                if stage.map_or(true, |(s, _)| ssd < s) {
                    stage = Some((ssd, m));
                }
                let score = match s_bits256 {
                    Some(b) => score256(ssd, lambda, b + 4 * 256),
                    None => ssd + lambda * (s_rate + 4),
                };
                if score < best_score {
                    best_score = score;
                    best_ci = sci;
                    comp = CompoundSel::AVERAGE;
                    ii_sel = Some((m, None));
                }
            }
            // Stage 2 โ€” the 16 wedge masks at the stage-1 distortion
            // winner (+ `wedge_index` S() โ‰ˆ 4 more bits).
            if crate::cdf::wedge_bits(b_size) > 0 {
                let (_, base_mode) = stage.expect("stage 1 ran");
                for wi in 0..16u8 {
                    ictx.predict_leaf(
                        mi_r,
                        mi_c,
                        b_size,
                        s_ref,
                        s_mode,
                        s_mv,
                        EIGHTTAP,
                        CompoundSel::AVERAGE,
                        Some(InterIntraTrial {
                            mode: base_mode,
                            wedge: Some(wi),
                            neigh: &*recon,
                        }),
                        MotionSel::Simple,
                    )?;
                    let score = match s_bits256 {
                        Some(b) => score256(leaf_ssd(ictx), lambda, b + 8 * 256),
                        None => leaf_ssd(ictx) + lambda * (s_rate + 8),
                    };
                    if score < best_score {
                        best_score = score;
                        best_ci = sci;
                        comp = CompoundSel::AVERAGE;
                        ii_sel = Some((base_mode, Some(wi)));
                    }
                }
            }
        }
    }
    let _ = best_score;
    let ModeCand {
        ref_frame,
        y_mode,
        mv,
        ref_mv_idx,
        ..
    } = cands[best_ci];

    // r412 โ€” ยง5.11.x SWITCHABLE interpolation-filter RD selection on
    // the winning (mode, MV): trial the three codable filters
    // (`EIGHTTAP` / `EIGHTTAP_SMOOTH` / `EIGHTTAP_SHARP`) through the
    // decoder's own ยง7.11.3.4 kernel and keep the lowest luma SSD
    // (the S() costs one ~equal-rate symbol whichever value is coded,
    // so distortion decides; ties keep EIGHTTAP). GLOBALMV /
    // GLOBAL_GLOBALMV leaves are `needs_interp_filter( ) == 0` on the
    // identity-warp frame configuration โ€” the reader derives EIGHTTAP
    // with no bits, so no search happens and the committed pair must
    // be EIGHTTAP.
    let leaf_luma_ssd = |ictx: &PSearchCtx| -> u64 {
        let mut ssd = 0u64;
        for i in 0..bh {
            for j in 0..bw {
                let d = i64::from(input.y[(row0 + i) * width + col0 + j])
                    - i64::from(ictx.scratch[0][(row0 + i) * width + col0 + j]);
                ssd += (d * d) as u64;
            }
        }
        ssd
    };
    let (mut filter, simple_ssd) = if ictx.ip.interpolation_filter != SWITCHABLE {
        // ยง5.11.26 else-arm: a non-SWITCHABLE frame filter is read
        // with no bits โ€” every leaf must carry exactly it (r421: the
        // rate twin's write-path validation surfaced searches trialling
        // filters the header cannot express).
        let f = ictx.ip.interpolation_filter;
        ictx.predict_leaf(
            mi_r,
            mi_c,
            b_size,
            ref_frame,
            y_mode,
            mv,
            f,
            comp,
            None,
            MotionSel::Simple,
        )?;
        (f, leaf_luma_ssd(ictx))
    } else if y_mode == MODE_GLOBALMV || y_mode == MODE_GLOBAL_GLOBALMV {
        ictx.predict_leaf(
            mi_r,
            mi_c,
            b_size,
            ref_frame,
            y_mode,
            mv,
            EIGHTTAP,
            comp,
            None,
            MotionSel::Simple,
        )?;
        (EIGHTTAP, leaf_luma_ssd(ictx))
    } else {
        use crate::inter_pred::{EIGHTTAP_SHARP, EIGHTTAP_SMOOTH};
        let mut best_f = (u64::MAX, EIGHTTAP);
        for f in [EIGHTTAP, EIGHTTAP_SMOOTH, EIGHTTAP_SHARP] {
            ictx.predict_leaf(
                mi_r,
                mi_c,
                b_size,
                ref_frame,
                y_mode,
                mv,
                f,
                comp,
                None,
                MotionSel::Simple,
            )?;
            let ssd = leaf_luma_ssd(ictx);
            if ssd < best_f.0 {
                best_f = (ssd, f);
            }
        }
        (best_f.1, best_f.0)
    };

    // r419 โ€” ยง5.11.27 motion-mode trials on the winning
    // single-reference (mode, MV): OBMC (the ยง7.11.3.9-10 overlap
    // blend, trialled per codable filter) and โ€” where the ยง5.11.27
    // arm-B gates open โ€” WARPED_CAUSAL (the ยง7.10.4 sample scan +
    // ยง7.11.3.8 least-squares fit + ยง7.11.3.5 warp, filter-silent
    // `EIGHTTAP` per `needs_interp_filter( )`). Every arm codes one
    // roughly-equal-rate S() whichever value it selects, so luma
    // distortion decides; ties keep the earlier arm (SIMPLE, then
    // OBMC). The eligibility derivation tracks the ยง5.11.27 reader's
    // short-circuit cascade exactly โ€” an ineligible leaf never trials
    // (and the write pass re-derives the same cascade and would
    // reject an uncodable commitment).
    let mut motion = MotionSel::Simple;
    if ictx.ip.is_motion_mode_switchable
        && ii_sel.is_none()
        && ref_frame[1] == -1
        && bw.min(bh) >= 8
        && !(!ictx.ip.force_integer_mv
            && y_mode == MODE_GLOBALMV
            && ictx.ip.gm_type[ref_frame[0] as usize] > crate::cdf::GM_TYPE_TRANSLATION)
        && ictx.mirror.has_overlappable_candidates(mi_r, mi_c, b_size)
    {
        // r421 โ€” the ยง5.11.27 arm is no longer priced as "roughly
        // equal-rate": under the twin model each candidate ordinal is
        // priced through the writer's own arm derivation against the
        // CURRENT adaptive CDFs (`use_obmc` and `motion_mode` rows
        // adapt away from uniform quickly, so SIMPLE vs OBMC vs
        // WARPED_CAUSAL can differ by whole bits), and the election
        // scores `Dยท256 + ฮปยทbits256`. The heuristic model keeps the
        // pre-r421 pure-distortion pick.
        let num_samples = ictx.warp_num_samples(mi_r, mi_c, b_size, ref_frame[0], mv);
        // Copies of the gating scalars, so the pricing closure holds
        // no borrow of `ictx` across the `predict_leaf` trials.
        let (mm_switchable, mm_warp, mm_fimv, mm_gm_type, mm_scaled) = (
            ictx.ip.is_motion_mode_switchable,
            ictx.ip.allow_warped_motion,
            ictx.ip.force_integer_mv,
            ictx.ip.gm_type,
            ictx.ip.is_scaled_per_ref,
        );
        let mm_bits = move |mm: u8| -> Result<u64, Error> {
            match pricing {
                Some((twin, _)) => twin.price_motion_mode(
                    mm,
                    b_size,
                    false,
                    [i32::from(ref_frame[0]), i32::from(ref_frame[1])],
                    y_mode,
                    num_samples,
                    mm_switchable,
                    mm_warp,
                    mm_fimv,
                    mm_gm_type,
                    mm_scaled,
                    true,
                ),
                None => Ok(0),
            }
        };
        let mut best_score = score256(simple_ssd, lambda, mm_bits(MOTION_MODE_SIMPLE)?);
        // OBMC trial โ€” the leaf's own prediction rides its own
        // ยง7.11.3.4 filter (GLOBALMV leaves stay filter-silent on
        // EIGHTTAP), the overlap bands the committed neighbours'.
        {
            use crate::inter_pred::{EIGHTTAP_SHARP, EIGHTTAP_SMOOTH};
            let obmc_bits = mm_bits(MOTION_MODE_OBMC)?;
            let fixed = [ictx.ip.interpolation_filter];
            let obmc_filters: &[u8] = if ictx.ip.interpolation_filter != SWITCHABLE {
                // ยง5.11.26 else-arm: the frame filter is the only
                // codable pair.
                &fixed
            } else if y_mode == MODE_GLOBALMV {
                &[EIGHTTAP]
            } else {
                &[EIGHTTAP, EIGHTTAP_SMOOTH, EIGHTTAP_SHARP]
            };
            for &f in obmc_filters {
                ictx.predict_leaf(
                    mi_r,
                    mi_c,
                    b_size,
                    ref_frame,
                    y_mode,
                    mv,
                    f,
                    comp,
                    None,
                    MotionSel::Obmc,
                )?;
                let score = score256(leaf_luma_ssd(ictx), lambda, obmc_bits);
                if score < best_score {
                    best_score = score;
                    motion = MotionSel::Obmc;
                    filter = f;
                }
            }
        }
        // WARPED_CAUSAL trial โ€” ยง5.11.27 arm B only (`NumSamples > 0`
        // over the same ยง7.10.4 scan the write pass and the decoder
        // re-run at this leaf, `allow_warped_motion`, unscaled
        // reference), and only when the ยง7.11.3.8 fit is
        // `setup_shear`-valid (an invalid fit decodes translationally
        // โ€” never worth the commitment).
        if ictx.ip.allow_warped_motion
            && !ictx.ip.force_integer_mv
            && !ictx.ip.is_scaled_per_ref[(ref_frame[0] - 1) as usize]
        {
            if let Some(params) = ictx.warp_fit(mi_r, mi_c, b_size, ref_frame[0], mv) {
                ictx.predict_leaf(
                    mi_r,
                    mi_c,
                    b_size,
                    ref_frame,
                    y_mode,
                    mv,
                    EIGHTTAP,
                    comp,
                    None,
                    MotionSel::Warp(params),
                )?;
                let score = score256(
                    leaf_luma_ssd(ictx),
                    lambda,
                    mm_bits(MOTION_MODE_WARPED_CAUSAL)?,
                );
                if score < best_score {
                    motion = MotionSel::Warp(params);
                    // `needs_interp_filter( ) == 0` on LOCALWARP โ€”
                    // the committed pair is the reader's bit-silent
                    // derivation: EIGHTTAP on the SWITCHABLE arm, the
                    // frame filter otherwise.
                    filter = if ictx.ip.interpolation_filter != SWITCHABLE {
                        ictx.ip.interpolation_filter
                    } else {
                        EIGHTTAP
                    };
                }
            }
        }
    }
    ictx.predict_leaf(
        mi_r,
        mi_c,
        b_size,
        ref_frame,
        y_mode,
        mv,
        filter,
        comp,
        ii_sel.map(|(m, w)| InterIntraTrial {
            mode: m,
            wedge: w,
            neigh: &*recon,
        }),
        motion,
    )?;

    // r413 โ€” per-leaf segment (deterministic activity policy) and its
    // quantiser; a leaf that quantises to all-zero commits `skip = 1`
    // and inherits the ยง5.11.20 `pred` instead (inside
    // `encode_inter_leaf_residual`).
    let segment_id = ictx.segment_for_block(input, mi_r, mi_c, b_size);
    let seg_qp = ictx.seg_qp(&recon.qp, segment_id);

    // r426 โ€” per-segment ยง5.9.2 `LosslessArray[]`: a leaf whose
    // segment derives `Lossless = 1` codes the ยง5.11.34 row-major
    // `TX_4X4` grid through the WHT chain with no ยง5.11.16 trees and
    // no ยง5.11.15 depth choice, whether the FRAME is CodedLossless
    // (the pre-r426 arm โ€” every segment lossless) or lossy (the r426
    // mixed configuration โ€” this segment only).
    if ictx.seg_lossless(segment_id) {
        // ยง5.11.15: Lossless forces TX_4X4, no ยง5.11.17 trees.
        return encode_inter_leaf_residual(
            mi_r,
            mi_c,
            b_size,
            input,
            recon,
            ictx,
            ref_frame,
            y_mode,
            mv,
            ref_mv_idx,
            filter,
            comp,
            ii_sel,
            motion.ordinal(),
            0,
            segment_id,
            &seg_qp,
            pricing,
        );
    }

    // ยง5.11.17 uniform-depth RD trial (TX_MODE_SELECT): code the leaf
    // at `Split_Tx_Size^depth[ Max_Tx_Size_Rect ]` for each reachable
    // depth against the same starting state, keep the lower `D + ฮปยทR`.
    let max_tx = MAX_TX_SIZE_RECT[b_size];
    let mut max_depth = 0u32;
    let mut t = max_tx;
    while max_depth < MAX_VARTX_DEPTH && t != TX_4X4 {
        t = SPLIT_TX_SIZE[t];
        max_depth += 1;
    }
    // r416 โ€” sub-8ร—8 leaves write the GROUP's chroma (the ยง5.11.34
    // `HasChroma` block covers the full 2ร—2-cell chroma area), which
    // extends past the leaf's own mi rect: snapshot / restore / score
    // over the group-aligned rect so no trial state leaks between
    // depth candidates.
    let (sr, sc, sw4, sh4) = {
        let (mut sr, mut sc, mut sw4, mut sh4) = (mi_r, mi_c, bw4, bh4);
        if bh4 == 1 {
            sr = mi_r & !1;
            sh4 = 2;
        }
        if bw4 == 1 {
            sc = mi_c & !1;
            sw4 = 2;
        }
        (sr, sc, sw4, sh4)
    };
    let before = save_region_wh(recon, sr, sc, sw4, sh4);
    let mut best: Option<(SyntaxBlock, RegionSnapshot, u64)> = None;
    for depth in 0..=max_depth {
        let leaf = encode_inter_leaf_residual(
            mi_r,
            mi_c,
            b_size,
            input,
            recon,
            ictx,
            ref_frame,
            y_mode,
            mv,
            ref_mv_idx,
            filter,
            comp,
            ii_sel,
            motion.ordinal(),
            depth,
            segment_id,
            &seg_qp,
            pricing,
        )?;
        let d = region_distortion_wh(recon, input, sr, sc, sw4, sh4);
        // r421 โ€” exact twin bits (the ยง5.11.17 depth symbols are part
        // of the block syntax, so no depth surcharge) or the pre-r421
        // proxy, one scale per call.
        let rate256 = match pricing {
            Some((twin, params)) => twin.price_block(&leaf, mi_r, mi_c, b_size, params)?,
            None => (p_leaf_rate(&leaf) + 2 * u64::from(depth)) * 256,
        };
        let score = score256(d, lambda, rate256);
        let improves = match best.as_ref() {
            Some((_, _, s)) => score < *s,
            None => true,
        };
        if improves {
            best = Some((leaf, save_region_wh(recon, sr, sc, sw4, sh4), score));
        }
        restore_region(recon, sr, sc, &before);
    }
    // r426 โ€” content-driven per-segment-lossless election: synthetic
    // leaves (tiny luma alphabet) additionally trial the lossless
    // segment โ€” same prediction, qindex-0 WHT residual, `D = 0` by
    // bit-exactness โ€” against the lossy depth ladder on the identical
    // `D + ฮปยทR` scale (twin bits when priced). The lossless arm wins
    // exactly when the ladder's distortion outprices the WHT chain's
    // rate premium.
    if ictx.auto_lossless && ictx.synthetic_leaf(input, mi_r, mi_c, b_size) {
        if let Some(ll_seg) = ictx.lossless_seg {
            let ll_qp = ictx.seg_qp(&recon.qp, ll_seg);
            let leaf = encode_inter_leaf_residual(
                mi_r,
                mi_c,
                b_size,
                input,
                recon,
                ictx,
                ref_frame,
                y_mode,
                mv,
                ref_mv_idx,
                filter,
                comp,
                ii_sel,
                motion.ordinal(),
                0,
                ll_seg,
                &ll_qp,
                pricing,
            )?;
            let d = region_distortion_wh(recon, input, sr, sc, sw4, sh4);
            let rate256 = match pricing {
                Some((twin, params)) => twin.price_block(&leaf, mi_r, mi_c, b_size, params)?,
                None => p_leaf_rate(&leaf) * 256,
            };
            let score = score256(d, lambda, rate256);
            let improves = match best.as_ref() {
                Some((_, _, s)) => score < *s,
                None => true,
            };
            if improves {
                best = Some((leaf, save_region_wh(recon, sr, sc, sw4, sh4), score));
            }
            restore_region(recon, sr, sc, &before);
        }
    }
    let (leaf, after, _) = best.expect("at least depth 0");
    restore_region(recon, sr, sc, &after);
    Ok(leaf)
}

/// ยง5.11.36 / ยง5.11.17 luma TU visit order for a uniform-depth
/// `read_var_tx_size` recursion rooted at `tx` (r412: rect-aware โ€”
/// each split level visits `(h4 / stepH) * (w4 / stepW)` children of
/// `Split_Tx_Size[ tx ]` in row-major `(i, j)` order, which is 4 for
/// square ordinals and 2 for rectangular ones; the pre-r412 square
/// quadtree order falls out as the square special case).
fn transform_tree_tu_order(
    x: usize,
    y: usize,
    tx: usize,
    depth: u32,
    out: &mut Vec<(usize, usize)>,
) {
    if depth == 0 {
        out.push((x, y));
        return;
    }
    let sub = SPLIT_TX_SIZE[tx];
    let (sw, sh) = (TX_WIDTH[sub], TX_HEIGHT[sub]);
    for i in 0..TX_HEIGHT[tx] / sh {
        for j in 0..TX_WIDTH[tx] / sw {
            transform_tree_tu_order(x + j * sw, y + i * sh, sub, depth - 1, out);
        }
    }
}

/// r411 โ€” ยง5.11.47 per-TU LUMA transform-type RD search on the INTER
/// arm: trials every `TxType` admissible in the ยง5.11.48 inter set for
/// `tx_sz` (all 16 at 4ร—4/8ร—8, 12 at 16ร—16, IDTX+DCT at 32ร—32, DCT
/// alone above), scoring each full quantiseโ†’dequantiseโ†’inverse chain
/// by `D + ฮปยทR` over the TU, then stitches the winner into the running
/// plane. The returned label is forced to `DCT_DCT` when the winning
/// TU quantises to all-zero (the ยง5.11.39 `all_zero` arm reads no
/// `inter_tx_type` symbol and the walker stamps `DCT_DCT`).
///
/// r424 โ€” with `fork = Some((tu_fork, tu_ctx))` each candidate's rate
/// is the EXACT ยง5.11.39 coefficient chain (priced through the
/// writer's own one-TU body against the fork's running CDF /
/// level-context state โ€” see [`TuFork`]) and the winner is COMMITTED
/// into the fork so the leaf's next TU prices against the true
/// post-TU state; `None` keeps the magnitude proxy (the pre-r424
/// heuristic and the `RateModel::Heuristic` baseline).
#[allow(clippy::too_many_arguments)]
pub(crate) fn residual_tx_search_luma_inter(
    input_plane: &[u16],
    recon_plane: &mut [u16],
    pw: usize,
    row0: usize,
    col0: usize,
    tx_sz: usize,
    pred: &[u16],
    qp: &QuantizerParams,
    fork: Option<(&mut TuFork, &TuCtx<'_>)>,
) -> Result<(Vec<i32>, u8), Error> {
    use crate::cdf::{dequantize_step1, is_tx_type_in_set, tx_size_sqr_index, TX_SIZE_SQR_UP};
    use crate::encoder::forward_quantize::forward_quantize;
    use crate::encoder::forward_transform_2d::forward_transform_2d;
    use crate::encoder::key_frame::repack_compact;
    use crate::transform::inverse_transform_2d;

    let w = TX_WIDTH[tx_sz];
    let h = TX_HEIGHT[tx_sz];
    let max_val = (1i64 << qp.bit_depth) - 1;
    let mut residual = vec![0i64; w * h];
    for i in 0..h {
        for j in 0..w {
            residual[i * w + j] =
                i64::from(input_plane[(row0 + i) * pw + (col0 + j)]) - i64::from(pred[i * w + j]);
        }
    }
    let set = inter_tx_type_set(
        tx_size_sqr_index(tx_sz) as u32,
        TX_SIZE_SQR_UP[tx_sz] as u32,
        false,
    );
    let lambda = lambda_for(qp);
    // r424 โ€” the fork prices the TU at its block-relative 4-sample
    // position; the winner is committed after the election.
    let fork_xy = fork.as_ref().map(|(_, ctx)| {
        (
            (col0 as u32 - ctx.base_x) / 4,
            (row0 as u32 - ctx.base_y) / 4,
        )
    });
    let mut best: Option<(Vec<i32>, Vec<i64>, u8, u64)> = None;
    for t in 0..crate::cdf::TX_TYPES {
        let admissible = t == DCT_DCT || (set > 0 && is_tx_type_in_set(true, set, t));
        if !admissible {
            continue;
        }
        let coeffs = forward_transform_2d(&residual, tx_sz, t, false);
        // r439 โ€” luma ยง5.9.12 QM row (15 = the no-QM ยง7.12.3
        // short-circuit; the QM election arms it on unsegmented lossy
        // frames โ€” the bundle's segment-0 row is the coded one).
        let qm = qp.seg_qm_level[0][0];
        let quant = repack_compact(forward_quantize(&coeffs, tx_sz, 0, 0, t, qm, qp), w, h);
        let all_zero = quant.iter().all(|&q| q == 0);
        let dequant = dequantize_step1(&quant, tx_sz, 0, 0, t, qm, qp);
        let res_back = inverse_transform_2d(&dequant, tx_sz, t, u32::from(qp.bit_depth), false);
        // ยง7.12.3 step-3 destination remap (FLIPADST family).
        let (flip_ud, flip_lr) = crate::encoder::key_frame::step3_flips(t);
        let mut d = 0u64;
        for i in 0..h {
            let yy = if flip_ud { h - 1 - i } else { i };
            for j in 0..w {
                let xx = if flip_lr { w - 1 - j } else { j };
                let rec = (i64::from(pred[yy * w + xx]) + res_back[i * w + j]).clamp(0, max_val);
                let diff = i64::from(input_plane[(row0 + yy) * pw + (col0 + xx)]) - rec;
                d += (diff * diff) as u64;
            }
        }
        let label = if all_zero { DCT_DCT as u8 } else { t as u8 };
        // r424 โ€” exact ยง5.11.39 chain bits through the running fork,
        // or the pre-r424 magnitude proxy. One scale per call.
        let score = match (&fork, fork_xy) {
            (Some((tu_fork, ctx)), Some((fx, fy))) => {
                let bits256 = tu_fork.price_luma_tu(ctx, tx_sz, fx, fy, &quant, label)?;
                crate::encoder::rate_twin::score256(d, lambda, bits256)
            }
            _ => {
                let mut rate = 0u64;
                for &qv in &quant {
                    if qv != 0 {
                        rate += 3 + u64::from(32 - qv.unsigned_abs().leading_zeros());
                    }
                }
                d + lambda * rate
            }
        };
        let improves = match best.as_ref() {
            Some((_, _, _, s)) => score < *s,
            None => true,
        };
        if improves {
            best = Some((quant, res_back, label, score));
        }
        // A below-floor residual at DCT_DCT is pred-exact โ€” skip the
        // remaining trials (they commit the same all-zero shape).
        if t == DCT_DCT && all_zero {
            break;
        }
    }
    let (quant, res_back, label, _) = best.expect("DCT_DCT is always admissible");
    // r424 โ€” commit the elected TU into the fork: the next TU's
    // candidates price against the true post-TU CDF / context state.
    if let (Some((tu_fork, ctx)), Some((fx, fy))) = (fork, fork_xy) {
        tu_fork.commit_luma_tu(ctx, tx_sz, fx, fy, &quant, label)?;
    }
    // NOTE: the winning trial's `label` may be DCT_DCT (all-zero) even
    // though `res_back` came from a FLIPADST trial โ€” but an all-zero
    // TU's residual is identically zero, so the remap is inert there;
    // for coded TUs `label` IS the trial type.
    let (flip_ud, flip_lr) = crate::encoder::key_frame::step3_flips(label as usize);
    for i in 0..h {
        let yy = if flip_ud { h - 1 - i } else { i };
        for j in 0..w {
            let xx = if flip_lr { w - 1 - j } else { j };
            let p = i64::from(pred[yy * w + xx]) + res_back[i * w + j];
            recon_plane[(row0 + yy) * pw + (col0 + xx)] = p.clamp(0, max_val) as u16;
        }
    }
    Ok((quant, label))
}

/// ยง5.11.17 uniform split-decision tree of the given depth rooted at
/// `tx` (r412: rect-aware โ€” the per-split child count is
/// `(h4 / stepH) * (w4 / stepW)`, 4 for square ordinals and 2 for
/// rectangular ones, matching [`VarTxSyntaxTree::Split`]'s contract).
pub(crate) fn uniform_var_tx_tree(tx: usize, depth: u32) -> VarTxSyntaxTree {
    if depth == 0 {
        VarTxSyntaxTree::Leaf
    } else {
        let sub = SPLIT_TX_SIZE[tx];
        let count = (TX_HEIGHT[tx] / TX_HEIGHT[sub]) * (TX_WIDTH[tx] / TX_WIDTH[sub]);
        VarTxSyntaxTree::Split(
            (0..count)
                .map(|_| uniform_var_tx_tree(sub, depth - 1))
                .collect(),
        )
    }
}

/// Residual-code one inter leaf at uniform ยง5.11.17 depth `depth`
/// (`0` = one `Max_Tx_Size_Rect` TU; the lossless arm ignores `depth`
/// and codes the `TX_4X4` grid). Consumes the prediction already in
/// `ictx.scratch`.
#[allow(clippy::too_many_arguments)]
fn encode_inter_leaf_residual(
    mi_r: u32,
    mi_c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &PSearchCtx,
    ref_frame: [i8; 2],
    y_mode: u8,
    mv: [[i32; 2]; 2],
    ref_mv_idx: u32,
    filter: u8,
    comp: CompoundSel,
    // r417 โ€” the committed ยง5.11.28 selection: `Some((mode, wedge))`
    // rides a single-reference leaf whose scratch prediction the
    // caller already ran through the inter-intra arm.
    ii: Option<(u8, Option<u8>)>,
    // r419 โ€” the committed ยง5.11.27 ordinal (the caller's final
    // `predict_leaf` already ran the matching prediction arm).
    motion_mode: u8,
    depth: u32,
    segment_id: u8,
    seg_qp: &QuantizerParams,
    // r424 โ€” `Some` threads a running per-TU twin fork through the
    // luma residual chain: each ยง5.11.47 tx-type candidate prices its
    // ACTUAL ยง5.11.39 coefficient chain (see [`TuFork`]).
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
) -> Result<SyntaxBlock, Error> {
    let bw4 = NUM_4X4_BLOCKS_WIDE[b_size];
    let bh4 = NUM_4X4_BLOCKS_HIGH[b_size];
    let (bw, bh) = (bw4 * 4, bh4 * 4);
    let row0 = (mi_r as usize) * 4;
    let col0 = (mi_c as usize) * 4;
    let width = recon.width;
    // r426 โ€” the leaf's OWN ยง5.9.2 `Lossless = LosslessArray[
    // segment_id ]` (per-segment on mixed frames; uniform on the
    // CodedLossless and plain-lossy configurations).
    let lossless = ictx.seg_lossless(segment_id);
    let qp = *seg_qp;
    // r424 โ€” the running per-TU fork (lossy arm only: the lossless
    // ยง5.11.47 guard never codes a tx-type symbol and the TU chain is
    // not searched).
    let mut tu_fork = match (&pricing, lossless) {
        (Some((twin, _)), false) => Some(twin.tu_fork()),
        _ => None,
    };
    let tu_ctx = pricing.map(|(_, params)| TuCtx {
        params,
        mi_row: mi_r,
        mi_col: mi_c,
        mi_size: b_size,
        base_x: col0 as u32,
        base_y: row0 as u32,
        is_inter: true,
        segment_id,
        y_mode: 0,
        use_filter_intra: false,
        filter_intra_mode: None,
    });

    // --- Luma residual over the ยง5.11.36 TU walk. ---
    let luma_tx = if lossless {
        TX_4X4
    } else {
        let mut t = MAX_TX_SIZE_RECT[b_size];
        for _ in 0..depth {
            t = SPLIT_TX_SIZE[t];
        }
        t
    };
    let (ltw, lth) = (TX_WIDTH[luma_tx], TX_HEIGHT[luma_tx]);
    let mut tu_order: Vec<(usize, usize)> = Vec::new();
    if lossless {
        // ยง5.11.34 direct row-major iteration (the `!is_inter ||
        // Lossless` arm).
        let mut ty = 0usize;
        while ty < bh {
            let mut tx = 0usize;
            while tx < bw {
                tu_order.push((tx, ty));
                tx += ltw;
            }
            ty += lth;
        }
    } else {
        // ยง5.11.36 transform-tree recursion order (`Max_Tx_Size_Rect`
        // covers the whole block, so exactly one tree โ€” its
        // uniform-depth leaves in the ยง5.11.17 row-major visit).
        transform_tree_tu_order(0, 0, MAX_TX_SIZE_RECT[b_size], depth, &mut tu_order);
    }
    let mut residual_quant: Vec<Vec<i32>> = Vec::new();
    let mut luma_tx_types: Vec<u8> = Vec::new();
    // Block-relative luma-TU-grid map of committed ยง5.11.47 types โ€”
    // the ยง5.11.40 chroma-inheritance source (`TxTypes[ y4 ][ x4 ]`).
    let tu_cols = bw / ltw;
    let mut tu_type_grid = vec![DCT_DCT as u8; tu_cols * (bh / lth)];
    for &(tx, ty) in &tu_order {
        let (tr, tc) = (row0 + ty, col0 + tx);
        let mut pred = vec![0u16; ltw * lth];
        for i in 0..lth {
            for j in 0..ltw {
                pred[i * ltw + j] = ictx.scratch[0][(tr + i) * width + (tc + j)];
            }
        }
        let (q, tt) = if lossless {
            (
                residual_tx(
                    &input.y,
                    &mut recon.y,
                    width,
                    tr,
                    tc,
                    luma_tx,
                    &pred,
                    0,
                    lossless,
                    DCT_DCT,
                    &qp,
                ),
                DCT_DCT as u8,
            )
        } else {
            // r411: ยง5.11.47 per-TU luma transform-type RD search over
            // the ยง5.11.48 INTER set for this TX size (r424: exact
            // chain pricing through the running fork when priced).
            residual_tx_search_luma_inter(
                &input.y,
                &mut recon.y,
                width,
                tr,
                tc,
                luma_tx,
                &pred,
                &qp,
                match (&mut tu_fork, &tu_ctx) {
                    (Some(f), Some(c)) => Some((f, c)),
                    _ => None,
                },
            )?
        };
        tu_bd_stamp(&mut recon.bd, 0, tc, tr, ltw, lth);
        residual_quant.push(q);
        luma_tx_types.push(tt);
        tu_type_grid[(ty / lth) * tu_cols + tx / ltw] = tt;
    }

    // --- Chroma (ยง5.11.34 `HasChroma` gate โ€” r416). ---
    // A sub-8ร—8 leaf has chroma only on the bottom / right cell of
    // its 2ร—2 group (`bh4 == 1 && even MiRow` or `bw4 == 1 && even
    // MiCol` โ‡’ no chroma planes); the `HasChroma` block's chroma
    // region is the ยง5.11.38 plane residual size of the block โ€”
    // covering the WHOLE group at the `(MiCol >> subX) * MI_SIZE`
    // lifted origin. ยง5.11.34: the chroma TU size derives from the
    // block's committed `TxSize` โ€” on the ยง5.11.16 var-tx arm that is
    // the recursion's last terminal-else `txSz` (the uniform TU size
    // here).
    let has_chroma = recon.num_planes > 1
        && (bh4 != 1 || recon.subsampling_y == 0 || (mi_r & 1) == 1)
        && (bw4 != 1 || recon.subsampling_x == 0 || (mi_c & 1) == 1);
    let (crow0, ccol0) = recon.chroma_origin(mi_r, mi_c);
    let (cbw, cbh) = match crate::cdf::get_plane_residual_size(
        b_size,
        1,
        recon.subsampling_x,
        recon.subsampling_y,
    ) {
        Some(psz) => (NUM_4X4_BLOCKS_WIDE[psz] * 4, NUM_4X4_BLOCKS_HIGH[psz] * 4),
        None => (0, 0),
    };
    let chroma_tx = if lossless {
        TX_4X4
    } else {
        get_tx_size(1, luma_tx, b_size, recon.subsampling_x, recon.subsampling_y).unwrap_or(TX_4X4)
    };
    let (ctw, cth) = (TX_WIDTH[chroma_tx], TX_HEIGHT[chroma_tx]);
    // ยง5.11.48 inter set at the CHROMA TX size โ€” the ยง5.11.40
    // inheritance filter.
    let chroma_set = inter_tx_type_set(
        tx_size_sqr_index(chroma_tx) as u32,
        TX_SIZE_SQR_UP[chroma_tx] as u32,
        false,
    );
    let cw = recon.chroma_w;
    let (lift_x_sh, lift_y_sh) = (
        2 + u32::from(recon.subsampling_x),
        2 + u32::from(recon.subsampling_y),
    );
    for plane in 1..usize::from(recon.num_planes) {
        if !has_chroma {
            break;
        }
        let mut ty = 0usize;
        while ty < cbh {
            let mut tx = 0usize;
            while tx < cbw {
                let (tr, tc) = (crow0 + ty, ccol0 + tx);
                // ยง5.11.40 inter-chroma `TxType`: the luma cell at the
                // subsampling-lifted position `Max( MiRow/MiCol,
                // blockY/blockX << sub )`, filtered by the chroma-size
                // inter set. For >= 8ร—8 blocks the lift walks the
                // block's own luma TUs; on a sub-8ร—8 `HasChroma` leaf
                // the `Max` clip binds to the leaf origin (its own
                // first TU).
                let chroma_tt = if lossless || TX_SIZE_SQR_UP[chroma_tx] > crate::cdf::TX_32X32 {
                    DCT_DCT
                } else {
                    let lifted_x = ((tc >> 2) << lift_x_sh).saturating_sub(col0);
                    let lifted_y = ((tr >> 2) << lift_y_sh).saturating_sub(row0);
                    let luma_tt =
                        tu_type_grid[(lifted_y / lth) * tu_cols + lifted_x / ltw] as usize;
                    if crate::cdf::is_tx_type_in_set(true, chroma_set, luma_tt) {
                        luma_tt
                    } else {
                        DCT_DCT
                    }
                };
                let mut pred = vec![0u16; ctw * cth];
                for i in 0..cth {
                    for j in 0..ctw {
                        pred[i * ctw + j] = ictx.scratch[plane][(tr + i) * cw + (tc + j)];
                    }
                }
                let plane_buf = if plane == 1 {
                    &mut recon.u
                } else {
                    &mut recon.v
                };
                let q = residual_tx(
                    if plane == 1 { &input.u } else { &input.v },
                    plane_buf,
                    cw,
                    tr,
                    tc,
                    chroma_tx,
                    &pred,
                    plane as u8,
                    lossless,
                    chroma_tt,
                    &qp,
                );
                tu_bd_stamp(&mut recon.bd, plane, tc, tr, ctw, cth);
                residual_quant.push(q);
                tx += ctw;
            }
            ty += cth;
        }
    }

    // ยง5.11.11 skip: 1 iff every TU quantised to zero (the recon then
    // equals the bare prediction on every plane). A skip leaf takes
    // the ยง5.11.16 else arm โ€” no ยง5.11.17 trees.
    let all_zero = residual_quant.iter().all(|tu| tu.iter().all(|&q| q == 0));
    let skip = u8::from(all_zero);
    if all_zero {
        residual_quant.clear();
        luma_tx_types.clear();
    }
    // An all-DCT_DCT vector is the writer's back-compat default โ€”
    // commit the compact empty form.
    if luma_tx_types.iter().all(|&t| t == DCT_DCT as u8) {
        luma_tx_types.clear();
    }

    let mut block = SyntaxBlock::skip_leaf(0, None);
    block.skip = skip;
    // r413 โ€” ยง5.11.19/ยง5.11.20: a `skip == 1` leaf's segment_id is the
    // bit-silent `pred` cascade; a coded leaf commits the segment its
    // residual was quantised at.
    // r426 โ€” under ยง5.9.14 `SegIdPreSkip = 1` (any inter-override
    // feature active) the segment id codes BEFORE skip, so a skip
    // leaf keeps its own committed segment.
    block.segment_id = if skip == 1 && !ictx.seg_id_pre_skip {
        ictx.segment_pred(mi_r, mi_c)
    } else {
        segment_id
    };
    block.residual_quant = residual_quant.into();
    block.residual_tx_type = luma_tx_types;
    if !lossless && skip == 0 && b_size > crate::cdf::BLOCK_4X4 {
        // ยง5.11.16 var-tx arm: one uniform tree per max-TU position
        // (`Max_Tx_Size_Rect` covers every block this driver codes).
        // BLOCK_4X4 takes the ยง5.11.16 else arm (`read_tx_size`) with
        // no trees.
        block.var_tx_trees = vec![uniform_var_tx_tree(MAX_TX_SIZE_RECT[b_size], depth)];
    }
    block.inter = Some(SyntaxInterBlock {
        ref_frame,
        y_mode,
        mv,
        ref_mv_idx,
        interp_filter: [filter; 2],
        skip_mode: 0,
        // r417 โ€” inter-intra leaves commit the ยง5.11.29 bit-silent
        // derivation (the write pass validates the exact value).
        compound_type: match ii {
            Some((_, Some(_))) => crate::inter_pred::COMPOUND_WEDGE,
            Some(_) => crate::inter_pred::COMPOUND_INTRA,
            None => comp.ctype,
        },
        wedge_index: comp.wedge_index,
        wedge_sign: comp.wedge_sign,
        mask_type: comp.mask_type,
        interintra_mode: ii.map(|(m, _)| m),
        wedge_interintra: u8::from(matches!(ii, Some((_, Some(_))))),
        interintra_wedge_index: ii.and_then(|(_, w)| w).unwrap_or(0),
        motion_mode,
    });
    Ok(block)
}

/// Crude per-leaf rate proxy for the RD decisions โ€” [`leaf_rate`]'s
/// coefficient model plus an MV-magnitude term for NEWMV leaves and a
/// small intra surcharge (intra blocks in inter frames also code
/// `is_inter = 0` against a heavily-inter-biased context).
fn p_leaf_rate(block: &SyntaxBlock) -> u64 {
    // r413 โ€” a skip-mode leaf codes ONE ยง5.11.10 S() and nothing else
    // (every other value is derived); keep a small constant so the
    // trial can actually win against coded leaves.
    if block.inter.as_ref().is_some_and(|ib| ib.skip_mode != 0) {
        return 2;
    }
    let mut rate = leaf_rate(block);
    match &block.inter {
        Some(ib) => {
            if ib.ref_frame[0] != 1 {
                // ยง5.11.25 single-ref cascade surcharge on the
                // non-LAST reference.
                rate += 1;
            }
            // r415 โ€” ยง5.11.29 masked side-data surcharge.
            match ib.compound_type {
                crate::inter_pred::COMPOUND_WEDGE => rate += 6,
                crate::inter_pred::COMPOUND_DIFFWTD => rate += 3,
                _ => {}
            }
            match ib.y_mode {
                MODE_NEWMV => {
                    let bits = |v: i32| u64::from(34 - v.unsigned_abs().leading_zeros());
                    rate += 6 + bits(ib.mv[0][0]) + bits(ib.mv[0][1]);
                }
                MODE_NEARESTMV => rate += 3,
                MODE_NEARMV => rate += 4 + u64::from(ib.ref_mv_idx.saturating_sub(1)),
                MODE_NEAREST_NEARESTMV => rate += 6,
                MODE_NEAR_NEARMV => rate += 7 + u64::from(ib.ref_mv_idx.saturating_sub(1)),
                MODE_NEW_NEWMV => {
                    let bits = |v: i32| u64::from(34 - v.unsigned_abs().leading_zeros());
                    rate += 8
                        + bits(ib.mv[0][0])
                        + bits(ib.mv[0][1])
                        + bits(ib.mv[1][0])
                        + bits(ib.mv[1][1]);
                }
                // GLOBALMV / GLOBAL_GLOBALMV / the remaining compound
                // modes โ€” cascade context bits plus headroom.
                _ => rate += 4 + 3 * u64::from(ib.ref_frame[1] > 0),
            }
        }
        None => rate += 16,
    }
    rate
}

/// Recursive rate proxy over a candidate subtree.
fn p_tree_rate(node: &SyntaxNode) -> u64 {
    match node {
        SyntaxNode::Leaf(b) => p_leaf_rate(b),
        SyntaxNode::Split(children) => 4 + children.iter().map(|c| p_tree_rate(c)).sum::<u64>(),
        SyntaxNode::Horz(_) | SyntaxNode::Vert(_) => {
            4 + node
                .asymmetric_blocks()
                .iter()
                .map(|b| p_leaf_rate(b))
                .sum::<u64>()
        }
        // r413 โ€” the EXT-alphabet shapes carry a slightly larger
        // partition-symbol weight.
        _ => {
            5 + node
                .asymmetric_blocks()
                .iter()
                .map(|b| p_leaf_rate(b))
                .sum::<u64>()
        }
    }
}

/// r426 โ€” the ยง5.11.22 INTRA fallback candidate with per-segment
/// lossless awareness: a leaf overlapping the exactness-demand mask
/// codes its intra arm ON THE LOSSLESS SEGMENT โ€” the KEY driver runs
/// with the segment's quantiser (`qindex = 0`) and the `Lossless`
/// leaf shape (TX_4X4 / WHT / row-major ยง5.11.34 walk), and every
/// candidate is priced carrying the committed segment id โ€” while
/// every other leaf keeps the r413 segment-0 shape. Skip leaves take
/// the ยง5.11.20 bit-silent pred cascade on both arms (a skip leaf in
/// a lossless coding pass has an all-zero qindex-0 residual, i.e. an
/// EXACT bare prediction, so the demand contract holds whatever
/// segment the cascade yields).
#[allow(clippy::too_many_arguments)]
fn encode_intra_candidate(
    r: u32,
    c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &PSearchCtx,
    pricing: Option<(&RateTwin, &SyntaxFrameParams)>,
) -> Result<SyntaxBlock, Error> {
    if !ictx.demands_exact(r, c, b_size) {
        let mut leaf = encode_leaf_sq(r, c, b_size, input, recon, pricing)?;
        // r413 โ€” a skip intra leaf inherits the ยง5.11.20 `pred`
        // (bit-silent); a coded intra leaf keeps segment 0 (its
        // residual ran at the frame quantiser โ€” `alt_q[ 0 ] == 0`).
        if !ictx.seg_alt_q.is_empty() && leaf.skip == 1 && !ictx.seg_id_pre_skip {
            leaf.segment_id = ictx.segment_pred(r, c);
            // r426 โ€” a lossless pred segment flips ยง5.11.15 to the
            // bit-silent TX_4X4 default; the skip leaf's lossy tx
            // commitment reverts to `None`.
            if ictx.seg_lossless(leaf.segment_id) {
                leaf.tx_size = None;
            }
        }
        stamp_delta_q(&mut leaf, b_size, ictx, pricing);
        return Ok(leaf);
    }
    let ll_seg = ictx
        .lossless_seg
        .expect("demand mask requires a lossless segment (validated at arm time)");
    // Scoped swap: the KEY driver reads its frame arm from
    // `recon.qp` / `recon.lossless`; the demanded leaf runs on the
    // lossless segment's qindex-0 configuration.
    let saved_qp = recon.qp;
    let saved_lossless = recon.lossless;
    // r429 โ€” keep the frame's real ยง6.4.1 `BitDepth` on the swapped-in
    // lossless bundle (the WHT chain's clip + the intra fallback's ฮป
    // are depth-keyed; see the `seg_qp` bug-fix note).
    recon.qp = QuantizerParams::neutral(0, saved_qp.bit_depth);
    recon.lossless = true;
    let out = crate::encoder::key_frame::encode_leaf_sq_seg(
        r,
        c,
        b_size,
        input,
        recon,
        pricing,
        Some(ll_seg),
    );
    recon.qp = saved_qp;
    recon.lossless = saved_lossless;
    let mut leaf = out?;
    // The ยง5.11.19 skip arm is bit-silent โ€” the override never
    // survives on a skip leaf (already applied inside the ladder for
    // priced candidates; re-derive here for the heuristic path).
    // r426: under SegIdPreSkip the id codes pre-skip and stands.
    if leaf.skip == 1 && !ictx.seg_id_pre_skip {
        leaf.segment_id = ictx.segment_pred(r, c);
    }
    stamp_delta_q(&mut leaf, b_size, ictx, pricing);
    Ok(leaf)
}

/// Recursive ยง5.11.4 rate-distortion partition search for a P-frame:
/// at every fully-in-frame square node from `BLOCK_64X64` down to
/// `BLOCK_8X8`, trial-encode an INTER leaf and an INTRA leaf against
/// the same starting state, and (above `BLOCK_8X8`) both against a
/// `PARTITION_SPLIT` of four recursively-searched quadrants, keeping
/// the lowest `D + ฮปยทR`. `BLOCK_8X8` is the P-frame leaf floor (see
/// the module docs). Frame-edge nodes take the ยง5.11.4 forced split.
#[allow(clippy::too_many_arguments)]
fn build_p_search_tree(
    r: u32,
    c: u32,
    b_size: usize,
    input: &YuvFrame,
    recon: &mut ReconState,
    ictx: &mut PSearchCtx,
    twin: &mut RateTwin,
    params: &SyntaxFrameParams,
    model: RateModel,
) -> Result<(SyntaxNode, u64), Error> {
    if r >= recon.mi_rows || c >= recon.mi_cols {
        return Ok((SyntaxNode::dummy_oob(), 0));
    }
    // r416 โ€” sub-8ร—8 floor: a BLOCK_4X4 node (reachable only through
    // PARTITION_SPLIT at BLOCK_8X8, and always fully inside โ€” dims
    // are multiples of 8) is a single leaf. r417 โ€” the r416
    // inter-only policy is lifted: the node RD-trials the ยง5.11.22
    // INTRA arm against the fully-searched inter leaf (the same
    // A-vs-B comparison the >= 8ร—8 nodes run). A mixed 2ร—2 group
    // (`RefFrames[ .. ][ 0 ] == INTRA_FRAME` on any cell) drives the
    // ยง5.11.33 `someUseIntra` chroma arm on the group's inter
    // `HasChroma` leaf โ€” the search predicts through the decoder's
    // own driver over the live grids, so the split is exact on both
    // sides.
    if b_size == BLOCK_4X4 {
        let lambda = lambda_for(&recon.qp);
        // Group-aligned snapshot rect: a `HasChroma` 4ร—4 leaf codes
        // the WHOLE 2ร—2 group's chroma (ยง5.11.38 plane residual size
        // at the lifted origin) โ€” trials must not leak between arms.
        let (sr, sc) = (r & !1, c & !1);
        let before = save_region_wh(recon, sr, sc, 2, 2);
        let m_before = ictx.mirror.snapshot_encoder_stamp_rect(r, c, 1);

        // Candidate A: the fully-searched INTER leaf.
        let inter_leaf = encode_inter_leaf(
            r,
            c,
            b_size,
            input,
            recon,
            ictx,
            (model == RateModel::Twin).then_some((&*twin, params)),
        )?;
        ictx.stamp_leaf(
            &inter_leaf,
            r,
            c,
            b_size,
            ictx.seg_lossless(inter_leaf.segment_id),
        );
        let d_inter = region_distortion_wh(recon, input, sr, sc, 2, 2);
        let h_rate_inter = p_leaf_rate(&inter_leaf);
        let node_inter = SyntaxNode::Leaf(Box::new(inter_leaf));
        let mut twin_inter = twin.clone();
        let cost_inter = twin_inter.commit_subtree(&node_inter, r, c, b_size, params)?;
        let score_inter = match model {
            RateModel::Twin => score256(d_inter, lambda, cost_inter),
            RateModel::Heuristic => score256(d_inter, lambda, h_rate_inter * 256),
        };
        let after_inter = save_region_wh(recon, sr, sc, 2, 2);
        let m_after_inter = ictx.mirror.snapshot_encoder_stamp_rect(r, c, 1);
        restore_region(recon, sr, sc, &before);
        ictx.mirror.restore_encoder_stamp_rect(&m_before);

        // Candidate B: the ยง5.11.22 INTRA leaf (the KEY driver's 4ร—4
        // arm โ€” group-chroma coding on the `HasChroma` SE cell).
        let intra_leaf = encode_intra_candidate(
            r,
            c,
            b_size,
            input,
            recon,
            ictx,
            (model == RateModel::Twin).then_some((&*twin, params)),
        )?;
        ictx.stamp_leaf(
            &intra_leaf,
            r,
            c,
            b_size,
            ictx.seg_lossless(intra_leaf.segment_id),
        );
        let d_intra = region_distortion_wh(recon, input, sr, sc, 2, 2);
        let h_rate_intra = p_leaf_rate(&intra_leaf);
        let node_intra = SyntaxNode::Leaf(Box::new(intra_leaf));
        let mut twin_intra = twin.clone();
        let cost_intra = twin_intra.commit_subtree(&node_intra, r, c, b_size, params)?;
        let score_intra = match model {
            RateModel::Twin => score256(d_intra, lambda, cost_intra),
            RateModel::Heuristic => score256(d_intra, lambda, h_rate_intra * 256),
        };

        if score_inter <= score_intra {
            restore_region(recon, sr, sc, &after_inter);
            ictx.mirror.restore_encoder_stamp_rect(&m_after_inter);
            let SyntaxNode::Leaf(inter_leaf) = &node_inter else {
                unreachable!("candidate A is a leaf");
            };
            // Re-stamp the inter winner's mirror footprint (the intra
            // trial overwrote the mi cell); the driver grids already
            // hold the winner's stamps ([`encode_inter_leaf`]'s
            // final-predict guarantee โ€” candidate B never touches
            // them).
            ictx.stamp_leaf(
                inter_leaf,
                r,
                c,
                b_size,
                ictx.seg_lossless(inter_leaf.segment_id),
            );
            *twin = twin_inter;
            return Ok((node_inter, cost_inter));
        }
        // Driver-grid intra stamps for the committed winner: a later
        // group cell's ยง5.11.33 `someUseIntra` scan must see
        // `RefFrames[ .. ][ 0 ] == INTRA_FRAME` here.
        let SyntaxNode::Leaf(intra_leaf) = &node_intra else {
            unreachable!("candidate B is a leaf");
        };
        ictx.stamp_intra_leaf_grids(r, c, b_size, intra_leaf.y_mode);
        *twin = twin_intra;
        return Ok((node_intra, cost_intra));
    }
    let n4 = NUM_4X4_BLOCKS_WIDE[b_size] as u32;
    let half = n4 >> 1;
    let sub = crate::cdf::partition_subsize(crate::cdf::PARTITION_SPLIT, b_size)
        .ok_or(Error::PartitionWalkOutOfRange)?;
    let fully_inside = r + n4 <= recon.mi_rows && c + n4 <= recon.mi_cols;

    if !fully_inside {
        // ยง5.11.4 forced arms (dims are multiples of 8, so BLOCK_8X8
        // nodes are always fully inside and the recursion terminates;
        // the partition arm may still cost bits โ€” the `split_or_*`
        // half-straddle bools).
        let mut cost = twin.commit_partition_symbol(crate::cdf::PARTITION_SPLIT, r, c, b_size)?;
        let (nw, c0) = build_p_search_tree(r, c, sub, input, recon, ictx, twin, params, model)?;
        let (ne, c1) =
            build_p_search_tree(r, c + half, sub, input, recon, ictx, twin, params, model)?;
        let (sw, c2) =
            build_p_search_tree(r + half, c, sub, input, recon, ictx, twin, params, model)?;
        let (se, c3) = build_p_search_tree(
            r + half,
            c + half,
            sub,
            input,
            recon,
            ictx,
            twin,
            params,
            model,
        )?;
        cost += c0 + c1 + c2 + c3;
        let children = [Box::new(nw), Box::new(ne), Box::new(sw), Box::new(se)];
        return Ok((SyntaxNode::Split(children), cost));
    }

    let lambda = lambda_for(&recon.qp);
    let before = save_region(recon, r, c, n4 as usize);
    // r412: the driver mirror follows the same trial / rollback
    // discipline as the pixel planes โ€” every candidate leaves the
    // mirror holding ITS committed stamps, and the loser's stamps are
    // rolled back so subsequent ยง7.10.2 scans see only the winner.
    // r419: the ยง5.11.5 driver grids join the discipline โ€” the OBMC
    // neighbour scan reads committed above/left cells through them,
    // so a losing trial's stamps must not survive the node.
    let m_before = ictx.mirror.snapshot_encoder_stamp_rect(r, c, n4);
    let g_before = ictx.snapshot_grids_rect(r, c, n4);

    // Per-candidate scoring: exact twin bits (the candidate node's
    // full symbol sequence committed to a twin fork) under the twin
    // model, the pre-r421 proxies (scaled by 256 โ€” identical
    // decisions) under the heuristic model.
    let score_of = |d: u64, cost256: u64, h_rate: u64| -> u64 {
        match model {
            RateModel::Twin => score256(d, lambda, cost256),
            RateModel::Heuristic => score256(d, lambda, h_rate * 256),
        }
    };

    // Candidate A: one INTER leaf.
    let inter_leaf = encode_inter_leaf(
        r,
        c,
        b_size,
        input,
        recon,
        ictx,
        (model == RateModel::Twin).then_some((&*twin, params)),
    )?;
    ictx.stamp_leaf(
        &inter_leaf,
        r,
        c,
        b_size,
        ictx.seg_lossless(inter_leaf.segment_id),
    );
    let d_inter = region_distortion(recon, input, r, c, n4 as usize);
    let h_rate_inter = p_leaf_rate(&inter_leaf);
    let node_inter = SyntaxNode::Leaf(Box::new(inter_leaf));
    let mut twin_inter = twin.clone();
    let cost_inter = twin_inter.commit_subtree(&node_inter, r, c, b_size, params)?;
    let score_inter = score_of(d_inter, cost_inter, h_rate_inter);
    let after_inter = save_region(recon, r, c, n4 as usize);
    let m_after_inter = ictx.mirror.snapshot_encoder_stamp_rect(r, c, n4);
    let g_after_inter = ictx.snapshot_grids_rect(r, c, n4);
    restore_region(recon, r, c, &before);
    ictx.mirror.restore_encoder_stamp_rect(&m_before);
    ictx.restore_grids_rect(&g_before);

    // Candidate B: one INTRA leaf (ยง5.11.22 arm) with the KEY
    // driver's ยง5.11.15 tx_depth RD search (TX_MODE_SELECT on the
    // lossy arm; the lossless arm stays on the TX_4X4 grid).
    let intra_leaf = encode_intra_candidate(
        r,
        c,
        b_size,
        input,
        recon,
        ictx,
        (model == RateModel::Twin).then_some((&*twin, params)),
    )?;
    ictx.stamp_leaf(
        &intra_leaf,
        r,
        c,
        b_size,
        ictx.seg_lossless(intra_leaf.segment_id),
    );
    // r419 โ€” driver-grid intra stamps (the decode walker's grid-fill
    // twins): a later leaf's OBMC neighbour scan must see
    // `RefFrames[ .. ][ 0 ] == INTRA_FRAME` on a committed intra
    // region, exactly as the decoder will.
    ictx.stamp_intra_leaf_grids(r, c, b_size, intra_leaf.y_mode);
    let d_intra = region_distortion(recon, input, r, c, n4 as usize);
    let h_rate_intra = p_leaf_rate(&intra_leaf);
    let node_intra = SyntaxNode::Leaf(Box::new(intra_leaf));
    let mut twin_intra = twin.clone();
    let cost_intra = twin_intra.commit_subtree(&node_intra, r, c, b_size, params)?;
    let score_intra = score_of(d_intra, cost_intra, h_rate_intra);
    let after_intra = save_region(recon, r, c, n4 as usize);
    let m_after_intra = ictx.mirror.snapshot_encoder_stamp_rect(r, c, n4);
    let g_after_intra = ictx.snapshot_grids_rect(r, c, n4);
    restore_region(recon, r, c, &before);
    ictx.mirror.restore_encoder_stamp_rect(&m_before);
    ictx.restore_grids_rect(&g_before);

    // Running best over the non-split candidates: NONE-leaf first,
    // then the r412 HORZ / VERT rectangular trials. Each entry
    // carries its committed twin fork + exact cost.
    let mut best_node: (
        SyntaxNode,
        RegionSnapshot,
        _,
        DriverGridSnapshot,
        u64,
        RateTwin,
        u64,
    ) = if score_inter <= score_intra {
        (
            node_inter,
            after_inter,
            m_after_inter,
            g_after_inter,
            score_inter,
            twin_inter,
            cost_inter,
        )
    } else {
        (
            node_intra,
            after_intra,
            m_after_intra,
            g_after_intra,
            score_intra,
            twin_intra,
            cost_intra,
        )
    };

    // Candidates D..K: every asymmetric ยง5.11.4 partition โ€” r412
    // PARTITION_HORZ / PARTITION_VERT (two rectangular INTER halves)
    // plus the r413 EXT-alphabet shapes (HORZ_A / HORZ_B / VERT_A /
    // VERT_B T-shapes with mixed splitSize/subSize leaves, and the
    // HORZ_4 / VERT_4 four-strip shapes at BLOCK_16X16..=BLOCK_64X64).
    // Sub-blocks are encoded in ยง5.11.4 dispatch order, so each later
    // block's ยง7.10.2 scan and prediction see the earlier blocks'
    // stamps exactly as the decoder will. Intra sub-blocks stay the
    // NONE-leaf's and SPLIT's territory.
    let quarter = half >> 1;
    let split_sz = sub;
    for part in [
        PARTITION_HORZ,
        PARTITION_VERT,
        crate::cdf::PARTITION_HORZ_A,
        crate::cdf::PARTITION_HORZ_B,
        crate::cdf::PARTITION_VERT_A,
        crate::cdf::PARTITION_VERT_B,
        crate::cdf::PARTITION_HORZ_4,
        crate::cdf::PARTITION_VERT_4,
    ] {
        let psub = match crate::cdf::partition_subsize(part, b_size) {
            Some(sz) => sz,
            None => continue,
        };
        // ยง5.11.4: the EXT alphabet (T-shapes + HORZ_4 / VERT_4) only
        // exists above BLOCK_8X8 โ€” the 8ร—8 partition symbol is the
        // 4-value NONE / HORZ / VERT / SPLIT alphabet. (r416: the
        // former sub-8 strip skip is lifted โ€” HORZ / VERT at 8ร—8 code
        // 8ร—4 / 4ร—8 leaves and HORZ_4 / VERT_4 at 16ร—16 code 16ร—4 /
        // 4ร—16 strips.)
        if b_size == BLOCK_8X8 && !matches!(part, PARTITION_HORZ | PARTITION_VERT) {
            continue;
        }
        // r427 โ€” ยง5.11.38 admissibility: under 4:2:2 the tall shapes
        // (VERT 32ร—64, VERT_4 4ร—16 strips, ...) subsample to
        // BLOCK_INVALID chroma and must never be elected (see
        // `key_frame::chroma_partition_ok`).
        if !crate::encoder::key_frame::chroma_partition_ok(recon, psub) {
            continue;
        }
        // ยง5.11.4 sub-block geometry per partition, in dispatch order.
        let cells: Vec<(u32, u32, usize)> = match part {
            PARTITION_HORZ => vec![(r, c, psub), (r + half, c, psub)],
            PARTITION_VERT => vec![(r, c, psub), (r, c + half, psub)],
            crate::cdf::PARTITION_HORZ_A => vec![
                (r, c, split_sz),
                (r, c + half, split_sz),
                (r + half, c, psub),
            ],
            crate::cdf::PARTITION_HORZ_B => vec![
                (r, c, psub),
                (r + half, c, split_sz),
                (r + half, c + half, split_sz),
            ],
            crate::cdf::PARTITION_VERT_A => vec![
                (r, c, split_sz),
                (r + half, c, split_sz),
                (r, c + half, psub),
            ],
            crate::cdf::PARTITION_VERT_B => vec![
                (r, c, psub),
                (r, c + half, split_sz),
                (r + half, c + half, split_sz),
            ],
            crate::cdf::PARTITION_HORZ_4 => (0..4u32).map(|i| (r + quarter * i, c, psub)).collect(),
            _ => (0..4u32).map(|i| (r, c + quarter * i, psub)).collect(),
        };
        // r421 โ€” a RUNNING twin fork threads the shape's blocks in
        // ยง5.11.4 dispatch order: each later block's leaf-internal
        // pricing AND the writer's own commitment validation (the
        // ยง5.11.27 cascade in particular) see the earlier siblings'
        // committed mirror stamps, exactly like the emitting pass.
        let mut twin_shape = twin.clone();
        let mut cost_shape = twin_shape.commit_partition_symbol(part, r, c, b_size)?;
        let mut blocks: Vec<SyntaxBlock> = Vec::with_capacity(cells.len());
        let mut h_rate = if cells.len() == 2 { 4 } else { 5 };
        for &(rr, cc, sz) in &cells {
            let blk = encode_inter_leaf(
                rr,
                cc,
                sz,
                input,
                recon,
                ictx,
                (model == RateModel::Twin).then_some((&twin_shape, params)),
            )?;
            ictx.stamp_leaf(&blk, rr, cc, sz, ictx.seg_lossless(blk.segment_id));
            h_rate += p_leaf_rate(&blk);
            cost_shape += twin_shape.commit_block(&blk, rr, cc, sz, params)?;
            blocks.push(blk);
        }
        let d = region_distortion(recon, input, r, c, n4 as usize);
        let bx = |b: SyntaxBlock| Box::new(b);
        let node = match part {
            PARTITION_HORZ | PARTITION_VERT => {
                let mut it = blocks.into_iter();
                let pair = [bx(it.next().unwrap()), bx(it.next().unwrap())];
                if part == PARTITION_HORZ {
                    SyntaxNode::Horz(pair)
                } else {
                    SyntaxNode::Vert(pair)
                }
            }
            crate::cdf::PARTITION_HORZ_A
            | crate::cdf::PARTITION_HORZ_B
            | crate::cdf::PARTITION_VERT_A
            | crate::cdf::PARTITION_VERT_B => {
                let mut it = blocks.into_iter();
                let trio = [
                    bx(it.next().unwrap()),
                    bx(it.next().unwrap()),
                    bx(it.next().unwrap()),
                ];
                match part {
                    crate::cdf::PARTITION_HORZ_A => SyntaxNode::HorzA(trio),
                    crate::cdf::PARTITION_HORZ_B => SyntaxNode::HorzB(trio),
                    crate::cdf::PARTITION_VERT_A => SyntaxNode::VertA(trio),
                    _ => SyntaxNode::VertB(trio),
                }
            }
            _ => {
                let mut it = blocks.into_iter();
                let four = [
                    bx(it.next().unwrap()),
                    bx(it.next().unwrap()),
                    bx(it.next().unwrap()),
                    bx(it.next().unwrap()),
                ];
                if part == crate::cdf::PARTITION_HORZ_4 {
                    SyntaxNode::Horz4(four)
                } else {
                    SyntaxNode::Vert4(four)
                }
            }
        };
        let score = score_of(d, cost_shape, h_rate);
        if score < best_node.4 {
            best_node = (
                node,
                save_region(recon, r, c, n4 as usize),
                ictx.mirror.snapshot_encoder_stamp_rect(r, c, n4),
                ictx.snapshot_grids_rect(r, c, n4),
                score,
                twin_shape,
                cost_shape,
            );
        }
        restore_region(recon, r, c, &before);
        ictx.mirror.restore_encoder_stamp_rect(&m_before);
        ictx.restore_grids_rect(&g_before);
    }
    let (
        node_leafish,
        after_leafish,
        m_after_leafish,
        g_after_leafish,
        score_leafish,
        twin_leafish,
        cost_leafish,
    ) = best_node;

    // Candidate C: PARTITION_SPLIT into four recursively-searched
    // quadrants (NW/NE/SW/SE dispatch order โ€” the mirror currently
    // holds the pre-node state, so each child's ยง7.10.2 scan sees its
    // earlier siblings' committed stamps exactly as the write pass
    // will; the twin fork enters each child holding the SPLIT arm +
    // earlier siblings' symbols, exactly like the writer).
    let mut twin_split = twin.clone();
    let mut cost_split =
        twin_split.commit_partition_symbol(crate::cdf::PARTITION_SPLIT, r, c, b_size)?;
    let (nw, c0) = build_p_search_tree(
        r,
        c,
        sub,
        input,
        recon,
        ictx,
        &mut twin_split,
        params,
        model,
    )?;
    let (ne, c1) = build_p_search_tree(
        r,
        c + half,
        sub,
        input,
        recon,
        ictx,
        &mut twin_split,
        params,
        model,
    )?;
    let (sw, c2) = build_p_search_tree(
        r + half,
        c,
        sub,
        input,
        recon,
        ictx,
        &mut twin_split,
        params,
        model,
    )?;
    let (se, c3) = build_p_search_tree(
        r + half,
        c + half,
        sub,
        input,
        recon,
        ictx,
        &mut twin_split,
        params,
        model,
    )?;
    cost_split += c0 + c1 + c2 + c3;
    let children = [Box::new(nw), Box::new(ne), Box::new(sw), Box::new(se)];
    let d_split = region_distortion(recon, input, r, c, n4 as usize);
    let h_rate_split = children.iter().map(|ch| p_tree_rate(ch)).sum::<u64>() + 4;
    let score_split = score_of(d_split, cost_split, h_rate_split);

    if score_leafish <= score_split {
        restore_region(recon, r, c, &after_leafish);
        ictx.mirror.restore_encoder_stamp_rect(&m_after_leafish);
        ictx.restore_grids_rect(&g_after_leafish);
        *twin = twin_leafish;
        Ok((node_leafish, cost_leafish))
    } else {
        *twin = twin_split;
        Ok((SyntaxNode::Split(children), cost_split))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encoder::yuv_frame::ChromaFormat;

    /// 8-bit view of a `u16` recon plane for byte-comparisons against
    /// the spec driver's 8-bit output surface.
    fn plane8(p: &[u16]) -> Vec<u8> {
        p.iter().map(|&s| s as u8).collect()
    }

    /// Test shims over the r427 general GOP core (the historical
    /// per-surface entry shapes, YuvFrame inputs).
    fn gop_seg_yuv(frames: &[YuvFrame], q: u8, alt_q: &[i16]) -> Result<EncodedGopYuv, Error> {
        encode_gop_yuv_seg_extras_tuned(frames, q, alt_q, &[], false, None, GopTuning::default())
            .map(|t| t.gop)
    }

    /// r421 โ€” persistent per-tile search state for the module tests: a
    /// fresh rate-twin source (ยง8.3.1 default CDFs at the recon's
    /// quantiser, whole-frame single-tile write state, live emitting
    /// writer) plus the frame-scope parameter bundle from the search
    /// context's own inter params. Multi-superblock tests MUST reuse
    /// one of these across superblocks โ€” the twin's mirror carries the
    /// earlier superblocks' committed stamps exactly like the real
    /// driver's.
    struct TestTileState {
        cdfs: TileCdfContext,
        state: PartitionSyntaxWriter,
        writer: SymbolWriter,
        params: SyntaxFrameParams,
    }

    fn test_tile_state(recon: &ReconState, ictx: &PSearchCtx) -> TestTileState {
        let writer = SymbolWriter::new(false);
        let mut cdfs = TileCdfContext::new_from_defaults();
        cdfs.init_coeff_cdfs(recon.qp.base_q_idx);
        let state = PartitionSyntaxWriter::new(
            recon.mi_rows,
            recon.mi_cols,
            TileGeometry {
                mi_row_start: 0,
                mi_row_end: recon.mi_rows,
                mi_col_start: 0,
                mi_col_end: recon.mi_cols,
            },
        )
        .expect("test geometry is valid");
        let params = SyntaxFrameParams {
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            seg_id_pre_skip: false,
            segmentation_enabled: !ictx.seg_alt_q.is_empty(),
            seg_ref_frame: [None; crate::uncompressed_header_tail::MAX_SEGMENTS],
            seg_skip: [false; crate::uncompressed_header_tail::MAX_SEGMENTS],
            seg_globalmv: [false; crate::uncompressed_header_tail::MAX_SEGMENTS],
            last_active_seg_id: ictx.seg_alt_q.len().saturating_sub(1) as u8,
            lossless_array: seg_lossless_array(recon.qp.base_q_idx, &ictx.seg_alt_q),
            coded_lossless: recon.lossless,
            enable_cdef: false,
            allow_intrabc: false,
            cdef_bits: 0,
            read_deltas: false,
            use_128x128_superblock: false,
            delta_q_res: 0,
            delta_lf_present: false,
            delta_lf_multi: false,
            mono_chrome: false,
            delta_lf_res: 0,
            allow_screen_content_tools: recon.allow_screen_content_tools,
            enable_filter_intra: true,
            bit_depth: 8,
            tx_mode_select: !recon.lossless,
            quant: recon.qp,
            reduced_tx_set: false,
            inter: Some(ictx.ip.clone()),
        };
        TestTileState {
            cdfs,
            state,
            writer,
            params,
        }
    }

    /// Search one superblock under the twin model, then COMMIT it to
    /// the persistent tile state through the real write pass and
    /// assert the anti-desync invariant โ€” the driver loop's exact
    /// shape.
    fn search_and_commit_sb(
        ts: &mut TestTileState,
        r: u32,
        c: u32,
        input: &YuvFrame,
        recon: &mut ReconState,
        ictx: &mut PSearchCtx,
    ) -> Result<SyntaxNode, Error> {
        ts.state.arm_read_deltas();
        let mut twin = RateTwin::snapshot(&ts.cdfs, &ts.state, &ts.writer);
        twin.arm_read_deltas();
        let (node, _) = build_p_search_tree(
            r,
            c,
            BLOCK_64X64,
            input,
            recon,
            ictx,
            &mut twin,
            &ts.params,
            RateModel::Twin,
        )?;
        write_partition_tree_syntax(
            &mut ts.writer,
            &mut ts.cdfs,
            &mut ts.state,
            &node,
            r,
            c,
            BLOCK_64X64,
            &ts.params,
        )?;
        assert!(
            twin.matches(&ts.cdfs, &ts.writer),
            "rate twin desynced from the test tile writer after superblock ({r},{c})"
        );
        Ok(node)
    }

    /// Single-superblock convenience wrapper (the pre-r421 call shape).
    fn build_p_search_tree_for_tests(
        r: u32,
        c: u32,
        b_size: usize,
        input: &YuvFrame,
        recon: &mut ReconState,
        ictx: &mut PSearchCtx,
    ) -> Result<SyntaxNode, Error> {
        assert_eq!(b_size, BLOCK_64X64, "tests search whole superblocks");
        let mut ts = test_tile_state(recon, ictx);
        search_and_commit_sb(&mut ts, r, c, input, recon, ictx)
    }

    /// Deterministic textured frame with translation `(sy, sx)` โ€” the
    /// `gop_inter_conformance.rs` generator, duplicated here so the
    /// module test can drive the search internals directly.
    fn moving_gradient(w: u32, h: u32, shift_y: usize, shift_x: usize, seed: u32) -> YuvFrame {
        let (wu, hu) = (w as usize, h as usize);
        let s = seed as usize;
        let mut f = YuvFrame::filled(w, h, 8, ChromaFormat::Yuv420, 0);
        for i in 0..hu {
            for j in 0..wu {
                let (si, sj) = (i + shift_y, j + shift_x);
                f.y[i * wu + j] = ((si * 5 + sj * 3 + (si / 16) * (sj / 16) + s) % 256) as u16;
            }
        }
        let (cw, ch) = (wu / 2, hu / 2);
        for i in 0..ch {
            for j in 0..cw {
                let (si, sj) = (i + shift_y / 2, j + shift_x / 2);
                f.u[i * cw + j] = ((128 + si * 2 + sj + s) % 256) as u16;
                f.v[i * cw + j] = ((64 + si + sj * 2 + s) % 256) as u16;
            }
        }
        f
    }

    fn count_modes(node: &SyntaxNode, counts: &mut [u32; 4]) {
        match node {
            SyntaxNode::Leaf(b) => {
                if let Some(ib) = b.inter.as_ref() {
                    match ib.y_mode {
                        MODE_NEARESTMV => counts[0] += 1,
                        MODE_NEARMV => counts[1] += 1,
                        MODE_GLOBALMV => counts[2] += 1,
                        MODE_NEWMV => counts[3] += 1,
                        _ => {}
                    }
                }
            }
            SyntaxNode::Split(children) => {
                for ch in children.iter() {
                    count_modes(ch, counts);
                }
            }
            other => {
                let blocks = other.asymmetric_blocks();
                for b in blocks.iter() {
                    if let Some(ib) = b.inter.as_ref() {
                        match ib.y_mode {
                            MODE_NEARESTMV => counts[0] += 1,
                            MODE_NEARMV => counts[1] += 1,
                            MODE_GLOBALMV => counts[2] += 1,
                            MODE_NEWMV => counts[3] += 1,
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    /// r412 โ€” on uniformly translating content the ยง5.11.24 mode
    /// selection must actually REACH the stack-predicted modes: after
    /// the first leaves code NEWMV, every later leaf's ยง7.10.2 stack
    /// carries the shared vector, so NEARESTMV / NEARMV (no MV bits)
    /// dominate. The search tree is inspected directly; the emitted
    /// stream's conformance is covered by `gop_inter_conformance.rs`
    /// (the write pass re-derives every stack and rejects any
    /// driver / write mirror divergence).
    #[test]
    fn r412_p_search_selects_stack_predicted_modes_on_uniform_motion() {
        let f0 = moving_gradient(64, 64, 0, 0, 7);
        let f1 = moving_gradient(64, 64, 3, 5, 7);
        let base_q_idx = 60u8;
        let key = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f0, base_q_idx).unwrap();
        let reference = GopFrameReconYuv {
            y: key.recon_y,
            u: key.recon_u,
            v: key.recon_v,
        };
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&key.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let qp = QuantizerParams::neutral(base_q_idx, 8);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp,
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        let mut ictx = PSearchCtx::new(
            &reference,
            &reference,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f1, &mut recon, &mut ictx).unwrap();
        let mut counts = [0u32; 4];
        count_modes(&tree, &mut counts);
        let total: u32 = counts.iter().sum();
        assert!(total > 0, "uniform motion must produce inter leaves");
        assert!(
            counts[0] + counts[1] > 0,
            "at least one NEARESTMV / NEARMV leaf must be selected on \
             uniformly translating content (got NEAREST={} NEAR={} \
             GLOBAL={} NEW={})",
            counts[0],
            counts[1],
            counts[2],
            counts[3]
        );
        assert!(
            counts[3] > 0,
            "the first block of the shared-motion region still codes NEWMV \
             (its stack is empty); got NEW={}",
            counts[3]
        );
    }

    /// r412 โ€” the SWITCHABLE filter search must actually reach a
    /// non-EIGHTTAP choice when it is the distortion winner: the
    /// target P-frame is constructed as the reference's OWN
    /// EIGHTTAP_SHARP half-pel interpolation (through
    /// [`PSearchCtx::predict_leaf`], the same kernel the search
    /// scores with), so a SHARP-filtered leaf predicts it exactly and
    /// every committed inter leaf must carry EIGHTTAP_SHARP.
    #[test]
    fn r412_p_search_selects_sharp_filter_on_kernel_matched_content() {
        use crate::inter_pred::EIGHTTAP_SHARP;
        let f0 = moving_gradient(64, 64, 0, 0, 77);
        let base_q_idx = 90u8;
        let key = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f0, base_q_idx).unwrap();
        let reference = GopFrameReconYuv {
            y: key.recon_y,
            u: key.recon_u,
            v: key.recon_v,
        };
        // Target frame = SHARP half-pel interpolation of the reference.
        let mut f1 = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        {
            let ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
            let mut probe = PSearchCtx::new(
                &reference,
                &reference,
                16,
                16,
                64,
                64,
                ip,
                1,
                base_q_idx,
                &[],
            )
            .unwrap();
            probe
                .predict_leaf(
                    0,
                    0,
                    BLOCK_64X64,
                    [1, -1],
                    MODE_NEWMV,
                    [[0, 4], [0, 0]],
                    EIGHTTAP_SHARP,
                    CompoundSel::AVERAGE,
                    None,
                    MotionSel::Simple,
                )
                .unwrap();
            for (dst, &src) in f1.y.iter_mut().zip(probe.scratch[0].iter()) {
                *dst = src;
            }
            for (dst, &src) in f1.u.iter_mut().zip(probe.scratch[1].iter()) {
                *dst = src;
            }
            for (dst, &src) in f1.v.iter_mut().zip(probe.scratch[2].iter()) {
                *dst = src;
            }
        }
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&key.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        let mut ictx = PSearchCtx::new(
            &reference,
            &reference,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f1, &mut recon, &mut ictx).unwrap();
        fn count_filters(node: &SyntaxNode, counts: &mut [u32; 3]) {
            match node {
                SyntaxNode::Leaf(b) => {
                    if let Some(ib) = b.inter.as_ref() {
                        counts[usize::from(ib.interp_filter[0].min(2))] += 1;
                    }
                }
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count_filters(ch, counts);
                    }
                }
                other => {
                    let blocks = other.asymmetric_blocks();
                    for b in blocks.iter() {
                        if let Some(ib) = b.inter.as_ref() {
                            counts[usize::from(ib.interp_filter[0].min(2))] += 1;
                        }
                    }
                }
            }
        }
        let mut counts = [0u32; 3];
        count_filters(&tree, &mut counts);
        let sharp = counts[usize::from(EIGHTTAP_SHARP)];
        assert!(
            sharp > 0,
            "kernel-matched half-pel content must commit EIGHTTAP_SHARP \
             leaves (got EIGHTTAP={} SMOOTH={} SHARP={sharp})",
            counts[0],
            counts[1]
        );
    }

    /// r412 โ€” the HORZ/VERT rectangular trials must actually be
    /// selected where they beat NONE and SPLIT: content whose motion
    /// boundary bisects a square node horizontally makes the two
    /// 32x16 halves each uniform-motion (two MVs โ€” NONE cannot code
    /// that; SPLIT costs four leaves), so the tree must carry at
    /// least one HORZ node โ€” and the emitted GOP must round-trip
    /// byte-exact through the spec driver.
    #[test]
    fn r412_p_search_selects_horz_partition_on_band_motion() {
        // Frame k: rows [0, 16) shift right by 4k, rows [16, ..)
        // shift left by 4k โ€” the boundary bisects the top 32x32
        // quadrants at their halfway row.
        let band = |k: usize| -> YuvFrame {
            let (w, h) = (64usize, 64usize);
            let mut f = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
            let tex = |x: i64, y: i64| -> u16 {
                let (xu, yu) = ((x + 512) as usize, (y + 512) as usize);
                ((xu * 7 + yu * 3 + (xu / 8) * (yu / 8) * 5) % 256) as u16
            };
            for i in 0..h {
                // The two bands slide in opposite directions over the
                // same infinite texture (no wraparound seam).
                let s: i64 = if i < 16 {
                    4 * k as i64
                } else {
                    -4 * (k as i64)
                };
                for j in 0..w {
                    f.y[i * w + j] = tex(j as i64 - s, i as i64);
                }
            }
            let (cw, ch) = (w / 2, h / 2);
            for i in 0..ch {
                let s: i64 = if i < 8 { 2 * k as i64 } else { -2 * (k as i64) };
                for j in 0..cw {
                    let x = ((j as i64 - s) + 512) as usize;
                    f.u[i * cw + j] = ((128 + x * 2 + i) % 256) as u16;
                    f.v[i * cw + j] = ((64 + x + i * 2) % 256) as u16;
                }
            }
            f
        };
        let frames: Vec<YuvFrame> = (0..3).map(band).collect();
        let base_q_idx = 60u8;

        // Tree inspection on the P-frame search.
        let key =
            crate::encoder::key_frame::encode_key_frame_yuv_with_q(&frames[0], base_q_idx).unwrap();
        let reference = GopFrameReconYuv {
            y: key.recon_y.clone(),
            u: key.recon_u.clone(),
            v: key.recon_v.clone(),
        };
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&key.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        let mut ictx = PSearchCtx::new(
            &reference,
            &reference,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &frames[1], &mut recon, &mut ictx)
                .unwrap();
        fn count_rect(node: &SyntaxNode, horz: &mut u32, vert: &mut u32) {
            match node {
                SyntaxNode::Leaf(_) => {}
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count_rect(ch, horz, vert);
                    }
                }
                SyntaxNode::Horz(_) => *horz += 1,
                SyntaxNode::Vert(_) => *vert += 1,
                // r413 โ€” the EXT shapes count as neither HORZ nor VERT
                // for this witness.
                _ => {}
            }
        }
        let (mut horz, mut vert) = (0u32, 0u32);
        count_rect(&tree, &mut horz, &mut vert);
        assert!(
            horz > 0,
            "band-split motion must select at least one PARTITION_HORZ node \
             (got HORZ={horz} VERT={vert})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&frames, base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), frames.len());
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(f.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r412 โ€” the per-block reference selection must actually reach
    /// GOLDEN_FRAME where it wins: a flash GOP (frame 2 is unrelated
    /// noise, frame 3 repeats frame 1's content) makes frame 3
    /// predict far better from the frame-before-previous, so its
    /// search tree must carry GOLDEN leaves โ€” and the emitted GOP
    /// must round-trip byte-exact through the spec driver (proving
    /// the ยง5.9.2 two-slot refresh rotation + `ref_frame_idx` map
    /// against the ยง7.20 store).
    #[test]
    fn r412_p_search_selects_golden_reference_across_flash() {
        let calm = moving_gradient(64, 64, 0, 0, 5);
        let mut flash = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        let mut state = 0x1234_5678u32;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state
        };
        for v in flash.y.iter_mut() {
            *v = (next() & 0xFF) as u16;
        }
        // frames: KEY(calm), P1(flash), P2(calm again).
        let frames = vec![calm.clone(), flash, calm];
        let base_q_idx = 90u8;

        // Drive the P2 search directly: prev = P1 recon (flash),
        // prevprev = P1's prev = KEY recon (calm).
        let enc = encode_gop_yuv_with_q(&frames, base_q_idx).unwrap();
        let prev = enc.recon[1].clone();
        let prevprev = enc.recon[0].clone();
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&enc.seq, 64, 64, base_q_idx, 2, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        let mut ictx = PSearchCtx::new(
            &prev,
            &prevprev,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            2,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &frames[2], &mut recon, &mut ictx)
                .unwrap();
        fn count_refs(node: &SyntaxNode, golden: &mut u32, last: &mut u32) {
            let leafs = |b: &SyntaxBlock, golden: &mut u32, last: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.ref_frame[0] == 4 {
                        *golden += 1;
                    } else {
                        *last += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafs(b, golden, last),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count_refs(ch, golden, last);
                    }
                }
                other => {
                    let blocks = other.asymmetric_blocks();
                    for b in blocks.iter() {
                        leafs(b, golden, last);
                    }
                }
            }
        }
        let (mut golden, mut last) = (0u32, 0u32);
        count_refs(&tree, &mut golden, &mut last);
        assert!(
            golden > 0,
            "frame after a flash must select GOLDEN_FRAME leaves \
             (got GOLDEN={golden} LAST={last})"
        );

        // Full-stream conformance through the spec driver.
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), frames.len());
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(f.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r412 โ€” the COMPOUND_AVERAGE candidates must actually be
    /// selected where the two-reference mean is the distortion
    /// winner: the third frame is constructed as the PIXELWISE
    /// AVERAGE of the first two frames' reconstructions (LAST and
    /// GOLDEN under the two-slot rotation), so a
    /// { LAST, GOLDEN } GLOBAL_GLOBALMV / NEAREST_NEARESTMV leaf
    /// predicts it almost exactly while either single reference
    /// misses by half the inter-frame delta โ€” the search tree must
    /// carry compound leaves, and the emitted GOP must round-trip
    /// byte-exact through the spec driver.
    #[test]
    fn r412_p_search_selects_compound_average_on_blended_content() {
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        let f1 = moving_gradient(64, 64, 0, 0, 140);
        let base_q_idx = 60u8;
        // Two-frame pre-pass to obtain the deterministic recons.
        let pre = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();
        let mut f2 = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        let avg = |a: &[u16], b: &[u16], out: &mut [u16]| {
            for ((o, &x), &y) in out.iter_mut().zip(a).zip(b) {
                *o = (u32::from(x) + u32::from(y)).div_ceil(2) as u16;
            }
        };
        avg(&pre.recon[0].y, &pre.recon[1].y, &mut f2.y);
        avg(&pre.recon[0].u, &pre.recon[1].u, &mut f2.u);
        avg(&pre.recon[0].v, &pre.recon[1].v, &mut f2.v);

        // Drive the P2 search directly (prev = f1 recon in LAST,
        // prevprev = KEY recon in GOLDEN).
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 2, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        let mut ictx = PSearchCtx::new(
            &pre.recon[1],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            2,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f2, &mut recon, &mut ictx).unwrap();
        fn count_compound(node: &SyntaxNode, compound: &mut u32, single: &mut u32) {
            let leafc = |b: &SyntaxBlock, compound: &mut u32, single: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.ref_frame[1] > 0 {
                        *compound += 1;
                    } else {
                        *single += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, compound, single),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count_compound(ch, compound, single);
                    }
                }
                other => {
                    let blocks = other.asymmetric_blocks();
                    for b in blocks.iter() {
                        leafc(b, compound, single);
                    }
                }
            }
        }
        let (mut compound, mut single) = (0u32, 0u32);
        count_compound(&tree, &mut compound, &mut single);
        assert!(
            compound > 0,
            "average-blend content must select COMPOUND_AVERAGE leaves \
             (got COMPOUND={compound} SINGLE={single})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f2], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(f.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r413 โ€” static content on a skip-mode frame must select
    /// ยง5.11.10 `skip_mode = 1` leaves (the one-symbol pure-derivation
    /// block beats every coded candidate once the two reference
    /// reconstructions have converged), and the resulting stream must
    /// stay byte-exact through the spec driver.
    #[test]
    fn r413_p_search_selects_skip_mode_on_static_content() {
        let f = moving_gradient(64, 64, 2, 3, 21);
        let base_q_idx = 60u8;
        let frames = vec![f.clone(), f.clone(), f.clone(), f.clone()];
        let pre = encode_gop_yuv_with_q(&frames[..3], base_q_idx).unwrap();

        // Drive the P3 search directly (LAST = P2 recon, GOLDEN = P1
        // recon; `p_index = 3` โ‡’ skip_mode_present per ยง5.9.22).
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 3, &[]);
        assert_eq!(fh.skip_mode_present, Some(true), "P3 header presence");
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.order_hints = gop_order_hints(3, pre.seq.order_hint_bits);
        ip.skip_mode_present = true;
        ip.skip_mode_frame = [1, 4];
        let mut ictx = PSearchCtx::new(
            &pre.recon[2],
            &pre.recon[1],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            3,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f, &mut recon, &mut ictx).unwrap();
        fn count_skip_mode(node: &SyntaxNode, sm: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, sm: &mut u32, other: &mut u32| {
                if b.inter.as_ref().is_some_and(|ib| ib.skip_mode != 0) {
                    *sm += 1;
                } else {
                    *other += 1;
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, sm, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count_skip_mode(ch, sm, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, sm, other);
                    }
                }
            }
        }
        let (mut sm, mut other) = (0u32, 0u32);
        count_skip_mode(&tree, &mut sm, &mut other);
        assert!(
            sm > 0,
            "static content on a skip-mode frame must select skip_mode leaves \
             (got SKIP_MODE={sm} OTHER={other})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&frames, base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 4);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r413 โ€” SEG_LVL_ALT_Q P-frames: the activity policy must code
    /// MULTIPLE segments on mixed flat/textured content, coded leaves
    /// must quantise at their segment's q-index (byte-exact spec-driver
    /// decode proves the whole chain), and invalid configurations are
    /// rejected.
    #[test]
    fn r413_segmentation_alt_q_gop_round_trips() {
        // Mixed content: flat left half, textured right half โ€” the
        // MAD policy assigns different segments per leaf.
        let mut frames: Vec<YuvFrame> = Vec::new();
        for k in 0..3u32 {
            let mut f = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 100);
            for i in 0..64usize {
                for j in 32..64usize {
                    f.y[i * 64 + j] = ((i * 17 + j * 31 + (k as usize) * 5) % 256) as u16;
                }
            }
            for v in f.u.iter_mut() {
                *v = 90;
            }
            for v in f.v.iter_mut() {
                *v = 160;
            }
            frames.push(f);
        }
        let base_q_idx = 60u8;
        let alt_q: [i16; 3] = [0, 24, 48];

        let enc = gop_seg_yuv(&frames, base_q_idx, &alt_q).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }

        // Segment-diversity witness: drive the P1 search directly and
        // count distinct committed segment ids.
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&enc.seq, 64, 64, base_q_idx, 1, &alt_q);
        let sp = fh.segmentation_params.as_ref().unwrap();
        assert!(sp.enabled && sp.update_map && !sp.temporal_update && sp.update_data);
        assert_eq!(sp.last_active_seg_id, 2);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: {
                let mut q = QuantizerParams::neutral(base_q_idx, 8);
                q.segmentation_enabled = true;
                for (seg, &d) in alt_q.iter().enumerate() {
                    q.seg_alt_q_active[seg] = true;
                    q.seg_alt_q_data[seg] = d;
                }
                q
            },
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.order_hints = gop_order_hints(1, enc.seq.order_hint_bits);
        ip.segmentation_update_map = true;
        let mut ictx = PSearchCtx::new(
            &enc.recon[0],
            &enc.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &alt_q,
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &frames[1], &mut recon, &mut ictx)
                .unwrap();
        fn collect_segments(node: &SyntaxNode, seen: &mut [u32; 8]) {
            match node {
                SyntaxNode::Leaf(b) => seen[b.segment_id as usize] += 1,
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        collect_segments(ch, seen);
                    }
                }
                other => {
                    let blocks = other.asymmetric_blocks();
                    for b in blocks.iter() {
                        seen[b.segment_id as usize] += 1;
                    }
                }
            }
        }
        let mut seen = [0u32; 8];
        collect_segments(&tree, &mut seen);
        let distinct = seen.iter().filter(|&&n| n > 0).count();
        assert!(
            distinct >= 2,
            "mixed content must code multiple segments (histogram: {seen:?})"
        );

        // Invalid configurations reject. (r426: a delta clamping the
        // ยง7.12.2 qindex to 0 is no longer an error โ€” it is the
        // per-segment lossless election, covered by
        // `tests/mixed_lossless.rs` โ€” but unrepresentable su(1+8)
        // deltas, over-255 sums and base-0 segmentation still do.)
        assert!(gop_seg_yuv(&frames, 60, &[1, 2]).is_err());
        assert!(gop_seg_yuv(&frames, 60, &[0]).is_err());
        assert!(gop_seg_yuv(&frames, 60, &[0, -256]).is_err());
        assert!(gop_seg_yuv(&frames, 200, &[0, 100]).is_err());
        assert!(gop_seg_yuv(&frames, 0, &[0, 10]).is_err());
    }

    /// r413 โ€” tri-motion content shaped exactly like a ยง5.11.4
    /// T-shape (one clean half + two clean quarters) must select an
    /// EXT-alphabet partition over HORZ/VERT/SPLIT (3 sub-blocks beat
    /// 4 at equal distortion), and the emitted stream must stay
    /// byte-exact through the spec driver.
    #[test]
    fn r413_p_search_selects_t_shape_partitions() {
        // Frame k: top 64x32 band shifts by (0, 2k); bottom-left
        // 32x32 by (2k, 0); bottom-right 32x32 by (2k, 2k) โ€” the
        // HORZ_B geometry at BLOCK_64X64.
        let gen = |k: usize| -> YuvFrame {
            let mut f = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
            let tex = |i: usize, j: usize| ((i * 7 + j * 13 + (i / 8) * (j / 8)) % 256) as u16;
            for i in 0..64usize {
                for j in 0..64usize {
                    let (si, sj) = if i < 32 {
                        (i, j + 2 * k)
                    } else if j < 32 {
                        (i + 2 * k, j)
                    } else {
                        (i + 2 * k, j + 2 * k)
                    };
                    f.y[i * 64 + j] = tex(si, sj);
                }
            }
            for v in f.u.iter_mut() {
                *v = 110;
            }
            for v in f.v.iter_mut() {
                *v = 150;
            }
            f
        };
        let frames: Vec<YuvFrame> = (0..3).map(gen).collect();
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(&frames[..1], base_q_idx).unwrap();
        let key_recon = GopFrameReconYuv {
            y: pre.recon[0].y.clone(),
            u: pre.recon[0].u.clone(),
            v: pre.recon[0].v.clone(),
        };

        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.order_hints = gop_order_hints(1, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &key_recon,
            &key_recon,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &frames[1], &mut recon, &mut ictx)
                .unwrap();
        fn count_ext(node: &SyntaxNode, ext: &mut u32) {
            match node {
                SyntaxNode::HorzA(_)
                | SyntaxNode::HorzB(_)
                | SyntaxNode::VertA(_)
                | SyntaxNode::VertB(_)
                | SyntaxNode::Horz4(_)
                | SyntaxNode::Vert4(_) => *ext += 1,
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count_ext(ch, ext);
                    }
                }
                _ => {}
            }
        }
        let mut ext = 0u32;
        count_ext(&tree, &mut ext);
        assert!(
            ext > 0,
            "tri-motion content must select an EXT-alphabet partition (tree: {tree:?})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&frames, base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r413 โ€” use_ref_frame_mvs groundwork: on a moving GOP the
    /// encoder-side ยง7.9 projection must produce VALID temporal
    /// candidates from P2 on (P1's store holds only the intra KEY),
    /// and the emitted streams (non-error-resilient headers,
    /// `use_ref_frame_mvs = 1`) must stay byte-exact through the spec
    /// driver โ€” proving search mirror, write mirror and decoder all
    /// derive the same motion field.
    #[test]
    fn r413_motion_field_estimation_projects_from_p2() {
        let frames: Vec<YuvFrame> = (0..4)
            .map(|k| moving_gradient(64, 64, k * 3, k * 2, 9))
            .collect();
        let enc = encode_gop_yuv_with_q(&frames, 60).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 4);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }

        // Recompute P2's projection from a rebuilt store (KEY intra in
        // every slot, then P1's ยง7.19 payload in slot 0) and assert at
        // least one valid cell โ€” moving content stores real MVs.
        let fh1 = build_p_frame_yuv420_8bit_fh_with_q(&enc.seq, 64, 64, 60, 1, &[]);
        let fs = fh1.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let key_recon = GopFrameReconYuv {
            y: enc.recon[0].y.clone(),
            u: enc.recon[0].u.clone(),
            v: enc.recon[0].v.clone(),
        };
        let mf_store: [SavedMotionField; 8] =
            core::array::from_fn(|_| SavedMotionField::intra(mi_rows, mi_cols));
        let (_, _, saved1, _, _) = encode_p_frame_yuv(
            &frames[1],
            &key_recon,
            &key_recon,
            &enc.seq,
            60,
            1,
            &[],
            &mf_store,
            RateModel::Twin,
            true,
            None,
            true,
            None,
            false,
            None,
            true,
            true,
            true,
            true,
            true,
            true,
            (0, 0),
            1,
            false,
            None,
            false,
            None,
            0,
            &key_recon,
            false,
            false,
            false,
            None,
            None,
        )
        .unwrap();
        assert!(!saved1.frame_is_intra);
        assert!(
            saved1.mf_ref_frames.iter().any(|&r| r > 0),
            "P1 must store ยง7.19 motion-field candidates on moving content"
        );

        use crate::inter_pred::{motion_field_estimation_core, MotionFieldSlot};
        let mut slots: [Option<MotionFieldSlot<'_>>; 8] = [None; 8];
        let intra = SavedMotionField::intra(mi_rows, mi_cols);
        for (i, s) in slots.iter_mut().enumerate() {
            let src = if i == 0 { &saved1 } else { &intra };
            *s = Some(MotionFieldSlot {
                mf_mvs: &src.mf_mvs,
                mf_ref_frames: &src.mf_ref_frames,
                saved_order_hints: src.saved_order_hints,
                mi_rows: src.mi_rows,
                mi_cols: src.mi_cols,
                frame_is_intra: src.frame_is_intra,
            });
        }
        // P2 reads LAST from slot 0 (p_index = 2), GOLDEN from slot 1.
        let mut ref_frame_idx = [0u8; 7];
        ref_frame_idx[3] = 1;
        let hints2 = gop_order_hints(2, enc.seq.order_hint_bits);
        let mut order_hints = [0i32; 8];
        order_hints.copy_from_slice(&hints2.order_hints_by_ref);
        let mfmvs = motion_field_estimation_core(
            &slots,
            &ref_frame_idx,
            &order_hints,
            2,
            u32::from(enc.seq.order_hint_bits),
            mi_rows,
            mi_cols,
        );
        let mut valid = 0u32;
        for r in 1..=7usize {
            for y8 in 0..mfmvs.h8() {
                for x8 in 0..mfmvs.w8() {
                    if mfmvs.get(r, y8, x8)[0] != crate::cdf::MFMV_INVALID {
                        valid += 1;
                    }
                }
            }
        }
        assert!(
            valid > 0,
            "P2 ยง7.9 projection must land valid temporal candidates"
        );
    }

    /// r412 โ€” [`PSearchCtx::predict_leaf`] must thread the trial
    /// filter into the ยง7.11.3.4 kernel: an isolated impulse column
    /// interpolated at a half-pel phase produces distinct samples per
    /// filter family.
    #[test]
    fn r412_predict_leaf_threads_interp_filter() {
        use crate::inter_pred::{EIGHTTAP_SHARP, EIGHTTAP_SMOOTH};
        let mut refr = GopFrameReconYuv {
            y: vec![0u16; 64 * 64],
            u: vec![128u16; 32 * 32],
            v: vec![128u16; 32 * 32],
        };
        for i in 0..64 {
            for j in 0..64 {
                refr.y[i * 64 + j] = if j == 10 { 255 } else { 0 };
            }
        }
        let ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
        let mut ictx = PSearchCtx::new(&refr, &refr, 16, 16, 64, 64, ip, 1, 0, &[]).unwrap();
        let mut outs = Vec::new();
        for f in [EIGHTTAP, EIGHTTAP_SMOOTH, EIGHTTAP_SHARP] {
            ictx.predict_leaf(
                2,
                2,
                BLOCK_8X8,
                [1, -1],
                MODE_NEWMV,
                [[0, 4], [0, 0]],
                f,
                CompoundSel::AVERAGE,
                None,
                MotionSel::Simple,
            )
            .unwrap();
            let mut v = Vec::new();
            for i in 8..16 {
                for j in 8..16 {
                    v.push(ictx.scratch[0][i * 64 + j]);
                }
            }
            outs.push(v);
        }
        assert_ne!(
            outs[0], outs[1],
            "EIGHTTAP vs SMOOTH must differ at half-pel"
        );
        assert_ne!(
            outs[0], outs[2],
            "EIGHTTAP vs SHARP must differ at half-pel"
        );
    }

    /// r417 โ€” `predict_leaf` with an [`InterIntraTrial`] realises the
    /// ยง5.11.33 `IsInterIntra` arm in the search scratch: the
    /// ยง7.11.5-translated intra half (predicted from the committed
    /// recon's neighbours through the decode walker's ยง7.11.2 core)
    /// blends with the inter prediction through the decoder's own
    /// ยง7.11.3.14 driver, on luma AND chroma, and the ยง5.11.5 grid
    /// stamps mirror the decode walker's ยง5.11.28 imperative
    /// overrides (`RefFrame[ 1 ] = INTRA_FRAME`, the bit-silent
    /// ยง5.11.29 `compound_type` derivation, the inter-intra side-data
    /// grids).
    #[test]
    fn r417_predict_leaf_inter_intra_blends_intra_half() {
        // Reference: flat luma 100, flat chroma 128 โ‡’ the zero-MV
        // inter half is flat.
        let refr = GopFrameReconYuv {
            y: vec![100u16; 64 * 64],
            u: vec![128u16; 32 * 32],
            v: vec![128u16; 32 * 32],
        };
        // Committed recon (the ยง7.11.2 neighbour source): flat luma
        // 200, flat chroma 60 โ‡’ the II_V_PRED intra half is flat 200
        // (luma) / 60 (chroma) over the block.
        let mut recon = fresh_recon(64, 64, 60);
        recon.y.fill(200);
        recon.u.fill(60);
        recon.v.fill(60);
        let ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
        let mut ictx = PSearchCtx::new(&refr, &refr, 16, 16, 64, 64, ip, 1, 60, &[]).unwrap();

        // Smooth (non-wedge) inter-intra trial at mi (2, 2), 8x8.
        ictx.predict_leaf(
            2,
            2,
            BLOCK_8X8,
            [1, -1],
            MODE_NEWMV,
            [[0, 0], [0, 0]],
            EIGHTTAP,
            CompoundSel::AVERAGE,
            Some(InterIntraTrial {
                mode: crate::cdf::II_V_PRED,
                wedge: None,
                neigh: &recon,
            }),
            MotionSel::Simple,
        )
        .unwrap();
        let mut smooth_luma = Vec::new();
        for i in 8..16usize {
            for j in 8..16usize {
                let v = ictx.scratch[0][i * 64 + j];
                assert!(
                    (100..=200).contains(&v),
                    "blend out of the [inter, intra] envelope at ({i}, {j}): {v}"
                );
                smooth_luma.push(v);
            }
        }
        assert!(
            smooth_luma.iter().any(|&v| v > 100),
            "intra half must contribute to the luma blend"
        );
        assert_ne!(
            &smooth_luma[0..8],
            &smooth_luma[56..64],
            "the ยง7.11.3.14 smooth II mask varies down the block"
        );
        // Chroma blends too (inter 128 vs intra 60).
        let cu = ictx.scratch[1][4 * 32 + 4];
        assert!(
            (60..128).contains(&cu),
            "chroma blend must pull toward the intra half: {cu}"
        );
        // ยง5.11.5 grid stamps at the origin cell.
        let cell = 2 * 16 + 2;
        assert_eq!(
            ictx.ref_frames[cell * 2 + 1],
            0,
            "RefFrame[1] = INTRA_FRAME"
        );
        assert_eq!(ictx.interintra_modes[cell], crate::cdf::II_V_PRED);
        assert_eq!(ictx.wedge_interintras[cell], 0);
        assert_eq!(
            ictx.compound_types[cell],
            crate::inter_pred::COMPOUND_INTRA,
            "ยง5.11.29 bit-silent derivation on the non-wedge arm"
        );

        // Wedge sub-arm: a different ยง7.11.3.11 mask โ‡’ different blend.
        ictx.predict_leaf(
            2,
            2,
            BLOCK_8X8,
            [1, -1],
            MODE_NEWMV,
            [[0, 0], [0, 0]],
            EIGHTTAP,
            CompoundSel::AVERAGE,
            Some(InterIntraTrial {
                mode: crate::cdf::II_V_PRED,
                wedge: Some(7),
                neigh: &recon,
            }),
            MotionSel::Simple,
        )
        .unwrap();
        let mut wedge_luma = Vec::new();
        for i in 8..16usize {
            for j in 8..16usize {
                wedge_luma.push(ictx.scratch[0][i * 64 + j]);
            }
        }
        assert_ne!(smooth_luma, wedge_luma, "wedge mask differs from smooth");
        assert_eq!(ictx.wedge_interintras[cell], 1);
        assert_eq!(ictx.interintra_wedge_indices[cell], 7);
        assert_eq!(ictx.compound_types[cell], crate::inter_pred::COMPOUND_WEDGE);

        // A subsequent plain trial restores the non-inter-intra stamps.
        ictx.predict_leaf(
            2,
            2,
            BLOCK_8X8,
            [1, -1],
            MODE_NEWMV,
            [[0, 0], [0, 0]],
            EIGHTTAP,
            CompoundSel::AVERAGE,
            None,
            MotionSel::Simple,
        )
        .unwrap();
        assert_eq!(ictx.ref_frames[cell * 2 + 1], -1);
        assert_eq!(ictx.wedge_interintras[cell], 0);
        assert_eq!(ictx.interintra_modes[cell], 0);
        for i in 8..16usize {
            for j in 8..16usize {
                assert_eq!(
                    ictx.scratch[0][i * 64 + j],
                    100,
                    "plain zero-MV inter pred is the flat reference"
                );
            }
        }
    }

    /// r412 โ€” the driver mirror must agree with the WRITE mirror leaf
    /// for leaf: a full multi-superblock lossy GOP encode (which
    /// re-runs ยง7.10.2 per leaf inside `write_partition_tree_syntax`
    /// and hard-errors on any committed non-NEWMV MV that differs
    /// from the write-side derivation) must succeed and self-decode
    /// byte-exact through the spec driver.
    #[test]
    fn r412_gop_with_stack_modes_round_trips_through_spec_driver() {
        let frames: Vec<YuvFrame> = (0..4)
            .map(|k| moving_gradient(96, 80, 2 * k, 4 * k, 31))
            .collect();
        let enc = encode_gop_yuv_with_q(&frames, 80).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), frames.len());
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(f.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r415 โ€” a B-frame search context: `refs[ 0 ]` = the forward
    /// anchor (LAST, hint 0), `refs[ 1 ]` = the backward reference
    /// (BWDREF/ALTREF2/ALTREF, hint 2), current hint 1 โ€” ยง7.8 sign
    /// bias 1 on the backward ordinals.
    fn b_frame_ctx<'a>(
        anchor: &'a GopFrameReconYuv,
        future: &'a GopFrameReconYuv,
        mi_rows: u32,
        mi_cols: u32,
        base_q_idx: u8,
        skip_mode: bool,
    ) -> PSearchCtx {
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.order_hints = crate::cdf::FrameInterOrderHints {
            order_hint_bits: 7,
            current_order_hint: 1,
            order_hints_by_ref: [0, 0, 0, 0, 0, 2, 2, 2],
        };
        for r in 5..=7usize {
            ip.ref_frame_sign_bias[r] = 1;
        }
        ip.skip_mode_present = skip_mode;
        ip.skip_mode_frame = [1, 5];
        let mut slot_to_plane = [0usize; 8];
        slot_to_plane[1] = 1;
        let mut ref_frame_idx = [0u8; 7];
        ref_frame_idx[4] = 1;
        ref_frame_idx[5] = 1;
        ref_frame_idx[6] = 1;
        PSearchCtx::with_refs(
            &[anchor, future],
            slot_to_plane,
            ref_frame_idx,
            vec![1, 5],
            vec![[1, 5]],
            mi_rows,
            mi_cols,
            (mi_cols * 4) as usize,
            (mi_rows * 4) as usize,
            &[(mi_cols * 4, mi_rows * 4); 2],
            ip,
            base_q_idx,
            &[],
            8,
            1,
            1,
            3,
        )
        .unwrap()
    }

    fn fresh_recon(w: usize, h: usize, q: u8) -> ReconState {
        ReconState {
            y: vec![0u16; w * h],
            u: vec![0u16; (w / 2) * (h / 2)],
            v: vec![0u16; (w / 2) * (h / 2)],
            width: w,
            height: h,
            chroma_w: w / 2,
            chroma_h: h / 2,
            mi_rows: (h / 4) as u32,
            mi_cols: (w / 4) as u32,
            lossless: q == 0,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(q, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        }
    }

    /// r415 โ€” bidirectional COMPOUND_AVERAGE must actually be selected
    /// where the forward/backward mean is the distortion winner: the
    /// target frame is the PIXELWISE AVERAGE of the anchor and the
    /// future reference, so a { LAST, BWDREF } compound leaf predicts
    /// it almost exactly while either single side misses by half the
    /// delta.
    #[test]
    fn r415_b_search_selects_bidir_compound_on_blended_content() {
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        let f2 = moving_gradient(64, 64, 0, 0, 140);
        let base_q_idx = 60u8;
        let k0 = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f0, base_q_idx).unwrap();
        let k2 = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f2, base_q_idx).unwrap();
        let anchor = GopFrameReconYuv {
            y: k0.recon_y,
            u: k0.recon_u,
            v: k0.recon_v,
        };
        let future = GopFrameReconYuv {
            y: k2.recon_y,
            u: k2.recon_u,
            v: k2.recon_v,
        };
        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        let avg = |a: &[u16], b: &[u16], out: &mut [u16]| {
            for ((o, &x), &y) in out.iter_mut().zip(a).zip(b) {
                *o = (u32::from(x) + u32::from(y)).div_ceil(2) as u16;
            }
        };
        avg(&anchor.y, &future.y, &mut target.y);
        avg(&anchor.u, &future.u, &mut target.u);
        avg(&anchor.v, &future.v, &mut target.v);

        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ictx = b_frame_ctx(&anchor, &future, 16, 16, base_q_idx, false);
        recon.bd.clear_for_sb(0, 0, 16, 16);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        fn count(node: &SyntaxNode, compound: &mut u32, single: &mut u32) {
            let leafc = |b: &SyntaxBlock, compound: &mut u32, single: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.ref_frame == [1, 5] {
                        *compound += 1;
                    } else {
                        *single += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, compound, single),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, compound, single);
                    }
                }
                other => {
                    for b in other.asymmetric_blocks().iter() {
                        leafc(b, compound, single);
                    }
                }
            }
        }
        let (mut compound, mut single) = (0u32, 0u32);
        count(&tree, &mut compound, &mut single);
        assert!(
            compound > 0,
            "average-blend content must select {{ LAST, BWDREF }} bidirectional \
             compound leaves (got COMPOUND={compound} SINGLE={single})"
        );
    }

    /// r415 โ€” the backward single reference must actually be selected
    /// where the future frame matches: the target IS the future
    /// reference's content, so BWDREF single-ref leaves dominate.
    #[test]
    fn r415_b_search_selects_backward_reference_on_future_matching_content() {
        let f0 = moving_gradient(64, 64, 0, 0, 5);
        let f2 = moving_gradient(64, 64, 9, 13, 505);
        let base_q_idx = 60u8;
        let k0 = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f0, base_q_idx).unwrap();
        let k2 = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f2, base_q_idx).unwrap();
        let anchor = GopFrameReconYuv {
            y: k0.recon_y,
            u: k0.recon_u,
            v: k0.recon_v,
        };
        let future = GopFrameReconYuv {
            y: k2.recon_y,
            u: k2.recon_u,
            v: k2.recon_v,
        };
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ictx = b_frame_ctx(&anchor, &future, 16, 16, base_q_idx, false);
        recon.bd.clear_for_sb(0, 0, 16, 16);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f2, &mut recon, &mut ictx).unwrap();
        fn count(node: &SyntaxNode, bwd: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, bwd: &mut u32, other: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.ref_frame == [5, -1] {
                        *bwd += 1;
                    } else {
                        *other += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, bwd, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, bwd, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, bwd, other);
                    }
                }
            }
        }
        let (mut bwd, mut other) = (0u32, 0u32);
        count(&tree, &mut bwd, &mut other);
        assert!(
            bwd > 0,
            "future-matching content must select BWDREF single-reference \
             leaves (got BWD={bwd} OTHER={other})"
        );
    }

    /// r415 โ€” ยง5.11.29 masked compound must actually be selected
    /// where a wedge blend is the distortion winner: each 32x32
    /// quadrant of the target frame is constructed as the decoder's
    /// OWN ยง7.11.3.11 COMPOUND_WEDGE blend of the two references
    /// (through [`PSearchCtx::predict_leaf`], the same kernel the
    /// search scores with), so a WEDGE leaf predicts it exactly while
    /// COMPOUND_AVERAGE misses along the wedge boundary โ€” the search
    /// tree must commit COMPOUND_WEDGE leaves, and a full GOP over
    /// the same construction must round-trip byte-exact through the
    /// spec driver (proving the coded ยง5.11.29 cascade end to end).
    #[test]
    fn r415_search_selects_wedge_compound_on_wedge_blend_content() {
        use crate::cdf::BLOCK_32X32;
        use crate::inter_pred::COMPOUND_WEDGE;
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        let f1 = moving_gradient(64, 64, 0, 0, 140);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();

        // Target: per-quadrant WEDGE blend (index 7, sign 0) of the
        // two reference reconstructions, through the real kernel.
        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        {
            let ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
            let mut probe =
                PSearchCtx::new(&pre.recon[1], &pre.recon[0], 16, 16, 64, 64, ip, 2, 0, &[])
                    .unwrap();
            let sel = CompoundSel {
                ctype: COMPOUND_WEDGE,
                wedge_index: 7,
                wedge_sign: 0,
                mask_type: 0,
            };
            for (r, c) in [(0u32, 0u32), (0, 8), (8, 0), (8, 8)] {
                probe
                    .predict_leaf(
                        r,
                        c,
                        BLOCK_32X32,
                        [1, 4],
                        MODE_NEW_NEWMV,
                        [[0, 0], [0, 0]],
                        EIGHTTAP,
                        sel,
                        None,
                        MotionSel::Simple,
                    )
                    .unwrap();
            }
            for (dst, &src) in target.y.iter_mut().zip(probe.scratch[0].iter()) {
                *dst = src;
            }
            for (dst, &src) in target.u.iter_mut().zip(probe.scratch[1].iter()) {
                *dst = src;
            }
            for (dst, &src) in target.v.iter_mut().zip(probe.scratch[2].iter()) {
                *dst = src;
            }
        }

        // Direct search drive (LAST = f1 recon, GOLDEN = f0 recon at
        // p_index = 2), masked compound enabled.
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 2, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_masked_compound = true;
        ip.order_hints = gop_order_hints(2, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &pre.recon[1],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            2,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        fn count(node: &SyntaxNode, wedge: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, wedge: &mut u32, other: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.compound_type == crate::inter_pred::COMPOUND_WEDGE {
                        *wedge += 1;
                    } else {
                        *other += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, wedge, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, wedge, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, wedge, other);
                    }
                }
            }
        }
        let (mut wedge, mut other) = (0u32, 0u32);
        count(&tree, &mut wedge, &mut other);
        assert!(
            wedge > 0,
            "wedge-blend content must commit COMPOUND_WEDGE leaves \
             (got WEDGE={wedge} OTHER={other})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f1, target], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
        // Env-gated fixture dump for external black-box validation /
        // corpus pinning (no-op in normal runs).
        if let Ok(dir) = std::env::var("OXIDEAV_AV1_WEDGE_FIXDIR") {
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                format!("{dir}/self-gop-64x64-q60-wedge.ivf"),
                &enc.ivf_bytes,
            )
            .unwrap();
        }
    }

    /// r418 โ€” the ยง5.11.46 palette arm must reach INTRA leaves inside
    /// INTER frames through the shared leaf encoder: a P-frame whose
    /// centre region is freshly-pasted 4-colour dither (inter
    /// prediction has nothing to track, every ยง7.11.2 mode misses the
    /// per-pixel pattern) commits `PaletteSizeY > 0` intra leaves in
    /// the P search tree, and the GOP round-trips byte-exact through
    /// the spec driver.
    #[test]
    fn r418_p_search_selects_palette_on_pasted_screen_content() {
        const COLORS: [u16; 4] = [16, 80, 160, 240];
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        let mut f1 = moving_gradient(64, 64, 0, 0, 40);
        // Paste a 32x32 dither block (chroma pair checker) at (16, 16).
        let mut state = 0x0DDB_A115u32;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state
        };
        for i in 16..48usize {
            for j in 16..48usize {
                f1.y[i * 64 + j] = COLORS[(next() & 3) as usize];
            }
        }
        for i in 8..24usize {
            for j in 8..24usize {
                let par = ((i / 2) + (j / 2)) & 1;
                f1.u[i * 32 + j] = if par == 0 { 96 } else { 168 };
                f1.v[i * 32 + j] = if ((i / 4) & 1) == par { 108 } else { 152 };
            }
        }
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();

        // Direct search drive over the same driver state (LAST = f0
        // recon at p_index = 1).
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.order_hints = gop_order_hints(1, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &pre.recon[0],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f1, &mut recon, &mut ictx).unwrap();
        fn count(node: &SyntaxNode, pal: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, pal: &mut u32, other: &mut u32| {
                if b.inter.is_none() && b.palette.size_y > 0 {
                    *pal += 1;
                } else {
                    *other += 1;
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, pal, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, pal, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, pal, other);
                    }
                }
            }
        }
        let (mut pal, mut other) = (0u32, 0u32);
        count(&tree, &mut pal, &mut other);
        assert!(
            pal > 0,
            "pasted dither content must commit PaletteSizeY > 0 intra leaves in the \
             P-frame search (got PALETTE={pal} OTHER={other})"
        );

        // Full-stream conformance through the spec driver.
        let decoded = crate::decoder::decode_av1_spec(&pre.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&pre.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&pre.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&pre.recon[idx].v), "frame {idx} V");
        }
    }

    /// r417 โ€” the ยง5.11.28 WEDGE sub-arm must actually be selected
    /// where a ยง7.11.3.11 wedge-masked inter-intra blend is the
    /// distortion winner: the target quadrants are constructed
    /// through the real driver with `wedge_interintra = 1` (wedge
    /// index 7) โ€” the same incremental neighbour-state technique as
    /// the smooth witness โ€” so a wedge inter-intra leaf predicts
    /// each quadrant near-exactly while the smooth mask and every
    /// plain arm miss the wedge boundary; the committed tree must
    /// carry `wedge_interintra = 1` leaves and the GOP must
    /// round-trip byte-exact through the spec driver.
    #[test]
    fn r417_search_selects_wedge_inter_intra_on_wedge_blend_content() {
        use crate::cdf::{BLOCK_32X32, II_V_PRED};
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        // r425 โ€” brightness 220 (was 140): the intra half of the
        // first quadrant's blend derives from border-constant
        // neighbours (~128), so the wedge contrast |inter โˆ’ intra|
        // must dwarf the coding noise of the anchors or the election
        // turns rate-marginal (the r425 KEY rect arms shifted the
        // anchor reconstruction by a hair and flipped it at 140).
        let f1 = moving_gradient(64, 64, 0, 0, 220);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();

        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        {
            let ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
            let mut probe =
                PSearchCtx::new(&pre.recon[1], &pre.recon[0], 16, 16, 64, 64, ip, 2, 0, &[])
                    .unwrap();
            let mut running = fresh_recon(64, 64, base_q_idx);
            for (r, c) in [(0u32, 0u32), (0, 8), (8, 0), (8, 8)] {
                probe
                    .predict_leaf(
                        r,
                        c,
                        BLOCK_32X32,
                        [1, -1],
                        MODE_NEARESTMV,
                        [[0, 0], [0, 0]],
                        EIGHTTAP,
                        CompoundSel::AVERAGE,
                        Some(InterIntraTrial {
                            mode: II_V_PRED,
                            wedge: Some(7),
                            neigh: &running,
                        }),
                        MotionSel::Simple,
                    )
                    .unwrap();
                let (row0, col0) = ((r as usize) * 4, (c as usize) * 4);
                for i in 0..32usize {
                    for j in 0..32usize {
                        let v = probe.scratch[0][(row0 + i) * 64 + col0 + j];
                        target.y[(row0 + i) * 64 + col0 + j] = v;
                        running.y[(row0 + i) * 64 + col0 + j] = v;
                    }
                }
                let (cr0, cc0) = (row0 / 2, col0 / 2);
                for i in 0..16usize {
                    for j in 0..16usize {
                        let u = probe.scratch[1][(cr0 + i) * 32 + cc0 + j];
                        let v = probe.scratch[2][(cr0 + i) * 32 + cc0 + j];
                        target.u[(cr0 + i) * 32 + cc0 + j] = u;
                        target.v[(cr0 + i) * 32 + cc0 + j] = v;
                        running.u[(cr0 + i) * 32 + cc0 + j] = u;
                        running.v[(cr0 + i) * 32 + cc0 + j] = v;
                    }
                }
            }
        }

        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 2, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_interintra_compound = true;
        ip.order_hints = gop_order_hints(2, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &pre.recon[1],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            2,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        fn count(node: &SyntaxNode, wedge_ii: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, wedge_ii: &mut u32, other: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.interintra_mode.is_some() && ib.wedge_interintra == 1 {
                        *wedge_ii += 1;
                    } else {
                        *other += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, wedge_ii, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, wedge_ii, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, wedge_ii, other);
                    }
                }
            }
        }
        let (mut wedge_ii, mut other) = (0u32, 0u32);
        count(&tree, &mut wedge_ii, &mut other);
        assert!(
            wedge_ii > 0,
            "wedge inter-intra blend content must commit wedge_interintra = 1 leaves \
             (got WEDGE_II={wedge_ii} OTHER={other})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f1, target], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
    }

    /// r417 โ€” sub-8ร—8 INTRA leaves in inter frames: content whose
    /// 8ร—8 groups mix a V_PRED-perfect 4ร—4 cell (its rows replicate
    /// the row above โ€” the ยง7.11.2 intra copy is near-exact while no
    /// reference contains the vertically-constant patch) with three
    /// trackable moving-texture cells must commit a PARTITION_SPLIT
    /// at BLOCK_8X8 whose leaves MIX `is_inter = 0` and
    /// `is_inter = 1` โ€” the ยง5.11.33 `someUseIntra` chroma arm fires
    /// on the group's inter `HasChroma` leaf โ€” and the full GOP must
    /// round-trip byte-exact through the spec driver.
    #[test]
    fn r417_search_selects_sub8_intra_in_mixed_groups() {
        let f0 = moving_gradient(64, 64, 0, 0, 71);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(std::slice::from_ref(&f0), base_q_idx).unwrap();
        let kr = &pre.recon[0];

        // Target: the r416 fine-motion checkerboard (per-4ร—4-cell
        // (0,0) / (4,4) sampling shifts of the KEY recon โ€” proven to
        // drive PARTITION_SPLIT down to BLOCK_4X4), with the NW cell
        // of four 8ร—8 groups overwritten by V-replication (rows copy
        // the row directly above โ€” vertically constant, absent from
        // the reference, near-exact under ยง7.11.2 V_PRED).
        let mut f2 = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        let at = |p: &[u16], w: usize, h: usize, i: i64, j: i64| -> u16 {
            let ii = i.clamp(0, h as i64 - 1) as usize;
            let jj = j.clamp(0, w as i64 - 1) as usize;
            p[ii * w + jj]
        };
        for i in 0..64i64 {
            for j in 0..64i64 {
                let par = ((i / 4) + (j / 4)) & 1;
                let (dy, dx) = if par == 0 { (0, 0) } else { (4, 4) };
                f2.y[(i * 64 + j) as usize] = at(&kr.y, 64, 64, i + dy, j + dx);
            }
        }
        f2.u.copy_from_slice(&kr.u);
        f2.v.copy_from_slice(&kr.v);
        for (r0, c0) in [(8usize, 8usize), (8, 40), (40, 8), (40, 40)] {
            for i in 0..4 {
                for j in 0..4 {
                    f2.y[(r0 + i) * 64 + c0 + j] = f2.y[(r0 - 1) * 64 + c0 + j];
                }
            }
        }

        // Direct search drive (LAST = GOLDEN = the KEY recon at
        // p_index = 1) over the target.
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_interintra_compound = true;
        ip.order_hints = gop_order_hints(1, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &pre.recon[0],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f2, &mut recon, &mut ictx).unwrap();

        // Walk the committed tree: collect BLOCK_4X4 leaves with
        // ยง5.11.4 SPLIT geometry.
        fn walk(
            node: &SyntaxNode,
            r: u32,
            c: u32,
            b_size: usize,
            found: &mut Vec<(u32, u32, bool)>,
        ) {
            match node {
                SyntaxNode::Leaf(b) if b_size == BLOCK_4X4 => {
                    found.push((r, c, b.inter.is_some()));
                }
                SyntaxNode::Split(children) => {
                    let sub =
                        crate::cdf::partition_subsize(crate::cdf::PARTITION_SPLIT, b_size).unwrap();
                    let half = (NUM_4X4_BLOCKS_WIDE[b_size] as u32) >> 1;
                    walk(&children[0], r, c, sub, found);
                    walk(&children[1], r, c + half, sub, found);
                    walk(&children[2], r + half, c, sub, found);
                    walk(&children[3], r + half, c + half, sub, found);
                }
                _ => {}
            }
        }
        let mut sub4: Vec<(u32, u32, bool)> = Vec::new();
        walk(&tree, 0, 0, BLOCK_64X64, &mut sub4);
        let n_intra4 = sub4.iter().filter(|&&(_, _, inter)| !inter).count();
        assert!(
            n_intra4 > 0,
            "V-replicated cells must commit BLOCK_4X4 intra leaves (got {sub4:?})"
        );
        // At least one 2ร—2 group mixes intra and inter โ€” the
        // ยง5.11.33 someUseIntra chroma arm is live in the stream.
        let mixed = sub4.iter().any(|&(r, c, inter)| {
            !inter
                && sub4
                    .iter()
                    .any(|&(r2, c2, inter2)| inter2 && (r2 & !1, c2 & !1) == (r & !1, c & !1))
        });
        assert!(mixed, "some 2x2 group must mix intra and inter ({sub4:?})");

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f2], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
        if let Ok(dir) = std::env::var("OXIDEAV_AV1_SUB8INTRA_FIXDIR") {
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                format!("{dir}/self-gop-64x64-q60-sub8-intra.ivf"),
                &enc.ivf_bytes,
            )
            .unwrap();
        }
    }

    /// r417 โ€” ยง5.11.28 inter-intra must actually be selected where
    /// the ยง7.11.3.14 blend is the distortion winner: the target
    /// frame is constructed QUADRANT BY QUADRANT as the encoder's
    /// own smooth II_V_PRED inter-intra blend (zero-MV LAST inter
    /// half, the intra half predicted from the running construction
    /// recon โ€” exactly the ยง5.11.33 ordering the search and the
    /// decoder both realise), so an inter-intra leaf predicts each
    /// quadrant near-exactly while any plain inter leaf misses the
    /// intra-weighted region โ€” the search tree must commit
    /// inter-intra leaves, and a full GOP over the same construction
    /// must round-trip byte-exact through the spec driver (proving
    /// the coded ยง5.11.28 cascade + ยง7.11.3.14 blend end to end).
    #[test]
    fn r417_search_selects_inter_intra_on_blended_content() {
        use crate::cdf::{BLOCK_32X32, II_V_PRED};
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        let f1 = moving_gradient(64, 64, 0, 0, 140);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();

        // Target: per-32x32-quadrant smooth inter-intra blend of the
        // LAST reconstruction and the ยง7.11.2 intra half, built
        // through the real driver with the SAME incremental
        // neighbour state the sequential search walk will hold.
        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        {
            let ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
            let mut probe =
                PSearchCtx::new(&pre.recon[1], &pre.recon[0], 16, 16, 64, 64, ip, 2, 0, &[])
                    .unwrap();
            let mut running = fresh_recon(64, 64, base_q_idx);
            for (r, c) in [(0u32, 0u32), (0, 8), (8, 0), (8, 8)] {
                probe
                    .predict_leaf(
                        r,
                        c,
                        BLOCK_32X32,
                        [1, -1],
                        MODE_NEARESTMV,
                        [[0, 0], [0, 0]],
                        EIGHTTAP,
                        CompoundSel::AVERAGE,
                        Some(InterIntraTrial {
                            mode: II_V_PRED,
                            wedge: None,
                            neigh: &running,
                        }),
                        MotionSel::Simple,
                    )
                    .unwrap();
                // Adopt the blended quadrant into the target AND the
                // running neighbour recon (the next quadrant's intra
                // half reads it, like the decode walk will).
                let (row0, col0) = ((r as usize) * 4, (c as usize) * 4);
                for i in 0..32usize {
                    for j in 0..32usize {
                        let v = probe.scratch[0][(row0 + i) * 64 + col0 + j];
                        target.y[(row0 + i) * 64 + col0 + j] = v;
                        running.y[(row0 + i) * 64 + col0 + j] = v;
                    }
                }
                let (cr0, cc0) = (row0 / 2, col0 / 2);
                for i in 0..16usize {
                    for j in 0..16usize {
                        let u = probe.scratch[1][(cr0 + i) * 32 + cc0 + j];
                        let v = probe.scratch[2][(cr0 + i) * 32 + cc0 + j];
                        target.u[(cr0 + i) * 32 + cc0 + j] = u;
                        target.v[(cr0 + i) * 32 + cc0 + j] = v;
                        running.u[(cr0 + i) * 32 + cc0 + j] = u;
                        running.v[(cr0 + i) * 32 + cc0 + j] = v;
                    }
                }
            }
        }

        // Direct search drive (LAST = f1 recon, GOLDEN = f0 recon at
        // p_index = 2), inter-intra compound enabled.
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 2, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_interintra_compound = true;
        ip.order_hints = gop_order_hints(2, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &pre.recon[1],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            2,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        fn count(node: &SyntaxNode, ii: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, ii: &mut u32, other: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.interintra_mode.is_some() {
                        *ii += 1;
                    } else {
                        *other += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, ii, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, ii, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, ii, other);
                    }
                }
            }
        }
        let (mut ii, mut other) = (0u32, 0u32);
        count(&tree, &mut ii, &mut other);
        assert!(
            ii > 0,
            "inter-intra blend content must commit ยง5.11.28 leaves \
             (got II={ii} OTHER={other})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f1, target], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
        // Env-gated fixture dump for external black-box validation /
        // corpus pinning (no-op in normal runs).
        if let Ok(dir) = std::env::var("OXIDEAV_AV1_INTERINTRA_FIXDIR") {
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                format!("{dir}/self-gop-64x64-q60-interintra.ivf"),
                &enc.ivf_bytes,
            )
            .unwrap();
        }
    }

    /// r416 โ€” ยง5.11.29 jnt-comp must actually be selected where the
    /// ยง7.11.3.15 distance-weighted blend is the distortion winner:
    /// the target frame is constructed as the decoder's OWN
    /// COMPOUND_DISTANCE blend of the two references (through
    /// [`PSearchCtx::predict_leaf`] under the real P-frame order
    /// hints โ€” LAST at distance 1, GOLDEN at distance 2 โ‡’ the
    /// asymmetric `(11, 5)/16` weight pair), so a DISTANCE leaf
    /// predicts it exactly while COMPOUND_AVERAGE misses by the
    /// weight asymmetry โ€” the search tree must commit
    /// COMPOUND_DISTANCE leaves, and a full GOP over the same
    /// construction must round-trip byte-exact through the spec
    /// driver (proving the coded `compound_idx` cascade end to end).
    #[test]
    fn r416_search_selects_distance_compound_on_weighted_blend_content() {
        use crate::cdf::BLOCK_32X32;
        use crate::inter_pred::COMPOUND_DISTANCE;
        let f0 = moving_gradient(64, 64, 0, 0, 40);
        let f1 = moving_gradient(64, 64, 0, 0, 140);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();

        // Target: the ยง7.11.3.15 DISTANCE blend of the two reference
        // reconstructions through the real kernel under the frame-2
        // order hints (the same hints the GOP encode derives).
        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        {
            let mut ip = SyntaxInterFrameParams::single_ref_baseline(16, 16, false);
            ip.order_hints = gop_order_hints(2, pre.seq.order_hint_bits);
            let mut probe =
                PSearchCtx::new(&pre.recon[1], &pre.recon[0], 16, 16, 64, 64, ip, 2, 0, &[])
                    .unwrap();
            let sel = CompoundSel {
                ctype: COMPOUND_DISTANCE,
                wedge_index: 0,
                wedge_sign: 0,
                mask_type: 0,
            };
            for (r, c) in [(0u32, 0u32), (0, 8), (8, 0), (8, 8)] {
                probe
                    .predict_leaf(
                        r,
                        c,
                        BLOCK_32X32,
                        [1, 4],
                        MODE_NEW_NEWMV,
                        [[0, 0], [0, 0]],
                        EIGHTTAP,
                        sel,
                        None,
                        MotionSel::Simple,
                    )
                    .unwrap();
            }
            for (dst, &src) in target.y.iter_mut().zip(probe.scratch[0].iter()) {
                *dst = src;
            }
            for (dst, &src) in target.u.iter_mut().zip(probe.scratch[1].iter()) {
                *dst = src;
            }
            for (dst, &src) in target.v.iter_mut().zip(probe.scratch[2].iter()) {
                *dst = src;
            }
        }

        // Direct search drive (LAST = f1 recon, GOLDEN = f0 recon at
        // p_index = 2), jnt-comp enabled.
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 2, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_masked_compound = true;
        ip.enable_jnt_comp = true;
        ip.order_hints = gop_order_hints(2, pre.seq.order_hint_bits);
        let mut ictx = PSearchCtx::new(
            &pre.recon[1],
            &pre.recon[0],
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            2,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        fn count(node: &SyntaxNode, dist: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, dist: &mut u32, other: &mut u32| {
                if let Some(ib) = b.inter.as_ref() {
                    if ib.compound_type == crate::inter_pred::COMPOUND_DISTANCE {
                        *dist += 1;
                    } else {
                        *other += 1;
                    }
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, dist, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, dist, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, dist, other);
                    }
                }
            }
        }
        let (mut dist, mut other) = (0u32, 0u32);
        count(&tree, &mut dist, &mut other);
        assert!(
            dist > 0,
            "distance-blend content must commit COMPOUND_DISTANCE leaves \
             (got DISTANCE={dist} OTHER={other})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f1, target], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
        // Env-gated fixture dump for external black-box validation /
        // corpus pinning (no-op in normal runs).
        if let Ok(dir) = std::env::var("OXIDEAV_AV1_JNT_FIXDIR") {
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(format!("{dir}/self-gop-64x64-q60-jnt.ivf"), &enc.ivf_bytes).unwrap();
        }
    }

    /// r416 โ€” walk a committed search tree tracking each leaf's block
    /// size: count sub-8ร—8 leaves (either axis < 8 samples), bare
    /// BLOCK_4X4 leaves, and four-strip (HORZ_4 / VERT_4) nodes.
    fn count_sub8(node: &SyntaxNode, b_size: usize, n_sub8: &mut u32, n_4x4: &mut u32) {
        use crate::cdf::{
            block_height, block_width, partition_subsize, BLOCK_4X4, PARTITION_HORZ,
            PARTITION_HORZ_4, PARTITION_HORZ_A, PARTITION_HORZ_B, PARTITION_SPLIT, PARTITION_VERT,
            PARTITION_VERT_4, PARTITION_VERT_A, PARTITION_VERT_B,
        };
        let leaf_hit = |sz: usize, n_sub8: &mut u32, n_4x4: &mut u32| {
            if block_width(sz) < 8 || block_height(sz) < 8 {
                *n_sub8 += 1;
            }
            if sz == BLOCK_4X4 {
                *n_4x4 += 1;
            }
        };
        match node {
            SyntaxNode::Leaf(_) => leaf_hit(b_size, n_sub8, n_4x4),
            SyntaxNode::Split(children) => {
                let s = partition_subsize(PARTITION_SPLIT, b_size).unwrap();
                for ch in children.iter() {
                    count_sub8(ch, s, n_sub8, n_4x4);
                }
            }
            SyntaxNode::Horz(_) | SyntaxNode::Vert(_) => {
                let part = if matches!(node, SyntaxNode::Horz(_)) {
                    PARTITION_HORZ
                } else {
                    PARTITION_VERT
                };
                let s = partition_subsize(part, b_size).unwrap();
                for _b in node.asymmetric_blocks() {
                    leaf_hit(s, n_sub8, n_4x4);
                }
            }
            SyntaxNode::HorzA(_)
            | SyntaxNode::HorzB(_)
            | SyntaxNode::VertA(_)
            | SyntaxNode::VertB(_) => {
                // T-shapes: two splitSize quarters + one subSize half.
                let (part, half_first) = match node {
                    SyntaxNode::HorzA(_) => (PARTITION_HORZ_A, false),
                    SyntaxNode::HorzB(_) => (PARTITION_HORZ_B, true),
                    SyntaxNode::VertA(_) => (PARTITION_VERT_A, false),
                    _ => (PARTITION_VERT_B, true),
                };
                let half = partition_subsize(part, b_size).unwrap();
                let quarter = partition_subsize(PARTITION_SPLIT, b_size).unwrap();
                let sizes: [usize; 3] = if half_first {
                    [half, quarter, quarter]
                } else {
                    [quarter, quarter, half]
                };
                for (i, _b) in node.asymmetric_blocks().iter().enumerate() {
                    leaf_hit(sizes[i], n_sub8, n_4x4);
                }
            }
            SyntaxNode::Horz4(_) | SyntaxNode::Vert4(_) => {
                let part = if matches!(node, SyntaxNode::Horz4(_)) {
                    PARTITION_HORZ_4
                } else {
                    PARTITION_VERT_4
                };
                let s = partition_subsize(part, b_size).unwrap();
                for _b in node.asymmetric_blocks() {
                    leaf_hit(s, n_sub8, n_4x4);
                }
            }
        }
    }

    /// r416 โ€” sub-8ร—8 inter leaves must actually be selected where
    /// motion has 4ร—4 granularity: the target frame samples the KEY
    /// reconstruction with a per-4ร—4-cell alternating whole-sample
    /// shift, so a BLOCK_8X8 leaf's single MV misses half its cells
    /// while a PARTITION_SPLIT into four BLOCK_4X4 NEWMV leaves
    /// predicts every cell exactly โ€” the search tree must commit
    /// BLOCK_4X4 leaves, and a full GOP over the same construction
    /// must round-trip byte-exact through the spec driver (proving
    /// the ยง5.11.34 `HasChroma` group-chroma coding end to end).
    #[test]
    fn r416_search_selects_sub8_split_on_fine_motion() {
        let f0 = moving_gradient(64, 64, 0, 0, 71);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(std::slice::from_ref(&f0), base_q_idx).unwrap();
        let kr = &pre.recon[0];

        // Target: cell (ci, cj) reads the KEY recon shifted by
        // (0, 0) / (4, 4) on the cell-parity checkerboard.
        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        let at = |p: &[u16], w: usize, h: usize, i: i64, j: i64| -> u16 {
            let ii = i.clamp(0, h as i64 - 1) as usize;
            let jj = j.clamp(0, w as i64 - 1) as usize;
            p[ii * w + jj]
        };
        for i in 0..64i64 {
            for j in 0..64i64 {
                let par = ((i / 4) + (j / 4)) & 1;
                let (dy, dx) = if par == 0 { (0, 0) } else { (4, 4) };
                target.y[(i * 64 + j) as usize] = at(&kr.y, 64, 64, i + dy, j + dx);
            }
        }
        // Chroma: zero-motion copy (luma alone drives the witness;
        // the group-chroma residual absorbs the tiled prediction).
        target.u.copy_from_slice(&kr.u);
        target.v.copy_from_slice(&kr.v);

        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_masked_compound = true;
        ip.enable_jnt_comp = true;
        ip.order_hints = gop_order_hints(1, pre.seq.order_hint_bits);
        let key_recon = GopFrameReconYuv {
            y: kr.y.clone(),
            u: kr.u.clone(),
            v: kr.v.clone(),
        };
        let mut ictx = PSearchCtx::new(
            &key_recon,
            &key_recon,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        let (mut n_sub8, mut n_4x4) = (0u32, 0u32);
        count_sub8(&tree, BLOCK_64X64, &mut n_sub8, &mut n_4x4);
        assert!(
            n_4x4 > 0,
            "4ร—4-granular motion must commit BLOCK_4X4 leaves (sub8={n_sub8} 4x4={n_4x4})"
        );

        // Full-stream conformance through the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, target], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
        // Env-gated fixture dump for external black-box validation /
        // corpus pinning (no-op in normal runs).
        if let Ok(dir) = std::env::var("OXIDEAV_AV1_SUB8_FIXDIR") {
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                format!("{dir}/self-gop-64x64-q60-sub8-split.ivf"),
                &enc.ivf_bytes,
            )
            .unwrap();
        }
    }

    /// r416 โ€” 4-sample-high band motion must commit sub-8 STRIPS: the
    /// target samples the KEY recon with a per-4-row-band alternating
    /// horizontal shift, so 16ร—4 (HORZ_4 at BLOCK_16X16) or 8ร—4
    /// (HORZ at BLOCK_8X8) leaves predict each band exactly while any
    /// 8-sample-high leaf straddles two bands โ€” the tree must commit
    /// height-4 leaves, and the full GOP round-trips byte-exact.
    #[test]
    fn r416_search_selects_sub8_strips_on_band_motion() {
        let f0 = moving_gradient(64, 64, 0, 0, 93);
        let base_q_idx = 60u8;
        let pre = encode_gop_yuv_with_q(std::slice::from_ref(&f0), base_q_idx).unwrap();
        let kr = &pre.recon[0];

        let mut target = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 0);
        let at = |p: &[u16], w: usize, h: usize, i: i64, j: i64| -> u16 {
            let ii = i.clamp(0, h as i64 - 1) as usize;
            let jj = j.clamp(0, w as i64 - 1) as usize;
            p[ii * w + jj]
        };
        for i in 0..64i64 {
            for j in 0..64i64 {
                let dx = if (i / 4) & 1 == 0 { 0 } else { 5 };
                target.y[(i * 64 + j) as usize] = at(&kr.y, 64, 64, i, j + dx);
            }
        }
        target.u.copy_from_slice(&kr.u);
        target.v.copy_from_slice(&kr.v);

        let fh = build_p_frame_yuv420_8bit_fh_with_q(&pre.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.reference_select = true;
        ip.enable_masked_compound = true;
        ip.enable_jnt_comp = true;
        ip.order_hints = gop_order_hints(1, pre.seq.order_hint_bits);
        let key_recon = GopFrameReconYuv {
            y: kr.y.clone(),
            u: kr.u.clone(),
            v: kr.v.clone(),
        };
        let mut ictx = PSearchCtx::new(
            &key_recon,
            &key_recon,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree = build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &target, &mut recon, &mut ictx)
            .unwrap();
        let (mut n_sub8, mut n_4x4) = (0u32, 0u32);
        count_sub8(&tree, BLOCK_64X64, &mut n_sub8, &mut n_4x4);
        assert!(
            n_sub8 > 0,
            "band motion must commit sub-8 strip leaves (sub8={n_sub8} 4x4={n_4x4})"
        );
        fn shape_census(node: &SyntaxNode, h4: &mut u32, v4: &mut u32, hz: &mut u32, vt: &mut u32) {
            match node {
                SyntaxNode::Horz4(_) => *h4 += 1,
                SyntaxNode::Vert4(_) => *v4 += 1,
                SyntaxNode::Horz(_) => *hz += 1,
                SyntaxNode::Vert(_) => *vt += 1,
                SyntaxNode::Split(ch) => {
                    for c in ch.iter() {
                        shape_census(c, h4, v4, hz, vt);
                    }
                }
                _ => {}
            }
        }
        let (mut h4, mut v4, mut hz, mut vt) = (0u32, 0u32, 0u32, 0u32);
        shape_census(&tree, &mut h4, &mut v4, &mut hz, &mut vt);
        let _ = (v4, vt);
        assert!(
            h4 > 0 && hz > 0,
            "band motion must commit both HORZ_4 strip nodes and HORZ-at-8x8 halves \
             (horz4={h4} horz={hz} sub8={n_sub8} 4x4={n_4x4})"
        );

        let enc = encode_gop_yuv_with_q(&[f0, target], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, fr) in decoded.iter().enumerate() {
            assert_eq!(fr.planes[0], plane8(&enc.recon[idx].y), "frame {idx} luma");
            assert_eq!(fr.planes[1], plane8(&enc.recon[idx].u), "frame {idx} U");
            assert_eq!(fr.planes[2], plane8(&enc.recon[idx].v), "frame {idx} V");
        }
        if let Ok(dir) = std::env::var("OXIDEAV_AV1_SUB8_FIXDIR") {
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                format!("{dir}/self-gop-64x64-q60-sub8-strips.ivf"),
                &enc.ivf_bytes,
            )
            .unwrap();
        }
    }

    /// r415 โ€” ยง5.9.22 forward/backward skip mode on a B frame:
    /// identical converged references make the one-symbol skip-mode
    /// block (compound NEAREST_NEARESTMV over
    /// SkipModeFrame[] = {{ LAST, BWDREF }}) the RD winner.
    #[test]
    fn r415_b_search_selects_skip_mode_between_converged_references() {
        let f = moving_gradient(64, 64, 2, 3, 21);
        let base_q_idx = 60u8;
        let k = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f, base_q_idx).unwrap();
        let anchor = GopFrameReconYuv {
            y: k.recon_y,
            u: k.recon_u,
            v: k.recon_v,
        };
        let future = anchor.clone();
        let mut recon = fresh_recon(64, 64, base_q_idx);
        let mut ictx = b_frame_ctx(&anchor, &future, 16, 16, base_q_idx, true);
        recon.bd.clear_for_sb(0, 0, 16, 16);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f, &mut recon, &mut ictx).unwrap();
        fn count(node: &SyntaxNode, sm: &mut u32, other: &mut u32) {
            let leafc = |b: &SyntaxBlock, sm: &mut u32, other: &mut u32| {
                if b.inter.as_ref().is_some_and(|ib| ib.skip_mode != 0) {
                    *sm += 1;
                } else {
                    *other += 1;
                }
            };
            match node {
                SyntaxNode::Leaf(b) => leafc(b, sm, other),
                SyntaxNode::Split(children) => {
                    for ch in children.iter() {
                        count(ch, sm, other);
                    }
                }
                rest => {
                    for b in rest.asymmetric_blocks().iter() {
                        leafc(b, sm, other);
                    }
                }
            }
        }
        let (mut sm, mut other) = (0u32, 0u32);
        count(&tree, &mut sm, &mut other);
        assert!(
            sm > 0,
            "converged references on a skip-mode B frame must select \
             skip_mode leaves (got SKIP_MODE={sm} OTHER={other})"
        );
    }

    /// Per-leaf ยง5.11.27 motion-mode census over a search tree.
    fn count_motion_modes(node: &SyntaxNode, counts: &mut [u32; 3]) {
        let leafc = |b: &SyntaxBlock, counts: &mut [u32; 3]| {
            if let Some(ib) = b.inter.as_ref() {
                counts[(ib.motion_mode as usize).min(2)] += 1;
            }
        };
        match node {
            SyntaxNode::Leaf(b) => leafc(b, counts),
            SyntaxNode::Split(children) => {
                for ch in children.iter() {
                    count_motion_modes(ch, counts);
                }
            }
            rest => {
                for b in rest.asymmetric_blocks().iter() {
                    leafc(b, counts);
                }
            }
        }
    }

    /// Vertically-sheared motion content: `f0` a dense texture, `f1`
    /// the same texture with a per-ROW horizontal shift that ramps
    /// from `dx_top` (rows above `ramp0`) down to 0 (rows below
    /// `ramp1`). No block-constant MV fits a ramp row band, and no
    /// ยง5.11.4 partition boundary aligns with it โ€” the ยง7.11.3.9-10
    /// OBMC blend of the above neighbour's larger shift over a
    /// block's top band is the best model the syntax offers.
    fn shear_pair(w: u32, h: u32, dx_top: usize, ramp0: usize, ramp1: usize) -> [YuvFrame; 2] {
        let (wu, hu) = (w as usize, h as usize);
        let tex = |i: usize, j: usize| -> u16 {
            ((i * 7 + j * 11 + (i / 4) * (j / 8) + ((i * j) / 13)) % 256) as u16
        };
        let mut f0 = YuvFrame::filled(w, h, 8, ChromaFormat::Yuv420, 128);
        for i in 0..hu {
            for j in 0..wu {
                f0.y[i * wu + j] = tex(i, j);
            }
        }
        let dx_of = |i: usize| -> usize {
            if i < ramp0 {
                dx_top
            } else if i >= ramp1 {
                0
            } else {
                dx_top * (ramp1 - i) / (ramp1 - ramp0)
            }
        };
        let mut f1 = YuvFrame::filled(w, h, 8, ChromaFormat::Yuv420, 128);
        for i in 0..hu {
            let dx = dx_of(i);
            for j in 0..wu {
                f1.y[i * wu + j] = tex(i, j + dx);
            }
        }
        [f0, f1]
    }

    /// r419 โ€” the ยง5.11.27 OBMC selection must actually be REACHED:
    /// on vertically-sheared motion (per-row shift ramp misaligned
    /// with every partition boundary) at least one committed leaf
    /// carries `motion_mode = OBMC`, and the emitted GOP stream
    /// round-trips byte-exact through the spec decoder.
    #[test]
    fn r419_p_search_selects_obmc_on_sheared_motion() {
        let [f0, f1] = shear_pair(64, 64, 8, 24, 48);
        let base_q_idx = 100u8;
        let key = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f0, base_q_idx).unwrap();
        let reference = GopFrameReconYuv {
            y: key.recon_y,
            u: key.recon_u,
            v: key.recon_v,
        };
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&key.seq, 64, 64, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 64 * 64],
            u: vec![0u16; 32 * 32],
            v: vec![0u16; 32 * 32],
            width: 64,
            height: 64,
            chroma_w: 32,
            chroma_h: 32,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        // r419 โ€” the frame configuration the GOP driver codes.
        ip.is_motion_mode_switchable = true;
        let mut ictx = PSearchCtx::new(
            &reference,
            &reference,
            mi_rows,
            mi_cols,
            64,
            64,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, &f1, &mut recon, &mut ictx).unwrap();
        let mut counts = [0u32; 3];
        count_motion_modes(&tree, &mut counts);
        assert!(
            counts[MOTION_MODE_OBMC as usize] > 0,
            "sheared motion must commit at least one ยง5.11.27 OBMC leaf \
             (got SIMPLE={} OBMC={} WARP={})",
            counts[0],
            counts[1],
            counts[2]
        );

        // Stream-level: the same content through the public GOP
        // driver decodes byte-exact in the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f1], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(
                f.planes[0],
                plane8(&enc.recon[idx].y),
                "display {idx}: luma"
            );
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "display {idx}: U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "display {idx}: V");
        }
    }

    /// Smoothly zooming texture pair: `f1` samples `f0`'s texture
    /// field scaled about the frame centre by `num/den` (a true
    /// affine motion field โ€” per-block translational MVs vary
    /// linearly across the frame, the ยง7.10.4 neighbour samples fit
    /// the ยง7.11.3.8 least squares exactly).
    fn zoom_pair(w: u32, h: u32, num: i64, den: i64) -> [YuvFrame; 2] {
        let (wu, hu) = (w as usize, h as usize);
        // Smooth wide-scale texture (sub-pel interpolable).
        let tex = |y: i64, x: i64| -> u16 {
            let (y, x) = (y as f64 / 8.0, x as f64 / 8.0);
            let v = 96.0
                + 60.0 * ((y * 0.11).sin() * (x * 0.13).cos())
                + 40.0 * ((y * 0.05 + x * 0.07).sin());
            v.clamp(0.0, 255.0) as u16
        };
        let mut f0 = YuvFrame::filled(w, h, 8, ChromaFormat::Yuv420, 128);
        let mut f1 = YuvFrame::filled(w, h, 8, ChromaFormat::Yuv420, 128);
        let (cy, cx) = ((hu / 2) as i64, (wu / 2) as i64);
        for i in 0..hu {
            for j in 0..wu {
                // f0 at identity, f1 zoomed about the centre in
                // 1/8-pel units.
                f0.y[i * wu + j] = tex((i as i64) * 8, (j as i64) * 8);
                let sy = cy * 8 + ((i as i64) - cy) * 8 * num / den;
                let sx = cx * 8 + ((j as i64) - cx) * 8 * num / den;
                f1.y[i * wu + j] = tex(sy, sx);
            }
        }
        [f0, f1]
    }

    /// r419 โ€” the ยง5.11.27 WARPED_CAUSAL selection must actually be
    /// REACHED: on zooming content (a true affine motion field, so
    /// the ยง7.10.4 neighbour MVs fit the ยง7.11.3.8 least squares)
    /// at least one committed leaf carries
    /// `motion_mode = WARPED_CAUSAL`, and the emitted GOP stream
    /// round-trips byte-exact through the spec decoder.
    #[test]
    fn r419_p_search_selects_warped_causal_on_zooming_motion() {
        let [f0, f1] = zoom_pair(96, 80, 17, 16);
        let base_q_idx = 100u8;
        let key = crate::encoder::key_frame::encode_key_frame_yuv_with_q(&f0, base_q_idx).unwrap();
        assert!(
            key.seq.enable_warped_motion,
            "r419: the sequence gate must be open for ยง5.11.27 arm B"
        );
        let reference = GopFrameReconYuv {
            y: key.recon_y,
            u: key.recon_u,
            v: key.recon_v,
        };
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&key.seq, 96, 80, base_q_idx, 1, &[]);
        assert_eq!(fh.allow_warped_motion, Some(true));
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; 96 * 80],
            u: vec![0u16; 48 * 40],
            v: vec![0u16; 48 * 40],
            width: 96,
            height: 80,
            chroma_w: 48,
            chroma_h: 40,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.is_motion_mode_switchable = true;
        ip.allow_warped_motion = true;
        let mut ictx = PSearchCtx::new(
            &reference,
            &reference,
            mi_rows,
            mi_cols,
            96,
            80,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        let mut counts = [0u32; 3];
        // r421 โ€” one persistent tile state across the superblocks (the
        // twin's mirror must carry the earlier superblocks' stamps).
        let mut ts = test_tile_state(&recon, &ictx);
        for (sb_r, sb_c) in [(0u32, 0u32), (0, 16), (16, 0), (16, 16)] {
            if sb_r >= mi_rows || sb_c >= mi_cols {
                continue;
            }
            recon.bd.clear_for_sb(sb_r, sb_c, mi_rows, mi_cols);
            let tree =
                search_and_commit_sb(&mut ts, sb_r, sb_c, &f1, &mut recon, &mut ictx).unwrap();
            count_motion_modes(&tree, &mut counts);
        }
        assert!(
            counts[MOTION_MODE_WARPED_CAUSAL as usize] > 0,
            "zooming motion must commit at least one ยง5.11.27 \
             WARPED_CAUSAL leaf (got SIMPLE={} OBMC={} WARP={})",
            counts[0],
            counts[1],
            counts[2]
        );

        // Stream-level: the same content through the public GOP
        // driver decodes byte-exact in the spec driver.
        let enc = encode_gop_yuv_with_q(&[f0, f1], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(
                f.planes[0],
                plane8(&enc.recon[idx].y),
                "display {idx}: luma"
            );
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "display {idx}: U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "display {idx}: V");
        }
    }

    /// Deterministic noise texture (xorshift over the seed).
    fn noise_frame(w: u32, h: u32, seed: u32) -> YuvFrame {
        let mut state = 0x1357_9BDFu32 ^ seed;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state
        };
        let mut f = YuvFrame::filled(w, h, 8, ChromaFormat::Yuv420, 0);
        for p in f.y.iter_mut() {
            *p = (next() & 0xFF) as u16;
        }
        for p in f.u.iter_mut() {
            *p = 96 + (next() & 0x3F) as u16;
        }
        for p in f.v.iter_mut() {
            *p = 64 + (next() & 0x3F) as u16;
        }
        f
    }

    /// GOP census over committed INTRA leaves inside the P-frame
    /// search tree: `(filter_intra, cfl)` counts.
    fn count_intra_tools(node: &SyntaxNode, fi: &mut u32, cfl: &mut u32) {
        let leafc = |b: &SyntaxBlock, fi: &mut u32, cfl: &mut u32| {
            if b.inter.is_none() {
                if b.use_filter_intra == 1 {
                    *fi += 1;
                }
                if b.uv_mode == Some(crate::cdf::UV_CFL_PRED as u8) {
                    *cfl += 1;
                }
            }
        };
        match node {
            SyntaxNode::Leaf(b) => leafc(b, fi, cfl),
            SyntaxNode::Split(children) => {
                for ch in children.iter() {
                    count_intra_tools(ch, fi, cfl);
                }
            }
            rest => {
                for b in rest.asymmetric_blocks().iter() {
                    leafc(b, fi, cfl);
                }
            }
        }
    }

    /// Shared driver for the two intra-tool witnesses: encode
    /// `[f0, f1]` through the public GOP driver, re-run the P-frame
    /// search tree with the same reference state, and return the
    /// intra-tool census plus the stream round-trip check.
    fn p_frame_intra_tool_census(f0: &YuvFrame, f1: &YuvFrame, base_q_idx: u8) -> (u32, u32) {
        let enc = encode_gop_yuv_with_q(&[f0.clone(), f1.clone()], base_q_idx).unwrap();
        let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
        assert_eq!(decoded.len(), 2);
        for (idx, f) in decoded.iter().enumerate() {
            assert_eq!(
                f.planes[0],
                plane8(&enc.recon[idx].y),
                "display {idx}: luma"
            );
            assert_eq!(f.planes[1], plane8(&enc.recon[idx].u), "display {idx}: U");
            assert_eq!(f.planes[2], plane8(&enc.recon[idx].v), "display {idx}: V");
        }
        // Search-tree census with the identical reference state.
        let reference = enc.recon[0].clone();
        let (w, h) = (f0.width, f0.height);
        let key = crate::encoder::key_frame::encode_key_frame_yuv_with_q(f0, base_q_idx).unwrap();
        let fh = build_p_frame_yuv420_8bit_fh_with_q(&key.seq, w, h, base_q_idx, 1, &[]);
        let fs = fh.frame_size.as_ref().unwrap();
        let (mi_rows, mi_cols) = (fs.mi_rows, fs.mi_cols);
        let mut recon = ReconState {
            y: vec![0u16; (w * h) as usize],
            u: vec![0u16; ((w / 2) * (h / 2)) as usize],
            v: vec![0u16; ((w / 2) * (h / 2)) as usize],
            width: w as usize,
            height: h as usize,
            chroma_w: (w / 2) as usize,
            chroma_h: (h / 2) as usize,
            mi_rows,
            mi_cols,
            lossless: false,
            allow_screen_content_tools: true,
            allow_intrabc: false,
            qp: QuantizerParams::neutral(base_q_idx, 8),
            bit_depth: 8,
            subsampling_x: 1,
            subsampling_y: 1,
            num_planes: 3,
            search: crate::encoder::key_frame::SearchLimits::default(),
            bd: BlockDecodedMirror::new(1, 1, 3),
            dv_hash: Default::default(),
        };
        let mut ip = SyntaxInterFrameParams::single_ref_baseline(mi_rows, mi_cols, false);
        ip.interpolation_filter = SWITCHABLE;
        ip.is_motion_mode_switchable = true;
        ip.allow_warped_motion = true;
        let mut ictx = PSearchCtx::new(
            &reference,
            &reference,
            mi_rows,
            mi_cols,
            w as usize,
            h as usize,
            ip,
            1,
            base_q_idx,
            &[],
        )
        .unwrap();
        recon.bd.clear_for_sb(0, 0, mi_rows, mi_cols);
        let tree =
            build_p_search_tree_for_tests(0, 0, BLOCK_64X64, f1, &mut recon, &mut ictx).unwrap();
        if std::env::var("OXIDEAV_AV1_DEBUG_CENSUS").is_ok() {
            fn dump(node: &SyntaxNode, depth: usize) {
                let leafd = |b: &SyntaxBlock, depth: usize| {
                    eprintln!(
                        "{:indent$}leaf inter={} y={} uv={:?} fi={} cfl=({:?},{:?})",
                        "",
                        b.inter.is_some(),
                        b.y_mode,
                        b.uv_mode,
                        b.use_filter_intra,
                        b.cfl_alpha_u,
                        b.cfl_alpha_v,
                        indent = depth * 2
                    );
                };
                match node {
                    SyntaxNode::Leaf(b) => leafd(b, depth),
                    SyntaxNode::Split(children) => {
                        for ch in children.iter() {
                            dump(ch, depth + 1);
                        }
                    }
                    rest => {
                        for b in rest.asymmetric_blocks().iter() {
                            leafd(b, depth);
                        }
                    }
                }
            }
            dump(&tree, 0);
        }
        let (mut fi, mut cfl) = (0u32, 0u32);
        count_intra_tools(&tree, &mut fi, &mut cfl);
        (fi, cfl)
    }

    /// r419 โ€” ยง5.11.24 FILTER-INTRA must be reachable on intra leaves
    /// INSIDE inter frames: the SE 32ร—32 quadrant of the P-frame is
    /// constructed as the ยง7.11.2.3 recursive prediction of its own
    /// decode-time neighbours (derived from a first static-GOP pass โ€”
    /// blocks above/left of the region commit identically in both
    /// passes, so the region predicts exactly and the FI pick beats
    /// every ยง7.11.2 plain mode), fresh content the inter search has
    /// no source for.
    #[test]
    fn r419_p_search_selects_filter_intra_inside_inter_frame() {
        let base_q_idx = 60u8;
        let f0 = noise_frame(64, 64, 40);
        // Pass 1 โ€” static GOP: the SE-quadrant neighbours' committed
        // reconstruction.
        let enc1 = encode_gop_yuv_with_q(&[f0.clone(), f0.clone()], base_q_idx).unwrap();
        let rec1 = &enc1.recon[1];
        // ยง7.11.2 neighbour arrays for the 32ร—32 TU at (32, 32) โ€”
        // the same derivation the leaf picker runs (frame corners
        // off-screen: no above-right / below-left).
        let (above_ext, left_ext, _, _) = super::super::key_frame::build_tu_neighbours(
            &rec1.y, 64, 64, 32, 32, 0, 0, 32, 32, false, false, 8,
        );
        let target = super::super::key_frame::predict_filter_intra_from_neighbours(
            /* FILTER_D157_PRED-class ordinal = */ 2, 32, 32, &above_ext, &left_ext, 8,
        )
        .expect("32x32 filter-intra prediction");
        // Pass 2 โ€” the region carries exactly that prediction.
        let mut f1 = f0.clone();
        for i in 0..32usize {
            for j in 0..32usize {
                f1.y[(32 + i) * 64 + 32 + j] = target[i * 32 + j];
            }
        }
        let (fi, _) = p_frame_intra_tool_census(&f0, &f1, base_q_idx);
        assert!(
            fi > 0,
            "the FI-constructed fresh region must commit at least one \
             ยง5.11.24 use_filter_intra = 1 intra leaf inside the \
             P-frame (got {fi})"
        );
    }

    /// r419 โ€” ยง5.11.45 CfL must be reachable on intra leaves INSIDE
    /// inter frames: the SE 32ร—32 quadrant of the P-frame carries
    /// fresh textured luma whose chroma tracks the subsampled luma AC
    /// (`c = mid ยฑ ac/2`) โ€” the ยง7.11.5 luma-feedthrough model no
    /// plain ยง7.11.2 chroma mode can express.
    #[test]
    fn r419_p_search_selects_cfl_inside_inter_frame() {
        let base_q_idx = 60u8;
        // Noise luma, FLAT mid chroma: every plain ยง7.11.2 chroma
        // mode collapses to the flat field, so the ยง7.11.5
        // luma-feedthrough is the only model that can track the
        // region's chroma AC.
        let mut f0 = noise_frame(64, 64, 41);
        f0.u.fill(128);
        f0.v.fill(128);
        let mut f1 = f0.clone();
        // Fresh smooth-textured luma in the SE quadrant.
        let tex = |i: usize, j: usize| -> u16 {
            let v = 128.0
                + 70.0 * ((i as f64) * 0.35).sin() * ((j as f64) * 0.29).cos()
                + 30.0 * (((i + j) as f64) * 0.11).sin();
            v.clamp(0.0, 255.0) as u16
        };
        for i in 0..32usize {
            for j in 0..32usize {
                f1.y[(32 + i) * 64 + 32 + j] = tex(i, j);
            }
        }
        // Chroma = mid ยฑ (subsampled luma AC) / 4 over the region โ€”
        // the ยง7.11.5 model at the (ฮฑU, ฮฑV) = (2, โˆ’2) grid point
        // (`chroma_ac = ฮฑ ยท luma_ac / 8`).
        let mut acc = 0i64;
        for i in 0..16usize {
            for j in 0..16usize {
                let s = i64::from(tex(2 * i, 2 * j))
                    + i64::from(tex(2 * i + 1, 2 * j))
                    + i64::from(tex(2 * i, 2 * j + 1))
                    + i64::from(tex(2 * i + 1, 2 * j + 1));
                acc += s;
            }
        }
        let mean4 = acc / 256; // 4x-scaled subsampled mean
        for i in 0..16usize {
            for j in 0..16usize {
                let s = i64::from(tex(2 * i, 2 * j))
                    + i64::from(tex(2 * i + 1, 2 * j))
                    + i64::from(tex(2 * i, 2 * j + 1))
                    + i64::from(tex(2 * i + 1, 2 * j + 1));
                let ac = (s - mean4) / 16; // ยฑ a quarter of the subsampled AC
                let cell = (16 + i) * 32 + 16 + j;
                f1.u[cell] = (128 + ac).clamp(0, 255) as u16;
                f1.v[cell] = (128 - ac).clamp(0, 255) as u16;
            }
        }
        let (_, cfl) = p_frame_intra_tool_census(&f0, &f1, base_q_idx);
        assert!(
            cfl > 0,
            "luma-tracking chroma on a fresh region must commit at \
             least one ยง5.11.22 UV_CFL_PRED intra leaf inside the \
             P-frame (got {cfl})"
        );
    }

    /// r419 conformance-fixture twins: the three self-encoded GOP
    /// streams pinned in `tests/fixture_conformance.rs` regenerate
    /// deterministically from the witness content families โ€”
    /// (1) sheared motion (ยง5.11.27 OBMC leaves, per the OBMC
    /// selection witness), (2) zooming motion (ยง5.11.27 WARPED_CAUSAL
    /// leaves, per the warp selection witness), (3) noise + FI-exact +
    /// CfL-tracking regions (ยง5.11.24 filter-intra and ยง5.11.22
    /// UV_CFL_PRED intra leaves INSIDE inter frames, per the two
    /// intra-tool witnesses). Each round-trips byte-exact through the
    /// spec driver; when `OXIDEAV_AV1_R419_FIXDIR` is set the exact
    /// streams + display-order reconstructions are written for
    /// external validation / fixture staging.
    #[test]
    fn r419_motion_mode_and_intra_tool_fixture_streams() {
        let dump = |name: &str, enc: &EncodedGopYuv| {
            let decoded = crate::decoder::decode_av1_spec(&enc.ivf_bytes).unwrap();
            assert_eq!(decoded.len(), enc.recon.len(), "{name}");
            for (idx, f) in decoded.iter().enumerate() {
                assert_eq!(
                    f.planes[0],
                    plane8(&enc.recon[idx].y),
                    "{name} display {idx}: luma"
                );
                assert_eq!(
                    f.planes[1],
                    plane8(&enc.recon[idx].u),
                    "{name} display {idx}: U"
                );
                assert_eq!(
                    f.planes[2],
                    plane8(&enc.recon[idx].v),
                    "{name} display {idx}: V"
                );
            }
            if let Ok(dir) = std::env::var("OXIDEAV_AV1_R419_FIXDIR") {
                std::fs::create_dir_all(&dir).unwrap();
                std::fs::write(format!("{dir}/{name}.ivf"), &enc.ivf_bytes).unwrap();
                let mut yuv = Vec::new();
                for rc in &enc.recon {
                    yuv.extend_from_slice(&plane8(&rc.y));
                    yuv.extend_from_slice(&plane8(&rc.u));
                    yuv.extend_from_slice(&plane8(&rc.v));
                }
                std::fs::write(format!("{dir}/{name}.yuv"), &yuv).unwrap();
            }
        };

        // --- self-gop-64x64-q100-shear-obmc: 3-frame shear GOP (the
        // OBMC witness content family โ€” per-row shift ramp 24..48,
        // dx_top = 4k). ---
        {
            let tex = |i: usize, j: usize| -> u16 {
                ((i * 7 + j * 11 + (i / 4) * (j / 8) + ((i * j) / 13)) % 256) as u16
            };
            let frames: Vec<YuvFrame> = (0..3)
                .map(|k| {
                    let mut f = YuvFrame::filled(64, 64, 8, ChromaFormat::Yuv420, 128);
                    for i in 0..64usize {
                        let (ramp0, ramp1, top) = (24usize, 48usize, 4 * k);
                        let dx = if i < ramp0 {
                            top
                        } else if i >= ramp1 {
                            0
                        } else {
                            top * (ramp1 - i) / (ramp1 - ramp0)
                        };
                        for j in 0..64usize {
                            f.y[i * 64 + j] = tex(i, j + dx);
                        }
                    }
                    f
                })
                .collect();
            let enc = encode_gop_yuv_with_q(&frames, 100).unwrap();
            dump("self-gop-64x64-q100-shear-obmc", &enc);
        }

        // --- self-gop-96x80-q100-zoom-warp: 2-frame zoom GOP (the
        // WARPED_CAUSAL witness content itself). ---
        {
            let [f0, f1] = zoom_pair(96, 80, 17, 16);
            let enc = encode_gop_yuv_with_q(&[f0, f1], 100).unwrap();
            dump("self-gop-96x80-q100-zoom-warp", &enc);
        }

        // --- self-gop-64x64-q60-fi-cfl: KEY + FI P-frame + CfL
        // P-frame (the two intra-tool witness constructions composed
        // into one GOP over a noise-luma / flat-chroma anchor). ---
        {
            let base_q_idx = 60u8;
            let mut f0 = noise_frame(64, 64, 41);
            f0.u.fill(128);
            f0.v.fill(128);
            // FI frame: SE quadrant = the ยง7.11.2.3 prediction of its
            // own decode-time neighbours (static pass 1).
            let enc1 = encode_gop_yuv_with_q(&[f0.clone(), f0.clone()], base_q_idx).unwrap();
            let rec1 = &enc1.recon[1];
            let (above_ext, left_ext, _, _) = super::super::key_frame::build_tu_neighbours(
                &rec1.y, 64, 64, 32, 32, 0, 0, 32, 32, false, false, 8,
            );
            let target = super::super::key_frame::predict_filter_intra_from_neighbours(
                2, 32, 32, &above_ext, &left_ext, 8,
            )
            .expect("32x32 filter-intra prediction");
            let mut f1 = f0.clone();
            for i in 0..32usize {
                for j in 0..32usize {
                    f1.y[(32 + i) * 64 + 32 + j] = target[i * 32 + j];
                }
            }
            // CfL frame: SE quadrant = smooth texture with
            // luma-tracking chroma at the (2, โˆ’2) grid point.
            let tex = |i: usize, j: usize| -> u16 {
                let v = 128.0
                    + 70.0 * ((i as f64) * 0.35).sin() * ((j as f64) * 0.29).cos()
                    + 30.0 * (((i + j) as f64) * 0.11).sin();
                v.clamp(0.0, 255.0) as u16
            };
            let mut f2 = f1.clone();
            for i in 0..32usize {
                for j in 0..32usize {
                    f2.y[(32 + i) * 64 + 32 + j] = tex(i, j);
                }
            }
            let mut acc = 0i64;
            for i in 0..16usize {
                for j in 0..16usize {
                    acc += i64::from(tex(2 * i, 2 * j))
                        + i64::from(tex(2 * i + 1, 2 * j))
                        + i64::from(tex(2 * i, 2 * j + 1))
                        + i64::from(tex(2 * i + 1, 2 * j + 1));
                }
            }
            let mean4 = acc / 256;
            for i in 0..16usize {
                for j in 0..16usize {
                    let s = i64::from(tex(2 * i, 2 * j))
                        + i64::from(tex(2 * i + 1, 2 * j))
                        + i64::from(tex(2 * i, 2 * j + 1))
                        + i64::from(tex(2 * i + 1, 2 * j + 1));
                    let ac = (s - mean4) / 16;
                    let cell = (16 + i) * 32 + 16 + j;
                    f2.u[cell] = (128 + ac).clamp(0, 255) as u16;
                    f2.v[cell] = (128 - ac).clamp(0, 255) as u16;
                }
            }
            let enc = encode_gop_yuv_with_q(&[f0, f1, f2], base_q_idx).unwrap();
            dump("self-gop-64x64-q60-fi-cfl", &enc);
        }
    }
}

#[cfg(test)]
mod delta_q_lossless_cap_tests {
    use super::delta_q_lossless_up_cap;

    /// ยง7.12.2: a lossless `data` exactly at `-base_q_idx` leaves no
    /// headroom (only downward swings); `-255` (the spec note) keeps
    /// the full span; a table without a lossless segment is unbound.
    #[test]
    fn cap_follows_the_lossless_headroom() {
        assert_eq!(delta_q_lossless_up_cap(60, &[0, -60]), 0);
        assert_eq!(delta_q_lossless_up_cap(60, &[0, -68]), 1);
        assert_eq!(delta_q_lossless_up_cap(60, &[0, -76]), 2);
        assert_eq!(delta_q_lossless_up_cap(100, &[0, -255]), 2);
        assert_eq!(delta_q_lossless_up_cap(72, &[0, 24, -72]), 0);
        assert_eq!(delta_q_lossless_up_cap(80, &[0, -40]), 2);
        assert_eq!(delta_q_lossless_up_cap(80, &[]), 2);
    }
}