oxideav-h264 0.1.9

Pure-Rust H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) codec for oxideav — under spec-driven rewrite, no decode/encode functionality yet
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
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
//! H.264 / AVC **encoder** — Baseline profile, IDR-only, with mb_type
//! switching between **I_16x16** (DC/V/H/Plane) and **I_NxN** (Intra_4x4
//! with all 9 §8.3.1.2 modes) based on per-MB SAD.
//!
//! Round-4 scope (round-1 DC-luma only; round-2 chroma residual +
//! multi-mode I_16x16; round-3 luma AC residual; round-4 I_NxN; see
//! `STATUS.md`):
//!
//! * **Profile:** Baseline (`profile_idc = 66`), 4:2:0, 8-bit, single
//!   slice per picture, no FMO.
//! * **Slice types:** IDR I-slices only.
//! * **Macroblock types:** per-MB choice between `I_16x16` (4 modes)
//!   and `I_NxN` / Intra_4x4 (9 per-block modes). The lower-SAD path
//!   wins. mb_type is signalled via Table 7-11.
//! * **Chroma intra:** §8.3.4 four modes (DC, V, H, Plane) selected per
//!   MB by minimum-SAD.
//! * **Transforms:** 4x4 integer transform + 4x4 luma-DC Hadamard
//!   (Intra_16x16 only) + 2x2 chroma-DC Hadamard. Flat scaling lists.
//! * **CBP:**
//!   - Intra_16x16: `cbp_luma` ∈ {0, 15} (per §7.4.5.1) — 15 whenever
//!     any 4x4 luma AC has a non-zero coefficient.
//!   - I_NxN: `cbp_luma` ∈ 0..=15, one bit per 8x8 quadrant.
//!   - `cbp_chroma` ∈ {0, 1, 2}.
//! * **Entropy:** CAVLC, with per-MB neighbour grid (`CavlcNcGrid`)
//!   driving §9.2.1.1 nC derivation for AC blocks.
//! * **In-loop filter:** §8.7 deblock applied to local recon as a
//!   picture-level pass after every MB has been emitted (round-14).
//!   `disable_deblocking_filter_idc = 0`, alpha/beta offsets = 0.
//!
//! Spec references throughout cite ITU-T Rec. H.264 (08/2024).

#![allow(dead_code)]

#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod bitstream;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod cabac_engine;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod cabac_path;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod cabac_syntax;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod cavlc;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod deblock;
pub mod deep;
pub mod field;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod intra4x4;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod intra_pred;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod macroblock;
pub mod mbaff;
pub mod mbaff_cabac;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod me;
pub mod multiref;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod nal;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod pps;
pub mod rate_control;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod rdo;
pub mod scp;
pub mod sei;
pub mod session;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod slice;
pub mod slices;
pub mod sp;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod sps;
#[doc(hidden)] // internal — exposed for tests/fuzz; not part of the stable API
pub mod transform;

use crate::cavlc::CoeffTokenContext;

/// See the note on [`Encoder::encode_p_mb`]: decoder-visible QP_Y
/// chain state for §7.4.5 `mb_qp_delta` emission.
#[derive(Debug, Clone, Copy)]
struct MbQpTracker {
    /// QP_Y the decoder holds after the most recent MB (the §7.4.5
    /// predictor for the next `mb_qp_delta`). Initialised to
    /// SliceQP_Y (§7.4.3).
    cur: i32,
    /// Round-453 MBAFF — §7.3.4: a pending `mb_field_decoding_flag`
    /// that must be written right after the next `mb_skip_run` flush
    /// (i.e. before the next coded `macroblock_layer()`), for the
    /// top MB of a pair or for a bottom MB whose top was skipped.
    /// `None` outside MBAFF frames and once the flag has been coded.
    mbaff_flag_pending: Option<bool>,
    /// Round-453 MBAFF — the current MB is a FIELD macroblock of an
    /// MBAFF frame: §7.3.5.1 codes `ref_idx_l0` te(v) even with one
    /// active reference frame (the field MB addresses
    /// `2 * num_ref_idx_l0_active` reference fields, §8.4.2.1).
    mbaff_field_mb: bool,
    /// Round-453 — §8.4.2.3.2 explicit weighted prediction for the
    /// slice's single L0 reference: the effective `(w0, o0)` and
    /// `logWD` (already §7.4.3.2-inferred). `None` = default
    /// (§8.4.2.3.1 copy-through) prediction.
    wp_l0: Option<WeightedPredL0>,
    /// Round-453 — §7.4.5.1 `ref_idx_l0` the current P macroblock
    /// codes (the driver's per-MB reference election; 0 in the
    /// single-reference paths). P_Skip is only legal at 0.
    ref_idx_l0: i32,
    /// Round-453 — the slice's `num_ref_idx_l0_active_minus1` (frame
    /// units, i.e. the §7.4.3 value after any override). The te(v)
    /// range of `ref_idx_l0` follows from it (doubled for MBAFF field
    /// MBs).
    num_ref_idx_l0_active_minus1_slice: u32,
    /// Round-453 — §6.4.11.1 intra neighbour availability override
    /// `(top, left, top-left)` for the current MB: `Some` in
    /// multi-slice / FMO pictures (§6.4.8 other-slice neighbours are
    /// unavailable) and under `constrained_intra_pred_flag` (§8.3.1.2
    /// inter neighbours are unavailable to intra prediction); `None`
    /// keeps the raster coordinate rule.
    intra_nb: Option<(bool, bool, bool)>,
}

/// Round-453 — §8.4.2.3.2 single-list explicit weighting parameters.
#[derive(Debug, Clone, Copy)]
struct WeightedPredL0 {
    log2_wd: u32,
    weight: i32,
    offset: i32,
}

impl WeightedPredL0 {
    /// §8.4.2.3.2 eq. 8-274 — weight one L0 prediction block in place
    /// (8-bit Clip1).
    fn apply(&self, pred: &mut [i32]) {
        for p in pred.iter_mut() {
            let v = if self.log2_wd >= 1 {
                ((*p * self.weight + (1i32 << (self.log2_wd - 1))) >> self.log2_wd) + self.offset
            } else {
                *p * self.weight + self.offset
            };
            *p = v.clamp(0, 255);
        }
    }
}

impl MbQpTracker {
    fn new(cur: i32) -> Self {
        Self {
            cur,
            mbaff_flag_pending: None,
            mbaff_field_mb: false,
            wp_l0: None,
            ref_idx_l0: 0,
            num_ref_idx_l0_active_minus1_slice: 0,
            intra_nb: None,
        }
    }

    /// §7.3.4 — emit the pending `mb_field_decoding_flag` (if any) at
    /// the position right after `mb_skip_run`.
    fn write_pending_mbaff_flag(&mut self, sw: &mut BitWriter) {
        if let Some(f) = self.mbaff_flag_pending.take() {
            sw.u(1, u32::from(f));
        }
    }

    /// §7.3.5.1 / §7.4.5.1 — `num_ref_idx_l0_active_minus1` as seen
    /// by the MB writers: the slice value, doubled-plus-one for MBAFF
    /// field MBs (two reference fields per reference frame,
    /// §8.4.2.1).
    fn num_ref_idx_l0_active_minus1(&self) -> u32 {
        let n = self.num_ref_idx_l0_active_minus1_slice;
        if self.mbaff_field_mb {
            2 * (n + 1) - 1
        } else {
            n
        }
    }
}
use crate::encoder::bitstream::BitWriter;
use crate::encoder::cavlc::encode_residual_block_cavlc;
use crate::encoder::deblock::{
    chroma_nz_mask_from_blocks, luma_nz_mask_from_blocks, MbDeblockInfo,
};
use crate::encoder::intra4x4::{
    availability as i4x4_avail, predict_4x4, Intra4x4Mode, LUMA_4X4_XY as I4X4_XY,
};
use crate::encoder::intra_pred::{
    predict_16x16, predict_16x16_avail, predict_chroma_8x8_avail, sad_8x8, I16x16Mode,
    IntraChromaMode,
};
use crate::encoder::macroblock::{
    write_b_16x16_mb, write_b_8x8_mixed_mb, write_i8x8_mb, write_i_nxn_mb, write_intra16x16_mb,
    write_intra16x16_mb_in_inter_slice, write_p_8x8_all_pl08x8_mb, B16x16McbConfig,
    B8x8MixedMcbConfig, BPartPred, BPred16x16, BSubMbCell, I16x16McbConfig, I8x8McbConfig,
    INxNMcbConfig, P8x8AllPL08x8McbConfig, PL016x16McbConfig,
};
use crate::encoder::me::{search_quarter_pel_16x16, search_quarter_pel_8x8};
use crate::encoder::nal::build_nal_unit;
use crate::encoder::pps::{build_baseline_pps_rbsp, BaselinePpsConfig};
use crate::encoder::rdo::{cost_combined, lambda_ssd, ssd_16x16, ssd_4x4};
use crate::encoder::slice::{
    write_b_slice_header, write_idr_i_slice_header, write_p_slice_header, BSliceHeaderConfig,
    ExplicitBipredWeightTable, ExplicitPredWeightTableL0, FieldPicSignal, IdrSliceHeaderConfig,
    PSliceHeaderConfig,
};
use crate::encoder::sps::{build_baseline_sps_rbsp, BaselineSpsConfig};
use crate::encoder::transform::{
    deinterleave_8x8_to_4x4, forward_core_4x4, forward_core_8x8, forward_hadamard_2x2,
    forward_hadamard_4x4, quantize_4x4_ac_w, quantize_4x4_w, quantize_8x8_w, quantize_chroma_dc_w,
    quantize_luma_dc_w, scan_8x8_for_cavlc, zigzag_scan_4x4, zigzag_scan_4x4_ac,
};
use crate::inter_pred::{interpolate_chroma, interpolate_luma};
use crate::intra_pred::{
    filter_samples_8x8, predict_8x8, Intra8x8Mode, Neighbour4x4Availability, Samples8x8,
};
use crate::macroblock_layer::{derive_nc_luma, CavlcNcGrid, LumaNcKind};
use crate::mv_deriv::{Mv, MvpredInputs, NeighbourMv};
use crate::nal::NalUnitType;
use crate::transform::{
    inverse_hadamard_chroma_dc_420, inverse_hadamard_luma_dc_16x16, inverse_scan_4x4_zigzag_ac,
    inverse_transform_4x4, inverse_transform_4x4_dc_preserved, inverse_transform_8x8, qp_bd_offset,
    qp_y_to_qp_c_with_bd_offset, FLAT_4X4_16,
};

/// §6.4.3 / Figure 6-10 — luma 4x4 block scan: index 0..=15 → (x, y)
/// offset of the block inside a macroblock (in 4-sample units, *not*
/// pixels). This mirrors `crate::reconstruct::LUMA_4X4_XY` but in
/// 4x4-block coordinates so the encoder can index the per-block AC
/// arrays directly.
const LUMA_4X4_BLK: [(usize, usize); 16] = [
    (0, 0),
    (1, 0),
    (0, 1),
    (1, 1),
    (2, 0),
    (3, 0),
    (2, 1),
    (3, 1),
    (0, 2),
    (1, 2),
    (0, 3),
    (1, 3),
    (2, 2),
    (3, 2),
    (2, 3),
    (3, 3),
];

/// One encoded YUV frame's worth of input planes. All planes are
/// 8-bit, row-major. Width and height must be multiples of 16 (no
/// cropping support yet).
///
/// Default chroma layout is 4:2:0 — `u` / `v` length is `(W/2) *
/// (H/2)`. When the encoder is configured for 4:2:2
/// (`EncoderConfig::chroma_format_idc = 2`, round 27), `u` / `v` length
/// is `(W/2) * H` — half-width, full-height per §6.2 Table 6-1.
pub struct YuvFrame<'a> {
    pub width: u32,
    pub height: u32,
    pub y: &'a [u8],
    pub u: &'a [u8],
    pub v: &'a [u8],
}

/// Encoder configuration.
/// §7.4.2.1.1.1 — encoder scaling-matrix signalling mode.
// The custom variants inline 640 bytes of list values so the enum (and
// `EncoderConfig`) stays `Copy` — a Box would force Clone-only configs
// for a rarely-hot struct that is passed by reference everywhere.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScalingMatrixMode {
    /// Flat lists (all 16s) — no matrices signalled. The round-1..387
    /// behaviour.
    #[default]
    Flat,
    /// Emit the Table 7-3 / Table 7-4 **default** matrices at sequence
    /// level (`seq_scaling_matrix_present_flag = 1`, every list coded
    /// as UseDefaultScalingMatrixFlag).
    SeqDefault,
    /// Emit the default matrices at picture level
    /// (`pic_scaling_matrix_present_flag = 1` in the PPS tail).
    PicDefault,
    /// Round-391 — emit **custom user-supplied** list values at
    /// sequence level: every `seq_scaling_list_present_flag[i] = 1`
    /// and the §7.3.2.1.1.1 delta_scale chain codes the caller's
    /// values explicitly (no UseDefaultScalingMatrixFlag shortcut).
    SeqCustom(CustomScalingLists),
    /// Round-391 — custom user-supplied list values at picture level
    /// (§7.3.2.2 PPS tail).
    PicCustom(CustomScalingLists),
}

/// Round-391 — user-supplied §7.4.2.1.1.1 scaling-list values.
///
/// Values are in the **bitstream list order** (the §7.3.2.1.1.1
/// `j`-loop order, i.e. the §8.5.6 / §8.5.7 zig-zag scan — the same
/// layout as the Table 7-3 / 7-4 defaults) and must each be in
/// `1..=255` (a first value of 0 would signal
/// UseDefaultScalingMatrixFlag; later zeros would freeze the list).
///
/// The encoder emits the same 4x4 values for the Y / Cb / Cr list
/// slots of a group (lists 0..=2 intra, 3..=5 inter) and applies them
/// uniformly in its own quantiser — matching the §8.5.9 weightScale
/// the decoder derives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CustomScalingLists {
    /// 4x4 intra list (SPS/PPS lists 0..=2), scan order.
    pub intra4: [i32; 16],
    /// 4x4 inter list (SPS/PPS lists 3..=5), scan order.
    pub inter4: [i32; 16],
    /// 8x8 intra Y list (list 6), scan order.
    pub intra8: [i32; 64],
    /// 8x8 inter Y list (list 7), scan order.
    pub inter8: [i32; 64],
}

impl CustomScalingLists {
    /// §7.4.2.1.1.1 — all entries must lie in `1..=255`.
    pub fn is_valid(&self) -> bool {
        self.intra4.iter().all(|v| (1..=255).contains(v))
            && self.inter4.iter().all(|v| (1..=255).contains(v))
            && self.intra8.iter().all(|v| (1..=255).contains(v))
            && self.inter8.iter().all(|v| (1..=255).contains(v))
    }
}

/// §7.3.2.1.1.1 — what an SPS / PPS scaling-list loop should emit.
// Same `Copy` rationale as [`ScalingMatrixMode`].
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalingListsSpec {
    /// Every list present, coded as UseDefaultScalingMatrixFlag
    /// (`delta_scale = -8` at `j == 0`) → Table 7-3 / 7-4 defaults.
    Default,
    /// Every list present with explicitly coded caller values.
    Custom(CustomScalingLists),
}

/// Effective weightScale matrices for the encoder's quantise +
/// reconstruct pipeline (row-major, §8.5.9 layout — the same arrays
/// the decoder's `select_scaling_list_*` return).
pub(crate) struct WeightPair {
    pub(crate) w4: [i32; 16],
    pub(crate) w8: [i32; 64],
}

impl ScalingMatrixMode {
    pub(crate) fn is_flat(self) -> bool {
        matches!(self, ScalingMatrixMode::Flat)
    }

    /// The `Some(spec)` to emit in the SPS scaling-list loop.
    pub(crate) fn seq_spec(self) -> Option<ScalingListsSpec> {
        match self {
            ScalingMatrixMode::SeqDefault => Some(ScalingListsSpec::Default),
            ScalingMatrixMode::SeqCustom(l) => Some(ScalingListsSpec::Custom(l)),
            _ => None,
        }
    }

    /// The `Some(spec)` to emit in the PPS scaling-list loop.
    pub(crate) fn pic_spec(self) -> Option<ScalingListsSpec> {
        match self {
            ScalingMatrixMode::PicDefault => Some(ScalingListsSpec::Default),
            ScalingMatrixMode::PicCustom(l) => Some(ScalingListsSpec::Custom(l)),
            _ => None,
        }
    }

    /// The intra weightScale pair this mode produces. All three 4x4
    /// intra lists (Y/Cb/Cr) carry the same values under every
    /// non-flat mode this encoder emits, and the matching 8x8 intra
    /// list covers the 8x8 shape, so one pair covers every intra
    /// block shape.
    pub(crate) fn intra_weights(self) -> WeightPair {
        use crate::transform::{
            weight_scale_4x4_from_scan, weight_scale_8x8_from_scan, DEFAULT_4X4_INTRA,
            DEFAULT_8X8_INTRA, FLAT_8X8_16,
        };
        match self {
            ScalingMatrixMode::Flat => WeightPair {
                w4: FLAT_4X4_16,
                w8: FLAT_8X8_16,
            },
            ScalingMatrixMode::SeqDefault | ScalingMatrixMode::PicDefault => WeightPair {
                w4: weight_scale_4x4_from_scan(&DEFAULT_4X4_INTRA),
                w8: weight_scale_8x8_from_scan(&DEFAULT_8X8_INTRA),
            },
            ScalingMatrixMode::SeqCustom(l) | ScalingMatrixMode::PicCustom(l) => WeightPair {
                w4: weight_scale_4x4_from_scan(&l.intra4),
                w8: weight_scale_8x8_from_scan(&l.intra8),
            },
        }
    }

    /// The inter weightScale pair (Default_4x4_Inter / Default_8x8_Inter
    /// under the default modes; the caller's inter lists under custom).
    /// Round-391 — consumed by the P/B residual quantisers.
    pub(crate) fn inter_weights(self) -> WeightPair {
        use crate::transform::{
            weight_scale_4x4_from_scan, weight_scale_8x8_from_scan, DEFAULT_4X4_INTER,
            DEFAULT_8X8_INTER, FLAT_8X8_16,
        };
        match self {
            ScalingMatrixMode::Flat => WeightPair {
                w4: FLAT_4X4_16,
                w8: FLAT_8X8_16,
            },
            ScalingMatrixMode::SeqDefault | ScalingMatrixMode::PicDefault => WeightPair {
                w4: weight_scale_4x4_from_scan(&DEFAULT_4X4_INTER),
                w8: weight_scale_8x8_from_scan(&DEFAULT_8X8_INTER),
            },
            ScalingMatrixMode::SeqCustom(l) | ScalingMatrixMode::PicCustom(l) => WeightPair {
                w4: weight_scale_4x4_from_scan(&l.inter4),
                w8: weight_scale_8x8_from_scan(&l.inter8),
            },
        }
    }
}

#[derive(Debug, Clone)]
pub struct EncoderConfig {
    pub width: u32,
    pub height: u32,
    /// Slice QP_Y. Range 0..=51. Default 26 (PPS pic_init_qp_minus26 = 0
    /// + slice_qp_delta = 0).
    pub qp: i32,
    /// §7.4.2.1 — `profile_idc` for the emitted SPS. Default 66
    /// (Baseline). Set to 77 (Main) when calling [`Encoder::encode_b`]
    /// because §A.2.2 forbids B-slices in Baseline.
    pub profile_idc: u8,
    /// §7.4.2.1.1 — `max_num_ref_frames`. Default 1 (one reference,
    /// sufficient for IDR + linear P chain). Round-20 B-slice support
    /// needs 2 (the prior IDR is the L0 reference, the prior P-frame
    /// is the L1 reference, both must remain in the DPB until the B
    /// MB has been decoded).
    pub max_num_ref_frames: u32,
    /// §7.4.3 / §8.4.1.2 — when `false` (default) the encoder emits
    /// `direct_spatial_mv_pred_flag = 1` in the B-slice header and
    /// drives B_Skip / B_Direct via §8.4.1.2.2 spatial direct
    /// derivation (round 21 / 23). When `true`, the encoder emits
    /// `direct_spatial_mv_pred_flag = 0` and uses §8.4.1.2.3
    /// **temporal direct** derivation: per-8x8 (mvL0, mvL1, refIdxL0,
    /// refIdxL1) are computed by POC-scaling the colocated L1
    /// anchor's L0 motion vectors. Round-24.
    pub direct_temporal_mv_pred: bool,
    /// Round-440 — restrict the B mode decision to modes whose motion
    /// stays representable in the L0-only colocated snapshot
    /// ([`FrameRefPartitionMv`]) a later B picture's §8.4.1.2
    /// direct-mode derivation reads: drops the explicit L1-only 16x16
    /// candidate and the Mixed8x8 candidate. Used when the coded B
    /// picture will itself serve as a REFERENCE (PAFF B reference
    /// fields) so the encoder-side co-located model matches what a
    /// decoder reads back from the stored picture.
    pub b_l0_bi_only: bool,
    /// Round-26 — §7.4.2.2 / §8.4.2.3.2 explicit weighted bipred for B
    /// slices. When `true` the encoder:
    ///   * Sets PPS `weighted_bipred_idc = 1` so the decoder pulls a
    ///     `pred_weight_table()` from each B slice header.
    ///   * Selects per-slice (luma_weight_l0, luma_weight_l1,
    ///     luma_offset_l0, luma_offset_l1) at `luma_log2_weight_denom = 5`
    ///     via the §8.4.2.3.2 forward least-squares fit
    ///     ([`compute_explicit_bipred_weights`]).
    ///   * Replaces the bipred merge in `build_b_predictors` with the
    ///     §8.4.2.3.2 eq. 8-276 explicit formula so the local recon
    ///     stays bit-equivalent to what the decoder produces.
    ///
    /// When `false` (default) bipred uses the §8.4.2.3.1 default
    /// average `(L0 + L1 + 1) >> 1` and the PPS / slice header carry no
    /// pred_weight_table.
    pub explicit_weighted_bipred: bool,
    /// Round-453 — §7.4.2.2 `weighted_pred_flag = 1`: P slices carry
    /// a §7.3.3.2 `pred_weight_table()` and predict through the
    /// §8.4.2.3.2 explicit process. Per P picture the encoder fits a
    /// slice-wide luma `(weight, offset)` against the reference
    /// (least squares, `logWD = 5`) and codes it when it beats the
    /// identity weighting by at least 1% SSD on the co-located
    /// planes (fade detection); otherwise the table codes
    /// `luma_weight_l0_flag = 0` (identity). Chroma weights are never
    /// coded. Default `false`.
    pub explicit_weighted_pred: bool,
    /// Round-29 — when `true` (default) the P/B-slice encoder runs an
    /// **intra fallback** RDO trial on every coded MB: the inter MB cost
    /// `J_inter = D_inter + λ·R_inter` is compared against an Intra_16x16
    /// trial cost `J_intra`, and the lower-J path wins. This covers
    /// occlusion, scene-cut frames, and high-detail areas where motion-
    /// compensated prediction's residual is more expensive to code than
    /// a fresh intra block. Per H.264 §7.3.5 (Tables 7-13 / 7-14) the
    /// chosen MB is emitted with the intra mb_type values shifted by +5
    /// (P-slice) or +23 (B-slice) so the decoder picks up Intra_16x16
    /// from the inter-slice mb_type tables.
    ///
    /// When `false`, P/B slices are inter-only (`P_Skip` / `P_L0_*` /
    /// `B_Skip` / `B_*_*`) — the round-16..28 behaviour. Useful for
    /// A/B tests against the new path.
    ///
    /// Round-29 scope: I_16x16 only (no I_NxN / I_PCM fallback). The
    /// intra trial runs only on coded inter MBs (P_Skip / B_Skip retain
    /// their zero-syntax fast path).
    pub intra_in_inter: bool,
    /// §7.4.2.1.1 / §6.2 — `chroma_format_idc`. Defaults to 1 (4:2:0).
    /// Round-27 supports 2 (4:2:2) on the `encode_idr` path: the
    /// emitted SPS is High 4:2:2 (profile_idc=122), the chroma plane
    /// is 8x16 per MB (two stacked 8x8 tiles), the chroma DC Hadamard
    /// is 2x4 per §8.5.11.2, and the deblock pass adapts via
    /// `Picture::chroma_array_type`.
    ///
    /// Round-28 adds 3 (4:4:4) on `encode_idr` (Intra_16x16 only):
    /// the emitted SPS is High 4:4:4 Predictive (profile_idc=244), the
    /// chroma plane is the full 16x16 per MB, each plane is encoded
    /// "like luma" (16x16 DC Hadamard + 16 4x4 AC blocks per plane —
    /// §7.3.5.3 / §8.5.10), and `intra_chroma_pred_mode` is omitted
    /// (chroma reuses the luma Intra_16x16 mode per §8.3.4.1). To
    /// keep round-28 scope manageable: I_NxN is disabled, deblocking
    /// is turned off (`disable_deblocking_filter_idc=1`), and
    /// `separate_colour_plane_flag` stays at 0 (separate planes are
    /// out of scope). Other values (0 monochrome) and the P/B-slice
    /// paths remain 4:2:0-only.
    pub chroma_format_idc: u32,
    /// Round-448 — separate-colour-plane per-plane encoding. When
    /// `Some(plane)`, this encoder instance codes ONE colour plane
    /// (0 = Y, 1 = Cb, 2 = Cr per §7.4.3) of a
    /// `separate_colour_plane_flag = 1` High 4:4:4 Predictive stream:
    /// the emitted SPS carries the on-wire pair
    /// (`chroma_format_idc = 3`, `separate_colour_plane_flag = 1`),
    /// every slice header codes `colour_plane_id = plane`, and the
    /// picture itself is coded with the monochrome pipeline
    /// (ChromaArrayType 0 — requires `chroma_format_idc = 0` and
    /// `profile_idc = 244`). A full three-plane stream is assembled by
    /// running three such encoders (one per plane) over the Y / Cb /
    /// Cr sample arrays and interleaving their slice NALs per access
    /// unit — see `encoder::scp::encode_scp_sequence`.
    pub colour_plane_id: Option<u8>,
    /// Round-30 — when `true`, the encoder emits CABAC entropy coding
    /// (`entropy_coding_mode_flag = 1` in the PPS). Use the
    /// [`Encoder::encode_idr_cabac`] / [`Encoder::encode_p_cabac`]
    /// entry points; the existing CAVLC paths
    /// ([`Encoder::encode_idr`] / [`Encoder::encode_p`]) ignore this
    /// flag and continue emitting CAVLC.
    ///
    /// CABAC is forbidden by Baseline profile (§A.2.1); enabling this
    /// flag requires `profile_idc >= 77` (Main).
    pub cabac: bool,
    /// Round-430 — §E.1.1 `vui_parameters()` appended to every SPS
    /// this encoder emits (`None` keeps the historical
    /// `vui_parameters_present_flag = 0`). The rate-controlled
    /// sessions set VUI timing info + §E.1.2 NAL HRD parameters here
    /// so CBR streams are formally HRD-annotated in-band.
    pub vui: Option<crate::vui::VuiParameters>,
    /// §7.4.2.1.1 / Annex A Table A-1 — `level_idc` to emit in the
    /// SPS. Default: derived from `(width, height)` so the smallest
    /// level whose `MaxFS` covers the picture is selected. A 720p
    /// stream rounds up to 31 (Level 3.1, MaxFS = 3600 mb), 1080p to
    /// 40 (Level 4, MaxFS = 8192 mb), 4K UHD to 51 (Level 5.1, MaxFS
    /// = 36864 mb). Override when you know the actual constraint set
    /// for the deployment (e.g. fixing a Level 4.0 cap because a
    /// downstream decoder doesn't support 4.1+).
    ///
    /// Pre-config-flag behaviour was a hard-coded `level_idc = 30`
    /// (Level 3, MaxFS 1620 mb = 720x576 SD). Encoding 720p / 1080p
    /// content with that signalling produced spec-non-conformant
    /// streams (PicSize > MaxFS) — strict decoders are entitled to
    /// reject them. The new derivation closes that gap without
    /// changing any other encoder behaviour.
    pub level_idc: u8,
    /// §7.4.2.1.1 — `bit_depth_chroma_minus8`. Defaults to 0 (8-bit
    /// chroma). The current SPS writer ([`crate::encoder::sps`]) pins
    /// the emitted bit_depth fields at 0 — High10/422/444 with bit
    /// depth >8 is out of round-30 scope. This field is plumbed through
    /// the encoder state so that the §8.5.8 chroma-QP derivation calls
    /// the BD-aware [`crate::transform::qp_y_to_qp_c_with_bd_offset`]
    /// with the correct `qp_bd_offset_c = 6 * bit_depth_chroma_minus8`.
    /// When a future round extends the SPS to emit non-zero bit_depth
    /// fields, the encoder's QPC math is already wired to follow.
    pub bit_depth_chroma_minus8: u32,
    /// Round-49 — trellis quantisation refinement (a.k.a. RDOQ-lite)
    /// for inter AC residual blocks. When `true` (default), after the
    /// open-loop `quantize_4x4` step in the CABAC inter path the
    /// encoder runs [`crate::encoder::transform::trellis_refine_4x4_ac`]
    /// over each 4x4 luma + chroma AC block to refine quantised levels
    /// toward zero whenever the resulting `D + λ·R` cost is strictly
    /// lower. The refinement is informative (§9 is silent on forward
    /// quant strategy beyond the round-trip property) so the decoder
    /// is unaffected.
    ///
    /// Empirical effect on the round-25 mixed-motion B-slice fixture:
    ///   * CABAC B-slice: 12 → 11 bytes (~8 %), PSNR_Y 44.20 → 44.20 dB
    ///     (no measurable loss; trellis only flips coefficients whose
    ///     rate cost dominates their distortion contribution).
    ///   * Wider GOPs on textured content see ~5-12 % saving on the
    ///     coded inter MBs.
    pub trellis_quant: bool,
    /// Round-453 — run the **full trellis RDOQ**
    /// ([`crate::encoder::transform::trellis_refine_4x4_ac_full`]:
    /// Viterbi over the §9.3.3.1.3 residual binarisation with
    /// §9.3.1.1-initialised context costs) on the CABAC paths instead
    /// of the round-49 lite pass. Measured on the textured-motion
    /// P + B fixture over QP 20..=36: 1.1 % smaller P + B payload at
    /// ≤ 0.1 dB (QP 32 P slice −8 %), but one QP-34 B slice grew by
    /// 4 bytes against the open-loop quantiser, so the lite pass
    /// (which never regresses size on that sweep) stays the default:
    /// `false`. Opt in with `true`.
    pub trellis_full: bool,
    /// Round-148 — opt-in trellis quantisation refinement on the CABAC
    /// **IDR Intra_16x16 luma AC** path. Default `false`.
    ///
    /// When enabled, the 16 per-block 4x4 AC arrays produced by
    /// `quantize_intra16x16_luma` are passed through
    /// [`crate::encoder::transform::trellis_refine_4x4_ac`] with
    /// `skip_dc=true` so the §8.5.10 inverse-Hadamard DC chain stays
    /// untouched. The bitstream syntax does not change; the decoder
    /// is unaffected; `cbp_luma` keeps the §7.4.5.1 Table 7-11 value
    /// (`15` whenever any AC remains non-zero across the MB).
    ///
    /// Default is `false` because the [`trellis_quant`] rate model is
    /// calibrated for inter blockCats and tends to *enlarge* dense
    /// intra IDR streams at low QP on textured content (the
    /// open-loop deadzone is already near-optimal on Intra_16x16 AC at
    /// QP >= 22). The flag is wired so that a future round can
    /// re-calibrate the rate model for blockCat 1 (Intra16x16AC) and
    /// then flip the default. Until then the lever stays useful for
    /// callers who want maximum-compression IDRs on high-noise
    /// content where the open-loop quantiser leaves obvious AC
    /// residue.
    ///
    /// Decoder-transparency is verified by the round-148
    /// `integration_trellis_quant_idr` regression: a flipped IDR
    /// self-roundtrips bit-equivalently and ffmpeg cross-decodes
    /// within 1 LSB of the encoder's local recon.
    pub trellis_quant_intra: bool,
    /// Round-151 — opt-in trellis quantisation refinement on the CABAC
    /// **IDR Intra_16x16 chroma AC** path. Default `false`.
    ///
    /// When enabled, the per-block 4x4 chroma AC arrays produced by
    /// `encode_chroma_intra16x16_420` (4 blocks per plane) and
    /// `encode_chroma_intra16x16_444` (16 blocks per plane) are passed
    /// through [`crate::encoder::transform::trellis_refine_4x4_ac`] with
    /// `skip_dc=true`. The §8.5.11 inverse-Hadamard chroma-DC chain
    /// (4:2:0: 2×2 Hadamard over the 4 plane DCs; 4:4:4: 4×4 Hadamard
    /// over the 16 plane DCs treated like luma) is left untouched, so
    /// `cbp_chroma` keeps the §7.4.5.1 Table 7-15 value (the
    /// AC-vs-DC-only distinction depends only on whether any AC remains
    /// non-zero across the MB).
    ///
    /// Default is `false` for the same reason as [`trellis_quant_intra`]:
    /// the [`trellis_quant`] rate model is calibrated for inter
    /// blockCat 2 and can enlarge dense intra chroma AC at low QP. The
    /// flag is wired so a future round can re-calibrate the rate model
    /// for blockCats 4 (ChromaACLevel @ 4:2:0) / 1 (Intra16x16AC @ 4:4:4
    /// treated like luma) and flip the default.
    ///
    /// Decoder-transparency is verified by the round-151
    /// `integration_trellis_quant_intra_chroma` regression: a flipped
    /// IDR with non-trivial chroma content self-roundtrips
    /// bit-equivalently through the local decoder.
    pub trellis_quant_intra_chroma: bool,
    /// Round-382 — High-profile **8x8 transform** (Intra_8x8) on the
    /// `encode_idr` CAVLC path. When `true`, the emitted SPS is High
    /// (`profile_idc = 100`), the PPS carries `transform_8x8_mode_flag =
    /// 1`, and the per-MB Lagrangian RDO trials **Intra_8x8** (I_NxN
    /// with `transform_size_8x8_flag = 1`: §8.3.2 8x8 intra prediction
    /// across all 9 modes + §8.6.4 forward 8x8 transform + §8.5.13.1
    /// quantiser + §7.4.5.3.3 CAVLC four-4x4 residual split) alongside
    /// the existing I_16x16 and I_4x4 trials; the lowest-J path wins
    /// per MB. I_4x4 MBs in such a stream code
    /// `transform_size_8x8_flag = 0` per §7.3.5. Requires 4:2:0 chroma.
    /// Default `false` (High-profile signalling and the third trial are
    /// omitted).
    pub transform_8x8: bool,
    /// Round-388 — §7.3.2.1.1.1 scaling matrices. Non-flat modes emit
    /// the Table 7-3/7-4 default quantisation matrices (sequence- or
    /// picture-level) and run the encoder's forward quantiser +
    /// normative inverse under the matching §8.5.9 weightScale.
    /// Currently supported on the CAVLC `encode_idr` path at 4:2:0
    /// (all three intra transform shapes); every other entry point
    /// requires `Flat`.
    pub scaling_matrix: ScalingMatrixMode,
    /// Round-416 PAFF — §8.4.1.4 Table 8-10 vertical chroma-MV
    /// adjustment, in the same numeric units as `mvLX[1]`
    /// (quarter-luma == eighth-chroma sample units at 4:2:0). A FIELD
    /// picture referencing the OPPOSITE-parity field derives
    /// `mvCLX[1] = mvLX[1] + 2` (top reference, bottom current) or
    /// `mvLX[1] - 2` (bottom reference, top current); same-parity
    /// references and frame pictures keep 0. Applied to the P-path
    /// chroma predictors only (luma MC uses `mvLX` unchanged), so the
    /// encoder's local recon matches what a conformant decoder
    /// produces for a cross-parity field reference. Set by the
    /// `encoder::field` PAFF driver; leave 0 everywhere else.
    pub table_8_10_cy_offset: i32,
}

impl EncoderConfig {
    pub fn new(width: u32, height: u32) -> Self {
        let width_in_mbs = width.div_ceil(16);
        let height_in_mbs = height.div_ceil(16);
        Self {
            width,
            height,
            qp: 26,
            profile_idc: 66,
            max_num_ref_frames: 1,
            direct_temporal_mv_pred: false,
            b_l0_bi_only: false,
            explicit_weighted_bipred: false,
            explicit_weighted_pred: false,
            intra_in_inter: true,
            chroma_format_idc: 1,
            colour_plane_id: None,
            cabac: false,
            vui: None,
            level_idc: min_level_idc_for_picture_size(width_in_mbs, height_in_mbs),
            bit_depth_chroma_minus8: 0,
            trellis_quant: true,
            trellis_full: false,
            trellis_quant_intra: false,
            trellis_quant_intra_chroma: false,
            transform_8x8: false,
            scaling_matrix: ScalingMatrixMode::default(),
            table_8_10_cy_offset: 0,
        }
    }
}

/// Annex A Table A-1 — pick the smallest `level_idc` whose MaxFS
/// (max frame size in macroblocks) is at least `width_in_mbs *
/// height_in_mbs`. Used by [`EncoderConfig::new`] to default the
/// emitted SPS `level_idc` so 720p / 1080p / 4K encodes don't
/// silently signal a too-low Level 3 (the historical hard-coded
/// default).
///
/// The table walks from low to high so the caller could later cap
/// to a downstream decoder's max supported level if needed. We
/// include Levels 6.0 / 6.1 / 6.2 (added in the 2017+ revisions,
/// MaxFS = 139264 each) so 8K UHD (480x270 mb) + larger settle on
/// a real level rather than the previous 5.2 ceiling. Pictures
/// beyond Level 6.2 (the highest in the 2024-08 edition) fall off
/// the end and return 62 (the encoder will still emit it; whether
/// a decoder honours it is its problem).
///
/// MaxFS values are pulled directly from §A.3.1 Table A-1.
pub(crate) fn min_level_idc_for_picture_size(width_in_mbs: u32, height_in_mbs: u32) -> u8 {
    let pic_size = width_in_mbs.saturating_mul(height_in_mbs);
    // (level_idc, MaxFS) walking low→high; first hit wins.
    const LEVELS: &[(u8, u32)] = &[
        (10, 99),      // Level 1
        (11, 396),     // Level 1.1
        (12, 396),     // Level 1.2
        (13, 396),     // Level 1.3
        (20, 396),     // Level 2
        (21, 792),     // Level 2.1
        (22, 1_620),   // Level 2.2
        (30, 1_620),   // Level 3
        (31, 3_600),   // Level 3.1 (~720p)
        (32, 5_120),   // Level 3.2
        (40, 8_192),   // Level 4 (~1080p)
        (41, 8_192),   // Level 4.1
        (42, 8_704),   // Level 4.2
        (50, 22_080),  // Level 5 (~2.5K)
        (51, 36_864),  // Level 5.1 (~4K UHD)
        (52, 36_864),  // Level 5.2
        (60, 139_264), // Level 6 (~8K UHD)
        (61, 139_264), // Level 6.1
        (62, 139_264), // Level 6.2
    ];
    for &(level, max_fs) in LEVELS {
        if pic_size <= max_fs {
            return level;
        }
    }
    // Pictures beyond every standardised level — emit the highest
    // anyway so the SPS is at least syntactically valid; a strict
    // decoder is entitled to reject the level + size pairing.
    62
}

/// Encoder-side per-MB grid for the §8.3.1.1 / §6.4.11.4 neighbour
/// lookup needed by I_NxN mode prediction. Mirrors the small subset
/// of fields the decoder's [`crate::reconstruct::MbGrid`] tracks for
/// intra prediction. The encoder must agree with the decoder
/// bit-for-bit on the predicted Intra4x4 mode of every block,
/// otherwise `prev_intra4x4_pred_mode_flag = 1` would mean a different
/// mode on each side.
#[derive(Debug, Clone, Default)]
pub(crate) struct IntraGridSlot {
    available: bool,
    is_i_nxn: bool,
    /// `intra_4x4_pred_modes[i]` per §6.4.3 raster-Z order. Only
    /// populated when `is_i_nxn`.
    intra_4x4_pred_modes: [u8; 16],
    /// Round-382 — the MB is Intra_8x8 (I_NxN with
    /// `transform_size_8x8_flag == 1`). Mutually exclusive with
    /// `is_i_nxn` on the encoder grid (the decoder distinguishes the two
    /// via `mb_is_intra_4x4` / `mb_is_intra_8x8`).
    is_i8x8: bool,
    /// `intra_8x8_pred_modes[blk8]` per §6.4.5 8x8 raster order. Only
    /// populated when `is_i8x8`.
    intra_8x8_pred_modes: [u8; 4],
}

#[derive(Debug, Clone)]
pub(crate) struct IntraGrid {
    width_mbs: usize,
    slots: Vec<IntraGridSlot>,
}

impl IntraGrid {
    fn new(width_mbs: usize, height_mbs: usize) -> Self {
        Self {
            width_mbs,
            slots: vec![IntraGridSlot::default(); width_mbs * height_mbs],
        }
    }
    fn slot(&self, mb_x: usize, mb_y: usize) -> &IntraGridSlot {
        &self.slots[mb_y * self.width_mbs + mb_x]
    }
    fn slot_mut(&mut self, mb_x: usize, mb_y: usize) -> &mut IntraGridSlot {
        &mut self.slots[mb_y * self.width_mbs + mb_x]
    }
}

/// §6.4.11.4 + §8.3.1.1 — predict the Intra_4x4 mode for block
/// `block_idx` of the MB at (mb_x, mb_y) using the modes of neighbour
/// 4x4 blocks A (left) and B (above).
///
/// Returns the §8.3.1.1 step 4 `predIntra4x4PredMode` value (0..=8).
///
/// Algorithm (mirrors decoder's `derive_intra_4x4_pred_mode`):
///   1. Compute (xN, yN) = (bx-1, by) for A and (bx, by-1) for B in
///      MB-relative pixel coordinates of the current 4x4 block.
///   2. Locate the neighbour MB and the neighbour 4x4 block index per
///      §6.4.3 / Table 6-3 / eq. 6-38 (non-MBAFF frame case).
///   3. dcPredModePredictedFlag (step 2): true iff either neighbour MB
///      is unavailable OR (constrained_intra_pred && neighbour is not
///      intra). We don't use constrained_intra_pred → only the
///      availability check.
///   4. modeN (step 3): 2 (DC) when dcPredFlag, else
///      `intra_4x4_pred_modes[blkN]` of the neighbour MB if it's
///      I_NxN, else 2 (DC) for I_16x16/I_PCM/inter neighbours.
///   5. predicted = min(modeA, modeB).
fn predicted_intra4x4_mode(
    grid: &IntraGrid,
    mb_x: usize,
    mb_y: usize,
    block_idx: usize,
    pic_w_mbs: usize,
) -> u8 {
    use crate::encoder::intra4x4::LUMA_4X4_XY as XY;
    let (bx, by) = XY[block_idx];

    let neigh = |xd: i32, yd: i32| -> Option<(usize, usize, usize)> {
        // Eq. 6-25 / 6-26 (block-of-4-samples xN, yN inside MB grid).
        let xn = bx as i32 + xd;
        let yn = by as i32 + yd;
        // Table 6-3 (non-MBAFF frame): pick neighbour MB.
        let (nmb_x, nmb_y) = if xn < 0 && (0..16).contains(&yn) {
            // mbAddrA: left MB.
            if mb_x == 0 {
                return None;
            }
            (mb_x - 1, mb_y)
        } else if (0..16).contains(&xn) && yn < 0 {
            // mbAddrB: above MB.
            if mb_y == 0 {
                return None;
            }
            (mb_x, mb_y - 1)
        } else if (0..16).contains(&xn) && (0..16).contains(&yn) {
            (mb_x, mb_y)
        } else {
            return None;
        };
        // Eq. 6-34 / 6-35 — coords inside neighbour MB.
        let xw = ((xn + 16) % 16) as usize;
        let yw = ((yn + 16) % 16) as usize;
        // Eq. 6-38.
        let nblk = 8 * (yw / 8) + 4 * (xw / 8) + 2 * ((yw % 8) / 4) + ((xw % 8) / 4);
        Some((nmb_x, nmb_y, nblk))
    };

    let na = neigh(-1, 0);
    let nb = neigh(0, -1);

    let mb_a_avail = na
        .and_then(|(nx, ny, _)| Some(grid.slot(nx, ny)).filter(|s| s.available))
        .is_some();
    let mb_b_avail = nb
        .and_then(|(nx, ny, _)| Some(grid.slot(nx, ny)).filter(|s| s.available))
        .is_some();
    let dc_pred_flag = !mb_a_avail || !mb_b_avail;

    let mode_for = |neigh: Option<(usize, usize, usize)>| -> u8 {
        if dc_pred_flag {
            return 2;
        }
        let Some((nx, ny, nblk)) = neigh else {
            return 2;
        };
        let s = grid.slot(nx, ny);
        if !s.available {
            return 2;
        }
        if s.is_i_nxn {
            s.intra_4x4_pred_modes[nblk]
        } else if s.is_i8x8 {
            // §8.3.1.1 step 3 — neighbour coded Intra_8x8:
            // intraMxMPredModeN = Intra8x8PredMode[ blkN >> 2 ].
            s.intra_8x8_pred_modes[nblk >> 2]
        } else {
            // Intra_16x16 / I_PCM / inter neighbour → DC fallback.
            2
        }
    };
    let mode_a = mode_for(na);
    let mode_b = mode_for(nb);
    let _ = pic_w_mbs;
    mode_a.min(mode_b)
}

/// §6.4.11.2 + §8.3.2.1 — predict the Intra_8x8 mode for 8x8 block
/// `blk8` (raster 0..=3) of the MB at (mb_x, mb_y). Mirror of the
/// decoder's `derive_intra_8x8_pred_mode` step 1..4 (non-MBAFF frame):
///
///   1. Neighbour locations per eq. 6-23/6-24 with (xD, yD) = (-1, 0)
///      for A and (0, -1) for B; neighbour 8x8 index per eq. 6-40.
///   2. dcPredModePredictedFlag: either neighbour MB unavailable.
///   3. intraMxMPredModeN: the neighbour's `Intra8x8PredMode[blkN]`
///      when it is Intra_8x8; `Intra4x4PredMode[blkN*4 + n]` (eq. 8-72,
///      n = 1 for A / 2 for B in the frame case) when it is Intra_4x4;
///      2 (DC) otherwise.
///   4. predIntra8x8PredMode = Min(modeA, modeB).
fn predicted_intra8x8_mode(grid: &IntraGrid, mb_x: usize, mb_y: usize, blk8: usize) -> u8 {
    let neigh = |xd: i32, yd: i32| -> Option<(usize, usize, usize)> {
        // Eq. 6-23 / 6-24.
        let xn = ((blk8 as i32) % 2) * 8 + xd;
        let yn = ((blk8 as i32) / 2) * 8 + yd;
        let (nmb_x, nmb_y) = if xn < 0 && (0..16).contains(&yn) {
            if mb_x == 0 {
                return None;
            }
            (mb_x - 1, mb_y)
        } else if (0..16).contains(&xn) && yn < 0 {
            if mb_y == 0 {
                return None;
            }
            (mb_x, mb_y - 1)
        } else if (0..16).contains(&xn) && (0..16).contains(&yn) {
            (mb_x, mb_y)
        } else {
            return None;
        };
        let xw = ((xn + 16) % 16) as usize;
        let yw = ((yn + 16) % 16) as usize;
        // Eq. 6-40 — neighbour luma8x8BlkIdx.
        let nblk8 = 2 * (yw / 8) + (xw / 8);
        Some((nmb_x, nmb_y, nblk8))
    };
    let na = neigh(-1, 0);
    let nb = neigh(0, -1);
    let avail = |n: Option<(usize, usize, usize)>| -> bool {
        n.map(|(nx, ny, _)| grid.slot(nx, ny).available)
            .unwrap_or(false)
    };
    let dc_pred_flag = !avail(na) || !avail(nb);
    let mode_for = |n: Option<(usize, usize, usize)>, n_for_4x4: usize| -> u8 {
        if dc_pred_flag {
            return 2;
        }
        let Some((nx, ny, nblk8)) = n else {
            return 2;
        };
        let s = grid.slot(nx, ny);
        if !s.available {
            return 2;
        }
        if s.is_i8x8 {
            s.intra_8x8_pred_modes[nblk8]
        } else if s.is_i_nxn {
            // §8.3.2.1 eq. 8-72 — Intra_4x4 neighbour.
            s.intra_4x4_pred_modes[nblk8 * 4 + n_for_4x4]
        } else {
            2
        }
    };
    mode_for(na, 1).min(mode_for(nb, 2))
}

/// §8.3.2.2 — gather the raw reference samples of the 8x8 luma block
/// `blk8` of the MB at (mb_x, mb_y) from the in-progress recon plane.
/// Availability mirrors the decoder's `gather_samples_8x8` for the
/// single-slice / `constrained_intra_pred = 0` case: left/top/top-left
/// from picture bounds; top-right additionally requires `blk8 != 3`
/// (the right-neighbour MB is not yet decoded) and the columns to fit
/// inside the picture.
fn gather_8x8_from_recon(
    recon_y: &[u8],
    width: usize,
    mb_x: usize,
    mb_y: usize,
    blk8: usize,
) -> Samples8x8 {
    let bx = (mb_x * 16 + (blk8 % 2) * 8) as i32;
    let by = (mb_y * 16 + (blk8 / 2) * 8) as i32;
    let left_avail = bx > 0;
    let top_avail = by > 0;
    let tl_avail = bx > 0 && by > 0;
    let tr_avail = by > 0 && blk8 != 3 && (bx + 8) < width as i32;
    let at = |x: i32, y: i32| -> i32 { recon_y[(y as usize) * width + (x as usize)] as i32 };

    let top_left = if tl_avail { at(bx - 1, by - 1) } else { 0 };
    let mut top = [0i32; 8];
    let mut top_right = [0i32; 8];
    for x in 0..8i32 {
        top[x as usize] = if top_avail { at(bx + x, by - 1) } else { 0 };
        top_right[x as usize] = if tr_avail { at(bx + 8 + x, by - 1) } else { 0 };
    }
    let mut left = [0i32; 8];
    for y in 0..8i32 {
        left[y as usize] = if left_avail { at(bx - 1, by + y) } else { 0 };
    }
    Samples8x8 {
        top_left,
        top,
        top_right,
        left,
        availability: Neighbour4x4Availability {
            top_left: tl_avail,
            top: top_avail,
            top_right: tr_avail,
            left: left_avail,
        },
    }
}

/// §8.3.2.2.2..2.10 — can `mode` be used given the reference-sample
/// availability of the 8x8 block? (The encoder must only pick modes
/// whose normative preconditions hold; the decoder assumes a
/// conforming stream.) Top-right never gates a mode on its own — the
/// §8.3.2.2.1 substitution fills p[8..15, -1] from p[7, -1] whenever
/// the top row is available.
fn intra8x8_mode_available(mode: Intra8x8Mode, avail: &Neighbour4x4Availability) -> bool {
    use Intra8x8Mode::*;
    match mode {
        Dc => true,
        Vertical | DiagonalDownLeft | VerticalLeft => avail.top,
        Horizontal | HorizontalUp => avail.left,
        DiagonalDownRight | VerticalRight | HorizontalDown => {
            avail.top && avail.left && avail.top_left
        }
    }
}

/// Per-MB output bundle from a trial encode (round-15 RDO).
///
/// `luma_cost` is the Lagrangian cost `J = D + λ · R` of the MB's
/// **luma** path only (chroma is identical for both I_16x16 and I_NxN
/// trials so we exclude it from the comparison). `deblock` is the
/// per-MB info needed by the §8.7 picture-level filter.
struct MbTrial {
    luma_cost: u64,
    deblock: MbDeblockInfo,
}

/// Snapshot of all encoder state mutated by one MB's encode, captured
/// inside `encode_mb` so we can roll back the losing trial.
///
/// Captures only the MB-sized window of the recon planes, which keeps
/// allocations small (256 + 64 + 64 = 384 bytes per snapshot) regardless
/// of picture size.
struct MbStateSnapshot {
    recon_y_mb: [u8; 256],
    /// Chroma MB tiles, sized for the worst case (16x16 at 4:4:4);
    /// 4:2:0 uses the first 64 bytes, 4:2:2 the first 128.
    recon_u_mb: [u8; 256],
    recon_v_mb: [u8; 256],
    /// Chroma tile geometry: (width, height) per §6.2 Table 6-1.
    chroma_tile: (usize, usize),
    sw: BitWriter,
    nc_slot: crate::macroblock_layer::CavlcMbNc,
    intra_slot: IntraGridSlot,
}

/// §6.2 Table 6-1 — per-MB chroma tile size for a chroma format.
fn chroma_tile_dims(chroma_array_type: u32) -> (usize, usize) {
    match chroma_array_type {
        0 => (0, 0),
        2 => (8, 16),
        3 => (16, 16),
        _ => (8, 8),
    }
}

impl MbStateSnapshot {
    #[allow(clippy::too_many_arguments)]
    fn capture(
        recon_y: &[u8],
        recon_u: &[u8],
        recon_v: &[u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &BitWriter,
        nc_grid: &CavlcNcGrid,
        intra_grid: &IntraGrid,
        mb_addr: usize,
        chroma_array_type: u32,
    ) -> Self {
        let (cw, ch) = chroma_tile_dims(chroma_array_type);
        let mut snap = Self {
            recon_y_mb: [0u8; 256],
            recon_u_mb: [0u8; 256],
            recon_v_mb: [0u8; 256],
            chroma_tile: (cw, ch),
            sw: sw.clone(),
            nc_slot: nc_grid.mbs[mb_addr],
            intra_slot: intra_grid.slot(mb_x, mb_y).clone(),
        };
        for j in 0..16usize {
            let src = (mb_y * 16 + j) * width + mb_x * 16;
            snap.recon_y_mb[j * 16..j * 16 + 16].copy_from_slice(&recon_y[src..src + 16]);
        }
        for j in 0..ch {
            let src = (mb_y * ch + j) * chroma_width + mb_x * cw;
            snap.recon_u_mb[j * cw..j * cw + cw].copy_from_slice(&recon_u[src..src + cw]);
            snap.recon_v_mb[j * cw..j * cw + cw].copy_from_slice(&recon_v[src..src + cw]);
        }
        snap
    }

    #[allow(clippy::too_many_arguments)]
    fn restore(
        &self,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_addr: usize,
    ) {
        for j in 0..16usize {
            let dst = (mb_y * 16 + j) * width + mb_x * 16;
            recon_y[dst..dst + 16].copy_from_slice(&self.recon_y_mb[j * 16..j * 16 + 16]);
        }
        let (cw, ch) = self.chroma_tile;
        for j in 0..ch {
            let dst = (mb_y * ch + j) * chroma_width + mb_x * cw;
            recon_u[dst..dst + cw].copy_from_slice(&self.recon_u_mb[j * cw..j * cw + cw]);
            recon_v[dst..dst + cw].copy_from_slice(&self.recon_v_mb[j * cw..j * cw + cw]);
        }
        *sw = self.sw.clone();
        nc_grid.mbs[mb_addr] = self.nc_slot;
        *intra_grid.slot_mut(mb_x, mb_y) = self.intra_slot.clone();
    }

    #[allow(clippy::too_many_arguments)]
    fn install(
        &self,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_addr: usize,
    ) {
        // Same as restore — fields are owned post-trial state to install.
        self.restore(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mb_addr,
        );
    }
}

/// Round-29 — extra snapshot fields needed to roll back a P/B-slice MB
/// trial. Wraps [`MbStateSnapshot`] with the inter-slice-only MV grid
/// slot and `pending_skip` counter so the intra-fallback RDO can
/// trial-encode a candidate MB and discard the loser without leaking
/// state into the next MB.
struct InterMbStateSnapshot {
    inner: MbStateSnapshot,
    mv_l0: MvGridSlot,
    /// `Some` only on the B-slice path — L1 grid slot.
    mv_l1: Option<MvGridSlot>,
    pending_skip: u32,
}

impl InterMbStateSnapshot {
    #[allow(clippy::too_many_arguments)]
    fn capture_p(
        recon_y: &[u8],
        recon_u: &[u8],
        recon_v: &[u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &BitWriter,
        nc_grid: &CavlcNcGrid,
        intra_grid: &IntraGrid,
        mv_grid: &MvGrid,
        mb_addr: usize,
        _width_mbs: usize,
        pending_skip: u32,
    ) -> Self {
        Self {
            inner: MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr,
                1,
            ),
            mv_l0: *mv_grid.slot(mb_x, mb_y),
            mv_l1: None,
            pending_skip,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn capture_b(
        recon_y: &[u8],
        recon_u: &[u8],
        recon_v: &[u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &BitWriter,
        nc_grid: &CavlcNcGrid,
        intra_grid: &IntraGrid,
        mv_grid_l0: &MvGrid,
        mv_grid_l1: &MvGrid,
        mb_addr: usize,
        _width_mbs: usize,
        pending_skip: u32,
    ) -> Self {
        Self {
            inner: MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr,
                1,
            ),
            mv_l0: *mv_grid_l0.slot(mb_x, mb_y),
            mv_l1: Some(*mv_grid_l1.slot(mb_x, mb_y)),
            pending_skip,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn restore_p(
        &self,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid: &mut MvGrid,
        mb_addr: usize,
        pending_skip: &mut u32,
    ) {
        self.inner.restore(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mb_addr,
        );
        *mv_grid.slot_mut(mb_x, mb_y) = self.mv_l0;
        *pending_skip = self.pending_skip;
    }

    #[allow(clippy::too_many_arguments)]
    fn restore_b(
        &self,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        width: usize,
        chroma_width: usize,
        mb_x: usize,
        mb_y: usize,
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid_l0: &mut MvGrid,
        mv_grid_l1: &mut MvGrid,
        mb_addr: usize,
        pending_skip: &mut u32,
    ) {
        self.inner.restore(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mb_addr,
        );
        *mv_grid_l0.slot_mut(mb_x, mb_y) = self.mv_l0;
        if let Some(slot) = self.mv_l1 {
            *mv_grid_l1.slot_mut(mb_x, mb_y) = slot;
        }
        *pending_skip = self.pending_skip;
    }
}

impl Encoder {
    /// §7.3.2.1 / §7.3.2.2 — the SPS and PPS RBSPs this encoder's IDR
    /// access units carry, for `cabac` (`entropy_coding_mode_flag`)
    /// off or on. Exactly the bytes [`Self::encode_idr`] /
    /// [`Self::encode_idr_cabac`] put in band, so a muxer can build an
    /// out-of-band `avcC` record ([`crate::avcc`]) before the first
    /// picture is coded. The 8x8 transform and non-flat scaling
    /// matrices promote the signalled profile to at least High (100)
    /// (§A.2.4 — High-profile tools). The CAVLC pairing carries the
    /// configured weighted-prediction flags; the CABAC pairing codes
    /// `weighted_pred_flag = 0` / `weighted_bipred_idc = 0` (the CABAC
    /// P / B paths predict unweighted).
    pub fn parameter_sets(&self, cabac: bool) -> (Vec<u8>, Vec<u8>) {
        let width_mbs = self.cfg.width / 16;
        let height_mbs = self.cfg.height / 16;
        let profile_idc = if (self.cfg.transform_8x8 || !self.cfg.scaling_matrix.is_flat())
            && self.cfg.profile_idc < 100
        {
            100
        } else {
            self.cfg.profile_idc
        };
        let sps_cfg = BaselineSpsConfig {
            seq_parameter_set_id: 0,
            level_idc: self.cfg.level_idc,
            width_in_mbs: width_mbs,
            height_in_mbs: height_mbs,
            log2_max_frame_num_minus4: 4,
            log2_max_poc_lsb_minus4: 4,
            max_num_ref_frames: self.cfg.max_num_ref_frames,
            profile_idc,
            chroma_format_idc: self.cfg.chroma_format_idc,
            separate_colour_plane: self.cfg.colour_plane_id.is_some(),
            seq_scaling_lists: self.cfg.scaling_matrix.seq_spec(),
            bit_depth_luma_minus8: 0,
            bit_depth_chroma_minus8: 0,
            interlaced_fields: false,
            mbaff: false,
            // Round-430 — rate-controlled sessions annotate CBR
            // streams with §E.1.1 VUI timing + §E.1.2 NAL HRD.
            vui: self.cfg.vui.clone(),
        };
        let pps_cfg = BaselinePpsConfig {
            redundant_pic_cnt_present_flag: false,
            slice_groups: None,
            constrained_intra_pred_flag: false,
            pic_scaling_lists: self.cfg.scaling_matrix.pic_spec(),
            chroma_format_idc: self.cfg.chroma_format_idc,
            pic_parameter_set_id: 0,
            seq_parameter_set_id: 0,
            pic_init_qp_minus26: self.cfg.qp - 26,
            chroma_qp_index_offset: 0,
            // Round-453 — §7.4.2.2 weighted_pred_flag: CAVLC P slices
            // ship a pred_weight_table() and use §8.4.2.3.2 explicit
            // weighting. Round-26 — explicit weighted bipred needs
            // idc=1 so B-slice headers may carry pred_weight_table().
            weighted_pred_flag: !cabac && self.cfg.explicit_weighted_pred,
            weighted_bipred_idc: if !cabac && self.cfg.explicit_weighted_bipred {
                1
            } else {
                0
            },
            entropy_coding_mode_flag: cabac,
            transform_8x8_mode_flag: self.cfg.transform_8x8,
        };
        (
            build_baseline_sps_rbsp(&sps_cfg),
            build_baseline_pps_rbsp(&pps_cfg),
        )
    }

    /// [`Self::parameter_sets`] as Annex B NAL units (4-byte start
    /// codes, emulation prevention applied): SPS then PPS.
    pub fn parameter_sets_annex_b(&self, cabac: bool) -> Vec<u8> {
        let (sps, pps) = self.parameter_sets(cabac);
        let mut out = build_nal_unit(3, NalUnitType::Sps, &sps);
        out.extend_from_slice(&build_nal_unit(3, NalUnitType::Pps, &pps));
        out
    }
}

/// Top-level encoder. Holds parameter set state but no per-picture
/// scratch — `encode_idr` is the one entry point.
pub struct Encoder {
    cfg: EncoderConfig,
    /// §7.4.3 `idr_pic_id` written into the slice header of the next
    /// IDR picture (0..=65535). The encoder is stateless per picture,
    /// so the caller that strings IDR access units together (the
    /// [`crate::encoder::session::EncoderSession`]) rotates it: two
    /// consecutive IDR access units shall not share the value.
    idr_pic_id: u32,
}

impl Encoder {
    /// Read-only access to the encoder config (used by the round-30
    /// CABAC entry points in [`crate::encoder::cabac_path`]).
    pub fn config(&self) -> &EncoderConfig {
        &self.cfg
    }

    /// §7.4.3 `idr_pic_id` the next IDR picture will carry.
    pub fn idr_pic_id(&self) -> u32 {
        self.idr_pic_id
    }

    /// Set the §7.4.3 `idr_pic_id` for the IDR pictures encoded from
    /// now on (`0..=65535`; all slices of one IDR picture carry the
    /// same value). Callers emitting consecutive IDR access units
    /// must change it between them (§7.4.3: "the value of idr_pic_id
    /// in the slices of the first such IDR access unit shall differ
    /// from the idr_pic_id in the second such IDR access unit").
    pub fn set_idr_pic_id(&mut self, idr_pic_id: u32) {
        assert!(idr_pic_id <= 65535, "idr_pic_id out of 0..=65535 (§7.4.3)");
        self.idr_pic_id = idr_pic_id;
    }

    /// Builder form of [`set_idr_pic_id`](Self::set_idr_pic_id).
    pub fn with_idr_pic_id(mut self, idr_pic_id: u32) -> Self {
        self.set_idr_pic_id(idr_pic_id);
        self
    }
}

impl Encoder {
    pub fn new(cfg: EncoderConfig) -> Self {
        assert!(
            cfg.width % 16 == 0 && cfg.height % 16 == 0,
            "encoder requires 16-pixel-aligned dimensions",
        );
        assert!((0..=51).contains(&cfg.qp));
        assert!(
            matches!(cfg.chroma_format_idc, 0..=3),
            "encoder only supports 4:0:0 (chroma_format_idc=0), 4:2:0 \
             (chroma_format_idc=1), 4:2:2 (chroma_format_idc=2), and \
             4:4:4 (chroma_format_idc=3); got {}",
            cfg.chroma_format_idc,
        );
        // Round-27: 4:2:2 currently requires the High 4:2:2 profile (122).
        // Round-28: 4:4:4 currently requires the High 4:4:4 Predictive
        // profile (244). The 4:2:0-only P/B paths still pin profile_idc
        // to 66/77; the chroma-extended IDR paths need a profile in the
        // §7.3.2.1.1 chroma-extended group.
        //
        // Round-448: 4:0:0 (monochrome) needs a High-family profile —
        // §A.2.4 (High, 100) is the lowest profile whose supported
        // chroma range includes chroma_format_idc = 0.
        if cfg.chroma_format_idc == 0 {
            assert!(
                matches!(cfg.profile_idc, 100 | 110 | 122 | 244),
                "4:0:0 (chroma_format_idc=0) requires a High-family profile \
                 (100 / 110 / 122 / 244); got {}",
                cfg.profile_idc,
            );
        }
        if let Some(plane) = cfg.colour_plane_id {
            assert!(plane <= 2, "colour_plane_id must be 0..=2 (§7.4.3)");
            assert_eq!(
                cfg.chroma_format_idc, 0,
                "a separate-colour-plane per-plane encoder codes monochrome \
                 pictures (ChromaArrayType 0): set chroma_format_idc = 0",
            );
            assert_eq!(
                cfg.profile_idc, 244,
                "separate_colour_plane_flag lives in the 4:4:4 SPS syntax \
                 (§7.3.2.1.1): profile_idc must be 244",
            );
            assert!(
                cfg.scaling_matrix.is_flat(),
                "separate-colour-plane encoding currently requires flat scaling lists",
            );
        }
        if cfg.chroma_format_idc == 2 {
            assert_eq!(
                cfg.profile_idc, 122,
                "4:2:2 (chroma_format_idc=2) requires profile_idc=122 (High 4:2:2)",
            );
        }
        if cfg.chroma_format_idc == 3 {
            assert_eq!(
                cfg.profile_idc, 244,
                "4:4:4 (chroma_format_idc=3) requires profile_idc=244 (High 4:4:4 Predictive)",
            );
        }
        Self { cfg, idr_pic_id: 0 }
    }

    /// Encode the SPS + PPS + IDR access unit for one frame as an
    /// Annex B byte stream. Also returns the per-plane reconstruction
    /// the decoder is expected to produce — useful for round-trip
    /// validation in tests.
    pub fn encode_idr(&self, frame: &YuvFrame<'_>) -> EncodedIdr {
        self.encode_idr_with_qp(frame, self.cfg.qp)
    }

    /// [`encode_idr`](Self::encode_idr) with a per-frame QP override.
    ///
    /// The PPS still carries `pic_init_qp_minus26 = cfg.qp - 26`; the
    /// difference is signalled through the §7.4.3 `slice_qp_delta`
    /// (`SliceQP_Y = 26 + pic_init_qp_minus26 + slice_qp_delta`), so a
    /// rate-controlled sequence keeps one PPS while every picture
    /// picks its own QP. `frame_qp` must be in 0..=51.
    pub fn encode_idr_with_qp(&self, frame: &YuvFrame<'_>, frame_qp: i32) -> EncodedIdr {
        self.encode_idr_impl(frame, frame_qp, None)
    }

    /// [`encode_idr_with_qp`](Self::encode_idr_with_qp) plus **MB-row
    /// QP modulation** toward a whole-picture bit budget (round 430) —
    /// the IDR counterpart of
    /// [`encode_p_rate_adaptive`](Self::encode_p_rate_adaptive). IDR
    /// pictures are the largest of a CBR GOP, so a mid-frame overshoot
    /// here is exactly where the session's VBV retry loop used to pay
    /// a whole re-encode; row modulation absorbs most of it in-slice.
    ///
    /// Row-QP steps ride the §7.4.5 `mb_qp_delta` syntax: Intra_16x16
    /// MBs always carry the delta (the luma DC block is always coded),
    /// I_NxN MBs only when cbp > 0 — a cbp==0 MB leaves the decoded
    /// QP_Y chain (and the §8.7 deblock strengths that follow it) at
    /// the previous MB's value, which the encoder mirrors exactly.
    ///
    /// 4:2:0 only, mirroring the P-path entry.
    pub fn encode_idr_rate_adaptive(
        &self,
        frame: &YuvFrame<'_>,
        frame_qp: i32,
        frame_budget_bits: u64,
    ) -> EncodedIdr {
        assert_eq!(
            self.cfg.chroma_format_idc, 1,
            "encode_idr_rate_adaptive requires 4:2:0"
        );
        self.encode_idr_impl(frame, frame_qp, Some(frame_budget_bits))
    }

    fn encode_idr_impl(
        &self,
        frame: &YuvFrame<'_>,
        frame_qp: i32,
        row_budget_bits: Option<u64>,
    ) -> EncodedIdr {
        assert!(
            (0..=51).contains(&frame_qp),
            "frame_qp {frame_qp} out of 0..=51"
        );
        assert_eq!(frame.width, self.cfg.width);
        assert_eq!(frame.height, self.cfg.height);
        let width_mbs = self.cfg.width / 16;
        let height_mbs = self.cfg.height / 16;
        // §6.2 / Table 6-1 — chroma plane dimensions per chroma_format_idc.
        // 4:0:0 → none; 4:2:0 → (W/2, H/2); 4:2:2 → (W/2, H);
        // 4:4:4 → (W, H).
        let chroma_width = match self.cfg.chroma_format_idc {
            0 => 0usize,
            3 => self.cfg.width as usize,
            _ => (self.cfg.width / 2) as usize,
        };
        let chroma_height = match self.cfg.chroma_format_idc {
            0 => 0usize,
            2 => self.cfg.height as usize,
            3 => self.cfg.height as usize,
            _ => (self.cfg.height / 2) as usize,
        };
        // Sanity-check the input frame's chroma plane sizes match what
        // we expect for the configured chroma_format_idc. Mis-sized
        // planes would silently produce out-of-bounds reads in the
        // encoder helpers.
        debug_assert_eq!(
            frame.u.len(),
            chroma_width * chroma_height,
            "Cb plane length {} does not match {}x{} for chroma_format_idc={}",
            frame.u.len(),
            chroma_width,
            chroma_height,
            self.cfg.chroma_format_idc,
        );
        debug_assert_eq!(frame.v.len(), chroma_width * chroma_height);

        // Round-397 — non-flat scaling matrices run at every chroma
        // format: the 4:2:2 §8.5.11.2 chroma chain and the 4:4:4
        // coded-like-luma planes quantise / reconstruct under the
        // §8.5.9 weightScale; the SPS/PPS writers emit the 12-list
        // loop at 4:4:4. The trellis refinements still assume flat
        // dequantisation.
        if !self.cfg.scaling_matrix.is_flat() {
            assert!(
                !self.cfg.trellis_quant_intra && !self.cfg.trellis_quant_intra_chroma,
                "trellis intra refinement assumes flat scaling lists",
            );
        }
        // Round-391 — §7.4.2.1.1.1 range check on user-supplied lists.
        if let ScalingMatrixMode::SeqCustom(l) | ScalingMatrixMode::PicCustom(l) =
            self.cfg.scaling_matrix
        {
            assert!(
                l.is_valid(),
                "custom scaling-list values must all be in 1..=255",
            );
        }
        // SPS / PPS bytes — shared with the CABAC IDR path and exposed
        // for out-of-band carriage (`avcC`) via [`Self::parameter_sets`].
        let (sps_rbsp, pps_rbsp) = self.parameter_sets(false);

        let mut stream: Vec<u8> = Vec::new();
        stream.extend_from_slice(&build_nal_unit(3, NalUnitType::Sps, &sps_rbsp));
        stream.extend_from_slice(&build_nal_unit(3, NalUnitType::Pps, &pps_rbsp));

        // Slice header + slice data → IDR NAL.
        let mut sw = BitWriter::new();
        write_idr_i_slice_header(
            &mut sw,
            &IdrSliceHeaderConfig {
                first_mb_in_slice: 0,
                slice_type_raw: 7,
                pic_parameter_set_id: 0,
                colour_plane_id: self.cfg.colour_plane_id,
                frame_num: 0,
                frame_num_bits: 8,
                idr_pic_id: self.idr_pic_id,
                pic_order_cnt_lsb: 0,
                poc_lsb_bits: 8,
                // §7.4.3 — SliceQP_Y = 26 + pic_init_qp_minus26 +
                // slice_qp_delta; the PPS carries cfg.qp, the delta
                // moves this picture to frame_qp.
                slice_qp_delta: frame_qp - self.cfg.qp,
                // §7.4.3 / round 14 — enable in-loop deblocking. We
                // mirror the decoder's §8.7 pass on the local recon so
                // EncodedIdr.recon_* matches what the decoder produces.
                //
                // Round-28 (4:4:4) intentionally disables deblocking:
                // §8.7 chroma deblocking for ChromaArrayType==3 uses
                // the LUMA filter ladder applied to each chroma plane
                // (per-plane bS derivation), which is a separate code
                // path the round-28 decoder doesn't yet exercise.
                // Setting `disable_deblocking_filter_idc=1` is per
                // §7.4.3 spec and yields a still-conformant bitstream.
                disable_deblocking_filter_idc: if self.cfg.chroma_format_idc == 3 {
                    1
                } else {
                    0
                },
                slice_alpha_c0_offset_div2: 0,
                slice_beta_offset_div2: 0,
                field: FieldPicSignal::FrameMbsOnly,
                idr: true,
                nal_ref_idc: 3,
                long_term_reference_flag: false,
                mmco: &[],
                redundant_pic_cnt: None,
                slice_group_change_cycle: None,
            },
        );

        // Reconstruction state, sized to the picture.
        let mut recon_y = vec![0u8; (self.cfg.width * self.cfg.height) as usize];
        let mut recon_u = vec![0u8; chroma_width * chroma_height];
        let mut recon_v = vec![0u8; chroma_width * chroma_height];

        // §7.4.5 decoded-QP chain (round 430): `qp_tracker.cur` is the
        // QP_Y the decoder holds after the most recent MB, `want_qp`
        // the row-modulated target. Without a row budget both stay at
        // `frame_qp`, every emitted mb_qp_delta is 0 and the bitstream
        // matches the pre-round-430 output exactly.
        let mut qp_tracker = MbQpTracker::new(frame_qp);
        let mut want_qp = frame_qp;
        // §8.5.8 — chroma-QP derivation, BD-aware. `qp_bd_offset_c =
        // 6 * bit_depth_chroma_minus8` extends the eq. 8-311 qPI clamp
        // from `0..=51` to `−QpBdOffsetC..=51`. Today the SPS pins
        // bit_depth_chroma_minus8=0 so this matches the legacy 8-bit
        // path; the BD-aware call lets a future High10/422/444 round
        // wire a non-zero BD without re-touching the encoder math.
        let qp_bd_offset_c = qp_bd_offset(self.cfg.bit_depth_chroma_minus8);

        // §9.2.1.1 — neighbour grid for CAVLC nC derivation. Encoder
        // mirrors what the decoder will reconstruct as it walks the MBs:
        // mark each MB's slot `is_available = true` after encode and
        // store the per-4x4 luma-AC TotalCoeff. The decoder uses the
        // same procedure to pick CAVLC tables, so we must match it
        // bit-exactly to avoid mis-parsing.
        let mut nc_grid = CavlcNcGrid::new(width_mbs, height_mbs);
        // Encoder-side intra-pred-mode grid mirroring what the decoder
        // will populate as it reconstructs each MB. Used to derive
        // `predIntra4x4PredMode` per §8.3.1.1 step 4.
        let mut intra_grid = IntraGrid::new(width_mbs as usize, height_mbs as usize);

        // §8.7 deblock info, one entry per MB (raster order). Filled by
        // the per-MB encode functions; consumed after the slice loop by
        // the picture-level deblock pass.
        let mut mb_deblock_infos: Vec<MbDeblockInfo> =
            vec![MbDeblockInfo::default(); (width_mbs * height_mbs) as usize];

        // Round-382 — the High-profile 8x8 transform runs the per-MB
        // RDO with a third (Intra_8x8) trial inside `encode_mb`.
        // Round-385 extends it to 4:2:2 (RDO) and to 4:4:4 (all-I_8x8
        // via the §8.3.4.5 chroma-coded-like-luma path).
        if self.cfg.transform_8x8 {
            assert!(
                matches!(self.cfg.chroma_format_idc, 0..=3),
                "transform_8x8 encode requires chroma_format_idc in {{0, 1, 2, 3}}"
            );
            // Round-448 — at 4:0:0 the CAVLC IDR path stays
            // Intra_16x16-only (no transform_size_8x8_flag is coded
            // for that mb_type), so the PPS merely PERMITS the 8x8
            // transform; the P/B inter paths run the §8.6.4 8x8-vs-4x4
            // luma trial and code the §7.3.5 second-gate flag.
        }
        let mut i8x8_mb_count = 0u32;
        let mut i4x4_mb_count = 0u32;

        // Iterate MBs in raster order.
        for mb_y in 0..height_mbs {
            // Round 430 — MB-row QP modulation (IDR): identical
            // response curve to the round-420 P controller (see
            // `encode_p_impl` for the asymmetric-clamp rationale).
            if let Some(budget) = row_budget_bits {
                if mb_y > 0 && budget > 0 {
                    let frac = f64::from(mb_y) / f64::from(height_mbs);
                    let spent = sw.bits_emitted() as f64;
                    let expected = (budget as f64 * frac).max(1.0);
                    let ratio = spent.max(1.0) / expected;
                    let adj = if ratio >= 1.0 {
                        (6.0 * ratio.log2()).round() as i32
                    } else {
                        (3.0 * ratio.log2()).round() as i32
                    };
                    let mut new_want = frame_qp + adj;
                    if new_want < frame_qp && frac < 0.6 {
                        new_want = frame_qp;
                    }
                    want_qp = new_want
                        .clamp(want_qp - 1, want_qp + 2)
                        .clamp(frame_qp - 2, frame_qp + 6)
                        .clamp(0, 51);
                }
            }
            let qp_y = want_qp;
            let qp_c = qp_y_to_qp_c_with_bd_offset(
                qp_y,
                0, /* PPS chroma_qp_index_offset */
                qp_bd_offset_c,
            );
            for mb_x in 0..width_mbs {
                let dbl = self.encode_mb(
                    frame,
                    mb_x as usize,
                    mb_y as usize,
                    qp_y,
                    qp_c,
                    chroma_width,
                    chroma_height,
                    &mut recon_y,
                    &mut recon_u,
                    &mut recon_v,
                    &mut sw,
                    &mut nc_grid,
                    &mut intra_grid,
                    &mut qp_tracker,
                );
                if dbl.transform_size_8x8_flag {
                    i8x8_mb_count += 1;
                }
                if dbl.is_intra_4x4 {
                    i4x4_mb_count += 1;
                }
                let mb_addr = (mb_y * width_mbs + mb_x) as usize;
                mb_deblock_infos[mb_addr] = dbl;
            }
        }

        // §7.3.2.8 / §7.3.2.9 — slice_data trailing bits.
        sw.rbsp_trailing_bits();
        let slice_rbsp = sw.into_bytes();
        stream.extend_from_slice(&build_nal_unit(3, NalUnitType::SliceIdr, &slice_rbsp));

        // §8.7 — picture-level in-loop deblocking. Runs *after* every MB
        // has been reconstructed, both because the spec defines the
        // filter per picture and because the encoder's intra-prediction
        // step (which reads `recon_y` for neighbours) must see the
        // pre-filter samples — same as the decoder.
        //
        // Round-28 (4:4:4) skips the deblock pass: the slice header
        // sets `disable_deblocking_filter_idc=1` so the decoder doesn't
        // run §8.7, and the encoder must mirror that on its local recon
        // to keep `EncodedIdr.recon_*` bit-equivalent with what the
        // decoder produces.
        if self.cfg.chroma_format_idc != 3 {
            crate::encoder::deblock::deblock_recon_with_chroma_array_type(
                self.cfg.width,
                self.cfg.height,
                chroma_width as u32,
                chroma_height as u32,
                &mut recon_y,
                &mut recon_u,
                &mut recon_v,
                &mb_deblock_infos,
                0, /* PPS chroma_qp_index_offset */
                width_mbs,
                height_mbs,
                self.cfg.chroma_format_idc,
            );
        }

        // IDR is all-intra: every partition is `is_intra = true`, so
        // colocated lookups return colZeroFlag = 0 (the §8.4.1.2.2 step 7
        // "intra colocated" branch).
        let n_parts = (width_mbs as usize) * (height_mbs as usize) * 4;
        let partition_mvs = vec![
            FrameRefPartitionMv {
                mv_l0: (0, 0),
                ref_idx_l0: -1,
                is_intra: true,
            };
            n_parts
        ];

        EncodedIdr {
            annex_b: stream,
            recon_y,
            recon_u,
            recon_v,
            recon_width: self.cfg.width,
            recon_height: self.cfg.height,
            partition_mvs,
            i8x8_mb_count,
            i4x4_mb_count,
        }
    }

    /// Round-15 entry point: **Lagrangian RDO** mb_type dispatch.
    ///
    /// Strategy:
    ///   1) Snapshot the recon planes (only the MB-sized window),
    ///      `BitWriter`, `CavlcNcGrid` slot, and `IntraGrid` slot.
    ///   2) Run the I_16x16 path, measuring `J = D + λ·R` for the luma
    ///      portion (chroma is identical for both paths so it doesn't
    ///      affect the comparison and is excluded from J).
    ///   3) Snapshot its output state; restore the original state.
    ///   4) Run the I_NxN path, measuring its luma J the same way.
    ///   5) Pick the lower J; if I_16x16 won, restore its snapshot.
    ///
    /// Compared to round-4 SAD: the new metric counts actual quantisation
    /// noise (D = SSD on recon) and actual entropy-coded bits (R = trial
    /// CAVLC encode), so the comparison is calibrated. λ comes from
    /// [`rdo::lambda_ssd`].
    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::too_many_arguments)]
    fn encode_mb(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        qp_tracker: &mut MbQpTracker,
    ) -> MbDeblockInfo {
        // §7.4.5 — the delta that moves the decoded QP_Y chain onto
        // this MB's (possibly row-modulated) target QP. Whether it is
        // actually transmitted depends on the winning shape
        // (Intra_16x16 always; I_NxN only with cbp > 0); the winner's
        // deblock info reports the resulting chain QP either way.
        let mb_qp_delta = qp_y - qp_tracker.cur;
        let dbl = self.encode_mb_inner(
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mb_qp_delta,
        );
        qp_tracker.cur = dbl.qp_y;
        dbl
    }

    #[allow(clippy::too_many_arguments)]
    fn encode_mb_inner(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_qp_delta: i32,
    ) -> MbDeblockInfo {
        let width = self.cfg.width as usize;
        let mb_addr = (mb_y as u32) * self.cfg.width / 16 + (mb_x as u32);

        // Round-448 — ChromaArrayType == 0 (monochrome, or one colour
        // plane of a `separate_colour_plane_flag = 1` stream): the MB
        // is luma-only. Two-way Lagrangian RDO between Intra_16x16 and
        // Intra_4x4 (I_NxN), each measured as J = D + λR over the real
        // emitted bits — the same snapshot discipline as the 4:4:4
        // block above, minus the chroma planes.
        if self.cfg.chroma_format_idc == 0 {
            let lambda = lambda_ssd(qp_y, true);
            let snap = MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
                0,
            );
            let bits_before = sw.bits_emitted();
            let mb_ssd_luma = |recon_y: &[u8]| -> u64 {
                let mut d = 0u64;
                for j in 0..16usize {
                    for i in 0..16usize {
                        let s = frame.y[(mb_y * 16 + j) * width + mb_x * 16 + i] as i64;
                        let r = recon_y[(mb_y * 16 + j) * width + mb_x * 16 + i] as i64;
                        d += ((s - r) * (s - r)) as u64;
                    }
                }
                d
            };

            // ----- Trial A: Intra_16x16. -----
            let trial_a = self.encode_mb_intra16x16(
                frame,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                chroma_height,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mb_qp_delta,
                None,
            );
            let d_a = mb_ssd_luma(recon_y);
            let r_a = sw.bits_emitted() - bits_before;
            let cost_a = cost_combined(d_a, r_a as u64, lambda);
            let post_a = MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
                0,
            );
            snap.restore(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
            );

            // ----- Trial B: Intra_4x4 (I_NxN). -----
            let dbl_b = self.encode_mb_intra4x4_mono(
                frame,
                mb_x,
                mb_y,
                qp_y,
                recon_y,
                sw,
                nc_grid,
                intra_grid,
                mb_qp_delta,
            );
            let d_b = mb_ssd_luma(recon_y);
            let r_b = sw.bits_emitted() - bits_before;
            let cost_b = cost_combined(d_b, r_b as u64, lambda);

            if cost_a <= cost_b {
                post_a.install(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                return trial_a.deblock;
            }
            return dbl_b;
        }

        // Round-28: 4:4:4 started Intra_16x16-only. Round-388 added a
        // two-way Lagrangian RDO vs Intra_8x8 under `transform_8x8`.
        // Round-391 adds the **I_4x4 leg** (chroma-as-luma 4x4 emit
        // with per-plane nC), making the trial two-way (I_16x16 /
        // I_4x4) in a 4x4-transform stream and three-way (+ Intra_8x8)
        // under `transform_8x8`. J = D + λR with D the SSD over all
        // three full-resolution planes and R the actual emitted bits —
        // every shape goes through the real writer, losers are rolled
        // back via the chroma-aware snapshot.
        if self.cfg.chroma_format_idc == 3 {
            let lambda = lambda_ssd(qp_y, true);
            let snap = MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
                3,
            );
            let bits_before = sw.bits_emitted();

            // ----- Trial A: Intra_16x16 (§7.3.5.3 chroma like luma). -----
            let trial_a = self.encode_mb_intra16x16(
                frame,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                chroma_height,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mb_qp_delta,
                None,
            );
            let d_a = mb_ssd_3planes_444(frame, recon_y, recon_u, recon_v, width, mb_x, mb_y);
            let r_a = sw.bits_emitted() - bits_before;
            let cost_a = cost_combined(d_a, r_a as u64, lambda);
            let post_a = MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
                3,
            );
            snap.restore(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
            );

            // ----- Trial B: Intra_4x4 (§8.3.4.5 chroma like luma). -----
            let dbl_b = self.encode_mb_intra4x4_444(
                frame, mb_x, mb_y, qp_y, qp_c, recon_y, recon_u, recon_v, sw, nc_grid, intra_grid,
            );
            let d_b = mb_ssd_3planes_444(frame, recon_y, recon_u, recon_v, width, mb_x, mb_y);
            let r_b = sw.bits_emitted() - bits_before;
            let cost_b = cost_combined(d_b, r_b as u64, lambda);

            if !self.cfg.transform_8x8 {
                // Two-way pick: I_16x16 vs I_4x4.
                if cost_a <= cost_b {
                    post_a.install(
                        recon_y,
                        recon_u,
                        recon_v,
                        width,
                        chroma_width,
                        mb_x,
                        mb_y,
                        sw,
                        nc_grid,
                        intra_grid,
                        mb_addr as usize,
                    );
                    return trial_a.deblock;
                }
                return dbl_b;
            }

            // ----- Trial C (`transform_8x8`): Intra_8x8. -----
            let post_b = MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
                3,
            );
            snap.restore(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
            );
            let dbl_c = self.encode_mb_intra8x8_444(
                frame, mb_x, mb_y, qp_y, qp_c, recon_y, recon_u, recon_v, sw, nc_grid, intra_grid,
            );
            let d_c = mb_ssd_3planes_444(frame, recon_y, recon_u, recon_v, width, mb_x, mb_y);
            let r_c = sw.bits_emitted() - bits_before;
            let cost_c = cost_combined(d_c, r_c as u64, lambda);

            // Three-way pick; ties prefer A (smaller MB syntax), then B.
            if cost_a <= cost_b && cost_a <= cost_c {
                post_a.install(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                return trial_a.deblock;
            }
            if cost_b <= cost_c {
                post_b.install(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                return dbl_b;
            }
            return dbl_c;
        }

        // -- Snapshot pre-state (so we can roll back the loser). --
        let snap = MbStateSnapshot::capture(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mb_addr as usize,
            1,
        );

        // ----- Trial 1: I_16x16 path. -----
        let trial_a = self.encode_mb_intra16x16(
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mb_qp_delta,
            None,
        );
        let snap_a = MbStateSnapshot::capture(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mb_addr as usize,
            1,
        );

        // -- Restore original state for the second trial. --
        snap.restore(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mb_addr as usize,
        );

        // ----- Trial 2: I_NxN (Intra_4x4) path. -----
        let trial_b = self.encode_mb_intra4x4(
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mb_qp_delta,
        );

        // ----- Trial 3 (round-382, `transform_8x8` only): Intra_8x8. -----
        // Runs after the I_NxN trial with the same snapshot discipline;
        // the last trial's state is left installed, so the winner pick
        // below restores + installs whichever snapshot won.
        let trial_c = if self.cfg.transform_8x8 {
            let snap_b = MbStateSnapshot::capture(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
                1,
            );
            snap.restore(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
            );
            let trial_c = self.encode_mb_intra8x8(
                frame,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                chroma_height,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mb_qp_delta,
            );
            Some((trial_c, snap_b))
        } else {
            None
        };

        // ----- Pick winner. -----
        // Each path returns its own luma `J = D + λR` inside `MbTrial`.
        // Lower J wins. On tie, prefer I_16x16 (smaller MB syntax),
        // then I_NxN 4x4, then I_8x8.
        if let Some((trial_c, snap_b)) = trial_c {
            // Three-way pick; the I_8x8 trial state is installed.
            if trial_a.luma_cost <= trial_b.luma_cost && trial_a.luma_cost <= trial_c.luma_cost {
                snap.restore(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                snap_a.install(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                trial_a.deblock
            } else if trial_b.luma_cost <= trial_c.luma_cost {
                snap.restore(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                snap_b.install(
                    recon_y,
                    recon_u,
                    recon_v,
                    width,
                    chroma_width,
                    mb_x,
                    mb_y,
                    sw,
                    nc_grid,
                    intra_grid,
                    mb_addr as usize,
                );
                trial_b.deblock
            } else {
                trial_c.deblock
            }
        } else if trial_a.luma_cost <= trial_b.luma_cost {
            // Roll back the I_NxN trial; install the I_16x16 results.
            snap.restore(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
            );
            snap_a.install(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mb_addr as usize,
            );
            trial_a.deblock
        } else {
            trial_b.deblock
        }
    }

    /// Intra_16x16 encoder path with round-15 Lagrangian RDO mode
    /// decision. Returns `MbTrial` carrying the luma `J = D + λ·R` cost
    /// alongside the deblock info.
    #[allow(clippy::too_many_arguments)]
    fn encode_mb_intra16x16(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_qp_delta: i32,
        nb: Option<(bool, bool, bool)>,
    ) -> MbTrial {
        debug_assert!(
            matches!(self.cfg.chroma_format_idc, 0 | 1) || mb_qp_delta == 0,
            "round-430 row modulation (non-zero mb_qp_delta) is 4:2:0/4:0:0-only; \
             the 4:2:2 / 4:4:4 writer branches still hard-code delta 0",
        );
        let width = self.cfg.width as usize;
        let height = self.cfg.height as usize;
        let lambda = lambda_ssd(qp_y, true);
        // §8.5.9 — effective intra weightScale (flat unless the config
        // requests the Table 7-3/7-4 default matrices).
        let wq = self.cfg.scaling_matrix.intra_weights();

        // ------- Luma: pick mode by full RDO -------
        // §8.3.3 — for each of 4 candidates compute D = SSD(source, recon)
        // and R = trial CAVLC bits, then pick min(D + λR). Modes whose
        // required neighbours are missing are skipped (the decoder would
        // reject them if we tried to signal them).
        let mut best_luma_mode = I16x16Mode::Dc;
        let mut best_luma_pred = [0i32; 256];
        let mut best_luma_cost = u64::MAX;
        for &mode in &[
            I16x16Mode::Vertical,
            I16x16Mode::Horizontal,
            I16x16Mode::Dc,
            I16x16Mode::Plane,
        ] {
            let Some(pred) = predict_16x16_avail(mode, recon_y, width, height, mb_x, mb_y, nb)
            else {
                continue;
            };
            let cost = trial_intra16x16_cost(frame, &pred, mb_x, mb_y, qp_y, width, lambda, &wq.w4);
            if cost < best_luma_cost {
                best_luma_cost = cost;
                best_luma_mode = mode;
                best_luma_pred = pred;
            }
        }

        // Sample residual (16x16 i32) against the chosen predictor.
        let mut residual = [0i32; 256];
        for j in 0..16usize {
            for i in 0..16usize {
                let s = frame.y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
                residual[j * 16 + i] = s - best_luma_pred[j * 16 + i];
            }
        }

        // For each 4x4 sub-block: forward 4x4. Then collect DCs and
        // run the Hadamard.
        let mut coeffs_4x4 = [[0i32; 16]; 16];
        for (blk, slot) in coeffs_4x4.iter_mut().enumerate() {
            let bx = blk % 4;
            let by = blk / 4;
            let mut block = [0i32; 16];
            for j in 0..4 {
                for i in 0..4 {
                    block[j * 4 + i] = residual[(by * 4 + j) * 16 + bx * 4 + i];
                }
            }
            *slot = forward_core_4x4(&block);
        }
        // Pull out the DCs into the row-major DC matrix.
        let mut dc_coeffs = [0i32; 16];
        for (blk, coeffs) in coeffs_4x4.iter().enumerate() {
            let bx = blk % 4;
            let by = blk / 4;
            dc_coeffs[by * 4 + bx] = coeffs[0];
        }
        // Forward Hadamard + quantize.
        let dc_hadamard = forward_hadamard_4x4(&dc_coeffs);
        let dc_levels = quantize_luma_dc_w(&dc_hadamard, qp_y, true, wq.w4[0]);

        // §8.5.10 — luma AC residual. Quantize each 4x4 block's AC
        // (positions 1..15 of the row-major coefficient block; position
        // 0 is the DC and is handled separately by the Hadamard above).
        // Pack into AC-only scan order (15 entries each) ready for
        // CAVLC emit.
        //
        // Ordering note: §6.4.3 raster-Z order (`LUMA_4X4_BLK`) is what
        // the decoder consumes when `cbp_luma == 15`. The local
        // `coeffs_4x4[blk]` array above is keyed by simple row-major
        // (`blk = by*4 + bx`); we re-index here.
        let mut luma_ac_levels = [[0i32; 16]; 16];
        let mut luma_ac_quant_raster = [[0i32; 16]; 16]; // for inverse path
        let mut any_luma_ac_nz = false;
        for blkz in 0..16usize {
            let (bx, by) = LUMA_4X4_BLK[blkz];
            let raster = by * 4 + bx;
            let z = quantize_4x4_ac_w(&coeffs_4x4[raster], qp_y, true, &wq.w4);
            luma_ac_quant_raster[raster] = z;
            // AC scan layout for the bitstream (positions 0..=14).
            let scan_ac = zigzag_scan_4x4_ac(&z);
            luma_ac_levels[blkz] = scan_ac;
            if scan_ac.iter().any(|&v| v != 0) {
                any_luma_ac_nz = true;
            }
        }
        // §7.4.5.1 — for Intra_16x16 cbp_luma is 0 or 15 only.
        // Round-28: for 4:4:4 we may need to promote cbp_luma to 15
        // post-hoc if either chroma plane has nonzero AC (so the
        // §7.3.5.3 chroma plane AC blocks reach the decoder under
        // the cbp_luma==15 gate). Done below after chroma encode.
        #[allow(unused_mut)]
        let mut cbp_luma: u8 = if any_luma_ac_nz { 15 } else { 0 };

        // §8.5.10 reconstruction: inverse Hadamard on the DC levels +
        // per-block inverse 4x4 with c[0,0] overwritten by the matching
        // pre-scaled DC entry. When `cbp_luma == 0` the AC is zeroed —
        // matching what the decoder will see (no AC blocks in the
        // bitstream → empty residual_luma → coeffs[1..] = 0).
        let inv_dc =
            inverse_hadamard_luma_dc_16x16(&dc_levels, qp_y, &wq.w4, 8).expect("luma DC inverse");
        #[allow(clippy::needless_range_loop)] // raster row-major over 16 4x4 blocks
        for blk in 0..16usize {
            let bx = blk % 4;
            let by = blk / 4;
            // Build the inverse coefficient block: AC from the
            // already-quantized levels (only when cbp_luma == 15 will
            // they actually reach the decoder — otherwise zero them
            // here so the encoder recon matches what the decoder will
            // produce).
            let mut coeffs_in = if cbp_luma == 15 {
                // Re-build the pre-AC-scan coeff matrix the decoder
                // produces by `inverse_scan_4x4_zigzag_ac` from the
                // AC-only layout. Identical to taking the original
                // `luma_ac_quant_raster[blk]` (which already has slot 0
                // zeroed by `quantize_4x4_ac`).
                luma_ac_quant_raster[blk]
            } else {
                [0i32; 16]
            };
            coeffs_in[0] = inv_dc[by * 4 + bx];
            let r = inverse_transform_4x4_dc_preserved(&coeffs_in, qp_y, &wq.w4, 8)
                .expect("inverse 4x4");
            for j in 0..4 {
                for i in 0..4 {
                    let px = mb_x * 16 + bx * 4 + i;
                    let py = mb_y * 16 + by * 4 + j;
                    let p = best_luma_pred[(by * 4 + j) * 16 + bx * 4 + i];
                    let raw = p + r[j * 4 + i];
                    recon_y[py * width + px] = raw.clamp(0, 255) as u8;
                }
            }
        }

        // ------- Chroma: dispatch to 4:2:0 / 4:2:2 / 4:4:4 helper -------
        // Round 27/28: the 4:2:0 / 4:2:2 helper picks the best §8.3.4
        // mode by SAD, encodes DC + AC residuals, reconstructs the
        // sample residual, and returns a `ChromaBlock`. For 4:4:4 the
        // chroma plane is "coded like luma" (§7.3.5.3 /
        // §8.3.4.1), so we skip the chroma-mode-decision entirely:
        // chroma reuses the luma Intra_16x16 mode, and each plane
        // runs the luma-style 16x16 DC + 16 AC pipeline via
        // `encode_intra16x16_chroma_plane_luma_like`.
        let chroma_array_type = self.cfg.chroma_format_idc;
        let mut chroma_block_for_mask: Option<ChromaBlock> = None;
        // Pre-declare 4:4:4 outputs (only populated on the 4:4:4 path).
        let mut cb_dc_444 = [0i32; 16];
        let mut cr_dc_444 = [0i32; 16];
        let mut cb_ac_scan_444 = [[0i32; 16]; 16];
        let mut cr_ac_scan_444 = [[0i32; 16]; 16];
        let mut cb_ac_quant_444 = [[0i32; 16]; 16];
        let mut cr_ac_quant_444 = [[0i32; 16]; 16];
        let (cbp_chroma, best_chroma_mode_u8): (u8, u8) = if chroma_array_type == 3 {
            // §8.3.4.1 — chroma reuses the luma mode for 4:4:4.
            let (cb_dc, cb_ac_scan, cb_ac_quant, cb_nz) = encode_intra16x16_chroma_plane_luma_like(
                best_luma_mode,
                frame.u,
                recon_u,
                chroma_width,
                chroma_height,
                mb_x,
                mb_y,
                qp_c,
                &wq.w4,
            );
            let (cr_dc, cr_ac_scan, cr_ac_quant, cr_nz) = encode_intra16x16_chroma_plane_luma_like(
                best_luma_mode,
                frame.v,
                recon_v,
                chroma_width,
                chroma_height,
                mb_x,
                mb_y,
                qp_c,
                &wq.w4,
            );
            cb_dc_444 = cb_dc;
            cr_dc_444 = cr_dc;
            cb_ac_scan_444 = cb_ac_scan;
            cr_ac_scan_444 = cr_ac_scan;
            cb_ac_quant_444 = cb_ac_quant;
            cr_ac_quant_444 = cr_ac_quant;
            // 4:4:4: cbp_chroma is held at 0 in mb_type (Table 7-11
            // entry chosen in the 0-chroma family). The chroma plane AC
            // emit is gated by `cbp_luma == 15` instead, per §7.3.5.3.
            //
            // When either chroma plane has nonzero AC, we promote
            // `cbp_luma` to 15 here so the bitstream gate fires and the
            // decoder reads the chroma plane AC blocks. The luma AC
            // payload is identically zero in that case, so 16 short
            // coeff_token=0 blocks add ~16 bits — a small and
            // predictable cost.
            if cb_nz || cr_nz {
                cbp_luma = 15;
            }
            (0u8, 0u8)
        } else if chroma_array_type == 0 {
            // Round-448 — monochrome: no chroma planes, no chroma
            // syntax (§7.3.5.1 / §7.3.5.3 at ChromaArrayType == 0).
            (0u8, 0u8)
        } else {
            let chroma_block = encode_chroma_block(
                chroma_array_type,
                frame.u,
                frame.v,
                recon_u,
                recon_v,
                chroma_width,
                chroma_height,
                mb_x,
                mb_y,
                qp_c,
                &wq.w4,
                nb,
            );
            let cm = chroma_block.pred_mode.as_u8();
            let ccbp = chroma_block.cbp_chroma;
            // Apply 4:2:0 / 4:2:2 chroma reconstruction.
            install_chroma_recon(
                chroma_array_type,
                chroma_width,
                mb_x,
                mb_y,
                &chroma_block,
                recon_u,
                recon_v,
            );
            chroma_block_for_mask = Some(chroma_block);
            (ccbp, cm)
        };
        let n_chroma_blk = ChromaBlock::cb_block_count(chroma_array_type);
        // Re-export the per-block AC arrays into local arrays of the
        // shape the legacy `I16x16McbConfig` expects (4 blocks). For
        // 4:2:2 the writer below uses `write_intra16x16_mb_chroma` with
        // `ChromaWriteKind::Yuv422` so these arrays are unused.
        let mut u_dc_levels = [0i32; 4];
        let mut v_dc_levels = [0i32; 4];
        let mut u_ac_levels = [[0i32; 16]; 4];
        let mut v_ac_levels = [[0i32; 16]; 4];
        if chroma_array_type == 1 {
            let cb = chroma_block_for_mask.as_ref().unwrap();
            u_dc_levels.copy_from_slice(&cb.dc_cb[..4]);
            v_dc_levels.copy_from_slice(&cb.dc_cr[..4]);
            u_ac_levels.copy_from_slice(&cb.ac_cb[..4]);
            v_ac_levels.copy_from_slice(&cb.ac_cr[..4]);
        }
        let _ = chroma_height;

        // ------- Build CAVLC neighbour-grid view + per-block nC ------
        // §9.2.1.1: nC for each AC residual block is derived from the
        // neighbour A (left) and B (above) blocks. The decoder will use
        // its own CavlcNcGrid for this; the encoder must match.
        //
        // Strategy: mark this MB available *before* emit and
        // progressively fill `luma_total_coeff[blk]` with the
        // TotalCoeff of each AC block as we enumerate them. Internal
        // neighbours then read the correct partial state via
        // `derive_nc_luma`'s `NeighbourSource::InternalBlock` →
        // `nc_nn_luma` → `info.luma_total_coeff[blk]` chain. External
        // neighbours read from previously-encoded MBs (already filled
        // by an earlier iteration of this loop).
        let width_mbs = self.cfg.width / 16;
        let mb_addr = (mb_y as u32) * width_mbs + (mb_x as u32);
        // NOTE: order of operations matters. We need to set
        // `is_available = true` and `is_intra = true` for the current
        // MB *before* deriving any nC values that might reference its
        // own internal blocks.
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16]; // start fresh
        }

        // §9.2.1.1 NOTE 1: nC for Intra16x16DCLevel uses *AC* TotalCoeff
        // of neighbour luma4x4 block 0 (the DC's "blk_idx" is fixed to
        // 0 by step 1). The neighbour A/B for block 0 are the
        // corresponding blocks of the left / above MBs. `derive_nc_luma`
        // with `LumaNcKind::Intra16x16Dc` does this lookup.
        let nc_dc = derive_nc_luma(nc_grid, mb_addr, 0, LumaNcKind::Intra16x16Dc, true, false);

        // Per-AC-block nC, in §6.4.3 raster-Z order. We compute every
        // entry up-front (using the freshly-zeroed own_luma_totals on
        // this MB) then progressively update the grid as we encode each
        // block, recomputing the next block's nC from the updated state.
        let mut luma_ac_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blkz in 0..16u8 {
            // Update grid view of own MB before computing this block's
            // nC, so internal neighbours read the right TotalCoeff.
            nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr, blkz, LumaNcKind::Ac, true, false);
            luma_ac_nc[blkz as usize] = nc;
            // Update own_totals with this block's TotalCoeff so the
            // next block's nC sees it.
            if cbp_luma == 15 {
                let tc = luma_ac_levels[blkz as usize]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8;
                own_totals[blkz as usize] = tc;
            }
        }
        // Final write of TotalCoeff into the grid for this MB so future
        // MBs see the correct neighbour state.
        nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;

        // ------- Emit MB syntax -------
        let nc_dc_ctx = CoeffTokenContext::Numeric(nc_dc);
        if chroma_array_type == 1 {
            let chroma_block = chroma_block_for_mask.as_ref().unwrap();
            let (nc_cb, nc_cr) = derive_chroma_ac_nc_and_commit_totals(
                nc_grid,
                mb_addr,
                true,
                cbp_chroma,
                &chroma_block.ac_cb[..4],
                &chroma_block.ac_cr[..4],
                1,
            );
            let mb_cfg = I16x16McbConfig {
                pred_mode: best_luma_mode.as_u8(),
                intra_chroma_pred_mode: best_chroma_mode_u8,
                cbp_luma,
                cbp_chroma,
                // §7.3.5 — Intra_16x16 always codes the luma DC block,
                // so the delta is always transmitted and the decoded
                // QP_Y chain lands on `qp_y` (round-430 row modulation
                // is 4:2:0-only; the other formats assert delta == 0
                // below).
                mb_qp_delta,
                luma_dc_levels_raster: dc_levels,
                luma_ac_levels,
                luma_ac_nc,
                chroma_dc_cb: u_dc_levels,
                chroma_dc_cr: v_dc_levels,
                chroma_ac_cb: u_ac_levels,
                chroma_ac_cr: v_ac_levels,
                chroma_ac_nc_cb: nc_cb,
                chroma_ac_nc_cr: nc_cr,
            };
            write_intra16x16_mb(sw, &mb_cfg, nc_dc_ctx).expect("write Intra16x16 mb");
        } else if chroma_array_type == 0 {
            // Round-448 — monochrome: luma syntax only. No
            // intra_chroma_pred_mode (§7.3.5.1), no chroma residual
            // (§7.3.5.3); `ChromaWriteKind::Mono` emits nothing.
            crate::encoder::macroblock::write_intra16x16_mb_chroma(
                sw,
                best_luma_mode.as_u8(),
                /* intra_chroma_pred_mode: absent at ChromaArrayType 0 */ 0,
                cbp_luma,
                cbp_chroma,
                mb_qp_delta,
                &dc_levels,
                &luma_ac_levels,
                &luma_ac_nc,
                crate::encoder::macroblock::ChromaWriteKind::Mono,
                nc_dc_ctx,
            )
            .expect("write Intra16x16 mb (4:0:0)");
        } else if chroma_array_type == 2 {
            // Round-27: 4:2:2 path. Pass per-plane 8-entry DC + 8-block
            // AC arrays via `ChromaWriteKind::Yuv422`.
            let chroma_block = chroma_block_for_mask.as_ref().unwrap();
            let (nc_cb, nc_cr) = derive_chroma_ac_nc_and_commit_totals(
                nc_grid,
                mb_addr,
                true,
                cbp_chroma,
                &chroma_block.ac_cb,
                &chroma_block.ac_cr,
                2,
            );
            crate::encoder::macroblock::write_intra16x16_mb_chroma(
                sw,
                best_luma_mode.as_u8(),
                best_chroma_mode_u8,
                cbp_luma,
                cbp_chroma,
                0,
                &dc_levels,
                &luma_ac_levels,
                &luma_ac_nc,
                crate::encoder::macroblock::ChromaWriteKind::Yuv422 {
                    chroma_dc_cb: &chroma_block.dc_cb,
                    chroma_dc_cr: &chroma_block.dc_cr,
                    chroma_ac_cb: &chroma_block.ac_cb,
                    chroma_ac_cr: &chroma_block.ac_cr,
                    cb_ac_nc: &nc_cb,
                    cr_ac_nc: &nc_cr,
                },
                nc_dc_ctx,
            )
            .expect("write Intra16x16 mb (4:2:2)");
        } else {
            // Round-28: 4:4:4 path. Each chroma plane is coded "like
            // luma" — its own 16x16 DC Hadamard block + 16 4x4 AC
            // blocks, gated by luma cbp==15 (per §7.3.5.3 / decoder
            // `residual_cb_16x16_dc` / `residual_cb_luma_like` etc).
            //
            // §9.2.1.1 — real per-plane nC from the neighbour grid's
            // `cb_luma_total_coeff[]` / `cr_luma_total_coeff[]` with
            // progressive in-MB commits (decoder parse-order mirror).
            // Round-388: the former nC=0 approximation desynchronised
            // as soon as a 4:4:4 Intra_8x8 neighbour committed real
            // per-plane totals (the two shapes now mix per-MB under
            // the I_16x16-vs-I_8x8 RDO).
            let (cb_dc_nc, cb_ac_nc) =
                derive_plane_nc_444_i16x16(nc_grid, mb_addr, false, cbp_luma, &cb_ac_scan_444);
            let (cr_dc_nc, cr_ac_nc) =
                derive_plane_nc_444_i16x16(nc_grid, mb_addr, true, cbp_luma, &cr_ac_scan_444);
            crate::encoder::macroblock::write_intra16x16_mb_chroma(
                sw,
                best_luma_mode.as_u8(),
                /* intra_chroma_pred_mode: ignored for 4:4:4 */ 0,
                cbp_luma,
                cbp_chroma,
                0,
                &dc_levels,
                &luma_ac_levels,
                &luma_ac_nc,
                crate::encoder::macroblock::ChromaWriteKind::Yuv444 {
                    cb_dc_raster: &cb_dc_444,
                    cr_dc_raster: &cr_dc_444,
                    cb_ac_levels: &cb_ac_scan_444,
                    cr_ac_levels: &cr_ac_scan_444,
                    cb_ac_nc: &cb_ac_nc,
                    cr_ac_nc: &cr_ac_nc,
                    cb_dc_nc,
                    cr_dc_nc,
                    cbp_luma_for_ac_gate: cbp_luma,
                },
                nc_dc_ctx,
            )
            .expect("write Intra16x16 mb (4:4:4)");
            // Suppress warnings for unused 4:4:4 reconstruction state
            // when the helper internally needs them.
            let _ = (cb_ac_quant_444, cr_ac_quant_444);
        }

        // Mark this MB as available + not-i_nxn for subsequent MBs'
        // §8.3.1.1 step 3 lookup. Intra_16x16 neighbours fall into
        // the "DC fallback" branch (intraMxMPredModeN = 2).
        let slot = intra_grid.slot_mut(mb_x, mb_y);
        slot.available = true;
        slot.is_i_nxn = false;

        // §8.7.2.1 — per-4x4 nonzero mask for the deblock walker.
        // Intra_16x16: when cbp_luma == 15 every 4x4 block transmits its
        // (DC + AC) coefficients and the DC plane guarantees the block
        // contains a non-zero coefficient. The deblock walker treats any
        // nonzero block (DC or AC) as "either has nonzero coeffs", which
        // promotes bS from 0 → 2 on internal edges. So we set the bit
        // for every block when cbp_luma == 15. When cbp_luma == 0 the
        // DC Hadamard levels may still be non-zero, but the spec's per-
        // 4x4 nonzero check (§8.7.2.1 third bullet) reads from the
        // luma4x4 blocks — for Intra_16x16 the DC plane is a separate
        // block (Intra16x16DCLevel) that the decoder marks as nonzero on
        // own_luma_total set by the DC's TotalCoeff. We reflect this
        // closely by setting all 16 bits when cbp_luma == 15 (AC nonzero
        // anywhere) — DC-only Intra_16x16 (cbp_luma == 0) leaves the
        // mask at 0, matching the spec's per-4x4 view: AC of those
        // blocks is identically zero so the bS=2 rule fires only on
        // edges where the OTHER side has AC.
        let luma_nonzero_4x4 = if cbp_luma == 15 {
            // Per-block nonzero: bit set iff the AC scan-order array
            // has at least one non-zero entry.
            let mut nz = [false; 16];
            for (blkz, scan_ac) in luma_ac_levels.iter().enumerate() {
                nz[blkz] = scan_ac.iter().any(|&v| v != 0);
            }
            luma_nz_mask_from_blocks(&nz)
        } else {
            0
        };
        // Chroma per-block AC nonzero. For 4:2:0: 4 blocks per plane,
        // packed as bits 0..=3 (Cb) and 8..=11 (Cr). For 4:2:2: 8 blocks
        // per plane, packed bits 0..=7 (Cb) and 8..=15 (Cr) per
        // `compute_chroma_nonzero_mask` in the decoder's reconstruct.rs.
        // Round-28 4:4:4: chroma deblocking uses the LUMA filter ladder,
        // which is gated entirely on the encoder side by setting
        // `disable_deblocking_filter_idc=1` in the slice header. The
        // chroma_nonzero_4x4 mask is left at 0 — it isn't consulted on
        // this path.
        let chroma_nz_mask = chroma_block_for_mask
            .as_ref()
            .map(|cb| chroma_nz_mask_from_chroma_block(cb, n_chroma_blk))
            .unwrap_or(0);
        MbTrial {
            luma_cost: best_luma_cost,
            deblock: MbDeblockInfo {
                is_intra: true,
                qp_y,
                luma_nonzero_4x4,
                chroma_nonzero_4x4: chroma_nz_mask,
                ..Default::default()
            },
        }
    }

    /// I_NxN (Intra_4x4) path: per-block 9-mode prediction, full luma
    /// 4x4 residual, chroma residual identical to I_16x16. Round-15: per-
    /// block Lagrangian RDO replaces SAD-on-predictor mode decision.
    #[allow(clippy::too_many_arguments)]
    fn encode_mb_intra4x4(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_qp_delta: i32,
    ) -> MbTrial {
        debug_assert!(
            self.cfg.chroma_format_idc == 1 || mb_qp_delta == 0,
            "round-430 row modulation (non-zero mb_qp_delta) is 4:2:0-only; \
             the 4:2:2 / 4:4:4 writer branches still hard-code delta 0",
        );
        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let lambda = lambda_ssd(qp_y, true);

        // Per-block: pick mode by full Lagrangian RDO (round-15).
        // Build the intra_grid slot incrementally so subsequent blocks
        // see this MB's chosen intra_4x4_pred_modes when computing
        // their predIntra4x4PredMode (§8.3.1.1 step 4).
        //
        // We MUST pre-mark the slot as I_NxN+available so that the
        // `predicted_4x4_mode` lookup for blocks 5..15 finds the
        // current MB's earlier-block modes.
        {
            let s = intra_grid.slot_mut(mb_x, mb_y);
            s.available = true;
            s.is_i_nxn = true;
            s.intra_4x4_pred_modes = [0u8; 16];
        }

        // Per-block scratch.
        let mut chosen_mode = [0u8; 16]; // Intra4x4Mode index per block.
        let mut prev_flag = [false; 16];
        let mut rem = [0u8; 16];
        let mut luma_4x4_levels_scan = [[0i32; 16]; 16]; // scan-order per block
                                                         // §8.5.9 — effective intra weightScale for this MB shape.
        let wq = self.cfg.scaling_matrix.intra_weights();
        let mut luma_4x4_quant_raster = [[0i32; 16]; 16]; // raster-order quantized levels (for inverse)
        let mut blk_has_nz = [false; 16];
        // Per-block cumulative luma cost (D + λR) — tracked for the
        // MB-level mb_type RDO comparison upstream in `encode_mb`. Each
        // block's contribution is the actual SSD on recon plus λ times
        // the per-block prev_flag/rem cost plus the trial CAVLC bit
        // count. We must approximate the per-block CAVLC bits because
        // the actual nC depends on neighbour state we won't fully
        // commit until after this loop; we use nC=0 as a stable lower-
        // bound estimate.
        //
        // Seed with the per-MB syntax overhead so the cost is comparable
        // to the I_16x16 trial:
        //   mb_type ue(0) = 1 bit
        //   intra_chroma_pred_mode ue(v) ≈ 3-bit average
        //   coded_block_pattern me(v) intra 4:2:0 = ~4-bit average
        //   mb_qp_delta se(0) = 1 bit (when any cbp non-zero)
        // → ~9 bits, roughly matching the I_16x16 path's 7 + 1 = 8 bits.
        //
        // Plus an empirical bias for "post-deblock D under-measurement":
        // mode decision happens before the picture-level §8.7 deblock
        // pass, so per-block D is measured on pre-filter recon. I_NxN at
        // the boundary of smooth regions tends to gain *more* deblock
        // smoothing than I_16x16; this bias keeps the smooth gradient
        // fixture's top-row / left-col MBs (where I_16x16 is restricted
        // to DC) from over-spending I_NxN there. The +16-bit value was
        // calibrated empirically against the round-15 fixture set.
        let mb_overhead_bits: u64 = 9 + 16;
        let mut mb_luma_cost: u64 = cost_combined(0, mb_overhead_bits, lambda);

        for blk in 0..16usize {
            let (bx, by) = I4X4_XY[blk];
            let avail = i4x4_avail(mb_x, mb_y, bx, by, width_mbs);
            let predicted = predicted_intra4x4_mode(intra_grid, mb_x, mb_y, blk, width_mbs);

            // Trial all 9 modes per RDO. For each: predict → forward →
            // quantize → inverse → add → SSD; trial CAVLC for rate.
            let mut best_mode = Intra4x4Mode::Dc;
            let mut best_cost = u64::MAX;
            let mut best_pred = [0i32; 16];
            let mut best_z_raster = [0i32; 16];
            let mut best_z_scan = [0i32; 16];
            let mut best_recon = [0i32; 16];
            for &mode in &Intra4x4Mode::ALL {
                let Some(pred) = predict_4x4(mode, recon_y, width, mb_x, mb_y, bx, by, avail)
                else {
                    continue;
                };
                let candidate = mode.as_u8();
                // ----- D component: build residual, transform, quant,
                // inverse, add → recon block. -----
                let mut block_res = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        let s = frame.y[(mb_y * 16 + by + j) * width + (mb_x * 16 + bx + i)] as i32;
                        block_res[j * 4 + i] = s - pred[j * 4 + i];
                    }
                }
                let w_coeffs = forward_core_4x4(&block_res);
                let z_raster = quantize_4x4_w(&w_coeffs, qp_y, true, &wq.w4);
                let z_scan = zigzag_scan_4x4(&z_raster);
                let r = inverse_transform_4x4(&z_raster, qp_y, &wq.w4, 8).expect("inverse 4x4");
                let mut recon_block = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        recon_block[j * 4 + i] = pred[j * 4 + i] + r[j * 4 + i];
                    }
                }
                let d = ssd_4x4(frame.y, width, mb_x * 16 + bx, mb_y * 16 + by, &recon_block);

                // ----- R component: prev_flag/rem cost + trial CAVLC. -----
                // 1 bit for prev_flag; if mode != predicted, +3 bits rem.
                let mut bits: u64 = 1;
                if candidate != predicted {
                    bits += 3;
                }
                // Trial CAVLC encode for the residual block. nC=0 is a
                // safe stable estimate during mode trial — the actual
                // nC depends on neighbour TotalCoeff values that vary
                // with the chosen mode, but the impact on coeff_token
                // bit count is small (1-2 bits) and using a constant
                // makes mode comparisons consistent. Quadrant-cbp gating
                // is also approximated: for trial scoring assume the
                // block IS transmitted (over-estimate at low QP).
                let mut trial_w = BitWriter::new();
                if encode_residual_block_cavlc(
                    &mut trial_w,
                    CoeffTokenContext::Numeric(0),
                    16,
                    &z_scan,
                )
                .is_ok()
                {
                    bits += trial_w.bits_emitted() as u64;
                }
                let cost = cost_combined(d, bits, lambda);
                if cost < best_cost {
                    best_cost = cost;
                    best_mode = mode;
                    best_pred = pred;
                    best_z_raster = z_raster;
                    best_z_scan = z_scan;
                    best_recon = recon_block;
                }
            }
            let chosen = best_mode.as_u8();
            chosen_mode[blk] = chosen;
            mb_luma_cost = mb_luma_cost.saturating_add(best_cost);

            if chosen == predicted {
                prev_flag[blk] = true;
            } else {
                prev_flag[blk] = false;
                // §7.3.5.1: rem in 0..=7. Map chosen → rem so that the
                // decoder's `if rem < predicted { rem } else { rem + 1 }`
                // recovers `chosen`.
                let r = if chosen < predicted {
                    chosen
                } else {
                    chosen - 1
                };
                rem[blk] = r;
            }

            // Update intra_grid with our chosen mode so subsequent
            // blocks (in this MB and in later MBs) see it for their
            // own neighbour lookup.
            intra_grid.slot_mut(mb_x, mb_y).intra_4x4_pred_modes[blk] = chosen;
            luma_4x4_quant_raster[blk] = best_z_raster;
            luma_4x4_levels_scan[blk] = best_z_scan;
            blk_has_nz[blk] = best_z_raster.iter().any(|&v| v != 0);

            // Commit reconstruction to the buffer so subsequent blocks
            // see it. Mirrors the decoder's per-block recon walk.
            // `best_pred` was folded into `best_recon` during the trial.
            // (Same caveat as round-4 about zero-cbp quadrant rollback —
            // applied below after the cbp_luma decision.)
            let _ = best_pred;
            for j in 0..4 {
                for i in 0..4 {
                    let px = mb_x * 16 + bx + i;
                    let py = mb_y * 16 + by + j;
                    recon_y[py * width + px] = best_recon[j * 4 + i].clamp(0, 255) as u8;
                }
            }
        }

        // §7.3.5 — cbp_luma per 8x8 quadrant: bit `q` set iff any of the
        // 4 child 4x4 blocks has at least one non-zero coefficient.
        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            let any_nz = (0..4).any(|sub| blk_has_nz[blk8 * 4 + sub]);
            if any_nz {
                cbp_luma |= 1u8 << blk8;
            }
        }

        // Roll back recon for any 8x8 quadrant whose cbp bit is 0:
        // the decoder will not receive those 4x4 residuals, so it
        // reconstructs `pred + 0`. Re-derive that here. We must use
        // each block's chosen predictor — recompute it from the modes
        // (the recon buffer is already updated to the residual recon,
        // which would diverge from the decoder for zero-cbp quadrants).
        for blk8 in 0..4usize {
            if (cbp_luma >> blk8) & 1 == 1 {
                continue;
            }
            for sub in 0..4usize {
                let blk = blk8 * 4 + sub;
                let (bx, by) = I4X4_XY[blk];
                let mode = Intra4x4Mode::from_u8(chosen_mode[blk]).expect("valid mode");
                // Re-gather neighbour samples — the recon buffer at the
                // (bx, by) position has already been updated to the
                // post-residual recon for the trial. To re-predict the
                // same way the decoder will, we need the recon as it
                // was BEFORE this block. But we already overwrote it.
                //
                // Fortunately, the decoder's prediction reads only
                // samples LEFT, ABOVE, ABOVE-LEFT, ABOVE-RIGHT of this
                // 4x4 block — none of which lie inside the block
                // itself. Those neighbour samples are unchanged: we
                // overwrote (bx..bx+4, by..by+4) only. So recompute
                // the predictor against the current recon and it will
                // match the decoder.
                let avail = i4x4_avail(mb_x, mb_y, bx, by, width_mbs);
                let pred = predict_4x4(mode, recon_y, width, mb_x, mb_y, bx, by, avail)
                    .expect("predictor exists for chosen mode");
                for j in 0..4 {
                    for i in 0..4 {
                        let px = mb_x * 16 + bx + i;
                        let py = mb_y * 16 + by + j;
                        recon_y[py * width + px] = pred[j * 4 + i].clamp(0, 255) as u8;
                    }
                }
            }
        }

        // ----- Chroma: dispatch via 4:2:0 / 4:2:2 helper. -----
        let chroma_array_type = self.cfg.chroma_format_idc;
        let chroma_block = encode_chroma_block(
            chroma_array_type,
            frame.u,
            frame.v,
            recon_u,
            recon_v,
            chroma_width,
            chroma_height,
            mb_x,
            mb_y,
            qp_c,
            &wq.w4,
            None,
        );
        let best_chroma_mode = chroma_block.pred_mode;
        let cbp_chroma = chroma_block.cbp_chroma;
        let n_chroma_blk = ChromaBlock::cb_block_count(chroma_array_type);
        let mut u_dc_levels = [0i32; 4];
        let mut v_dc_levels = [0i32; 4];
        let mut u_ac_levels = [[0i32; 16]; 4];
        let mut v_ac_levels = [[0i32; 16]; 4];
        if chroma_array_type == 1 {
            u_dc_levels.copy_from_slice(&chroma_block.dc_cb[..4]);
            v_dc_levels.copy_from_slice(&chroma_block.dc_cr[..4]);
            u_ac_levels.copy_from_slice(&chroma_block.ac_cb[..4]);
            v_ac_levels.copy_from_slice(&chroma_block.ac_cr[..4]);
        }
        install_chroma_recon(
            chroma_array_type,
            chroma_width,
            mb_x,
            mb_y,
            &chroma_block,
            recon_u,
            recon_v,
        );
        let _ = chroma_height;

        // ----- CAVLC neighbour grid update. -----
        let pic_w_mbs = self.cfg.width / 16;
        let mb_addr = (mb_y as u32) * pic_w_mbs + (mb_x as u32);
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }
        // Per-AC-block nC for the I_NxN luma path. Same nC derivation
        // (LumaNcKind::Ac), updated progressively as in the I_16x16
        // path. Blocks whose 8x8 quadrant cbp is 0 contribute
        // TotalCoeff = 0.
        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr, blk as u8, LumaNcKind::Ac, true, false);
            luma_4x4_nc[blk] = nc;
            // Only blocks in transmitted quadrants contribute non-zero
            // TotalCoeff.
            if (cbp_luma >> blk8) & 1 == 1 {
                let tc = luma_4x4_levels_scan[blk]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8;
                own_totals[blk] = tc;
            } else {
                own_totals[blk] = 0;
            }
        }
        nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;

        // §9.2.1.1 — per-block chroma-AC nC + grid totals commit.
        let (chroma_nc_cb, chroma_nc_cr) = derive_chroma_ac_nc_and_commit_totals(
            nc_grid,
            mb_addr,
            true,
            cbp_chroma,
            &chroma_block.ac_cb[..ChromaBlock::cb_block_count(chroma_array_type)],
            &chroma_block.ac_cr[..ChromaBlock::cb_block_count(chroma_array_type)],
            chroma_array_type,
        );

        // ----- Emit syntax. -----
        if chroma_array_type == 1 {
            let mb_cfg = INxNMcbConfig {
                // §7.3.5 — inside a transform_8x8_mode_flag=1 stream an
                // I_NxN MB must code transform_size_8x8_flag = 0 to
                // select the 4x4 transform.
                emit_transform_size_8x8_zero: self.cfg.transform_8x8,
                prev_intra4x4_pred_mode_flag: prev_flag,
                rem_intra4x4_pred_mode: rem,
                intra_chroma_pred_mode: best_chroma_mode.as_u8(),
                cbp_luma,
                cbp_chroma,
                // §7.3.5 — transmitted only when cbp > 0 (the writer
                // gates on that); a cbp==0 MB leaves the decoded QP_Y
                // chain untouched, mirrored in `deblock.qp_y` below.
                mb_qp_delta,
                luma_4x4_levels: luma_4x4_levels_scan,
                luma_4x4_nc,
                chroma_dc_cb: u_dc_levels,
                chroma_dc_cr: v_dc_levels,
                chroma_ac_cb: u_ac_levels,
                chroma_ac_cr: v_ac_levels,
                chroma_ac_nc_cb: chroma_nc_cb,
                chroma_ac_nc_cr: chroma_nc_cr,
            };
            write_i_nxn_mb(sw, &mb_cfg).expect("write I_NxN mb");
        } else {
            // Round-27: 4:2:2 chroma layout.
            crate::encoder::macroblock::write_i_nxn_mb_chroma(
                sw,
                // §7.3.5 — code transform_size_8x8_flag = 0 inside a
                // transform_8x8_mode_flag = 1 stream (round-385).
                self.cfg.transform_8x8,
                &prev_flag,
                &rem,
                best_chroma_mode.as_u8(),
                cbp_luma,
                cbp_chroma,
                0,
                &luma_4x4_levels_scan,
                &luma_4x4_nc,
                crate::encoder::macroblock::ChromaWriteKind::Yuv422 {
                    chroma_dc_cb: &chroma_block.dc_cb,
                    chroma_dc_cr: &chroma_block.dc_cr,
                    chroma_ac_cb: &chroma_block.ac_cb,
                    chroma_ac_cr: &chroma_block.ac_cr,
                    cb_ac_nc: &chroma_nc_cb,
                    cr_ac_nc: &chroma_nc_cr,
                },
            )
            .expect("write I_NxN mb (4:2:2)");
        }

        // intra_grid was updated incrementally above; nothing else to
        // commit here.

        // §8.7.2.1 — per-4x4 nonzero mask. For I_NxN the per-block
        // nonzero status is exactly the per-block AC scan flags computed
        // earlier (`blk_has_nz`); blocks in zero-cbp 8x8 quadrants are
        // already false there.
        let luma_nonzero_4x4 = luma_nz_mask_from_blocks(&blk_has_nz);
        let chroma_nz_mask = chroma_nz_mask_from_chroma_block(&chroma_block, n_chroma_blk);
        MbTrial {
            luma_cost: mb_luma_cost,
            deblock: MbDeblockInfo {
                is_intra: true,
                // §7.4.5 / §8.7 — the decoder's chain QP_Y after this
                // MB: `qp_y` when the delta was transmitted (cbp > 0),
                // otherwise the inherited previous-MB QP.
                qp_y: if cbp_luma > 0 || cbp_chroma > 0 {
                    qp_y
                } else {
                    qp_y - mb_qp_delta
                },
                luma_nonzero_4x4,
                chroma_nonzero_4x4: chroma_nz_mask,
                is_intra_4x4: true,
                ..Default::default()
            },
        }
    }

    /// Round-382 — encode one **Intra_8x8** macroblock (I_NxN with
    /// `transform_size_8x8_flag = 1`, High-profile 8x8 transform,
    /// CAVLC, 4:2:0). Per 8x8 block: §8.3.2 prediction (9 modes,
    /// Lagrangian RDO), §8.6.4 forward 8x8 transform + §8.5.13.1
    /// quantiser, and local reconstruction through the decoder's
    /// normative `inverse_transform_8x8` so the recon is bit-equivalent
    /// with what any conforming decoder produces. The residual is
    /// emitted as the §7.4.5.3.3 four-4x4 CAVLC split.
    #[allow(clippy::too_many_arguments)]
    fn encode_mb_intra8x8(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_qp_delta: i32,
    ) -> MbTrial {
        debug_assert!(
            self.cfg.chroma_format_idc == 1 || mb_qp_delta == 0,
            "round-430 row modulation (non-zero mb_qp_delta) is 4:2:0-only; \
             the 4:2:2 / 4:4:4 writer branches still hard-code delta 0",
        );
        let width = self.cfg.width as usize;
        let lambda = lambda_ssd(qp_y, true);
        // §8.5.9 — effective intra weightScale (8x8 intra Y list).
        let wq = self.cfg.scaling_matrix.intra_weights();
        let sl8 = wq.w8;

        // Pre-mark the slot so in-MB neighbour lookups (blocks 1..3)
        // see this MB's earlier-block modes — mirrors the decoder,
        // which stamps the grid entry before deriving pred modes.
        {
            let s = intra_grid.slot_mut(mb_x, mb_y);
            s.available = true;
            s.is_i_nxn = false;
            s.is_i8x8 = true;
            s.intra_8x8_pred_modes = [2u8; 4];
        }

        let mut prev_flag = [false; 4];
        let mut rem = [0u8; 4];
        // §7.4.5.3.3 de-interleaved CAVLC sub-blocks, `blk8*4 + i4x4`.
        let mut luma_4x4_levels = [[0i32; 16]; 16];
        let mut blk8_has_nz = [false; 4];
        // Same MB-overhead seeding rationale as the I_NxN path (mb_type
        // + transform_size_8x8_flag + chroma mode + cbp + qp_delta).
        let mb_overhead_bits: u64 = 10 + 16;
        let mut mb_luma_cost: u64 = cost_combined(0, mb_overhead_bits, lambda);

        for blk8 in 0..4usize {
            let bx = mb_x * 16 + (blk8 % 2) * 8;
            let by = mb_y * 16 + (blk8 / 2) * 8;
            let predicted = predicted_intra8x8_mode(intra_grid, mb_x, mb_y, blk8);

            // Gather + §8.3.2.2.1 filter once per block; the nine mode
            // predictions all consume the same filtered sample set.
            let raw = gather_8x8_from_recon(recon_y, width, mb_x, mb_y, blk8);
            let filtered = filter_samples_8x8(&raw, 8);

            let mut best_mode = Intra8x8Mode::Dc;
            let mut best_cost = u64::MAX;
            let mut best_z_raster = [0i32; 64];
            let mut best_recon = [0i32; 64];
            for mode_idx in 0..9u8 {
                let mode = Intra8x8Mode::from_index(mode_idx).expect("mode index in range");
                if !intra8x8_mode_available(mode, &raw.availability) {
                    continue;
                }
                let mut pred = [0i32; 64];
                predict_8x8(mode, &filtered, 8, &mut pred);

                // Residual → forward 8x8 → quantize → inverse → recon.
                let mut res = [0i32; 64];
                for j in 0..8 {
                    for i in 0..8 {
                        let s = frame.y[(by + j) * width + bx + i] as i32;
                        res[j * 8 + i] = s - pred[j * 8 + i];
                    }
                }
                let w_coeffs = forward_core_8x8(&res);
                let z_raster = quantize_8x8_w(&w_coeffs, qp_y, true, &wq.w8);
                let r = inverse_transform_8x8(&z_raster, qp_y, &sl8, 8).expect("inverse 8x8");
                let mut recon_blk = [0i32; 64];
                let mut d: u64 = 0;
                for j in 0..8 {
                    for i in 0..8 {
                        let v = (pred[j * 8 + i] + r[j * 8 + i]).clamp(0, 255);
                        recon_blk[j * 8 + i] = v;
                        let s = frame.y[(by + j) * width + bx + i] as i32;
                        let e = (s - v) as i64;
                        d += (e * e) as u64;
                    }
                }

                // Rate: prev_flag (1) + rem (3 when miss) + trial CAVLC
                // of the four de-interleaved sub-blocks at nC=0 (stable
                // estimate — same policy as the I_NxN mode trial).
                let mut bits: u64 = 1;
                if mode_idx != predicted {
                    bits += 3;
                }
                let scan = scan_8x8_for_cavlc(&z_raster, sw.field_scan());
                let subs = deinterleave_8x8_to_4x4(&scan);
                let mut trial_w = BitWriter::new();
                for sub in &subs {
                    if encode_residual_block_cavlc(
                        &mut trial_w,
                        CoeffTokenContext::Numeric(0),
                        16,
                        sub,
                    )
                    .is_err()
                    {
                        break;
                    }
                }
                bits += trial_w.bits_emitted() as u64;
                let cost = cost_combined(d, bits, lambda);
                if cost < best_cost {
                    best_cost = cost;
                    best_mode = mode;
                    best_z_raster = z_raster;
                    best_recon = recon_blk;
                }
            }

            let chosen = best_mode.as_index();
            mb_luma_cost = mb_luma_cost.saturating_add(best_cost);
            if chosen == predicted {
                prev_flag[blk8] = true;
            } else {
                prev_flag[blk8] = false;
                rem[blk8] = if chosen < predicted {
                    chosen
                } else {
                    chosen - 1
                };
            }
            intra_grid.slot_mut(mb_x, mb_y).intra_8x8_pred_modes[blk8] = chosen;

            let scan = scan_8x8_for_cavlc(&best_z_raster, sw.field_scan());
            let subs = deinterleave_8x8_to_4x4(&scan);
            for (i4x4, sub) in subs.iter().enumerate() {
                luma_4x4_levels[blk8 * 4 + i4x4] = *sub;
            }
            blk8_has_nz[blk8] = best_z_raster.iter().any(|&v| v != 0);

            // Commit the recon so later blocks (and MBs) predict from
            // it. A zero-residual block reconstructs to pred + 0, which
            // is exactly what the decoder computes for a skipped
            // (cbp bit 0) quadrant — no rollback pass is needed.
            for j in 0..8 {
                for i in 0..8 {
                    recon_y[(by + j) * width + bx + i] = best_recon[j * 8 + i] as u8;
                }
            }
        }

        // §7.4.5.1 — cbp_luma bit per 8x8 quadrant.
        let mut cbp_luma: u8 = 0;
        for (blk8, &has_nz) in blk8_has_nz.iter().enumerate() {
            if has_nz {
                cbp_luma |= 1u8 << blk8;
            }
        }

        // Chroma — identical to the I_NxN path (4:2:0 or 4:2:2).
        let chroma_array_type = self.cfg.chroma_format_idc;
        debug_assert!(
            matches!(chroma_array_type, 1 | 2),
            "Intra_8x8 encode supports 4:2:0 and 4:2:2 chroma"
        );
        let chroma_block = encode_chroma_block(
            chroma_array_type,
            frame.u,
            frame.v,
            recon_u,
            recon_v,
            chroma_width,
            chroma_height,
            mb_x,
            mb_y,
            qp_c,
            &wq.w4,
            None,
        );
        let cbp_chroma = chroma_block.cbp_chroma;
        let n_chroma_blk = ChromaBlock::cb_block_count(chroma_array_type);
        install_chroma_recon(
            chroma_array_type,
            chroma_width,
            mb_x,
            mb_y,
            &chroma_block,
            recon_u,
            recon_v,
        );
        let _ = chroma_height;

        // CAVLC nC grid — mirrors the decoder's §9.2.1.1 walk over the
        // four 4x4 CAVLC sub-blocks of each transmitted 8x8 quadrant.
        let pic_w_mbs = self.cfg.width / 16;
        let mb_addr = (mb_y as u32) * pic_w_mbs + (mb_x as u32);
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }
        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr, blk as u8, LumaNcKind::Ac, true, false);
            luma_4x4_nc[blk] = nc;
            if (cbp_luma >> blk8) & 1 == 1 {
                let tc = luma_4x4_levels[blk].iter().filter(|&&v| v != 0).count() as u8;
                own_totals[blk] = tc;
            } else {
                own_totals[blk] = 0;
            }
        }
        nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;

        // §9.2.1.1 — per-block chroma-AC nC + grid totals commit.
        let (chroma_nc_cb, chroma_nc_cr) = derive_chroma_ac_nc_and_commit_totals(
            nc_grid,
            mb_addr,
            true,
            cbp_chroma,
            &chroma_block.ac_cb[..ChromaBlock::cb_block_count(chroma_array_type)],
            &chroma_block.ac_cr[..ChromaBlock::cb_block_count(chroma_array_type)],
            chroma_array_type,
        );

        // Emit syntax.
        if chroma_array_type == 1 {
            let mut u_dc_levels = [0i32; 4];
            let mut v_dc_levels = [0i32; 4];
            let mut u_ac_levels = [[0i32; 16]; 4];
            let mut v_ac_levels = [[0i32; 16]; 4];
            u_dc_levels.copy_from_slice(&chroma_block.dc_cb[..4]);
            v_dc_levels.copy_from_slice(&chroma_block.dc_cr[..4]);
            u_ac_levels.copy_from_slice(&chroma_block.ac_cb[..4]);
            v_ac_levels.copy_from_slice(&chroma_block.ac_cr[..4]);
            let mb_cfg = I8x8McbConfig {
                prev_intra8x8_pred_mode_flag: prev_flag,
                rem_intra8x8_pred_mode: rem,
                intra_chroma_pred_mode: chroma_block.pred_mode.as_u8(),
                cbp_luma,
                cbp_chroma,
                // §7.3.5 — transmitted only when cbp > 0 (the writer
                // gates on that); see `deblock.qp_y` below.
                mb_qp_delta,
                luma_4x4_levels,
                luma_4x4_nc,
                chroma_dc_cb: u_dc_levels,
                chroma_dc_cr: v_dc_levels,
                chroma_ac_cb: u_ac_levels,
                chroma_ac_cr: v_ac_levels,
                chroma_ac_nc_cb: chroma_nc_cb,
                chroma_ac_nc_cr: chroma_nc_cr,
            };
            write_i8x8_mb(sw, &mb_cfg).expect("write I_8x8 mb");
        } else {
            // Round-385 — 4:2:2 chroma layout (§7.3.5.3: 4x2 chroma DC
            // Hadamard + 8 AC blocks per plane, ChromaDc422 CAVLC ctx).
            crate::encoder::macroblock::write_i8x8_mb_chroma(
                sw,
                &prev_flag,
                &rem,
                chroma_block.pred_mode.as_u8(),
                cbp_luma,
                cbp_chroma,
                0,
                &luma_4x4_levels,
                &luma_4x4_nc,
                crate::encoder::macroblock::ChromaWriteKind::Yuv422 {
                    chroma_dc_cb: &chroma_block.dc_cb,
                    chroma_dc_cr: &chroma_block.dc_cr,
                    chroma_ac_cb: &chroma_block.ac_cb,
                    chroma_ac_cr: &chroma_block.ac_cr,
                    cb_ac_nc: &chroma_nc_cb,
                    cr_ac_nc: &chroma_nc_cr,
                },
            )
            .expect("write I_8x8 mb (4:2:2)");
        }

        // §8.7.2.1 — every 4x4 of a transmitted 8x8 quadrant inherits
        // the quadrant's nonzero status (the decoder's
        // `compute_luma_nonzero_mask` 8x8 branch does the same).
        let mut blk_has_nz = [false; 16];
        for blk8 in 0..4usize {
            for sub in 0..4usize {
                blk_has_nz[blk8 * 4 + sub] = blk8_has_nz[blk8];
            }
        }
        let luma_nonzero_4x4 = luma_nz_mask_from_blocks(&blk_has_nz);
        let chroma_nz_mask = chroma_nz_mask_from_chroma_block(&chroma_block, n_chroma_blk);
        MbTrial {
            luma_cost: mb_luma_cost,
            deblock: MbDeblockInfo {
                is_intra: true,
                // §7.4.5 / §8.7 — chain QP_Y: see encode_mb_intra4x4.
                qp_y: if cbp_luma > 0 || cbp_chroma > 0 {
                    qp_y
                } else {
                    qp_y - mb_qp_delta
                },
                luma_nonzero_4x4,
                chroma_nonzero_4x4: chroma_nz_mask,
                transform_size_8x8_flag: true,
                ..Default::default()
            },
        }
    }

    /// Round-385 — encode one **4:4:4 Intra_8x8** macroblock (I_NxN
    /// with `transform_size_8x8_flag = 1`, ChromaArrayType == 3,
    /// CAVLC). Luma runs the same §8.3.2 9-mode Lagrangian trial as
    /// [`Self::encode_mb_intra8x8`]; the Cb / Cr planes are coded like
    /// luma per §7.3.5.3 with the §8.3.4.5 mode reuse (each plane
    /// predicts with the quadrant's chosen luma Intra_8x8 mode), the
    /// §8.6.4 forward 8x8 transform at the chroma QP, and the
    /// §7.4.5.3.3 de-interleaved four-4x4 CAVLC split gated by the
    /// shared `cbp_luma` (a quadrant bit is set when ANY of the three
    /// planes carries a non-zero level; zero planes then emit
    /// TotalCoeff = 0 sub-blocks). Per-plane §9.2.1.1 nC comes from
    /// [`derive_nc_plane_luma_like`] with the per-plane totals tracked
    /// progressively in the shared [`CavlcNcGrid`] — mirroring the
    /// decoder's plane walker exactly.
    /// Round-391 — encode one **4:4:4 Intra_4x4** macroblock (I_NxN
    /// with the 4x4 transform at ChromaArrayType == 3, CAVLC).
    ///
    /// Per 4x4 block the luma mode is picked by Lagrangian RDO over
    /// the 9 §8.3.1.2 modes (same trial as the 4:2:0 path); the Cb and
    /// Cr planes then reuse that per-block mode per §8.3.4.5 ("chroma
    /// coded like luma"): the §8.3.1.2 prediction runs on each chroma
    /// plane's own recon neighbours, the residual goes through the
    /// forward 4x4 + §8.5.12.1 quantiser at the chroma QP, and the
    /// recon is committed through the same normative inverse the
    /// decoder runs. §7.4.5.1 — a quadrant's CBP bit covers all three
    /// planes; per-plane §9.2.1.1 nC comes from the `CavlcNcGrid`
    /// plane-luma-like derivation with progressive in-MB commits.
    #[allow(clippy::too_many_arguments)]
    fn encode_mb_intra4x4_444(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
    ) -> MbDeblockInfo {
        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let lambda = lambda_ssd(qp_y, true);
        // 4:4:4 requires flat scaling lists (asserted on encode_idr).
        let wq = self.cfg.scaling_matrix.intra_weights();

        // Pre-mark the slot so in-MB neighbour lookups see this MB's
        // earlier-block modes (decoder ordering mirror).
        {
            let s = intra_grid.slot_mut(mb_x, mb_y);
            s.available = true;
            s.is_i_nxn = true;
            s.is_i8x8 = false;
            s.intra_4x4_pred_modes = [0u8; 16];
        }

        let mut chosen_mode = [0u8; 16];
        let mut prev_flag = [false; 16];
        let mut rem = [0u8; 16];
        let mut luma_4x4_levels = [[0i32; 16]; 16];
        let mut cb_4x4_levels = [[0i32; 16]; 16];
        let mut cr_4x4_levels = [[0i32; 16]; 16];
        let mut blk_luma_nz = [false; 16];
        let mut blk_cb_nz = [false; 16];
        let mut blk_cr_nz = [false; 16];

        for blk in 0..16usize {
            let (bx, by) = I4X4_XY[blk];
            let avail = i4x4_avail(mb_x, mb_y, bx, by, width_mbs);
            let predicted = predicted_intra4x4_mode(intra_grid, mb_x, mb_y, blk, width_mbs);

            // ----- Luma: 9-mode Lagrangian trial (4:2:0-path mirror). -----
            let mut best_mode = Intra4x4Mode::Dc;
            let mut best_cost = u64::MAX;
            let mut best_z_scan = [0i32; 16];
            let mut best_recon = [0i32; 16];
            for &mode in &Intra4x4Mode::ALL {
                let Some(pred) = predict_4x4(mode, recon_y, width, mb_x, mb_y, bx, by, avail)
                else {
                    continue;
                };
                let candidate = mode.as_u8();
                let mut block_res = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        let s = frame.y[(mb_y * 16 + by + j) * width + (mb_x * 16 + bx + i)] as i32;
                        block_res[j * 4 + i] = s - pred[j * 4 + i];
                    }
                }
                let w_coeffs = forward_core_4x4(&block_res);
                let z_raster = quantize_4x4_w(&w_coeffs, qp_y, true, &wq.w4);
                let z_scan = zigzag_scan_4x4(&z_raster);
                let r = inverse_transform_4x4(&z_raster, qp_y, &wq.w4, 8).expect("inverse 4x4");
                let mut recon_block = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        recon_block[j * 4 + i] = pred[j * 4 + i] + r[j * 4 + i];
                    }
                }
                let d = ssd_4x4(frame.y, width, mb_x * 16 + bx, mb_y * 16 + by, &recon_block);
                let mut bits: u64 = 1;
                if candidate != predicted {
                    bits += 3;
                }
                let mut trial_w = BitWriter::new();
                if encode_residual_block_cavlc(
                    &mut trial_w,
                    CoeffTokenContext::Numeric(0),
                    16,
                    &z_scan,
                )
                .is_ok()
                {
                    bits += trial_w.bits_emitted() as u64;
                }
                let cost = cost_combined(d, bits, lambda);
                if cost < best_cost {
                    best_cost = cost;
                    best_mode = mode;
                    best_z_scan = z_scan;
                    best_recon = recon_block;
                }
            }
            let chosen = best_mode.as_u8();
            chosen_mode[blk] = chosen;
            if chosen == predicted {
                prev_flag[blk] = true;
            } else {
                prev_flag[blk] = false;
                rem[blk] = if chosen < predicted {
                    chosen
                } else {
                    chosen - 1
                };
            }
            intra_grid.slot_mut(mb_x, mb_y).intra_4x4_pred_modes[blk] = chosen;
            luma_4x4_levels[blk] = best_z_scan;
            blk_luma_nz[blk] = best_z_scan.iter().any(|&v| v != 0);
            for j in 0..4 {
                for i in 0..4 {
                    recon_y[(mb_y * 16 + by + j) * width + mb_x * 16 + bx + i] =
                        best_recon[j * 4 + i].clamp(0, 255) as u8;
                }
            }

            // ----- Chroma planes: §8.3.4.5 mode reuse at the chroma QP. -----
            for plane_is_cr in [false, true] {
                let (plane_src, plane_recon): (&[u8], &mut [u8]) = if plane_is_cr {
                    (frame.v, &mut *recon_v)
                } else {
                    (frame.u, &mut *recon_u)
                };
                let pred = predict_4x4(best_mode, plane_recon, width, mb_x, mb_y, bx, by, avail)
                    .expect("chosen mode is available on the chroma plane (same geometry)");
                let mut block_res = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        let s =
                            plane_src[(mb_y * 16 + by + j) * width + (mb_x * 16 + bx + i)] as i32;
                        block_res[j * 4 + i] = s - pred[j * 4 + i];
                    }
                }
                let w_coeffs = forward_core_4x4(&block_res);
                let z_raster = quantize_4x4_w(&w_coeffs, qp_c, true, &wq.w4);
                let z_scan = zigzag_scan_4x4(&z_raster);
                let r = inverse_transform_4x4(&z_raster, qp_c, &wq.w4, 8).expect("inverse 4x4");
                for j in 0..4 {
                    for i in 0..4 {
                        let v = (pred[j * 4 + i] + r[j * 4 + i]).clamp(0, 255);
                        plane_recon[(mb_y * 16 + by + j) * width + mb_x * 16 + bx + i] = v as u8;
                    }
                }
                let any_nz = z_scan.iter().any(|&v| v != 0);
                if plane_is_cr {
                    cr_4x4_levels[blk] = z_scan;
                    blk_cr_nz[blk] = any_nz;
                } else {
                    cb_4x4_levels[blk] = z_scan;
                    blk_cb_nz[blk] = any_nz;
                }
            }
        }

        // §7.4.5.1 — a quadrant's CBP bit covers all three planes.
        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            if (0..4).any(|sub| {
                let blk = blk8 * 4 + sub;
                blk_luma_nz[blk] || blk_cb_nz[blk] || blk_cr_nz[blk]
            }) {
                cbp_luma |= 1u8 << blk8;
            }
        }
        // A cbp-0 quadrant has all three planes quantised to zero, so
        // the committed recon already equals the predictor everywhere
        // in it — no rollback needed (decoder mirror).

        // ----- §9.2.1.1 nC bookkeeping (luma + per-plane). -----
        let pic_w_mbs = self.cfg.width / 16;
        let mb_addr = (mb_y as u32) * pic_w_mbs + (mb_x as u32);
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
            cur.cb_luma_total_coeff = [0u8; 16];
            cur.cr_luma_total_coeff = [0u8; 16];
        }
        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr, blk as u8, LumaNcKind::Ac, true, false);
            luma_4x4_nc[blk] = nc;
            own_totals[blk] = if (cbp_luma >> blk8) & 1 == 1 {
                luma_4x4_levels[blk].iter().filter(|&&v| v != 0).count() as u8
            } else {
                0
            };
        }
        nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;

        let mut cb_4x4_nc = [0i32; 16];
        let mut cr_4x4_nc = [0i32; 16];
        for plane_is_cr in [false, true] {
            let levels = if plane_is_cr {
                &cr_4x4_levels
            } else {
                &cb_4x4_levels
            };
            let mut own_plane = [0u8; 16];
            for blk in 0..16usize {
                let blk8 = blk / 4;
                {
                    let cur = &mut nc_grid.mbs[mb_addr as usize];
                    if plane_is_cr {
                        cur.cr_luma_total_coeff = own_plane;
                    } else {
                        cur.cb_luma_total_coeff = own_plane;
                    }
                }
                let nc = crate::macroblock_layer::derive_nc_plane_luma_like(
                    nc_grid,
                    mb_addr,
                    blk as u8,
                    plane_is_cr,
                    true,
                    false,
                );
                if plane_is_cr {
                    cr_4x4_nc[blk] = nc;
                } else {
                    cb_4x4_nc[blk] = nc;
                }
                own_plane[blk] = if (cbp_luma >> blk8) & 1 == 1 {
                    levels[blk].iter().filter(|&&v| v != 0).count() as u8
                } else {
                    0
                };
            }
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            if plane_is_cr {
                cur.cr_luma_total_coeff = own_plane;
            } else {
                cur.cb_luma_total_coeff = own_plane;
            }
        }

        // ----- Emit syntax. -----
        crate::encoder::macroblock::write_i4x4_mb_444(
            sw,
            // §7.3.5 — code transform_size_8x8_flag = 0 inside a
            // transform_8x8_mode_flag = 1 stream.
            self.cfg.transform_8x8,
            &prev_flag,
            &rem,
            cbp_luma,
            0,
            &luma_4x4_levels,
            &luma_4x4_nc,
            &cb_4x4_levels,
            &cb_4x4_nc,
            &cr_4x4_levels,
            &cr_4x4_nc,
        )
        .expect("write I_4x4 mb (4:4:4)");

        // Deblocking is disabled for 4:4:4 streams (slice header sets
        // disable_deblocking_filter_idc = 1).
        MbDeblockInfo {
            is_intra: true,
            qp_y,
            is_intra_4x4: true,
            ..Default::default()
        }
    }

    /// Round-448 — **monochrome** Intra_4x4 macroblock (I_NxN,
    /// ChromaArrayType == 0, CAVLC): the luma half of the
    /// [`Self::encode_mb_intra4x4_444`] pipeline — per-block 9-mode
    /// Lagrangian trial, luma-only CBP (Table 9-4(b)), §9.2.1.1 luma
    /// nC chain — with no chroma work at any stage (§7.3.5.1 /
    /// §7.3.5.3 at ChromaArrayType 0). `mb_qp_delta` is transmitted
    /// only when cbp > 0 (§7.3.5); with cbp == 0 the decoder's QP_Y
    /// chain keeps the previous MB's value, which the returned
    /// deblock info mirrors.
    #[allow(clippy::too_many_arguments)]
    fn encode_mb_intra4x4_mono(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        recon_y: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_qp_delta: i32,
    ) -> MbDeblockInfo {
        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let lambda = lambda_ssd(qp_y, true);
        let wq = self.cfg.scaling_matrix.intra_weights();

        // Pre-mark the slot so in-MB neighbour lookups see this MB's
        // earlier-block modes (decoder ordering mirror).
        {
            let s = intra_grid.slot_mut(mb_x, mb_y);
            s.available = true;
            s.is_i_nxn = true;
            s.is_i8x8 = false;
            s.intra_4x4_pred_modes = [0u8; 16];
        }

        let mut prev_flag = [false; 16];
        let mut rem = [0u8; 16];
        let mut luma_4x4_levels = [[0i32; 16]; 16];
        let mut blk_luma_nz = [false; 16];

        for blk in 0..16usize {
            let (bx, by) = I4X4_XY[blk];
            let avail = i4x4_avail(mb_x, mb_y, bx, by, width_mbs);
            let predicted = predicted_intra4x4_mode(intra_grid, mb_x, mb_y, blk, width_mbs);

            // 9-mode Lagrangian trial (mirror of the 4:2:0 / 4:4:4 legs).
            let mut best_mode = Intra4x4Mode::Dc;
            let mut best_cost = u64::MAX;
            let mut best_z_scan = [0i32; 16];
            let mut best_recon = [0i32; 16];
            for &mode in &Intra4x4Mode::ALL {
                let Some(pred) = predict_4x4(mode, recon_y, width, mb_x, mb_y, bx, by, avail)
                else {
                    continue;
                };
                let candidate = mode.as_u8();
                let mut block_res = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        let s = frame.y[(mb_y * 16 + by + j) * width + (mb_x * 16 + bx + i)] as i32;
                        block_res[j * 4 + i] = s - pred[j * 4 + i];
                    }
                }
                let w_coeffs = forward_core_4x4(&block_res);
                let z_raster = quantize_4x4_w(&w_coeffs, qp_y, true, &wq.w4);
                let z_scan = zigzag_scan_4x4(&z_raster);
                let r = inverse_transform_4x4(&z_raster, qp_y, &wq.w4, 8).expect("inverse 4x4");
                let mut recon_block = [0i32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        recon_block[j * 4 + i] = pred[j * 4 + i] + r[j * 4 + i];
                    }
                }
                let d = ssd_4x4(frame.y, width, mb_x * 16 + bx, mb_y * 16 + by, &recon_block);
                let mut bits: u64 = 1;
                if candidate != predicted {
                    bits += 3;
                }
                let mut trial_w = BitWriter::new();
                if encode_residual_block_cavlc(
                    &mut trial_w,
                    CoeffTokenContext::Numeric(0),
                    16,
                    &z_scan,
                )
                .is_ok()
                {
                    bits += trial_w.bits_emitted() as u64;
                }
                let cost = cost_combined(d, bits, lambda);
                if cost < best_cost {
                    best_cost = cost;
                    best_mode = mode;
                    best_z_scan = z_scan;
                    best_recon = recon_block;
                }
            }
            let chosen = best_mode.as_u8();
            if chosen == predicted {
                prev_flag[blk] = true;
            } else {
                prev_flag[blk] = false;
                rem[blk] = if chosen < predicted {
                    chosen
                } else {
                    chosen - 1
                };
            }
            intra_grid.slot_mut(mb_x, mb_y).intra_4x4_pred_modes[blk] = chosen;
            luma_4x4_levels[blk] = best_z_scan;
            blk_luma_nz[blk] = best_z_scan.iter().any(|&v| v != 0);
            for j in 0..4 {
                for i in 0..4 {
                    recon_y[(mb_y * 16 + by + j) * width + mb_x * 16 + bx + i] =
                        best_recon[j * 4 + i].clamp(0, 255) as u8;
                }
            }
        }

        // §7.4.5.1 — luma-only CBP (no chroma planes exist).
        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            if (0..4).any(|sub| blk_luma_nz[blk8 * 4 + sub]) {
                cbp_luma |= 1u8 << blk8;
            }
        }
        // A cbp-0 quadrant quantised to zero everywhere: the committed
        // recon already equals the predictor (decoder mirror).

        // ----- §9.2.1.1 luma nC bookkeeping. -----
        let pic_w_mbs = self.cfg.width / 16;
        let mb_addr = (mb_y as u32) * pic_w_mbs + (mb_x as u32);
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }
        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr, blk as u8, LumaNcKind::Ac, true, false);
            luma_4x4_nc[blk] = nc;
            own_totals[blk] = if (cbp_luma >> blk8) & 1 == 1 {
                luma_4x4_levels[blk].iter().filter(|&&v| v != 0).count() as u8
            } else {
                0
            };
        }
        nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;

        // ----- Emit syntax. -----
        crate::encoder::macroblock::write_i4x4_mb_mono(
            sw,
            self.cfg.transform_8x8,
            &prev_flag,
            &rem,
            cbp_luma,
            mb_qp_delta,
            &luma_4x4_levels,
            &luma_4x4_nc,
        )
        .expect("write I_4x4 mb (4:0:0)");

        // §8.7 — the luma deblock pass runs on 4:0:0 pictures; per-4x4
        // nonzero bits promote internal edges to bS = 2.
        let mut nz = [false; 16];
        for (blk, &b) in blk_luma_nz.iter().enumerate() {
            nz[blk] = b && (cbp_luma >> (blk / 4)) & 1 == 1;
        }
        MbDeblockInfo {
            is_intra: true,
            // §7.4.5 — no delta transmitted with cbp == 0: the decoded
            // QP_Y chain (and the §8.7 strengths) keep the previous
            // MB's value.
            qp_y: if cbp_luma > 0 {
                qp_y
            } else {
                qp_y - mb_qp_delta
            },
            luma_nonzero_4x4: luma_nz_mask_from_blocks(&nz),
            is_intra_4x4: true,
            ..Default::default()
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn encode_mb_intra8x8_444(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
    ) -> MbDeblockInfo {
        let width = self.cfg.width as usize;
        let lambda = lambda_ssd(qp_y, true);
        // §8.5.9 — round-397: the 8x8 quantise / reconstruct chain
        // honours the intra weightScale (flat reduces bit-exactly).
        let wq = self.cfg.scaling_matrix.intra_weights();
        let sl8 = wq.w8;

        // Pre-mark the slot so in-MB neighbour lookups see this MB's
        // earlier-block modes (decoder ordering mirror).
        {
            let s = intra_grid.slot_mut(mb_x, mb_y);
            s.available = true;
            s.is_i_nxn = false;
            s.is_i8x8 = true;
            s.intra_8x8_pred_modes = [2u8; 4];
        }

        let mut prev_flag = [false; 4];
        let mut rem = [0u8; 4];
        let mut luma_4x4_levels = [[0i32; 16]; 16];
        let mut cb_4x4_levels = [[0i32; 16]; 16];
        let mut cr_4x4_levels = [[0i32; 16]; 16];
        let mut blk8_luma_nz = [false; 4];
        let mut blk8_cb_nz = [false; 4];
        let mut blk8_cr_nz = [false; 4];

        for blk8 in 0..4usize {
            let bx = mb_x * 16 + (blk8 % 2) * 8;
            let by = mb_y * 16 + (blk8 / 2) * 8;
            let predicted = predicted_intra8x8_mode(intra_grid, mb_x, mb_y, blk8);

            // ----- Luma: §8.3.2 9-mode trial (same as the 4:2:0 path). -----
            let raw = gather_8x8_from_recon(recon_y, width, mb_x, mb_y, blk8);
            let filtered = filter_samples_8x8(&raw, 8);
            let mut best_mode = Intra8x8Mode::Dc;
            let mut best_cost = u64::MAX;
            let mut best_z_raster = [0i32; 64];
            let mut best_recon = [0i32; 64];
            for mode_idx in 0..9u8 {
                let mode = Intra8x8Mode::from_index(mode_idx).expect("mode index in range");
                if !intra8x8_mode_available(mode, &raw.availability) {
                    continue;
                }
                let mut pred = [0i32; 64];
                predict_8x8(mode, &filtered, 8, &mut pred);
                let mut res = [0i32; 64];
                for j in 0..8 {
                    for i in 0..8 {
                        let s = frame.y[(by + j) * width + bx + i] as i32;
                        res[j * 8 + i] = s - pred[j * 8 + i];
                    }
                }
                let w_coeffs = forward_core_8x8(&res);
                let z_raster = quantize_8x8_w(&w_coeffs, qp_y, true, &sl8);
                let r = inverse_transform_8x8(&z_raster, qp_y, &sl8, 8).expect("inverse 8x8");
                let mut recon_blk = [0i32; 64];
                let mut d: u64 = 0;
                for j in 0..8 {
                    for i in 0..8 {
                        let v = (pred[j * 8 + i] + r[j * 8 + i]).clamp(0, 255);
                        recon_blk[j * 8 + i] = v;
                        let s = frame.y[(by + j) * width + bx + i] as i32;
                        let e = (s - v) as i64;
                        d += (e * e) as u64;
                    }
                }
                let mut bits: u64 = 1;
                if mode_idx != predicted {
                    bits += 3;
                }
                let scan = scan_8x8_for_cavlc(&z_raster, sw.field_scan());
                let subs = deinterleave_8x8_to_4x4(&scan);
                let mut trial_w = BitWriter::new();
                for sub in &subs {
                    if encode_residual_block_cavlc(
                        &mut trial_w,
                        CoeffTokenContext::Numeric(0),
                        16,
                        sub,
                    )
                    .is_err()
                    {
                        break;
                    }
                }
                bits += trial_w.bits_emitted() as u64;
                let cost = cost_combined(d, bits, lambda);
                if cost < best_cost {
                    best_cost = cost;
                    best_mode = mode;
                    best_z_raster = z_raster;
                    best_recon = recon_blk;
                }
            }
            let chosen = best_mode.as_index();
            if chosen == predicted {
                prev_flag[blk8] = true;
            } else {
                prev_flag[blk8] = false;
                rem[blk8] = if chosen < predicted {
                    chosen
                } else {
                    chosen - 1
                };
            }
            intra_grid.slot_mut(mb_x, mb_y).intra_8x8_pred_modes[blk8] = chosen;
            let scan = scan_8x8_for_cavlc(&best_z_raster, sw.field_scan());
            let subs = deinterleave_8x8_to_4x4(&scan);
            for (i4x4, sub) in subs.iter().enumerate() {
                luma_4x4_levels[blk8 * 4 + i4x4] = *sub;
            }
            blk8_luma_nz[blk8] = best_z_raster.iter().any(|&v| v != 0);
            for j in 0..8 {
                for i in 0..8 {
                    recon_y[(by + j) * width + bx + i] = best_recon[j * 8 + i] as u8;
                }
            }

            // ----- Chroma planes: §8.3.4.5 mode reuse + 8x8 transform. -----
            for plane_is_cr in [false, true] {
                let (plane_src, plane_recon): (&[u8], &mut [u8]) = if plane_is_cr {
                    (frame.v, &mut *recon_v)
                } else {
                    (frame.u, &mut *recon_u)
                };
                let raw_c = gather_8x8_from_recon(plane_recon, width, mb_x, mb_y, blk8);
                let filtered_c = filter_samples_8x8(&raw_c, 8);
                let mut pred = [0i32; 64];
                predict_8x8(best_mode, &filtered_c, 8, &mut pred);
                let mut res = [0i32; 64];
                for j in 0..8 {
                    for i in 0..8 {
                        let s = plane_src[(by + j) * width + bx + i] as i32;
                        res[j * 8 + i] = s - pred[j * 8 + i];
                    }
                }
                let w_coeffs = forward_core_8x8(&res);
                let z_raster = quantize_8x8_w(&w_coeffs, qp_c, true, &sl8);
                let r = inverse_transform_8x8(&z_raster, qp_c, &sl8, 8).expect("inverse 8x8");
                for j in 0..8 {
                    for i in 0..8 {
                        let v = (pred[j * 8 + i] + r[j * 8 + i]).clamp(0, 255);
                        plane_recon[(by + j) * width + bx + i] = v as u8;
                    }
                }
                let scan = scan_8x8_for_cavlc(&z_raster, sw.field_scan());
                let subs = deinterleave_8x8_to_4x4(&scan);
                let any_nz = z_raster.iter().any(|&v| v != 0);
                if plane_is_cr {
                    for (i4x4, sub) in subs.iter().enumerate() {
                        cr_4x4_levels[blk8 * 4 + i4x4] = *sub;
                    }
                    blk8_cr_nz[blk8] = any_nz;
                } else {
                    for (i4x4, sub) in subs.iter().enumerate() {
                        cb_4x4_levels[blk8 * 4 + i4x4] = *sub;
                    }
                    blk8_cb_nz[blk8] = any_nz;
                }
            }
        }

        // §7.4.5.1 — a quadrant's CBP bit covers all three planes.
        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            if blk8_luma_nz[blk8] || blk8_cb_nz[blk8] || blk8_cr_nz[blk8] {
                cbp_luma |= 1u8 << blk8;
            }
        }
        // A cbp-0 quadrant must reconstruct as pred + 0 on every plane;
        // all three planes quantised to zero there, so the committed
        // recon already equals the predictor — no rollback needed.

        // ----- §9.2.1.1 nC bookkeeping (luma + per-plane). -----
        let pic_w_mbs = self.cfg.width / 16;
        let mb_addr = (mb_y as u32) * pic_w_mbs + (mb_x as u32);
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
            cur.cb_luma_total_coeff = [0u8; 16];
            cur.cr_luma_total_coeff = [0u8; 16];
        }
        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr, blk as u8, LumaNcKind::Ac, true, false);
            luma_4x4_nc[blk] = nc;
            own_totals[blk] = if (cbp_luma >> blk8) & 1 == 1 {
                luma_4x4_levels[blk].iter().filter(|&&v| v != 0).count() as u8
            } else {
                0
            };
        }
        nc_grid.mbs[mb_addr as usize].luma_total_coeff = own_totals;

        let mut cb_4x4_nc = [0i32; 16];
        let mut cr_4x4_nc = [0i32; 16];
        for plane_is_cr in [false, true] {
            let levels = if plane_is_cr {
                &cr_4x4_levels
            } else {
                &cb_4x4_levels
            };
            let mut own_plane = [0u8; 16];
            for blk in 0..16usize {
                let blk8 = blk / 4;
                {
                    let cur = &mut nc_grid.mbs[mb_addr as usize];
                    if plane_is_cr {
                        cur.cr_luma_total_coeff = own_plane;
                    } else {
                        cur.cb_luma_total_coeff = own_plane;
                    }
                }
                let nc = crate::macroblock_layer::derive_nc_plane_luma_like(
                    nc_grid,
                    mb_addr,
                    blk as u8,
                    plane_is_cr,
                    true,
                    false,
                );
                if plane_is_cr {
                    cr_4x4_nc[blk] = nc;
                } else {
                    cb_4x4_nc[blk] = nc;
                }
                own_plane[blk] = if (cbp_luma >> blk8) & 1 == 1 {
                    levels[blk].iter().filter(|&&v| v != 0).count() as u8
                } else {
                    0
                };
            }
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            if plane_is_cr {
                cur.cr_luma_total_coeff = own_plane;
            } else {
                cur.cb_luma_total_coeff = own_plane;
            }
        }

        // ----- Emit syntax. -----
        crate::encoder::macroblock::write_i8x8_mb_444(
            sw,
            &prev_flag,
            &rem,
            cbp_luma,
            0,
            &luma_4x4_levels,
            &luma_4x4_nc,
            &cb_4x4_levels,
            &cb_4x4_nc,
            &cr_4x4_levels,
            &cr_4x4_nc,
        )
        .expect("write I_8x8 mb (4:4:4)");

        // Deblocking is disabled for 4:4:4 streams (slice header sets
        // disable_deblocking_filter_idc = 1); the flag still drives the
        // per-picture Intra_8x8 counter.
        MbDeblockInfo {
            is_intra: true,
            qp_y,
            transform_size_8x8_flag: true,
            ..Default::default()
        }
    }
}

/// Output of [`Encoder::encode_idr`].
pub struct EncodedIdr {
    pub annex_b: Vec<u8>,
    pub recon_y: Vec<u8>,
    pub recon_u: Vec<u8>,
    pub recon_v: Vec<u8>,
    pub recon_width: u32,
    pub recon_height: u32,
    /// Per-8x8-partition MV state. IDR is all-intra so every partition's
    /// `is_intra = true`. Provided for API symmetry with `EncodedP` so
    /// that an IDR can be passed as an L0/L1 anchor to a B-slice — the
    /// §8.4.1.2.2 step 7 colZeroFlag check then short-circuits to 0
    /// (the `if is_intra` branch in `is_colocated_zero_mv`).
    pub partition_mvs: Vec<FrameRefPartitionMv>,
    /// Round-382 — number of macroblocks the per-MB RDO coded as
    /// Intra_8x8 (`transform_size_8x8_flag = 1`). Always 0 unless
    /// [`EncoderConfig::transform_8x8`] is set. Exposed so callers /
    /// tests can verify the 8x8 transform is actually being selected.
    pub i8x8_mb_count: u32,
    /// Round-391 — number of macroblocks the per-MB RDO coded as
    /// I_NxN with the 4x4 transform (Intra_4x4). Exposed so tests can
    /// verify the 4:4:4 I_4x4 leg (and the legacy 4:2:0 I_NxN trial)
    /// is actually being selected.
    pub i4x4_mb_count: u32,
}

/// One 8x8 partition's per-list MV state, captured at picture-level so
/// later B-slices can use this picture as the L1 anchor for §8.4.1.2.2
/// spatial direct derivation (specifically the colZeroFlag step).
///
/// Indexing: `partition` is 0..=3 (top-left, top-right, bottom-left,
/// bottom-right of the parent MB, mirroring `MvGridSlot::mv_l0_8x8` order).
/// `(mb_y * width_mbs + mb_x) * 4 + partition`.
#[derive(Debug, Clone, Copy, Default)]
pub struct FrameRefPartitionMv {
    /// L0 motion vector in quarter-pel units. `(0, 0)` for intra MBs.
    pub mv_l0: (i16, i16),
    /// L0 reference index. `-1` for intra MBs or when L0 not used.
    pub ref_idx_l0: i8,
    /// True when the parent MB is intra-coded (mvCol = 0, refIdxCol = -1
    /// per §8.4.1.2.1 NOTE). Drives §8.4.1.2.2 step 7's colZeroFlag = 0
    /// fallback for intra colocated MBs.
    pub is_intra: bool,
}

/// Output of [`Encoder::encode_p`] — a single P-slice access unit and
/// the matching reconstruction. Same layout as [`EncodedIdr`] except
/// the bitstream contains only the slice NAL (no SPS/PPS — those were
/// emitted by the IDR).
pub struct EncodedP {
    pub annex_b: Vec<u8>,
    pub recon_y: Vec<u8>,
    pub recon_u: Vec<u8>,
    pub recon_v: Vec<u8>,
    pub recon_width: u32,
    pub recon_height: u32,
    /// `frame_num` of this P-frame. Increments from the IDR's 0.
    pub frame_num: u32,
    /// `pic_order_cnt_lsb` of this P-frame.
    pub pic_order_cnt_lsb: u32,
    /// Per-8x8-partition MV state for each MB. Length =
    /// `(width / 16) * (height / 16) * 4`. Used by [`Encoder::encode_b`]
    /// when this P-frame is the L1 anchor — the spatial direct
    /// derivation (§8.4.1.2.2 step 7) needs the colocated block's L0
    /// MV / refIdx to evaluate `colZeroFlag`.
    pub partition_mvs: Vec<FrameRefPartitionMv>,
    /// Round-382 — number of macroblocks coded with
    /// `transform_size_8x8_flag = 1` (High-profile 8x8 transform).
    /// Always 0 unless [`EncoderConfig::transform_8x8`] is set.
    pub i8x8_mb_count: u32,
    /// Round-453 — the §7.3.3.2 `pred_weight_table()` this P slice
    /// carried (`Some` iff `EncoderConfig::explicit_weighted_pred`);
    /// `luma.is_some()` means a non-identity fade weighting was
    /// elected.
    pub pred_weight_table: Option<ExplicitPredWeightTableL0>,
}

/// Per-MB encoder-side MV / refIdx slot for the §8.4.1.3 mvp neighbour
/// grid. Round-19 extends round-16's single-MV slot to track **per-8x8
/// partition** MVs (4 entries) so that the encoder can emit P_8x8 MBs
/// (mb_type=3, sub_mb_type=PL08x8) with mvds that match the §8.4.1.3
/// neighbour-mv predictor the decoder will use.
///
/// Indexing of `mv_l0` / `ref_idx_l0_8x8`:
///   0 → top-left 8x8, 1 → top-right, 2 → bottom-left, 3 → bottom-right
/// (Figure 6-10 8x8 partition order; same as `LUMA_4X4_BLK[blk*4]`.)
///
/// For P_L0_16x16 MBs all four 8x8 entries carry the same MV / ref —
/// downstream MBs reading any 8x8 see the single 16x16 MV, preserving
/// round-16 / round-17 / round-18 behaviour exactly.
#[derive(Debug, Clone, Copy)]
pub(crate) struct MvGridSlot {
    /// True once this MB has been encoded (so subsequent MBs can read it).
    available: bool,
    /// True for intra-coded MBs (their mvp contribution is mv=0, ref=-1).
    is_intra: bool,
    /// L0 reference index per 8x8 partition (always 0 in our single-ref
    /// P-slice — kept per-partition to leave room for multi-ref later).
    ref_idx_l0_8x8: [i32; 4],
    /// L0 motion vector per 8x8 partition, in 1/4-pel units.
    mv_l0_8x8: [Mv; 4],
}

impl MvGridSlot {
    /// Round-16 compat shim — many call sites only need the single
    /// representative MV / ref. Returns the top-left 8x8's values which
    /// equals the unique 16x16 MV for non-4MV MBs.
    fn ref_idx_l0(&self) -> i32 {
        self.ref_idx_l0_8x8[0]
    }
    fn mv_l0(&self) -> Mv {
        self.mv_l0_8x8[0]
    }
}

impl Default for MvGridSlot {
    fn default() -> Self {
        Self {
            available: false,
            is_intra: false,
            ref_idx_l0_8x8: [-1; 4],
            mv_l0_8x8: [Mv::ZERO; 4],
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct MvGrid {
    width_mbs: usize,
    slots: Vec<MvGridSlot>,
}

impl MvGrid {
    fn new(width_mbs: usize, height_mbs: usize) -> Self {
        Self {
            width_mbs,
            slots: vec![MvGridSlot::default(); width_mbs * height_mbs],
        }
    }
    fn slot(&self, mb_x: usize, mb_y: usize) -> &MvGridSlot {
        &self.slots[mb_y * self.width_mbs + mb_x]
    }
    fn slot_mut(&mut self, mb_x: usize, mb_y: usize) -> &mut MvGridSlot {
        &mut self.slots[mb_y * self.width_mbs + mb_x]
    }
}

/// Build the (A, B, C, D) NeighbourMv records for the current MB
/// (mb_x, mb_y) — single 16x16 partition. Per §6.4.11.7 the four
/// neighbours of a 16x16 partition's top-left 4x4 (block 0) are:
///
/// * A: the 4x4 at (-1, 0) of current MB → MB(mb_x-1, mb_y) 8x8 #1
///   (top-right 4x4 column, row 0 → 8x8 partition that contains 4x4
///   (3, 0) = top-right).
/// * B: the 4x4 at (0, -1) → MB(mb_x, mb_y-1) 8x8 #2 (bottom-left 4x4
///   column → contains 4x4 (0, 3) = bottom-left).
/// * C: the 4x4 at (16, -1) → MB(mb_x+1, mb_y-1) 8x8 #2 (bottom-left
///   of MB above-right, which contains 4x4 (0, 3)).
/// * D: the 4x4 at (-1, -1) → MB(mb_x-1, mb_y-1) 8x8 #3 (bottom-right).
///
/// For 16x16-partitioned neighbours, all 4 8x8 cells share the same MV
/// so the read is unambiguous. For 16x8 / 8x16 / 8x8 partitioned
/// neighbours, we read the 8x8 cell that **spatially** contains the
/// requested 4x4 corner — matching what the decoder does when it
/// derives mvpLX for the current MB's partition.
///
/// Each neighbour is "MVpred-usable" iff its MB is encoded AND not intra.
/// Intra neighbours collapse to (mv=0, ref=-1) per §8.4.1.3.2 step 2a.
fn neighbour_mvs_16x16(
    grid: &MvGrid,
    mb_x: usize,
    mb_y: usize,
) -> (NeighbourMv, NeighbourMv, NeighbourMv, NeighbourMv) {
    // (8x8 partition index in neighbour MB) — picks the 8x8 cell
    // spatially adjacent to the current MB's top-left 4x4 (block 0).
    let make = |maybe: Option<&MvGridSlot>, part_idx: usize| -> NeighbourMv {
        match maybe {
            Some(s) if s.available => {
                if s.is_intra {
                    NeighbourMv::intra_but_mb_available()
                } else {
                    NeighbourMv {
                        available: s.ref_idx_l0_8x8[part_idx] >= 0,
                        mb_available: true,
                        partition_available: true,
                        ref_idx: s.ref_idx_l0_8x8[part_idx],
                        mv: s.mv_l0_8x8[part_idx],
                    }
                }
            }
            _ => NeighbourMv::UNAVAILABLE,
        }
    };
    let a = if mb_x > 0 {
        Some(grid.slot(mb_x - 1, mb_y))
    } else {
        None
    };
    let b = if mb_y > 0 {
        Some(grid.slot(mb_x, mb_y - 1))
    } else {
        None
    };
    let c = if mb_y > 0 && mb_x + 1 < grid.width_mbs {
        Some(grid.slot(mb_x + 1, mb_y - 1))
    } else {
        None
    };
    let d = if mb_x > 0 && mb_y > 0 {
        Some(grid.slot(mb_x - 1, mb_y - 1))
    } else {
        None
    };
    (
        make(a, 1), // left  → top-right 8x8 (#1)
        make(b, 2), // above → bottom-left 8x8 (#2)
        make(c, 2), // above-right → bottom-left 8x8 (#2)
        make(d, 3), // above-left → bottom-right 8x8 (#3)
    )
}

/// Per §8.4.1.3 + the §8.4.1.3.2 C→D substitution — derive the MVpred
/// for a single 16x16 P_L0 partition at (mb_x, mb_y).
pub(crate) fn mvp_for_16x16(grid: &MvGrid, mb_x: usize, mb_y: usize, ref_idx: i32) -> Mv {
    let (a, b, c, d) = neighbour_mvs_16x16(grid, mb_x, mb_y);
    let inputs = MvpredInputs::from_abc(a, b, c, ref_idx, Default::default());
    crate::mv_deriv::derive_mvpred_with_d(&inputs, d)
}

/// Per §8.4.1.2 — derive the (refIdxL0, mvL0) for a P_Skip MB at
/// (mb_x, mb_y). With the C→D substitution.
pub(crate) fn p_skip_mv(grid: &MvGrid, mb_x: usize, mb_y: usize) -> (i32, Mv) {
    let (a, b, c, d) = neighbour_mvs_16x16(grid, mb_x, mb_y);
    crate::mv_deriv::derive_p_skip_mv_with_d(a, b, c, d)
}

/// Round-19 — read the MV/refIdx of the 8x8 partition containing the
/// 4x4 block at MB-relative coordinates `(bx_4x4, by_4x4) ∈ {0,1,2,3}²`
/// of the MB at `(mb_x, mb_y)`. Returns a [`NeighbourMv`] with the
/// availability flags set per §8.4.1.1 / §6.4.11.1:
///
/// * `mb_xy` outside the picture or referencing an unencoded MB →
///   [`NeighbourMv::UNAVAILABLE`].
/// * intra-coded MB → [`NeighbourMv::intra_but_mb_available`] (so the
///   median collapses for that slot but the §8.4.1.3.2 C→D substitution
///   does **not** fire).
/// * MB encoded but the targeted 8x8 partition is in a sub-MB whose
///   `available` bit is false (e.g. the encoder is mid-MB): the partition
///   is `partition_not_yet_decoded_same_mb` so C→D substitution fires.
///
/// `inflight_avail` (length 4) is the per-8x8-partition availability
/// for the **current** MB-in-flight (`mb_x`, `mb_y`), allowing within-MB
/// neighbour reads of already-decoded sub-partitions. `mv_inflight` and
/// `ref_inflight` are the corresponding MVs / refs of those partitions
/// (slots gated by `inflight_avail[i]==true`).
#[allow(clippy::too_many_arguments)]
fn neighbour_8x8_partition_mv(
    grid: &MvGrid,
    mb_x: usize,
    mb_y: usize,
    bx_4x4: i32,
    by_4x4: i32,
    inflight_avail: [bool; 4],
    mv_inflight: [Mv; 4],
    ref_inflight: [i32; 4],
) -> NeighbourMv {
    // Map (bx_4x4, by_4x4) ∈ Z² (allowing -1) onto a (mb_x', mb_y',
    // 8x8 partition index ∈ 0..=3).
    let (nmb_x, nmb_y, lx, ly) = if bx_4x4 < 0 && (0..4).contains(&by_4x4) {
        // Left MB.
        if mb_x == 0 {
            return NeighbourMv::UNAVAILABLE;
        }
        // Wrap into right edge of left MB: bx becomes 3.
        (mb_x - 1, mb_y, 3, by_4x4)
    } else if (0..4).contains(&bx_4x4) && by_4x4 < 0 {
        // Above MB.
        if mb_y == 0 {
            return NeighbourMv::UNAVAILABLE;
        }
        (mb_x, mb_y - 1, bx_4x4, 3)
    } else if bx_4x4 < 0 && by_4x4 < 0 {
        // Above-left MB (only used as D).
        if mb_x == 0 || mb_y == 0 {
            return NeighbourMv::UNAVAILABLE;
        }
        (mb_x - 1, mb_y - 1, 3, 3)
    } else if (0..4).contains(&bx_4x4) && (0..4).contains(&by_4x4) {
        // Same MB.
        let part = 2 * (by_4x4 as usize / 2) + (bx_4x4 as usize / 2);
        if inflight_avail[part] {
            return NeighbourMv {
                available: ref_inflight[part] >= 0,
                mb_available: true,
                partition_available: true,
                ref_idx: ref_inflight[part],
                mv: mv_inflight[part],
            };
        } else {
            // Partition not yet decoded → §6.4.11.1 partition-unavailable.
            return NeighbourMv::partition_not_yet_decoded_same_mb();
        }
    } else if (4..).contains(&bx_4x4) && by_4x4 < 0 {
        // Above-right MB.
        if mb_y == 0 || mb_x + 1 >= grid.width_mbs {
            return NeighbourMv::UNAVAILABLE;
        }
        (mb_x + 1, mb_y - 1, bx_4x4 - 4, 3)
    } else {
        return NeighbourMv::UNAVAILABLE;
    };
    let s = grid.slot(nmb_x, nmb_y);
    if !s.available {
        return NeighbourMv::UNAVAILABLE;
    }
    if s.is_intra {
        return NeighbourMv::intra_but_mb_available();
    }
    let part = 2 * (ly as usize / 2) + (lx as usize / 2);
    NeighbourMv {
        available: s.ref_idx_l0_8x8[part] >= 0,
        mb_available: true,
        partition_available: true,
        ref_idx: s.ref_idx_l0_8x8[part],
        mv: s.mv_l0_8x8[part],
    }
}

/// Round-19 — derive the §8.4.1.3 mvpLX for one 8x8 partition of a
/// P_8x8 MB at `(mb_x, mb_y)`. `sub_idx` ∈ 0..=3 in 8x8 raster
/// (0=TL, 1=TR, 2=BL, 3=BR). `inflight_*` arrays carry the already-
/// decoded sub-partitions' MVs/refs of the **current** MB so within-MB
/// neighbour reads work.
#[allow(clippy::too_many_arguments)]
fn mvp_for_p_8x8_partition(
    grid: &MvGrid,
    mb_x: usize,
    mb_y: usize,
    sub_idx: usize,
    ref_idx: i32,
    inflight_avail: [bool; 4],
    mv_inflight: [Mv; 4],
    ref_inflight: [i32; 4],
) -> Mv {
    // Top-left 4x4 of this 8x8 partition, in 4x4-block units.
    let sub_x = (sub_idx % 2) as i32;
    let sub_y = (sub_idx / 2) as i32;
    let bx = sub_x * 2;
    let by = sub_y * 2;
    // Partition width = 8 = 2 4x4 blocks → C is at (bx + 2, by - 1).
    let a = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx - 1,
        by,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let b = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx,
        by - 1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let c = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx + 2,
        by - 1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let d = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx - 1,
        by - 1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let inputs = MvpredInputs::from_abc(a, b, c, ref_idx, Default::default());
    crate::mv_deriv::derive_mvpred_with_d(&inputs, d)
}

/// Round-16 — generate the inter predictor for one 16x16 luma MB at
/// (mb_x, mb_y), using mv_l0 (in 1/4-pel units) against the reference
/// luma plane. Output is `[i32; 256]` row-major (16 rows of 16 samples
/// each).
///
/// For integer-pel MVs (mv_l0 is a multiple of 4), `x_frac == y_frac
/// == 0` and the call simplifies to a clipped copy.
fn build_inter_pred_luma(
    ref_y: &[u8],
    ref_w: u32,
    ref_h: u32,
    mb_x: usize,
    mb_y: usize,
    mv: Mv,
) -> [i32; 256] {
    // Convert ref to i32 plane.
    let stride = ref_w as usize;
    let h = ref_h as usize;
    let ref_i32: Vec<i32> = ref_y.iter().take(stride * h).map(|&v| v as i32).collect();

    let mv_int_x = mv.x >> 2;
    let mv_int_y = mv.y >> 2;
    let x_frac = (mv.x & 3) as u8;
    let y_frac = (mv.y & 3) as u8;
    let int_x = (mb_x * 16) as i32 + mv_int_x;
    let int_y = (mb_y * 16) as i32 + mv_int_y;

    let mut dst = [0i32; 256];
    interpolate_luma(
        &ref_i32, stride, stride, h, int_x, int_y, x_frac, y_frac, 16, 16, 8, &mut dst, 16,
    )
    .expect("luma interpolation");
    dst
}

/// Round-19 — generate the inter predictor for one 8x8 luma sub-MB
/// **partition** of a P_8x8 MB at `(mb_x, mb_y)`. `(sub_x, sub_y) ∈
/// {0, 1}` selects which 8x8 inside the MB. Output is `[i32; 64]`
/// row-major (8 rows of 8 samples).
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_inter_pred_luma_8x8(
    ref_y: &[u8],
    ref_w: u32,
    ref_h: u32,
    mb_x: usize,
    mb_y: usize,
    sub_x: usize,
    sub_y: usize,
    mv: Mv,
) -> [i32; 64] {
    let stride = ref_w as usize;
    let h = ref_h as usize;
    let ref_i32: Vec<i32> = ref_y.iter().take(stride * h).map(|&v| v as i32).collect();

    let mv_int_x = mv.x >> 2;
    let mv_int_y = mv.y >> 2;
    let x_frac = (mv.x & 3) as u8;
    let y_frac = (mv.y & 3) as u8;
    let int_x = (mb_x * 16 + sub_x * 8) as i32 + mv_int_x;
    let int_y = (mb_y * 16 + sub_y * 8) as i32 + mv_int_y;

    let mut dst = [0i32; 64];
    interpolate_luma(
        &ref_i32, stride, stride, h, int_x, int_y, x_frac, y_frac, 8, 8, 8, &mut dst, 8,
    )
    .expect("luma interpolation 8x8");
    dst
}

/// Round-397 — motion-compensate one chroma rectangle at any chroma
/// format. `(cx0, cy0)` is the rect's top-left in CHROMA samples and
/// `(rw, rh)` its size. Per §8.4.1.4 / §8.4.2.2:
///   * fmt 1 (4:2:0) / 2 (4:2:2) — 1/8-pel bilinear; `mvC.x = mvL.x`
///     and `mvC.y = mvL.y` (4:2:0) or `mvL.y * 2` (4:2:2, eq. 8-227)
///     in 1/8-pel units.
///   * fmt 3 (4:4:4) — the §8.4.2.2.1 LUMA 6-tap process with
///     `mvC = mvL` (1/4-pel, eq. 8-235..8-238).
#[allow(clippy::too_many_arguments)]
pub(super) fn build_chroma_rect_pred_fmt(
    plane: &[u8],
    plane_w: u32,
    plane_h: u32,
    cx0: usize,
    cy0: usize,
    rw: usize,
    rh: usize,
    mv: Mv,
    fmt: u32,
) -> Vec<i32> {
    // Round-448 — 4:0:0: no chroma planes, no rect to predict.
    if fmt == 0 || rw == 0 || rh == 0 {
        return Vec::new();
    }
    let stride = plane_w as usize;
    let h = plane_h as usize;
    let ref_i32: Vec<i32> = plane.iter().take(stride * h).map(|&v| v as i32).collect();
    let mut dst = vec![0i32; rw * rh];
    if fmt == 3 {
        let int_x = cx0 as i32 + (mv.x >> 2);
        let int_y = cy0 as i32 + (mv.y >> 2);
        let x_frac = (mv.x & 3) as u8;
        let y_frac = (mv.y & 3) as u8;
        interpolate_luma(
            &ref_i32, stride, stride, h, int_x, int_y, x_frac, y_frac, rw as u32, rh as u32, 8,
            &mut dst, rw,
        )
        .expect("4:4:4 luma-like chroma interpolation");
    } else {
        let mv_cx = mv.x;
        let mv_cy = if fmt == 2 { mv.y * 2 } else { mv.y };
        let int_x = cx0 as i32 + (mv_cx >> 3);
        let int_y = cy0 as i32 + (mv_cy >> 3);
        let x_frac = (mv_cx & 7) as u8;
        let y_frac = (mv_cy & 7) as u8;
        interpolate_chroma(
            &ref_i32, stride, stride, h, int_x, int_y, x_frac, y_frac, rw as u32, rh as u32, 8,
            &mut dst, rw,
        )
        .expect("chroma rect interpolation");
    }
    dst
}

/// Round-397 — B-partition chroma rect predictor: per-list rect MC via
/// [`build_chroma_rect_pred_fmt`] merged per §8.4.2.3.1 (default
/// average) according to the partition's list usage.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_b_partition_chroma_rect_fmt(
    pred: BPartPred,
    plane_l0: &[u8],
    plane_l1: &[u8],
    plane_w: u32,
    plane_h: u32,
    cx0: usize,
    cy0: usize,
    rw: usize,
    rh: usize,
    mv_l0: Mv,
    mv_l1: Mv,
    fmt: u32,
) -> Vec<i32> {
    match pred {
        BPartPred::L0 => {
            build_chroma_rect_pred_fmt(plane_l0, plane_w, plane_h, cx0, cy0, rw, rh, mv_l0, fmt)
        }
        BPartPred::L1 => {
            build_chroma_rect_pred_fmt(plane_l1, plane_w, plane_h, cx0, cy0, rw, rh, mv_l1, fmt)
        }
        BPartPred::Bi => {
            let a = build_chroma_rect_pred_fmt(
                plane_l0, plane_w, plane_h, cx0, cy0, rw, rh, mv_l0, fmt,
            );
            let b = build_chroma_rect_pred_fmt(
                plane_l1, plane_w, plane_h, cx0, cy0, rw, rh, mv_l1, fmt,
            );
            a.iter().zip(&b).map(|(&x, &y)| (x + y + 1) >> 1).collect()
        }
    }
}

/// Round-19 — generate the inter predictor for one 4x4 chroma sub-MB
/// partition of a P_8x8 MB (4:2:0). `(sub_x, sub_y) ∈ {0, 1}` selects
/// the sub-block. Output is `[i32; 16]` row-major.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_inter_pred_chroma_4x4(
    ref_c: &[u8],
    ref_cw: u32,
    ref_ch: u32,
    mb_x: usize,
    mb_y: usize,
    sub_x: usize,
    sub_y: usize,
    mv: Mv,
) -> [i32; 16] {
    let stride = ref_cw as usize;
    let h = ref_ch as usize;
    let ref_i32: Vec<i32> = ref_c.iter().take(stride * h).map(|&v| v as i32).collect();

    // §8.4.1.4 — 4:2:0 chroma uses luma MV directly, with 1/8-pel
    // fractional positions (mvC = mv_luma; xFracC = mvC & 7).
    let mv_cx = mv.x;
    let mv_cy = mv.y;
    let int_x = (mb_x * 8 + sub_x * 4) as i32 + (mv_cx >> 3);
    let int_y = (mb_y * 8 + sub_y * 4) as i32 + (mv_cy >> 3);
    let x_frac = (mv_cx & 7) as u8;
    let y_frac = (mv_cy & 7) as u8;

    let mut dst = [0i32; 16];
    interpolate_chroma(
        &ref_i32, stride, stride, h, int_x, int_y, x_frac, y_frac, 4, 4, 8, &mut dst, 4,
    )
    .expect("chroma interpolation 4x4");
    dst
}

/// Round-16 — generate the inter predictor for one 8x8 chroma MB
/// (4:2:0) at (mb_x, mb_y), using `mv_l0` (luma 1/4-pel units; chroma
/// derives 1/8-pel units per §8.4.1.4 for 4:2:0).
fn build_inter_pred_chroma(
    ref_c: &[u8],
    ref_cw: u32,
    ref_ch: u32,
    mb_x: usize,
    mb_y: usize,
    mv: Mv,
) -> [i32; 64] {
    let stride = ref_cw as usize;
    let h = ref_ch as usize;
    let ref_i32: Vec<i32> = ref_c.iter().take(stride * h).map(|&v| v as i32).collect();

    // §8.4.1.4 / eq. 8-228..8-231 — chroma MV is luma MV (4:2:0).
    // xIntC = mb_x*8 + (mvC >> 3); xFracC = mvC & 7. mvC = mv (luma 1/4-pel).
    let mv_cx = mv.x;
    let mv_cy = mv.y;
    let int_x = (mb_x * 8) as i32 + (mv_cx >> 3);
    let int_y = (mb_y * 8) as i32 + (mv_cy >> 3);
    let x_frac = (mv_cx & 7) as u8;
    let y_frac = (mv_cy & 7) as u8;

    let mut dst = [0i32; 64];
    interpolate_chroma(
        &ref_i32, stride, stride, h, int_x, int_y, x_frac, y_frac, 8, 8, 8, &mut dst, 8,
    )
    .expect("chroma interpolation");
    dst
}

/// Encode the chroma residual for one P_L0 MB given the chroma
/// inter predictor (instead of the intra predictor used by
/// [`encode_chroma_residual`]). Same machinery as the intra path —
/// shared via a small wrapper; we just need an `i32` predictor.
///
/// Returns `(dc_levels, ac_levels, recon_residual)` matching
/// [`encode_chroma_residual`]'s signature.
fn encode_chroma_residual_inter(
    src_plane: &[u8],
    chroma_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 64],
    qp_c: i32,
    w4: &[i32; 16],
) -> ([i32; 4], [[i32; 16]; 4], [i32; 64]) {
    // Re-use the intra path — its only assumption on the predictor is
    // that it's a `[i32; 64]` row-major 8x8 block. The is_intra=true
    // rounding flag in the AC quantization differs slightly from inter,
    // but for round-16 we accept the intra rounding for chroma (the
    // bitstream is correct either way; only the rate-distortion trade-
    // off shifts marginally).
    encode_chroma_residual(src_plane, chroma_stride, mb_x, mb_y, pred, qp_c, w4)
}

/// Round-388 — SSD between the source and the reconstruction over one
/// MB's three full-resolution planes (4:4:4). Distortion term for the
/// I_16x16-vs-I_8x8 RDO where chroma is coded like luma and therefore
/// dominates the trade-off just as much as luma.
fn mb_ssd_3planes_444(
    frame: &YuvFrame<'_>,
    recon_y: &[u8],
    recon_u: &[u8],
    recon_v: &[u8],
    width: usize,
    mb_x: usize,
    mb_y: usize,
) -> u64 {
    let mut d: u64 = 0;
    for (src, rec) in [(frame.y, recon_y), (frame.u, recon_u), (frame.v, recon_v)] {
        for j in 0..16usize {
            let row = (mb_y * 16 + j) * width + mb_x * 16;
            for i in 0..16usize {
                let e = src[row + i] as i64 - rec[row + i] as i64;
                d += (e * e) as u64;
            }
        }
    }
    d
}

/// §9.2.1.1 — derive the per-block chroma-AC `nC` values for the
/// current MB and commit its per-block `TotalCoeff` into the encoder's
/// [`CavlcNcGrid`] (progressively, so in-MB neighbour reads during the
/// derivation see the earlier blocks — exactly the state the decoder
/// has when it derives `nC` before parsing each block).
///
/// Per §9.2.1.1 NOTE 1 only AC coefficients count: when `cbp_chroma !=
/// 2` no chroma AC block is coded and every total stays 0. The
/// coeff_token *table* (not just the codeword) depends on `nC`, so a
/// wrong value here desynchronises every spec decoder — the historical
/// hard-coded `Numeric(0)` was only safe while neighbour totals stayed
/// below 2.
///
/// Returns `(nc_cb, nc_cr)` sized for 4:2:2 (first 4 entries used at
/// 4:2:0). The caller must have marked the current MB slot
/// `is_available = true` beforehand (the luma-nC bookkeeping does).
pub(crate) fn derive_chroma_ac_nc_and_commit_totals(
    nc_grid: &mut CavlcNcGrid,
    mb_addr: u32,
    is_intra: bool,
    cbp_chroma: u8,
    ac_cb: &[[i32; 16]],
    ac_cr: &[[i32; 16]],
    chroma_array_type: u32,
) -> ([i32; 8], [i32; 8]) {
    let n_blk = if chroma_array_type == 2 { 8usize } else { 4 };
    let mut nc_cb = [0i32; 8];
    let mut nc_cr = [0i32; 8];
    for is_cr in [false, true] {
        let (ncs, acs): (&mut [i32; 8], &[[i32; 16]]) = if is_cr {
            (&mut nc_cr, ac_cr)
        } else {
            (&mut nc_cb, ac_cb)
        };
        let mut own = [0u8; 8];
        for blk in 0..n_blk {
            {
                let slot = &mut nc_grid.mbs[mb_addr as usize];
                if is_cr {
                    slot.cr_total_coeff = own;
                } else {
                    slot.cb_total_coeff = own;
                }
            }
            ncs[blk] = crate::macroblock_layer::derive_nc_chroma_ac(
                nc_grid,
                mb_addr,
                blk as u8,
                is_cr,
                chroma_array_type,
                is_intra,
                false,
            );
            own[blk] = if cbp_chroma == 2 {
                acs[blk][..15].iter().filter(|&&v| v != 0).count() as u8
            } else {
                0
            };
        }
        let slot = &mut nc_grid.mbs[mb_addr as usize];
        if is_cr {
            slot.cr_total_coeff = own;
        } else {
            slot.cb_total_coeff = own;
        }
    }
    (nc_cb, nc_cr)
}

/// §9.2.1.1 (ChromaArrayType == 3) — per-plane nC for a 4:4:4
/// Intra_16x16 MB's coded-like-luma chroma plane: the plane 16x16 DC
/// nC (derived at blkIdx 0 BEFORE any of this MB's plane totals exist,
/// mirroring the decoder's parse order) plus the 16 per-AC-block nC
/// values with progressive TotalCoeff commits into the grid's
/// `cb_luma_total_coeff` / `cr_luma_total_coeff` (which stay committed
/// for subsequent MBs — I_8x8 4:4:4 neighbours read the same arrays).
/// AC totals are zeroed when `cbp_luma != 15` (no plane AC coded).
pub(crate) fn derive_plane_nc_444_i16x16(
    nc_grid: &mut CavlcNcGrid,
    mb_addr: u32,
    is_cr: bool,
    cbp_luma: u8,
    ac_scan: &[[i32; 16]; 16],
) -> (i32, [i32; 16]) {
    let dc_nc =
        crate::macroblock_layer::derive_nc_plane_luma_like(nc_grid, mb_addr, 0, is_cr, true, false);
    let mut ac_nc = [0i32; 16];
    let mut own = [0u8; 16];
    for blk in 0..16usize {
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            if is_cr {
                cur.cr_luma_total_coeff = own;
            } else {
                cur.cb_luma_total_coeff = own;
            }
        }
        ac_nc[blk] = crate::macroblock_layer::derive_nc_plane_luma_like(
            nc_grid, mb_addr, blk as u8, is_cr, true, false,
        );
        own[blk] = if cbp_luma == 15 {
            ac_scan[blk][..15].iter().filter(|&&v| v != 0).count() as u8
        } else {
            0
        };
    }
    let cur = &mut nc_grid.mbs[mb_addr as usize];
    if is_cr {
        cur.cr_luma_total_coeff = own;
    } else {
        cur.cb_luma_total_coeff = own;
    }
    (dc_nc, ac_nc)
}

/// Round-397 — §9.2.1.1 (ChromaArrayType == 3) per-plane nC for an
/// **inter** MB's coded-like-luma chroma plane: 16 full 4x4 blocks
/// (no separate plane DC), each block's TotalCoeff committed
/// progressively into the grid's `cb_luma_total_coeff` /
/// `cr_luma_total_coeff` so in-MB neighbour reads mirror the decoder's
/// parse order. Blocks in un-coded 8x8 quadrants contribute 0.
pub(crate) fn derive_plane_nc_444_inter(
    nc_grid: &mut CavlcNcGrid,
    mb_addr: u32,
    is_cr: bool,
    cbp_luma: u8,
    levels_scan: &[[i32; 16]; 16],
) -> [i32; 16] {
    let mut ac_nc = [0i32; 16];
    let mut own = [0u8; 16];
    for blk in 0..16usize {
        {
            let cur = &mut nc_grid.mbs[mb_addr as usize];
            if is_cr {
                cur.cr_luma_total_coeff = own;
            } else {
                cur.cb_luma_total_coeff = own;
            }
        }
        ac_nc[blk] = crate::macroblock_layer::derive_nc_plane_luma_like(
            nc_grid, mb_addr, blk as u8, is_cr, false, false,
        );
        own[blk] = if (cbp_luma >> (blk / 4)) & 1 == 1 {
            levels_scan[blk].iter().filter(|&&v| v != 0).count() as u8
        } else {
            0
        };
    }
    let cur = &mut nc_grid.mbs[mb_addr as usize];
    if is_cr {
        cur.cr_luma_total_coeff = own;
    } else {
        cur.cb_luma_total_coeff = own;
    }
    ac_nc
}

/// Round-27 — Chroma block encode result. Holds residual coefficients
/// (DC + AC, both planes, sized for 4:2:0 or 4:2:2), the chosen
/// intra-chroma mode, derived `cbp_chroma`, and the reconstructed
/// chroma residual to be added back to the predictor.
///
/// 4:2:0 path fills the first 4 entries of every array; 4:2:2 fills
/// all 8.
struct ChromaBlock {
    pred_mode: IntraChromaMode,
    cbp_chroma: u8,
    /// Quantized chroma DC levels for Cb / Cr. Length 4 (4:2:0) or 8
    /// (4:2:2 — already in spec scan order).
    dc_cb: [i32; 8],
    dc_cr: [i32; 8],
    /// Per-4x4-block AC scan for Cb / Cr. Up to 8 blocks for 4:2:2;
    /// 4:2:0 uses only the first 4.
    ac_cb: [[i32; 16]; 8],
    ac_cr: [[i32; 16]; 8],
    /// Reconstructed residual (sample-domain) for both planes. Size
    /// 64 (4:2:0 8x8) or 128 (4:2:2 8x16). Stored in the upper bound
    /// length so the caller iterates over the right number of rows.
    recon_cb: Vec<i32>,
    recon_cr: Vec<i32>,
    /// Predictor samples used (64 / 128 entries).
    pred_cb: Vec<i32>,
    pred_cr: Vec<i32>,
}

impl ChromaBlock {
    /// Per-4x4-block AC nonzero flags for Cb / Cr (length 4 for 4:2:0,
    /// 8 for 4:2:2). Used by the deblock walker's chroma-nonzero mask.
    fn cb_block_count(chroma_array_type: u32) -> usize {
        match chroma_array_type {
            1 => 4,
            2 => 8,
            _ => 0,
        }
    }
}

/// Round-27 — pick the best chroma intra-prediction mode (DC / H / V /
/// Plane) by SAD, encode the residual, reconstruct the samples, and
/// return everything the caller needs to install the recon, emit the
/// MB syntax, and update the deblock walker mask.
///
/// `chroma_array_type` selects 4:2:0 (1) vs 4:2:2 (2). 4:4:4 is out
/// of scope and panics.
#[allow(clippy::too_many_arguments)]
fn encode_chroma_block(
    chroma_array_type: u32,
    frame_u: &[u8],
    frame_v: &[u8],
    recon_u: &[u8],
    recon_v: &[u8],
    chroma_width: usize,
    chroma_height: usize,
    mb_x: usize,
    mb_y: usize,
    qp_c: i32,
    w4: &[i32; 16],
    nb: Option<(bool, bool, bool)>,
) -> ChromaBlock {
    use crate::encoder::intra_pred::{predict_chroma_8x16, sad_8x16};
    let (h_chroma, n_blk) = match chroma_array_type {
        1 => (8usize, 4usize),
        2 => (16usize, 8usize),
        _ => panic!("encode_chroma_block: unsupported chroma_array_type {chroma_array_type}"),
    };

    let mut best_mode = IntraChromaMode::Dc;
    let mut best_pred_u_64 = [0i32; 64];
    let mut best_pred_v_64 = [0i32; 64];
    let mut best_pred_u_128 = [0i32; 128];
    let mut best_pred_v_128 = [0i32; 128];
    let mut best_sad = u64::MAX;
    for &mode in &[
        IntraChromaMode::Dc,
        IntraChromaMode::Horizontal,
        IntraChromaMode::Vertical,
        IntraChromaMode::Plane,
    ] {
        if chroma_array_type == 1 {
            let (Some(pu), Some(pv)) = (
                predict_chroma_8x8_avail(
                    mode,
                    recon_u,
                    chroma_width,
                    chroma_height,
                    mb_x,
                    mb_y,
                    nb,
                ),
                predict_chroma_8x8_avail(
                    mode,
                    recon_v,
                    chroma_width,
                    chroma_height,
                    mb_x,
                    mb_y,
                    nb,
                ),
            ) else {
                continue;
            };
            let s = sad_8x8(frame_u, chroma_width, mb_x * 8, mb_y * 8, &pu)
                + sad_8x8(frame_v, chroma_width, mb_x * 8, mb_y * 8, &pv);
            if s < best_sad {
                best_sad = s;
                best_mode = mode;
                best_pred_u_64 = pu;
                best_pred_v_64 = pv;
            }
        } else {
            // 4:2:2
            let (Some(pu), Some(pv)) = (
                predict_chroma_8x16(mode, recon_u, chroma_width, chroma_height, mb_x, mb_y),
                predict_chroma_8x16(mode, recon_v, chroma_width, chroma_height, mb_x, mb_y),
            ) else {
                continue;
            };
            let s = sad_8x16(frame_u, chroma_width, mb_x * 8, mb_y * 16, &pu)
                + sad_8x16(frame_v, chroma_width, mb_x * 8, mb_y * 16, &pv);
            if s < best_sad {
                best_sad = s;
                best_mode = mode;
                best_pred_u_128 = pu;
                best_pred_v_128 = pv;
            }
        }
    }

    let mut dc_cb = [0i32; 8];
    let mut dc_cr = [0i32; 8];
    let mut ac_cb = [[0i32; 16]; 8];
    let mut ac_cr = [[0i32; 16]; 8];
    let mut recon_cb = vec![0i32; 8 * h_chroma];
    let mut recon_cr = vec![0i32; 8 * h_chroma];

    if chroma_array_type == 1 {
        let (u_dc, u_ac, u_recon) =
            encode_chroma_residual(frame_u, chroma_width, mb_x, mb_y, &best_pred_u_64, qp_c, w4);
        let (v_dc, v_ac, v_recon) =
            encode_chroma_residual(frame_v, chroma_width, mb_x, mb_y, &best_pred_v_64, qp_c, w4);
        dc_cb[..4].copy_from_slice(&u_dc);
        dc_cr[..4].copy_from_slice(&v_dc);
        ac_cb[..4].copy_from_slice(&u_ac);
        ac_cr[..4].copy_from_slice(&v_ac);
        recon_cb[..64].copy_from_slice(&u_recon);
        recon_cr[..64].copy_from_slice(&v_recon);
    } else {
        let (u_dc, u_ac, u_recon) = encode_chroma_residual_422(
            frame_u,
            chroma_width,
            mb_x,
            mb_y,
            &best_pred_u_128,
            qp_c,
            w4,
        );
        let (v_dc, v_ac, v_recon) = encode_chroma_residual_422(
            frame_v,
            chroma_width,
            mb_x,
            mb_y,
            &best_pred_v_128,
            qp_c,
            w4,
        );
        dc_cb = u_dc;
        dc_cr = v_dc;
        ac_cb = u_ac;
        ac_cr = v_ac;
        recon_cb[..128].copy_from_slice(&u_recon);
        recon_cr[..128].copy_from_slice(&v_recon);
    }

    let any_dc_nz =
        dc_cb[..n_blk].iter().any(|&v| v != 0) || dc_cr[..n_blk].iter().any(|&v| v != 0);
    let any_ac_nz = ac_cb[..n_blk].iter().any(|blk| blk.iter().any(|&v| v != 0))
        || ac_cr[..n_blk].iter().any(|blk| blk.iter().any(|&v| v != 0));
    let cbp_chroma: u8 = if any_ac_nz {
        2
    } else if any_dc_nz {
        1
    } else {
        0
    };

    let pred_cb: Vec<i32> = if chroma_array_type == 1 {
        best_pred_u_64.to_vec()
    } else {
        best_pred_u_128.to_vec()
    };
    let pred_cr: Vec<i32> = if chroma_array_type == 1 {
        best_pred_v_64.to_vec()
    } else {
        best_pred_v_128.to_vec()
    };

    ChromaBlock {
        pred_mode: best_mode,
        cbp_chroma,
        dc_cb,
        dc_cr,
        ac_cb,
        ac_cr,
        recon_cb,
        recon_cr,
        pred_cb,
        pred_cr,
    }
}

/// Round-27 — pack a `ChromaBlock`'s per-4x4 AC nonzero flags into the
/// 16-bit mask the deblock walker reads. Same packing as the decoder's
/// `compute_chroma_nonzero_mask`: bits 0..=(n-1) are Cb, bits
/// 8..=(8+n-1) are Cr, where n = 4 for 4:2:0 and n = 8 for 4:2:2.
fn chroma_nz_mask_from_chroma_block(block: &ChromaBlock, n_blk: usize) -> u16 {
    let mut mask = 0u16;
    if block.cbp_chroma != 2 {
        return mask;
    }
    for k in 0..n_blk {
        if block.ac_cb[k].iter().any(|&v| v != 0) {
            mask |= 1u16 << k;
        }
        if block.ac_cr[k].iter().any(|&v| v != 0) {
            mask |= 1u16 << (8 + k);
        }
    }
    mask
}

/// Round-28 — Intra_16x16 encode of one chroma plane for 4:4:4
/// ("coded like luma" per §7.3.5.3). Mirrors the luma pipeline:
///
///   1. Build §8.3.3 16x16 predictor on the chroma plane using the
///      caller-supplied luma `mode` (per §8.3.4.1, ChromaArrayType==3
///      reuses the luma Intra_16x16 mode and predictor formula).
///   2. Sample residual against the predictor.
///   3. Per-4x4-block forward integer transform; collect the 16 DCs;
///      forward 4x4 Hadamard + quantize.
///   4. Per-block AC quantize.
///   5. Inverse: Hadamard-DC → per-block DC-preserved inverse → add
///      predictor → clamp into recon plane.
///
/// Returns:
///   * `dc_levels` — quantized 16-entry DC array in raster order
///     (caller applies `zigzag_scan_4x4` for emit).
///   * `ac_levels_scan` — per-block AC scan layout (positions 0..=14;
///     §6.4.3 raster-Z indexing).
///   * `ac_quant_raster` — per-block AC raster-order quantized levels
///     (slot 0 zeroed) — used for the inverse path.
///   * `any_ac_nz` — true iff any 4x4 AC block has at least one
///     non-zero level (drives `cbp_luma == 15` gating).
///
/// Stateful side-effect: writes the reconstructed chroma plane samples
/// into `recon_chroma` (16x16 tile at MB origin).
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
fn encode_intra16x16_chroma_plane_luma_like(
    mode: I16x16Mode,
    src_plane: &[u8],
    recon_chroma: &mut [u8],
    chroma_width: usize,
    chroma_height: usize,
    mb_x: usize,
    mb_y: usize,
    qp_c: i32,
    w4: &[i32; 16],
) -> ([i32; 16], [[i32; 16]; 16], [[i32; 16]; 16], bool) {
    // (1) Build the 16x16 predictor from the chroma plane's prior
    // recon. `predict_16x16` is plane-agnostic — it just reads u8
    // samples at MB-relative offsets. For mb_x==0 / mb_y==0 the
    // predictor falls back to mid-grey (128) per the helper's
    // unavailability handling — that's the same fallback the decoder
    // uses for the §8.3.3.1/2/3/4 not-available branches.
    let pred = predict_16x16(mode, recon_chroma, chroma_width, chroma_height, mb_x, mb_y)
        .unwrap_or([128i32; 256]);

    // (2) Sample residual.
    let mut residual = [0i32; 256];
    for j in 0..16usize {
        for i in 0..16usize {
            let s = src_plane[(mb_y * 16 + j) * chroma_width + (mb_x * 16 + i)] as i32;
            residual[j * 16 + i] = s - pred[j * 16 + i];
        }
    }

    // (3) Per-4x4 forward integer transform.
    let mut coeffs_4x4 = [[0i32; 16]; 16];
    for (blk, slot) in coeffs_4x4.iter_mut().enumerate() {
        let bx = blk % 4;
        let by = blk / 4;
        let mut block = [0i32; 16];
        for j in 0..4 {
            for i in 0..4 {
                block[j * 4 + i] = residual[(by * 4 + j) * 16 + bx * 4 + i];
            }
        }
        *slot = forward_core_4x4(&block);
    }
    // Pull DCs into a row-major 4x4 matrix.
    let mut dc_coeffs = [0i32; 16];
    for (blk, c) in coeffs_4x4.iter().enumerate() {
        let bx = blk % 4;
        let by = blk / 4;
        dc_coeffs[by * 4 + bx] = c[0];
    }
    // Forward Hadamard + quantize. Same helper as luma — chroma DC
    // for 4:4:4 follows the luma DC path per §8.5.10.
    let dc_t = forward_hadamard_4x4(&dc_coeffs);
    let dc_levels = quantize_luma_dc_w(&dc_t, qp_c, true, w4[0]);

    // (4) Per-block AC quantize. Reorder into §6.4.3 raster-Z.
    let mut ac_quant_raster = [[0i32; 16]; 16];
    let mut ac_scan = [[0i32; 16]; 16];
    let mut any_ac_nz = false;
    for blkz in 0..16usize {
        let (bx, by) = LUMA_4X4_BLK[blkz];
        let raster = by * 4 + bx;
        let z = quantize_4x4_ac_w(&coeffs_4x4[raster], qp_c, true, w4);
        ac_quant_raster[raster] = z;
        ac_scan[blkz] = zigzag_scan_4x4_ac(&z);
        if ac_scan[blkz].iter().any(|&v| v != 0) {
            any_ac_nz = true;
        }
    }

    // (5) Inverse path — produce decoder-bit-exact recon.
    let inv_dc =
        inverse_hadamard_luma_dc_16x16(&dc_levels, qp_c, w4, 8).expect("4:4:4 chroma DC inverse");
    #[allow(clippy::needless_range_loop)] // raster row-major over 16 4x4 blocks
    for blk in 0..16usize {
        let bx = blk % 4;
        let by = blk / 4;
        let mut coeffs_in = if any_ac_nz {
            ac_quant_raster[blk]
        } else {
            [0i32; 16]
        };
        coeffs_in[0] = inv_dc[by * 4 + bx];
        let r = inverse_transform_4x4_dc_preserved(&coeffs_in, qp_c, w4, 8)
            .expect("4:4:4 chroma 4x4 inverse");
        for j in 0..4 {
            for i in 0..4 {
                let px = mb_x * 16 + bx * 4 + i;
                let py = mb_y * 16 + by * 4 + j;
                let p = pred[(by * 4 + j) * 16 + bx * 4 + i];
                let raw = p + r[j * 4 + i];
                recon_chroma[py * chroma_width + px] = raw.clamp(0, 255) as u8;
            }
        }
    }

    (dc_levels, ac_scan, ac_quant_raster, any_ac_nz)
}

/// Round-27 — install the chroma block reconstruction back into the
/// per-plane recon buffers. 4:2:0 → 8x8 tile per MB. 4:2:2 → 8x16 tile.
fn install_chroma_recon(
    chroma_array_type: u32,
    chroma_width: usize,
    mb_x: usize,
    mb_y: usize,
    block: &ChromaBlock,
    recon_u: &mut [u8],
    recon_v: &mut [u8],
) {
    let (h_chroma, base_y) = match chroma_array_type {
        1 => (8usize, mb_y * 8),
        2 => (16usize, mb_y * 16),
        _ => return,
    };
    for j in 0..h_chroma {
        for i in 0..8usize {
            let cx = mb_x * 8 + i;
            let cy = base_y + j;
            let pred_u = block.pred_cb[j * 8 + i];
            let pred_v = block.pred_cr[j * 8 + i];
            let res_u = if block.cbp_chroma == 0 {
                0
            } else {
                block.recon_cb[j * 8 + i]
            };
            let res_v = if block.cbp_chroma == 0 {
                0
            } else {
                block.recon_cr[j * 8 + i]
            };
            recon_u[cy * chroma_width + cx] = (pred_u + res_u).clamp(0, 255) as u8;
            recon_v[cy * chroma_width + cx] = (pred_v + res_v).clamp(0, 255) as u8;
        }
    }
}

/// Round-27 — encode one chroma plane's residual (DC + AC) for an 8x16
/// chroma MB (4:2:2). Returns:
///   * 8 quantized scan-order DC levels (already in `ChromaDCLevel`
///     scan order — the decoder consumes this verbatim).
///   * 8 per-4x4-block AC levels in scan order (AC-only layout).
///   * Reconstructed 8x16 residual (`[i32; 128]`, row-major).
///
/// 8 4x4 sub-blocks per plane laid out as:
///   (0,0), (4,0), (0,4), (4,4), (0,8), (4,8), (0,12), (4,12)
/// matching the decoder's `chroma_block_xy` ordering for 4:2:2.
fn encode_chroma_residual_422(
    src_plane: &[u8],
    chroma_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 128],
    qp_c: i32,
    w4: &[i32; 16],
) -> ([i32; 8], [[i32; 16]; 8], [i32; 128]) {
    use crate::encoder::transform::{
        forward_hadamard_4x2, quantize_4x4_ac_w, quantize_chroma_dc_422_w, scan_chroma_dc_422,
    };
    use crate::transform::inverse_hadamard_chroma_dc_422;

    // Build sample residual against the predictor.
    let mut residual = [0i32; 128];
    for j in 0..16usize {
        for i in 0..8usize {
            let s = src_plane[(mb_y * 16 + j) * chroma_stride + mb_x * 8 + i] as i32;
            residual[j * 8 + i] = s - pred[j * 8 + i];
        }
    }

    // Forward 4x4 on each of the 8 sub-blocks. Order matches the
    // decoder's `chroma_block_xy` for 4:2:2 (raster: 2x4 layout).
    let blocks_xy: [(usize, usize); 8] = [
        (0, 0),
        (4, 0),
        (0, 4),
        (4, 4),
        (0, 8),
        (4, 8),
        (0, 12),
        (4, 12),
    ];
    let mut sub_coeffs = [[0i32; 16]; 8];
    for (k, &(bx, by)) in blocks_xy.iter().enumerate() {
        let mut block = [0i32; 16];
        for j in 0..4 {
            for i in 0..4 {
                block[j * 4 + i] = residual[(by + j) * 8 + bx + i];
            }
        }
        sub_coeffs[k] = forward_core_4x4(&block);
    }

    // Collect the 8 DCs into a row-major 4x2 layout. Block (xO, yO):
    //   k=0 (0,0)  → c[0,0]
    //   k=1 (4,0)  → c[0,1]
    //   k=2 (0,4)  → c[1,0]
    //   k=3 (4,4)  → c[1,1]
    //   k=4 (0,8)  → c[2,0]
    //   k=5 (4,8)  → c[2,1]
    //   k=6 (0,12) → c[3,0]
    //   k=7 (4,12) → c[3,1]
    let dc_in: [i32; 8] = [
        sub_coeffs[0][0], // c[0,0]
        sub_coeffs[1][0], // c[0,1]
        sub_coeffs[2][0], // c[1,0]
        sub_coeffs[3][0], // c[1,1]
        sub_coeffs[4][0], // c[2,0]
        sub_coeffs[5][0], // c[2,1]
        sub_coeffs[6][0], // c[3,0]
        sub_coeffs[7][0], // c[3,1]
    ];

    // Forward 4x2 Hadamard + quantize. §8.5.11.2 — the DC scaling
    // uses LevelScale4x4(qP % 6, 0, 0) of the chroma list (round-397:
    // non-flat weightScale honoured; a flat list reduces bit-exactly).
    let dc_t = forward_hadamard_4x2(&dc_in);
    let dc_q = quantize_chroma_dc_422_w(&dc_t, qp_c, true, w4[0]);
    // Pack into spec scan order so the bitstream can carry it directly.
    let dc_levels = scan_chroma_dc_422(&dc_q);

    // Quantize AC of each sub-block (positions 1..15 in scan order).
    let mut ac_levels = [[0i32; 16]; 8];
    for (k, coeffs) in sub_coeffs.iter().enumerate() {
        let z = quantize_4x4_ac_w(coeffs, qp_c, true, w4);
        ac_levels[k] = zigzag_scan_4x4_ac(&z);
    }

    // ------- Reconstruct the chroma 8x16 residual -------
    // §8.5.11.2: inverse Hadamard → per-block DC-preserved inverse.
    let dc_back =
        inverse_hadamard_chroma_dc_422(&dc_levels, qp_c, w4, 8).expect("chroma DC 422 inverse");
    // dc_back is row-major 4x2 → maps to blocks 0..=7 by (k as above).
    let dc_block_index_to_dc_back: [usize; 8] = [0, 1, 2, 3, 4, 5, 6, 7];

    let mut recon_residual = [0i32; 128];
    for (k, &(bx, by)) in blocks_xy.iter().enumerate() {
        let mut coeffs = inverse_scan_4x4_zigzag_ac(&ac_levels[k]);
        coeffs[0] = dc_back[dc_block_index_to_dc_back[k]];
        let r = inverse_transform_4x4_dc_preserved(&coeffs, qp_c, w4, 8)
            .expect("chroma 4x4 422 inverse");
        for j in 0..4 {
            for i in 0..4 {
                recon_residual[(by + j) * 8 + bx + i] = r[j * 4 + i];
            }
        }
    }

    (dc_levels, ac_levels, recon_residual)
}

/// Encode one chroma plane's residual (DC + AC) for an 8x8 chroma MB,
/// returning (raster-order DC levels for the 2x2 DC matrix,
/// per-4x4-block AC levels in scan order, reconstructed 8x8 residual).
///
/// Implements §8.5.11 (encoder side). Chroma block layout for 4:2:0:
/// 2x2 grid of 4x4 sub-blocks at (0,0), (4,0), (0,4), (4,4). The
/// decoder's inverse path uses `inverse_hadamard_chroma_dc_420` →
/// per-block `inverse_transform_4x4_dc_preserved` (with the 2x2-Hadamard
/// DC plugged in at `c[0,0]`). The forward path mirrors that.
///
/// `chroma_dc_indices` are the four spec-order DC slots:
///   0 → (0,0), 1 → (1,0), 2 → (0,1), 3 → (1,1)
/// in *block* coordinates (each step = 4 samples). That matches
/// `inverse_hadamard_chroma_dc_420`.
fn encode_chroma_residual(
    src_plane: &[u8],
    chroma_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 64],
    qp_c: i32,
    w4: &[i32; 16],
) -> ([i32; 4], [[i32; 16]; 4], [i32; 64]) {
    // Build sample residual against the predictor.
    let mut residual = [0i32; 64];
    for j in 0..8usize {
        for i in 0..8usize {
            let s = src_plane[(mb_y * 8 + j) * chroma_stride + mb_x * 8 + i] as i32;
            residual[j * 8 + i] = s - pred[j * 8 + i];
        }
    }

    // Forward 4x4 on each of the four 4x4 sub-blocks. Order matches the
    // inverse_hadamard_chroma_dc_420 input order (raster: TL, TR, BL, BR).
    let blocks_xy = [(0usize, 0usize), (4, 0), (0, 4), (4, 4)];
    let mut sub_coeffs = [[0i32; 16]; 4]; // forward-transformed 4x4 blocks
    for (k, &(bx, by)) in blocks_xy.iter().enumerate() {
        let mut block = [0i32; 16];
        for j in 0..4 {
            for i in 0..4 {
                block[j * 4 + i] = residual[(by + j) * 8 + bx + i];
            }
        }
        sub_coeffs[k] = forward_core_4x4(&block);
    }
    // Collect the 4 DCs.
    let dc_in: [i32; 4] = [
        sub_coeffs[0][0],
        sub_coeffs[1][0],
        sub_coeffs[2][0],
        sub_coeffs[3][0],
    ];
    // Forward 2x2 Hadamard.
    let dc_t = forward_hadamard_2x2(&dc_in);
    // Quantize the four DC levels (§8.5.11.1 LevelScale(qP%6, 0, 0)).
    let dc_levels = quantize_chroma_dc_w(&dc_t, qp_c, true, w4[0]);

    // Quantize AC of each sub-block (positions 1..15 in scan order).
    // The encoder zeroes scan-position 0; the decoder will overwrite
    // with the inverse-Hadamard DC.
    let mut ac_levels = [[0i32; 16]; 4];
    for (k, coeffs) in sub_coeffs.iter().enumerate() {
        // Run AC quantization on positions 1..15. Position 0 is
        // already part of the DC path.
        let z = quantize_4x4_ac_w(coeffs, qp_c, true, w4);
        // Pack into the encoder's "AC scan" layout: 15 entries at
        // positions 0..14, mirroring the decoder's
        // `inverse_scan_4x4_zigzag_ac` reading.
        ac_levels[k] = zigzag_scan_4x4_ac(&z);
    }

    // ------- Reconstruct the chroma 8x8 residual -------
    // §8.5.11: inverse Hadamard → per-block DC-preserved inverse.
    let dc_back =
        inverse_hadamard_chroma_dc_420(&dc_levels, qp_c, w4, 8).expect("chroma DC inverse");

    let mut recon_residual = [0i32; 64];
    for (k, &(bx, by)) in blocks_xy.iter().enumerate() {
        // Re-build a 4x4 coefficient block from the AC scan, then
        // overwrite c[0,0] with the inverse-Hadamard DC.
        let mut coeffs = inverse_scan_4x4_zigzag_ac(&ac_levels[k]);
        coeffs[0] = dc_back[k];
        let r =
            inverse_transform_4x4_dc_preserved(&coeffs, qp_c, w4, 8).expect("chroma 4x4 inverse");
        for j in 0..4 {
            for i in 0..4 {
                recon_residual[(by + j) * 8 + bx + i] = r[j * 4 + i];
            }
        }
    }

    (dc_levels, ac_levels, recon_residual)
}

/// Round-15 RDO trial for one Intra_16x16 luma mode.
///
/// Performs a *full* trial: forward 4x4 on each of the 16 sub-blocks,
/// pulls DCs into the Hadamard, quantises DC + AC, runs the inverse
/// path back through `inverse_hadamard_luma_dc_16x16` +
/// `inverse_transform_4x4_dc_preserved` to land on the same recon the
/// decoder will produce, then computes:
///
///   * `D` = SSD between source 16x16 luma and the reconstructed 16x16.
///   * `R` = trial CAVLC bit count for the DC block + 16 AC blocks
///     (only when AC has any non-zero level — matches `cbp_luma == 15`
///     gating in the real emit).
///
/// Returns `J = D + λ·R`. Lower = better.
///
/// The chroma path is identical for all luma modes so it is excluded
/// from `J` (its contribution would just be a constant offset).
#[allow(clippy::too_many_arguments)]
fn trial_intra16x16_cost(
    frame: &YuvFrame<'_>,
    pred: &[i32; 256],
    mb_x: usize,
    mb_y: usize,
    qp_y: i32,
    width: usize,
    lambda: f64,
    w4: &[i32; 16],
) -> u64 {
    // Build the 16x16 sample residual.
    let mut residual = [0i32; 256];
    for j in 0..16usize {
        for i in 0..16usize {
            let s = frame.y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
            residual[j * 16 + i] = s - pred[j * 16 + i];
        }
    }
    // Forward 4x4 on each sub-block.
    let mut coeffs_4x4 = [[0i32; 16]; 16];
    for (blk, slot) in coeffs_4x4.iter_mut().enumerate() {
        let bx = blk % 4;
        let by = blk / 4;
        let mut block = [0i32; 16];
        for j in 0..4 {
            for i in 0..4 {
                block[j * 4 + i] = residual[(by * 4 + j) * 16 + bx * 4 + i];
            }
        }
        *slot = forward_core_4x4(&block);
    }
    let mut dc_coeffs = [0i32; 16];
    for (blk, c) in coeffs_4x4.iter().enumerate() {
        let bx = blk % 4;
        let by = blk / 4;
        dc_coeffs[by * 4 + bx] = c[0];
    }
    let dc_t = forward_hadamard_4x4(&dc_coeffs);
    let dc_levels = quantize_luma_dc_w(&dc_t, qp_y, true, w4[0]);

    let mut ac_quant_raster = [[0i32; 16]; 16];
    let mut ac_scan = [[0i32; 16]; 16];
    let mut any_ac_nz = false;
    for blkz in 0..16usize {
        let (bx, by) = LUMA_4X4_BLK[blkz];
        let raster = by * 4 + bx;
        let z = quantize_4x4_ac_w(&coeffs_4x4[raster], qp_y, true, w4);
        ac_quant_raster[raster] = z;
        ac_scan[blkz] = zigzag_scan_4x4_ac(&z);
        if ac_scan[blkz].iter().any(|&v| v != 0) {
            any_ac_nz = true;
        }
    }

    // Inverse path: build the recon planes for SSD measurement.
    let inv_dc = inverse_hadamard_luma_dc_16x16(&dc_levels, qp_y, w4, 8).expect("luma DC inverse");
    let mut recon = [0i32; 256];
    #[allow(clippy::needless_range_loop)]
    for blk in 0..16usize {
        let bx = blk % 4;
        let by = blk / 4;
        let mut coeffs_in = if any_ac_nz {
            ac_quant_raster[blk]
        } else {
            [0i32; 16]
        };
        coeffs_in[0] = inv_dc[by * 4 + bx];
        let r = inverse_transform_4x4_dc_preserved(&coeffs_in, qp_y, w4, 8).expect("inv 4x4");
        for j in 0..4 {
            for i in 0..4 {
                let p = pred[(by * 4 + j) * 16 + bx * 4 + i];
                recon[(by * 4 + j) * 16 + bx * 4 + i] = p + r[j * 4 + i];
            }
        }
    }
    let d = ssd_16x16(frame.y, width, mb_x * 16, mb_y * 16, &recon);

    // Trial CAVLC for the rate term. nC=0 estimate (same rationale as
    // the I_NxN per-block trial above). The DC block is always
    // transmitted; AC blocks are transmitted only when cbp_luma == 15.
    let mut bits: u64 = 0;
    // mb_type ue(v): for Intra_16x16 the codeNum is 1..=24 (4-bit field
    // approximately). We don't try to enumerate it here; the choice
    // between cbp_luma 0/15 and the 4 pred_modes shifts the codeNum by
    // a small constant. Use a fixed estimate of 7 bits for Intra_16x16
    // mb_type — accurate to within ±2 bits across the (pred_mode, cbp)
    // space (Table 7-11 entries 1..24 → ue(v) widths 1, 3, 5, 7, 9 bits
    // depending on codeNum). The constant cancels out in *between-mode*
    // comparisons but matters for the I_16x16 vs I_NxN comparison; we
    // keep it as a stable midpoint.
    bits += 7;
    // intra_chroma_pred_mode ue(v): also a constant offset (we'll pick
    // chroma later, identical for all luma modes). Skip in J.
    // mb_qp_delta se(0) = 1 bit.
    bits += 1;

    // Luma DC block.
    let dc_scan = zigzag_scan_4x4(&dc_levels);
    let mut trial_w = BitWriter::new();
    if encode_residual_block_cavlc(&mut trial_w, CoeffTokenContext::Numeric(0), 16, &dc_scan)
        .is_ok()
    {
        bits += trial_w.bits_emitted() as u64;
    }
    // Luma AC blocks (only when cbp_luma == 15).
    if any_ac_nz {
        for scan in ac_scan.iter() {
            let mut tw = BitWriter::new();
            if encode_residual_block_cavlc(&mut tw, CoeffTokenContext::Numeric(0), 15, &scan[..15])
                .is_ok()
            {
                bits += tw.bits_emitted() as u64;
            }
        }
    }
    cost_combined(d, bits, lambda)
}

// ===========================================================================
// Round-16 — P-slice (inter) encoder.
// ===========================================================================

impl Encoder {
    /// Round-16 — encode one P-frame using `prev` as the reference. Emits
    /// just the slice NAL (caller has already emitted SPS/PPS via the IDR).
    ///
    /// Strategy per MB:
    ///   1. Run integer-pel motion estimation around (0, 0) ±range.
    ///   2. Build the inter predictor (luma 6-tap reduces to integer copy
    ///      for our integer-pel MVs; chroma bilinear with 0..=4 frac).
    ///   3. Compute the residual against the predictor, run forward 4x4 +
    ///      AC quantization (no luma DC Hadamard for inter MBs).
    ///   4. Decide P_Skip vs P_L0_16x16: P_Skip when chosen MV equals
    ///      the §8.4.1.2-derived skip-MV AND CBP would be 0.
    ///   5. (Round-16 simplification) No intra-fallback RDO yet — we trust
    ///      the inter path. Future round can add it.
    ///
    /// The bitstream emits an `mb_skip_run` ue(v) before each coded MB
    /// (per §7.3.4 CAVLC), counting the consecutive P_Skip MBs.
    #[allow(clippy::too_many_arguments)]
    pub fn encode_p(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
    ) -> EncodedP {
        self.encode_p_with_qp(frame, prev, frame_num, pic_order_cnt_lsb, self.cfg.qp)
    }

    /// [`encode_p`](Self::encode_p) with a per-frame QP override —
    /// same §7.4.3 `slice_qp_delta` mechanics as
    /// [`encode_idr_with_qp`](Self::encode_idr_with_qp).
    pub fn encode_p_with_qp(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
        frame_qp: i32,
    ) -> EncodedP {
        self.encode_p_impl(frame, prev, frame_num, pic_order_cnt_lsb, frame_qp, None)
    }

    /// [`encode_p_with_qp`](Self::encode_p_with_qp) plus **MB-row QP
    /// modulation** toward a whole-slice bit budget (round-420).
    ///
    /// Before each MB row (except the first) the encoder compares the
    /// bits spent so far against the pro-rata share of
    /// `frame_budget_bits` and steps the working QP by up to ±2
    /// (bounded to `frame_qp` ± 6): rows landing over budget code at
    /// a coarser QP, rows under budget claw quality back. The QP
    /// changes ride the §7.4.5 `mb_qp_delta` syntax — emitted only on
    /// MBs with coded residual, with skipped / cbp==0 MBs inheriting
    /// the previous MB's QP_Y exactly as the decoder derives it (the
    /// §8.7 deblock strengths follow the same chain).
    ///
    /// 4:2:0 only (the modulated paths' §7.3.5 mb_qp_delta gating is
    /// exercised at ChromaArrayType == 1).
    pub fn encode_p_rate_adaptive(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
        frame_qp: i32,
        frame_budget_bits: u64,
    ) -> EncodedP {
        assert_eq!(
            self.cfg.chroma_format_idc, 1,
            "encode_p_rate_adaptive requires 4:2:0"
        );
        self.encode_p_impl(
            frame,
            prev,
            frame_num,
            pic_order_cnt_lsb,
            frame_qp,
            Some(frame_budget_bits),
        )
    }

    fn encode_p_impl(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
        frame_qp: i32,
        row_budget_bits: Option<u64>,
    ) -> EncodedP {
        assert!(
            (0..=51).contains(&frame_qp),
            "frame_qp {frame_qp} out of 0..=51"
        );
        assert_eq!(frame.width, self.cfg.width);
        assert_eq!(frame.height, self.cfg.height);
        assert_eq!(prev.width, self.cfg.width);
        assert_eq!(prev.height, self.cfg.height);
        let width_mbs = self.cfg.width / 16;
        let height_mbs = self.cfg.height / 16;
        // §6.2 Table 6-1 — chroma plane dimensions per chroma format
        // (round-397: encode_p runs at 4:2:0, 4:2:2 and 4:4:4;
        // round-448 adds 4:0:0).
        let chroma_width = match self.cfg.chroma_format_idc {
            0 => 0usize,
            3 => self.cfg.width as usize,
            _ => (self.cfg.width / 2) as usize,
        };
        let chroma_height = match self.cfg.chroma_format_idc {
            0 => 0usize,
            2 | 3 => self.cfg.height as usize,
            _ => (self.cfg.height / 2) as usize,
        };

        // SPS/PPS are not re-emitted for non-IDR slices. Caller already
        // shipped them with the IDR.
        let mut stream: Vec<u8> = Vec::new();

        let log2_max_frame_num_minus4: u32 = 4;
        let log2_max_poc_lsb_minus4: u32 = 4;
        let chroma_qp_index_offset: i32 = 0;

        // Round-453 — §8.4.2.3.2 explicit weighted prediction: fit
        // the slice-wide luma weighting against the reference and
        // elect it on measured SSD gain (fade detection).
        let p_wp_table: Option<ExplicitPredWeightTableL0> = if self.cfg.explicit_weighted_pred {
            Some(compute_explicit_p_weight(
                frame.y,
                prev.recon_y,
                self.cfg.width as usize,
                self.cfg.height as usize,
            ))
        } else {
            None
        };
        let wp_l0 = p_wp_table.map(|t| {
            let (weight, offset) = t.effective();
            WeightedPredL0 {
                log2_wd: t.luma_log2_weight_denom,
                weight,
                offset,
            }
        });
        // Motion search runs against the WEIGHTED reference (exact at
        // integer positions; the sub-pel refinement's interpolate-
        // then-weight vs weight-then-interpolate difference only
        // perturbs the search, never the coded prediction).
        let me_plane: Vec<u8> = match wp_l0 {
            Some(wp) => {
                let mut v: Vec<i32> = prev.recon_y.iter().map(|&p| p as i32).collect();
                wp.apply(&mut v);
                v.iter().map(|&p| p as u8).collect()
            }
            None => Vec::new(),
        };
        let me_luma: &[u8] = if me_plane.is_empty() {
            prev.recon_y
        } else {
            &me_plane
        };

        let mut sw = BitWriter::new();
        write_p_slice_header(
            &mut sw,
            &PSliceHeaderConfig {
                first_mb_in_slice: 0,
                slice_type_raw: 5, // P, all-same-type
                pic_parameter_set_id: 0,
                colour_plane_id: self.cfg.colour_plane_id,
                frame_num,
                frame_num_bits: log2_max_frame_num_minus4 + 4,
                pic_order_cnt_lsb,
                poc_lsb_bits: log2_max_poc_lsb_minus4 + 4,
                slice_qp_delta: frame_qp - self.cfg.qp,
                // 4:4:4 mirrors encode_idr: deblocking disabled per
                // §7.4.3 (the §8.7 luma-filter-on-chroma path for
                // ChromaArrayType == 3 is not wired).
                disable_deblocking_filter_idc: if self.cfg.chroma_format_idc == 3 {
                    1
                } else {
                    0
                },
                slice_alpha_c0_offset_div2: 0,
                slice_beta_offset_div2: 0,
                nal_ref_idc: 2,
                cabac: None,
                field: FieldPicSignal::FrameMbsOnly,
                rplm_l0: &[],
                mmco: &[],
                pred_weight_table: p_wp_table,
                num_ref_idx_l0_active_minus1: None,
                redundant_pic_cnt: None,
                slice_group_change_cycle: None,
            },
        );

        // Reconstruction state for THIS picture.
        let mut recon_y = vec![0u8; (self.cfg.width * self.cfg.height) as usize];
        let mut recon_u = vec![0u8; chroma_width * chroma_height];
        let mut recon_v = vec![0u8; chroma_width * chroma_height];

        // §8.5.8 BD-aware chroma-QP — see encode_idr; identical
        // reasoning. Derived per row when MB-row modulation is active.
        let qp_bd_offset_c = qp_bd_offset(self.cfg.bit_depth_chroma_minus8);

        let mut nc_grid = CavlcNcGrid::new(width_mbs, height_mbs);
        let mut intra_grid = IntraGrid::new(width_mbs as usize, height_mbs as usize);
        let mut mv_grid = MvGrid::new(width_mbs as usize, height_mbs as usize);

        let mut mb_deblock_infos: Vec<MbDeblockInfo> =
            vec![MbDeblockInfo::default(); (width_mbs * height_mbs) as usize];

        // §7.3.4 CAVLC P-slice walker — emit `mb_skip_run` before each
        // coded MB. We accumulate skips and flush them just before writing
        // a coded MB (or at end-of-slice). Note: the spec also requires
        // an `mb_skip_run` even at the *very end* of a slice if the last
        // MBs were skips — we always emit one final `mb_skip_run` to
        // ensure consistency.
        let mut pending_skip: u32 = 0;
        let mut i8x8_mb_count = 0u32;

        // §7.4.5 decoded-QP chain: starts at SliceQP_Y (§7.4.3).
        let mut qp_tracker = MbQpTracker::new(frame_qp);
        qp_tracker.wp_l0 = wp_l0;
        let mut want_qp = frame_qp;

        for mb_y in 0..height_mbs as usize {
            // Round-420 — MB-row QP modulation: compare bits spent so
            // far to the pro-rata share of the slice budget and step
            // the working QP. +6 QP doubles the quantiser step, so
            // log2 of the overshoot ratio is the natural correction
            // unit. The response is deliberately asymmetric: running
            // out of budget mid-frame is the harmful direction, so
            // overshoot climbs fast (up to +2 per row, ceiling
            // frame_qp + 6) while undershoot descends one step per
            // row with a floor of frame_qp - 2 — early cheap rows say
            // nothing about the rows still to come (a mid-frame
            // complexity cliff would otherwise be entered at a
            // too-fine QP), and sustained underspend is reclaimed by
            // the frame-level controller on the next picture anyway.
            if let Some(budget) = row_budget_bits {
                if mb_y > 0 && budget > 0 {
                    let frac = mb_y as f64 / height_mbs as f64;
                    let spent = sw.bits_emitted() as f64;
                    let expected = (budget as f64 * frac).max(1.0);
                    let ratio = spent.max(1.0) / expected;
                    let adj = if ratio >= 1.0 {
                        (6.0 * ratio.log2()).round() as i32
                    } else {
                        (3.0 * ratio.log2()).round() as i32
                    };
                    let mut new_want = frame_qp + adj;
                    // Refinement below the frame QP is only trusted
                    // once most of the slice has proven cheap — a
                    // front-loaded saving is routinely an artefact of
                    // a rear-loaded complexity distribution.
                    if new_want < frame_qp && frac < 0.6 {
                        new_want = frame_qp;
                    }
                    want_qp = new_want
                        .clamp(want_qp - 1, want_qp + 2)
                        .clamp(frame_qp - 2, frame_qp + 6)
                        .clamp(0, 51);
                }
            }
            let qp_y = want_qp;
            let qp_c = qp_y_to_qp_c_with_bd_offset(qp_y, chroma_qp_index_offset, qp_bd_offset_c);

            for mb_x in 0..width_mbs as usize {
                let mb_addr = mb_y * width_mbs as usize + mb_x;

                // Round-29 — Decide P_Skip / P_L0_16x16 / P_8x8 for this
                // MB, with optional Intra_16x16 fallback when configured.
                let dbl = self.encode_p_mb_with_intra_fallback(
                    frame,
                    prev,
                    me_luma,
                    mb_x,
                    mb_y,
                    qp_y,
                    qp_c,
                    chroma_width,
                    chroma_height,
                    &mut recon_y,
                    &mut recon_u,
                    &mut recon_v,
                    &mut sw,
                    &mut nc_grid,
                    &mut intra_grid,
                    &mut mv_grid,
                    &mut pending_skip,
                    &mut qp_tracker,
                );
                if dbl.transform_size_8x8_flag {
                    i8x8_mb_count += 1;
                }
                mb_deblock_infos[mb_addr] = dbl;
            }
        }

        // Flush any trailing skip run.
        if pending_skip > 0 {
            sw.ue(pending_skip);
            pending_skip = 0;
        }
        let _ = pending_skip;

        // §7.3.2.8 / §7.3.2.9 — slice_data trailing bits.
        sw.rbsp_trailing_bits();
        let slice_rbsp = sw.into_bytes();
        stream.extend_from_slice(&build_nal_unit(2, NalUnitType::SliceNonIdr, &slice_rbsp));

        // §8.7 — picture-level in-loop deblocking. 4:4:4 skips the
        // pass (the slice header set disable_deblocking_filter_idc = 1
        // so the decoder doesn't run §8.7 either).
        if self.cfg.chroma_format_idc != 3 {
            crate::encoder::deblock::deblock_recon_with_chroma_array_type(
                self.cfg.width,
                self.cfg.height,
                chroma_width as u32,
                chroma_height as u32,
                &mut recon_y,
                &mut recon_u,
                &mut recon_v,
                &mb_deblock_infos,
                chroma_qp_index_offset,
                width_mbs,
                height_mbs,
                self.cfg.chroma_format_idc,
            );
        }

        // §8.4.1.2.1 / §8.4.1.2.2 — capture per-8x8 MV state so a later
        // B-slice can use this P-frame as the L1 anchor and probe the
        // colocated block's L0 MV/refIdx for colZeroFlag (step 7).
        let n_parts = (width_mbs as usize) * (height_mbs as usize) * 4;
        let mut partition_mvs = Vec::with_capacity(n_parts);
        for slot in &mv_grid.slots {
            for part in 0..4usize {
                // Both "not available" and "intra" map to (mv=0,
                // ref=-1, is_intra=true) per §8.4.1.2.1: an intra
                // colocated MB has refIdxCol=-1, and an unencoded slot
                // is treated identically to "intra" by the colocated
                // probe.
                let (mv, ref_idx, is_intra) = if !slot.available || slot.is_intra {
                    (Mv::ZERO, -1, true)
                } else {
                    (slot.mv_l0_8x8[part], slot.ref_idx_l0_8x8[part], false)
                };
                partition_mvs.push(FrameRefPartitionMv {
                    mv_l0: (
                        mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                        mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                    ),
                    ref_idx_l0: ref_idx.clamp(-1, 127) as i8,
                    is_intra,
                });
            }
        }

        EncodedP {
            annex_b: stream,
            recon_y,
            recon_u,
            recon_v,
            recon_width: self.cfg.width,
            recon_height: self.cfg.height,
            frame_num,
            pic_order_cnt_lsb,
            partition_mvs,
            i8x8_mb_count,
            pred_weight_table: p_wp_table,
        }
    }

    /// Encode one P-slice macroblock: run ME, build inter predictor,
    /// transmit residual (or skip if equivalent). Updates `mv_grid`,
    /// `nc_grid`, `intra_grid`, the recon planes, and `pending_skip`.
    /// Returns the deblock info for the §8.7 pass.
    ///
    /// Round-19 adds a **4MV (P_8x8 with all sub_mb_type = PL08x8)**
    /// trial: each 8x8 sub-block runs its own quarter-pel ME, and 4MV
    /// wins when its sum-of-SADs beats the 16x16 SAD by more than the
    /// 4MV bit-cost overhead. On smooth content the two paths converge
    /// to the same MV → identical SAD → 1MV wins (no regression).
    #[allow(clippy::too_many_arguments)]
    /// §7.4.5 — decoder-visible QP_Y tracker for MB-level delta-QP
    /// emission. `mb_qp_delta` is only present on MBs with coded
    /// residual (inter cbp != 0, or Intra_16x16 which always codes
    /// the luma DC block); every other MB inherits the previous MB's
    /// QP_Y in decoding order. The encoder mirrors that chain so (a)
    /// the emitted delta is relative to the decoder's actual
    /// predictor, and (b) the deblock pass filters each MB at the QP
    /// the decoder will assign it (skip / cbp==0 MBs keep `cur`).
    #[doc(hidden)]
    fn encode_p_mb(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        me_luma: &[u8],
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid: &mut MvGrid,
        pending_skip: &mut u32,
        qp_tracker: &mut MbQpTracker,
    ) -> MbDeblockInfo {
        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;

        // 1. Motion estimation: integer-pel full search ±16 followed by
        //    §8.4.2.2.1 half-pel and then quarter-pel refinement against
        //    the 6-tap interpolated predictor. Encoder and decoder agree
        //    on the predictor for sub-pel MVs because the refinement
        //    uses the same `interpolate_luma` the decoder calls.
        let me = search_quarter_pel_16x16(
            frame.y,
            width,
            self.cfg.width,
            self.cfg.height,
            me_luma,
            prev.width as usize,
            prev.width,
            prev.height,
            mb_x,
            mb_y,
            16,
            16,
        );
        let chosen_mv = Mv::new(me.mv_x, me.mv_y);
        let me_16x16_sad = me.sad;

        // 2. Compute MVpred + skip-MV for this MB position.
        // Round-453 — the macroblock's reference index (driver
        // election; 0 on the single-reference paths) and the §8.7.2.1
        // NOTE 1 identity key of that reference picture.
        let ref_idx = qp_tracker.ref_idx_l0;
        let ref_key = prev.pic_order_cnt.wrapping_mul(4);
        let mvp = mvp_for_16x16(mv_grid, mb_x, mb_y, ref_idx);
        let (skip_ref, skip_mv) = p_skip_mv(mv_grid, mb_x, mb_y);

        // 3. Build the inter predictor against the chosen MV.
        //    §8.4.1.4 / §8.4.2.2 — chroma predictor per format
        //    (round-397):
        //      * 4:2:0 — 1/8-pel bilinear, mvC = mvL.
        //      * 4:2:2 — x subsampled as 4:2:0, y full height
        //        (mvC.y = mvL.y·2 in 1/8-pel units).
        //      * 4:4:4 — the §8.4.2.2.1 LUMA 6-tap process on each
        //        chroma plane with mvC = mvL (eq. 8-235..8-238).
        let chroma_array_type = self.cfg.chroma_format_idc;
        let mut pred_y =
            build_inter_pred_luma(prev.recon_y, prev.width, prev.height, mb_x, mb_y, chosen_mv);
        // Round-453 — §8.4.2.3.2 explicit weighting (luma; chroma
        // keeps the default since chroma_weight_l0_flag = 0). Applies
        // to P_Skip too: the skip decision below compares the
        // weighted predictor.
        if let Some(wp) = qp_tracker.wp_l0 {
            wp.apply(&mut pred_y);
        }
        let chroma_w = chroma_width as u32;
        let chroma_h = chroma_height as u32;
        let (pred_u, pred_v): (Vec<i32>, Vec<i32>) = match chroma_array_type {
            // Round-448 — 4:0:0: no chroma planes to predict.
            0 => (Vec::new(), Vec::new()),
            3 => (
                build_inter_pred_luma(prev.recon_u, chroma_w, chroma_h, mb_x, mb_y, chosen_mv)
                    .to_vec(),
                build_inter_pred_luma(prev.recon_v, chroma_w, chroma_h, mb_x, mb_y, chosen_mv)
                    .to_vec(),
            ),
            2 => (
                cabac_path::build_inter_pred_chroma_local_422(
                    prev.recon_u,
                    chroma_w,
                    chroma_h,
                    mb_x,
                    mb_y,
                    chosen_mv,
                )
                .to_vec(),
                cabac_path::build_inter_pred_chroma_local_422(
                    prev.recon_v,
                    chroma_w,
                    chroma_h,
                    mb_x,
                    mb_y,
                    chosen_mv,
                )
                .to_vec(),
            ),
            _ => {
                // §8.4.1.4 Table 8-10 — cross-parity field reference
                // chroma-MV adjustment (0 for frame coding).
                let cmv = Mv::new(chosen_mv.x, chosen_mv.y + self.cfg.table_8_10_cy_offset);
                (
                    build_inter_pred_chroma(prev.recon_u, chroma_w, chroma_h, mb_x, mb_y, cmv)
                        .to_vec(),
                    build_inter_pred_chroma(prev.recon_v, chroma_w, chroma_h, mb_x, mb_y, cmv)
                        .to_vec(),
                )
            }
        };

        // ----- Round-19: 4MV (P_8x8) ME trial -----
        //
        // Run a per-8x8 quarter-pel ME. Each sub-block carries its own
        // MV; the sum of SADs lower-bounds the 4MV path's distortion.
        // 4MV is preferred over 1MV when the savings exceed the 4MV
        // bit-cost overhead (3 extra mb_type bits + 4× sub_mb_type "0"
        // = 4 extra bits + 6 extra mvd se(v) values vs 2 in 1MV path,
        // i.e. ~4 + 4·avg_mvd_se(v) − 2·avg_mvd_se(v) bits on top of
        // the residual-rate delta).
        let me_4mv: [crate::encoder::me::MeResult; 4] = std::array::from_fn(|i| {
            let sub_x = i % 2;
            let sub_y = i / 2;
            search_quarter_pel_8x8(
                frame.y,
                width,
                self.cfg.width,
                self.cfg.height,
                me_luma,
                prev.width as usize,
                prev.width,
                prev.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                16,
                16,
            )
        });
        let me_4mv_sad_sum: u32 = me_4mv.iter().map(|m| m.sad).sum();

        // Heuristic: pick 4MV when the per-8x8 SAD sum beats the 16x16
        // SAD by a CLEAR margin AND the 1MV residual is large enough
        // that fragmenting the predictor across sub-blocks is
        // worthwhile. Two gates:
        //
        //   (a) Absolute floor: 1MV SAD ≥ 1024 (avg ≥ 4/pixel over the
        //       16×16 = 256 samples). Below that, the residual is in
        //       quantisation-noise territory — splitting only adds
        //       syntax bits without fixing real motion error.
        //
        //   (b) Relative margin: 4MV SAD sum < 70% of 1MV SAD. This is
        //       large enough that the syntax overhead (3 extra mvd
        //       se(v) values + mb_type + 4× sub_mb_type) is amortised
        //       even at low QP.
        //
        // On smooth or lightly-quantised content the two paths converge
        // (often identical SADs) → 4MV is never picked → no regression
        // on the round 16/17/18 PSNR fixtures.
        // Round-397 — the 4MV P_8x8 writer's per-4x4 chroma predictor
        // assembly is 4:2:0-only; the 4:2:2 / 4:4:4 encoder keeps the
        // single-MV shapes (P_Skip / P_L0_16x16).
        let try_4mv = chroma_array_type == 1
            && me_16x16_sad >= 1024
            && (me_4mv_sad_sum as u64) * 10 < (me_16x16_sad as u64) * 7;

        if try_4mv {
            return self.encode_p_mb_4mv(
                frame,
                prev,
                me_luma,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                chroma_height,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mv_grid,
                pending_skip,
                qp_tracker,
                me_4mv,
            );
        }

        // 4. Compute the luma residual, transform, AC-quantize, inverse,
        //    and reconstruct. §8.5.9 — inter MBs quantise / dequantise
        //    under the inter weightScale lists (round-391).
        let wq = self.cfg.scaling_matrix.inter_weights();
        let inter_luma = forward_inter_luma(frame.y, width, mb_x, mb_y, &pred_y, qp_y, &wq.w4);
        let mut luma_4x4_levels_scan = inter_luma.levels_scan;
        let luma_4x4_quant_raster = inter_luma.quant_raster;
        let mut blk_has_nz = inter_luma.blk_has_nz;
        let mut recon_block_residual = inter_luma.recon_residual;

        // 5. Decide cbp_luma (per 8x8 quadrant).
        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            let any_nz = (0..4).any(|sub| blk_has_nz[blk8 * 4 + sub]);
            if any_nz {
                cbp_luma |= 1u8 << blk8;
            }
        }

        // 5b. Round-382 — High-profile 8x8-transform alternative. When
        // the PPS carries transform_8x8_mode_flag, trial the §8.6.4
        // 8x8 transform of the same residual and keep the lower-J
        // coding (the transform_size_8x8_flag bit itself is coded for
        // both alternatives whenever cbp_luma > 0, so it cancels out
        // of the comparison).
        let mut transform_size_8x8 = false;
        if self.cfg.transform_8x8 {
            let inter_luma8 = forward_inter_luma_8x8(
                frame.y,
                width,
                mb_x,
                mb_y,
                &pred_y,
                qp_y,
                &wq.w8,
                sw.field_scan(),
            );
            let mut cbp_luma8: u8 = 0;
            for blk8 in 0..4usize {
                if inter_luma8.blk_has_nz[blk8 * 4] {
                    cbp_luma8 |= 1u8 << blk8;
                }
            }
            let lambda = lambda_ssd(qp_y, false);
            let j4 = inter_luma_transform_cost(
                frame.y,
                width,
                mb_x,
                mb_y,
                &pred_y,
                &inter_luma,
                cbp_luma,
                lambda,
            );
            let j8 = inter_luma_transform_cost(
                frame.y,
                width,
                mb_x,
                mb_y,
                &pred_y,
                &inter_luma8,
                cbp_luma8,
                lambda,
            );
            if j8 < j4 {
                transform_size_8x8 = true;
                luma_4x4_levels_scan = inter_luma8.levels_scan;
                blk_has_nz = inter_luma8.blk_has_nz;
                recon_block_residual = inter_luma8.recon_residual;
                cbp_luma = cbp_luma8;
            }
        }

        // 6. Encode chroma residual against the inter predictor —
        //    per-format dispatch (round-397).
        // 4:2:0 containers.
        let mut u_dc_levels = [0i32; 4];
        let mut v_dc_levels = [0i32; 4];
        let mut u_ac_levels = [[0i32; 16]; 4];
        let mut v_ac_levels = [[0i32; 16]; 4];
        let mut u_recon_residual = [0i32; 64];
        let mut v_recon_residual = [0i32; 64];
        // 4:2:2 containers (§8.5.11.2 — 8-coefficient DC + 2x4 AC grid).
        let mut u_dc8 = [0i32; 8];
        let mut v_dc8 = [0i32; 8];
        let mut u_ac8 = [[0i32; 16]; 8];
        let mut v_ac8 = [[0i32; 16]; 8];
        let mut u_recon_res_422 = [0i32; 128];
        let mut v_recon_res_422 = [0i32; 128];
        // 4:4:4 containers (§7.3.5.3 — chroma coded like luma; the
        // per-plane residual follows the LUMA transform-size pick).
        let mut cb444 = InterLumaForward::default();
        let mut cr444 = InterLumaForward::default();
        let mut cbp_chroma: u8 = 0;
        match chroma_array_type {
            // Round-448 — 4:0:0: no chroma residual exists
            // (§7.3.5.3 residual() is luma-only); cbp_chroma stays 0.
            0 => {}
            3 => {
                let pu: &[i32; 256] = pred_u[..256].try_into().expect("pred tile");
                let pv: &[i32; 256] = pred_v[..256].try_into().expect("pred tile");
                if transform_size_8x8 {
                    cb444 = forward_inter_luma_8x8(
                        frame.u,
                        chroma_width,
                        mb_x,
                        mb_y,
                        pu,
                        qp_c,
                        &wq.w8,
                        sw.field_scan(),
                    );
                    cr444 = forward_inter_luma_8x8(
                        frame.v,
                        chroma_width,
                        mb_x,
                        mb_y,
                        pv,
                        qp_c,
                        &wq.w8,
                        sw.field_scan(),
                    );
                } else {
                    cb444 = forward_inter_luma(frame.u, chroma_width, mb_x, mb_y, pu, qp_c, &wq.w4);
                    cr444 = forward_inter_luma(frame.v, chroma_width, mb_x, mb_y, pv, qp_c, &wq.w4);
                }
                // §7.4.5.1 at ChromaArrayType == 3 — a CBP quadrant bit
                // covers all three planes; CodedBlockPatternChroma is 0
                // (Table 9-4(b) has no chroma column).
                for blk8 in 0..4usize {
                    let cb_nz = (0..4).any(|sub| cb444.blk_has_nz[blk8 * 4 + sub]);
                    let cr_nz = (0..4).any(|sub| cr444.blk_has_nz[blk8 * 4 + sub]);
                    if cb_nz || cr_nz {
                        cbp_luma |= 1u8 << blk8;
                    }
                }
                // §7.3.5 — with cbp_luma == 0 the second-gate flag is
                // not coded and the decoder infers 0; normalise so the
                // recon / grids agree with the decoder.
                if cbp_luma == 0 {
                    transform_size_8x8 = false;
                }
            }
            2 => {
                let pu: &[i32; 128] = pred_u[..128].try_into().expect("pred tile");
                let pv: &[i32; 128] = pred_v[..128].try_into().expect("pred tile");
                let (dcu, acu, ru) =
                    encode_chroma_residual_422(frame.u, chroma_width, mb_x, mb_y, pu, qp_c, &wq.w4);
                let (dcv, acv, rv) =
                    encode_chroma_residual_422(frame.v, chroma_width, mb_x, mb_y, pv, qp_c, &wq.w4);
                u_dc8 = dcu;
                v_dc8 = dcv;
                u_ac8 = acu;
                v_ac8 = acv;
                u_recon_res_422 = ru;
                v_recon_res_422 = rv;
                let any_dc_nz = u_dc8.iter().any(|&v| v != 0) || v_dc8.iter().any(|&v| v != 0);
                let any_ac_nz = u_ac8.iter().any(|b| b.iter().any(|&v| v != 0))
                    || v_ac8.iter().any(|b| b.iter().any(|&v| v != 0));
                cbp_chroma = if any_ac_nz {
                    2
                } else if any_dc_nz {
                    1
                } else {
                    0
                };
            }
            _ => {
                let pu: &[i32; 64] = pred_u[..64].try_into().expect("pred tile");
                let pv: &[i32; 64] = pred_v[..64].try_into().expect("pred tile");
                let (dcu, acu, ru) = encode_chroma_residual_inter(
                    frame.u,
                    chroma_width,
                    mb_x,
                    mb_y,
                    pu,
                    qp_c,
                    &wq.w4,
                );
                let (dcv, acv, rv) = encode_chroma_residual_inter(
                    frame.v,
                    chroma_width,
                    mb_x,
                    mb_y,
                    pv,
                    qp_c,
                    &wq.w4,
                );
                u_dc_levels = dcu;
                v_dc_levels = dcv;
                u_ac_levels = acu;
                v_ac_levels = acv;
                u_recon_residual = ru;
                v_recon_residual = rv;
                let any_dc_nz =
                    u_dc_levels.iter().any(|&v| v != 0) || v_dc_levels.iter().any(|&v| v != 0);
                let any_ac_nz = u_ac_levels.iter().any(|blk| blk.iter().any(|&v| v != 0))
                    || v_ac_levels.iter().any(|blk| blk.iter().any(|&v| v != 0));
                cbp_chroma = if any_ac_nz {
                    2
                } else if any_dc_nz {
                    1
                } else {
                    0
                };
            }
        }

        // 7. P_Skip eligibility:
        //    * chosen MV must equal the §8.4.1.2 skip-MV
        //    * cbp_luma == 0 AND cbp_chroma == 0
        //    * skip_ref_idx == 0 (always 0 for our single-ref slice)
        let _ = skip_ref;
        // §7.4.5 — P_Skip infers refIdxL0 = 0 (§8.4.1.1), so a
        // macroblock predicting from another reference is never
        // skipped.
        let is_skip = ref_idx == 0 && chosen_mv == skip_mv && cbp_luma == 0 && cbp_chroma == 0;

        if is_skip {
            // P_Skip: do NOT emit any MB syntax; just bump pending_skip
            // and update grid state for neighbour lookups.
            *pending_skip += 1;

            // Update mv_grid: P_Skip MB carries its derived (skip_mv, ref=0)
            // — the same MV applies to all four 8x8 partitions.
            *mv_grid.slot_mut(mb_x, mb_y) = MvGridSlot {
                available: true,
                is_intra: false,
                ref_idx_l0_8x8: [0; 4],
                mv_l0_8x8: [skip_mv; 4],
            };

            // Update intra_grid: P_Skip is not intra, not I_NxN.
            let s = intra_grid.slot_mut(mb_x, mb_y);
            s.available = true;
            s.is_i_nxn = false;

            // Update nc_grid: P_Skip neighbour contributes nN=0 (§9.2.1.1
            // step 6).
            {
                let cur = &mut nc_grid.mbs[mb_addr];
                cur.is_available = true;
                cur.is_intra = false;
                cur.is_skip = true;
                cur.is_i_pcm = false;
                cur.luma_total_coeff = [0u8; 16];
                cur.cb_total_coeff = [0u8; 8];
                cur.cr_total_coeff = [0u8; 8];
            }

            // Apply the inter predictor to the recon (no residual).
            for j in 0..16usize {
                for i in 0..16usize {
                    let py = mb_y * 16 + j;
                    let px = mb_x * 16 + i;
                    recon_y[py * width + px] = pred_y[j * 16 + i].clamp(0, 255) as u8;
                }
            }
            let (ct_w, ct_h) = chroma_tile_dims(chroma_array_type);
            for j in 0..ct_h {
                for i in 0..ct_w {
                    let cy = mb_y * ct_h + j;
                    let cx = mb_x * ct_w + i;
                    recon_u[cy * chroma_width + cx] = pred_u[j * ct_w + i].clamp(0, 255) as u8;
                    recon_v[cy * chroma_width + cx] = pred_v[j * ct_w + i].clamp(0, 255) as u8;
                }
            }
            let _ = chroma_height;

            // Populate per-4x4 MV + per-8x8 ref_idx for the deblock
            // walker's different_ref_or_mv_luma. P_Skip uses skip_mv +
            // ref=0; ref_poc=0 (POC of the single IDR ref).
            let mv_t = (
                skip_mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                skip_mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            );
            return MbDeblockInfo {
                is_intra: false,
                // §7.4.5 — a skipped MB carries no mb_qp_delta; its
                // QP_Y (used by the §8.7 deblock strength derivation)
                // is the decoder's running QP, not this row's target.
                qp_y: qp_tracker.cur,
                luma_nonzero_4x4: 0,
                chroma_nonzero_4x4: 0,
                mv_l0: [mv_t; 16],
                ref_idx_l0: [0; 4],
                ref_poc_l0: [ref_key; 4],
                ..Default::default()
            };
        }

        // P_L0_16x16: flush any pending skip-run, then emit the coded MB.
        sw.ue(*pending_skip);
        *pending_skip = 0;
        qp_tracker.write_pending_mbaff_flag(sw);

        // mvd = chosen_mv - mvp.
        let mvd_x = chosen_mv.x - mvp.x;
        let mvd_y = chosen_mv.y - mvp.y;

        // Apply luma reconstruction now that cbp_luma is known.
        // For 8x8 quadrants whose cbp bit is 0, the decoder reconstructs
        // pred + 0 (no residual). Mirror that here.
        for blk8 in 0..4usize {
            let send = (cbp_luma >> blk8) & 1 == 1;
            for sub in 0..4usize {
                let blk = blk8 * 4 + sub;
                let (bx, by) = LUMA_4X4_BLK[blk];
                let bx_pix = bx * 4;
                let by_pix = by * 4;
                for j in 0..4usize {
                    for i in 0..4usize {
                        let p = pred_y[(by_pix + j) * 16 + bx_pix + i];
                        let r = if send {
                            recon_block_residual[blk][j * 4 + i]
                        } else {
                            0
                        };
                        let py = mb_y * 16 + by_pix + j;
                        let px = mb_x * 16 + bx_pix + i;
                        recon_y[py * width + px] = (p + r).clamp(0, 255) as u8;
                    }
                }
            }
        }
        match chroma_array_type {
            // Round-448 — 4:0:0: nothing to reconstruct.
            0 => {}
            3 => {
                // §7.3.5.3 — per-plane luma-like recon: pred + residual
                // on coded quadrants, pred-only elsewhere (mirror of
                // the luma loop above).
                for (pred, fwd, recon) in [
                    (&pred_u, &cb444, &mut *recon_u),
                    (&pred_v, &cr444, &mut *recon_v),
                ] {
                    for blk8 in 0..4usize {
                        let send = (cbp_luma >> blk8) & 1 == 1;
                        for sub in 0..4usize {
                            let blk = blk8 * 4 + sub;
                            let (bx, by) = LUMA_4X4_BLK[blk];
                            for j in 0..4usize {
                                for i in 0..4usize {
                                    let p = pred[(by * 4 + j) * 16 + bx * 4 + i];
                                    let r = if send {
                                        fwd.recon_residual[blk][j * 4 + i]
                                    } else {
                                        0
                                    };
                                    let cy = mb_y * 16 + by * 4 + j;
                                    let cx = mb_x * 16 + bx * 4 + i;
                                    recon[cy * chroma_width + cx] = (p + r).clamp(0, 255) as u8;
                                }
                            }
                        }
                    }
                }
            }
            2 => {
                for j in 0..16usize {
                    for i in 0..8usize {
                        let cy = mb_y * 16 + j;
                        let cx = mb_x * 8 + i;
                        let pu = pred_u[j * 8 + i];
                        let pv = pred_v[j * 8 + i];
                        let res_u = if cbp_chroma == 0 {
                            0
                        } else {
                            u_recon_res_422[j * 8 + i]
                        };
                        let res_v = if cbp_chroma == 0 {
                            0
                        } else {
                            v_recon_res_422[j * 8 + i]
                        };
                        recon_u[cy * chroma_width + cx] = (pu + res_u).clamp(0, 255) as u8;
                        recon_v[cy * chroma_width + cx] = (pv + res_v).clamp(0, 255) as u8;
                    }
                }
            }
            _ => {
                for j in 0..8usize {
                    for i in 0..8usize {
                        let cy = mb_y * 8 + j;
                        let cx = mb_x * 8 + i;
                        let pu = pred_u[j * 8 + i];
                        let pv = pred_v[j * 8 + i];
                        let res_u = if cbp_chroma == 0 {
                            0
                        } else {
                            u_recon_residual[j * 8 + i]
                        };
                        let res_v = if cbp_chroma == 0 {
                            0
                        } else {
                            v_recon_residual[j * 8 + i]
                        };
                        recon_u[cy * chroma_width + cx] = (pu + res_u).clamp(0, 255) as u8;
                        recon_v[cy * chroma_width + cx] = (pv + res_v).clamp(0, 255) as u8;
                    }
                }
            }
        }
        let _ = chroma_height;

        // CAVLC neighbour-grid update (per §9.2.1.1).
        {
            let cur = &mut nc_grid.mbs[mb_addr];
            cur.is_available = true;
            cur.is_intra = false;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }

        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(
                nc_grid,
                mb_addr as u32,
                blk as u8,
                LumaNcKind::Ac,
                true,
                false,
            );
            luma_4x4_nc[blk] = nc;
            if (cbp_luma >> blk8) & 1 == 1 {
                let tc = luma_4x4_levels_scan[blk]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8;
                own_totals[blk] = tc;
            } else {
                own_totals[blk] = 0;
            }
        }
        nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;

        // §7.3.5 — mb_qp_delta is present iff the MB has coded
        // residual (cbp != 0). Only then does the decoder's QP_Y
        // advance to this MB's QP; a cbp==0 MB transmits no delta and
        // keeps the predecessor QP (its dequant is a no-op anyway).
        let mb_qp_delta = if cbp_luma > 0 || cbp_chroma > 0 {
            let d = qp_y - qp_tracker.cur;
            qp_tracker.cur = qp_y;
            d
        } else {
            0
        };

        // Emit the MB syntax — per-format chroma layout + §9.2.1.1 nC
        // with grid totals commit (round-397).
        let mb_cfg = PL016x16McbConfig {
            ref_idx_l0: ref_idx as u32,
            transform_size_8x8_flag: if self.cfg.transform_8x8 {
                Some(transform_size_8x8)
            } else {
                None
            },
            mvd_l0_x: mvd_x,
            mvd_l0_y: mvd_y,
            cbp_luma,
            cbp_chroma,
            mb_qp_delta,
            luma_4x4_levels: luma_4x4_levels_scan,
            luma_4x4_nc,
            chroma_dc_cb: [0; 4],
            chroma_dc_cr: [0; 4],
            chroma_ac_cb: [[0; 16]; 4],
            chroma_ac_cr: [[0; 16]; 4],
            chroma_ac_nc_cb: [0; 8],
            chroma_ac_nc_cr: [0; 8],
        };
        let _ = luma_4x4_quant_raster; // already folded into recon_block_residual
        match chroma_array_type {
            // Round-448 — 4:0:0: luma-only P_L0_16x16 syntax; the
            // Table 9-4(b) inter CBP column applies (shared with 4:4:4).
            0 => {
                crate::encoder::macroblock::write_p_l0_16x16_mb_chroma(
                    sw,
                    &mb_cfg,
                    qp_tracker.num_ref_idx_l0_active_minus1(),
                    0,
                    crate::encoder::macroblock::ChromaWriteKind::Mono,
                )
                .expect("write P_L0_16x16 mb (4:0:0)");
            }
            3 => {
                let cb_nc = derive_plane_nc_444_inter(
                    nc_grid,
                    mb_addr as u32,
                    false,
                    cbp_luma,
                    &cb444.levels_scan,
                );
                let cr_nc = derive_plane_nc_444_inter(
                    nc_grid,
                    mb_addr as u32,
                    true,
                    cbp_luma,
                    &cr444.levels_scan,
                );
                crate::encoder::macroblock::write_p_l0_16x16_mb_chroma(
                    sw,
                    &mb_cfg,
                    qp_tracker.num_ref_idx_l0_active_minus1(),
                    3,
                    crate::encoder::macroblock::ChromaWriteKind::Yuv444Inter {
                        cb_levels: &cb444.levels_scan,
                        cr_levels: &cr444.levels_scan,
                        cb_nc: &cb_nc,
                        cr_nc: &cr_nc,
                        cbp_luma,
                    },
                )
                .expect("write P_L0_16x16 mb (4:4:4)");
            }
            2 => {
                let (nc_cb, nc_cr) = derive_chroma_ac_nc_and_commit_totals(
                    nc_grid,
                    mb_addr as u32,
                    false,
                    cbp_chroma,
                    &u_ac8,
                    &v_ac8,
                    2,
                );
                crate::encoder::macroblock::write_p_l0_16x16_mb_chroma(
                    sw,
                    &mb_cfg,
                    qp_tracker.num_ref_idx_l0_active_minus1(),
                    2,
                    crate::encoder::macroblock::ChromaWriteKind::Yuv422 {
                        chroma_dc_cb: &u_dc8,
                        chroma_dc_cr: &v_dc8,
                        chroma_ac_cb: &u_ac8,
                        chroma_ac_cr: &v_ac8,
                        cb_ac_nc: &nc_cb,
                        cr_ac_nc: &nc_cr,
                    },
                )
                .expect("write P_L0_16x16 mb (4:2:2)");
            }
            _ => {
                let (chroma_nc_cb, chroma_nc_cr) = derive_chroma_ac_nc_and_commit_totals(
                    nc_grid,
                    mb_addr as u32,
                    false,
                    cbp_chroma,
                    &u_ac_levels,
                    &v_ac_levels,
                    1,
                );
                crate::encoder::macroblock::write_p_l0_16x16_mb_chroma(
                    sw,
                    &mb_cfg,
                    qp_tracker.num_ref_idx_l0_active_minus1(),
                    1,
                    crate::encoder::macroblock::ChromaWriteKind::Yuv420 {
                        chroma_dc_cb: &u_dc_levels,
                        chroma_dc_cr: &v_dc_levels,
                        chroma_ac_cb: &u_ac_levels,
                        chroma_ac_cr: &v_ac_levels,
                        cb_ac_nc: &chroma_nc_cb,
                        cr_ac_nc: &chroma_nc_cr,
                    },
                )
                .expect("write P_L0_16x16 mb");
            }
        }

        // Update mv_grid + intra_grid for subsequent MBs. P_L0_16x16
        // → all four 8x8 partitions carry the same MV / ref_idx.
        *mv_grid.slot_mut(mb_x, mb_y) = MvGridSlot {
            available: true,
            is_intra: false,
            ref_idx_l0_8x8: [ref_idx; 4],
            mv_l0_8x8: [chosen_mv; 4],
        };
        let s = intra_grid.slot_mut(mb_x, mb_y);
        s.available = true;
        s.is_i_nxn = false;

        // Per-4x4 nonzero mask for the §8.7 deblock walker (4:2:0 —
        // 4 blocks per plane at bits 0..=3 / 8..=11; 4:2:2 — 8 blocks
        // at bits 0..=7 / 8..=15; 4:4:4 — deblocking disabled, mask
        // unused).
        let luma_nonzero_4x4 = luma_nz_mask_from_blocks(&blk_has_nz);
        let chroma_nonzero_4x4: u16 = match chroma_array_type {
            0 | 3 => 0,
            2 => {
                let mut m = 0u16;
                for blk in 0..8usize {
                    if cbp_chroma == 2 && u_ac8[blk].iter().any(|&v| v != 0) {
                        m |= 1 << blk;
                    }
                    if cbp_chroma == 2 && v_ac8[blk].iter().any(|&v| v != 0) {
                        m |= 1 << (8 + blk);
                    }
                }
                m
            }
            _ => {
                let cb_nz: [bool; 4] = std::array::from_fn(|i| {
                    cbp_chroma == 2 && u_ac_levels[i].iter().any(|&v| v != 0)
                });
                let cr_nz: [bool; 4] = std::array::from_fn(|i| {
                    cbp_chroma == 2 && v_ac_levels[i].iter().any(|&v| v != 0)
                });
                chroma_nz_mask_from_blocks(&cb_nz, &cr_nz)
            }
        };

        let mv_t = (
            chosen_mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            chosen_mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        );
        MbDeblockInfo {
            is_intra: false,
            // §7.4.5 chain: qp_tracker.cur is qp_y when this MB coded
            // residual (delta emitted above) and the inherited QP when
            // cbp == 0.
            qp_y: qp_tracker.cur,
            luma_nonzero_4x4,
            chroma_nonzero_4x4,
            transform_size_8x8_flag: transform_size_8x8,
            mv_l0: [mv_t; 16],
            ref_idx_l0: [ref_idx as i8; 4],
            ref_poc_l0: [ref_key; 4],
            ..Default::default()
        }
    }

    /// Round-19 — encode one P-slice MB using **4MV** P_8x8 with all
    /// four sub_mb_type set to PL08x8. Mirrors `encode_p_mb`'s post-ME
    /// pipeline (residual + recon + grid update + emit) but with a
    /// per-8x8 luma + chroma predictor and the §8.4.1.3 MVpred derived
    /// **per partition** (with within-MB neighbour reads as the four
    /// sub-blocks decode in raster order 0→1→2→3).
    #[allow(clippy::too_many_arguments)]
    fn encode_p_mb_4mv(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        _me_luma: &[u8],
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid: &mut MvGrid,
        pending_skip: &mut u32,
        qp_tracker: &mut MbQpTracker,
        me_4mv: [crate::encoder::me::MeResult; 4],
    ) -> MbDeblockInfo {
        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;
        let chroma_w = prev.width / 2;
        let chroma_h = prev.height / 2;
        let _ = chroma_height;
        // Round-453 — reference election + §8.7.2.1 NOTE 1 identity key.
        let ref_idx = qp_tracker.ref_idx_l0;
        let ref_key = prev.pic_order_cnt.wrapping_mul(4);

        // 1. Per-8x8 chosen MVs (in qpel) and per-partition mvds against
        //    the §8.4.1.3 within-MB-aware MVpred.
        let mvs: [Mv; 4] = std::array::from_fn(|i| Mv::new(me_4mv[i].mv_x, me_4mv[i].mv_y));
        let mut mvds: [(i32, i32); 4] = [(0, 0); 4];
        let mut inflight_avail = [false; 4];
        let mut mv_inflight = [Mv::ZERO; 4];
        let mut ref_inflight = [-1i32; 4];
        for sub_idx in 0..4usize {
            let mvp = mvp_for_p_8x8_partition(
                mv_grid,
                mb_x,
                mb_y,
                sub_idx,
                ref_idx,
                inflight_avail,
                mv_inflight,
                ref_inflight,
            );
            mvds[sub_idx] = (mvs[sub_idx].x - mvp.x, mvs[sub_idx].y - mvp.y);
            inflight_avail[sub_idx] = true;
            mv_inflight[sub_idx] = mvs[sub_idx];
            ref_inflight[sub_idx] = ref_idx;
        }

        // 2. Build composite per-8x8 luma predictor.
        let mut pred_y = [0i32; 256];
        for (sub_idx, &mv) in mvs.iter().enumerate() {
            let sub_x = sub_idx % 2;
            let sub_y = sub_idx / 2;
            let p = build_inter_pred_luma_8x8(
                prev.recon_y,
                prev.width,
                prev.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv,
            );
            for j in 0..8usize {
                for i in 0..8usize {
                    pred_y[(sub_y * 8 + j) * 16 + sub_x * 8 + i] = p[j * 8 + i];
                }
            }
        }

        // Round-453 — §8.4.2.3.2 explicit luma weighting of the
        // composite predictor (the process is per-sample, so the
        // per-partition assembly order is immaterial).
        if let Some(wp) = qp_tracker.wp_l0 {
            wp.apply(&mut pred_y);
        }

        // 3. Build composite per-(4x4) chroma predictor (4:2:0).
        let mut pred_u = [0i32; 64];
        let mut pred_v = [0i32; 64];
        for (sub_idx, &mv) in mvs.iter().enumerate() {
            let sub_x = sub_idx % 2;
            let sub_y = sub_idx / 2;
            // §8.4.1.4 Table 8-10 — cross-parity field reference
            // chroma-MV adjustment (0 for frame coding).
            let cmv = Mv::new(mv.x, mv.y + self.cfg.table_8_10_cy_offset);
            let pu = build_inter_pred_chroma_4x4(
                prev.recon_u,
                chroma_w,
                chroma_h,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                cmv,
            );
            let pv = build_inter_pred_chroma_4x4(
                prev.recon_v,
                chroma_w,
                chroma_h,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                cmv,
            );
            for j in 0..4usize {
                for i in 0..4usize {
                    pred_u[(sub_y * 4 + j) * 8 + sub_x * 4 + i] = pu[j * 4 + i];
                    pred_v[(sub_y * 4 + j) * 8 + sub_x * 4 + i] = pv[j * 4 + i];
                }
            }
        }

        // 4. Forward + quantize luma residual (§8.5.9 inter
        //    weightScale — round-391).
        let wq = self.cfg.scaling_matrix.inter_weights();
        let inter_luma = forward_inter_luma(frame.y, width, mb_x, mb_y, &pred_y, qp_y, &wq.w4);
        let luma_4x4_levels_scan = inter_luma.levels_scan;
        let blk_has_nz = inter_luma.blk_has_nz;
        let recon_block_residual = inter_luma.recon_residual;

        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            let any_nz = (0..4).any(|sub| blk_has_nz[blk8 * 4 + sub]);
            if any_nz {
                cbp_luma |= 1u8 << blk8;
            }
        }

        // 5. Forward + quantize chroma residual.
        let (u_dc_levels, u_ac_levels, u_recon_residual) =
            encode_chroma_residual_inter(frame.u, chroma_width, mb_x, mb_y, &pred_u, qp_c, &wq.w4);
        let (v_dc_levels, v_ac_levels, v_recon_residual) =
            encode_chroma_residual_inter(frame.v, chroma_width, mb_x, mb_y, &pred_v, qp_c, &wq.w4);
        let any_dc_nz = u_dc_levels.iter().any(|&v| v != 0) || v_dc_levels.iter().any(|&v| v != 0);
        let any_ac_nz = u_ac_levels.iter().any(|blk| blk.iter().any(|&v| v != 0))
            || v_ac_levels.iter().any(|blk| blk.iter().any(|&v| v != 0));
        let cbp_chroma: u8 = if any_ac_nz {
            2
        } else if any_dc_nz {
            1
        } else {
            0
        };

        // P_8x8 cannot be P_Skip (P_Skip is single-MV by definition);
        // always emit the MB. Flush pending skip-run first.
        sw.ue(*pending_skip);
        *pending_skip = 0;
        qp_tracker.write_pending_mbaff_flag(sw);

        // 6. Apply luma reconstruction (pred + residual or pred-only on
        //    cbp_luma=0 quadrants).
        for blk8 in 0..4usize {
            let send = (cbp_luma >> blk8) & 1 == 1;
            for sub in 0..4usize {
                let blk = blk8 * 4 + sub;
                let (bx, by) = LUMA_4X4_BLK[blk];
                let bx_pix = bx * 4;
                let by_pix = by * 4;
                for j in 0..4usize {
                    for i in 0..4usize {
                        let p = pred_y[(by_pix + j) * 16 + bx_pix + i];
                        let r = if send {
                            recon_block_residual[blk][j * 4 + i]
                        } else {
                            0
                        };
                        let py = mb_y * 16 + by_pix + j;
                        let px = mb_x * 16 + bx_pix + i;
                        recon_y[py * width + px] = (p + r).clamp(0, 255) as u8;
                    }
                }
            }
        }
        for j in 0..8usize {
            for i in 0..8usize {
                let cy = mb_y * 8 + j;
                let cx = mb_x * 8 + i;
                let pu = pred_u[j * 8 + i];
                let pv = pred_v[j * 8 + i];
                let res_u = if cbp_chroma == 0 {
                    0
                } else {
                    u_recon_residual[j * 8 + i]
                };
                let res_v = if cbp_chroma == 0 {
                    0
                } else {
                    v_recon_residual[j * 8 + i]
                };
                recon_u[cy * chroma_width + cx] = (pu + res_u).clamp(0, 255) as u8;
                recon_v[cy * chroma_width + cx] = (pv + res_v).clamp(0, 255) as u8;
            }
        }

        // 7. CAVLC neighbour-grid update.
        {
            let cur = &mut nc_grid.mbs[mb_addr];
            cur.is_available = true;
            cur.is_intra = false;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }

        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(
                nc_grid,
                mb_addr as u32,
                blk as u8,
                LumaNcKind::Ac,
                true,
                false,
            );
            luma_4x4_nc[blk] = nc;
            if (cbp_luma >> blk8) & 1 == 1 {
                let tc = luma_4x4_levels_scan[blk]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8;
                own_totals[blk] = tc;
            } else {
                own_totals[blk] = 0;
            }
        }
        nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;

        // §9.2.1.1 — per-block chroma-AC nC + grid totals commit.
        let (chroma_nc_cb, chroma_nc_cr) = derive_chroma_ac_nc_and_commit_totals(
            nc_grid,
            mb_addr as u32,
            false,
            cbp_chroma,
            &u_ac_levels,
            &v_ac_levels,
            1,
        );

        // 8. Emit P_8x8 syntax.
        let mb_cfg = P8x8AllPL08x8McbConfig {
            ref_idx_l0: ref_idx as u32,
            // §7.3.5 — inside a transform_8x8_mode_flag=1 stream the
            // all-PL08x8 4MV MB codes transform_size_8x8_flag = 0 when
            // cbp_luma > 0 (this path keeps 4x4 residual coding).
            emit_transform_size_8x8_zero: self.cfg.transform_8x8,
            mvd_l0: mvds,
            cbp_luma,
            cbp_chroma,
            // §7.3.5 — present iff cbp != 0; see encode_p_mb.
            mb_qp_delta: {
                if cbp_luma > 0 || cbp_chroma > 0 {
                    let d = qp_y - qp_tracker.cur;
                    qp_tracker.cur = qp_y;
                    d
                } else {
                    0
                }
            },
            luma_4x4_levels: luma_4x4_levels_scan,
            luma_4x4_nc,
            chroma_dc_cb: u_dc_levels,
            chroma_dc_cr: v_dc_levels,
            chroma_ac_cb: u_ac_levels,
            chroma_ac_cr: v_ac_levels,
            chroma_ac_nc_cb: chroma_nc_cb,
            chroma_ac_nc_cr: chroma_nc_cr,
        };
        write_p_8x8_all_pl08x8_mb(sw, &mb_cfg, qp_tracker.num_ref_idx_l0_active_minus1())
            .expect("write P_8x8 mb");

        // 9. Update mv_grid + intra_grid for subsequent MBs.
        *mv_grid.slot_mut(mb_x, mb_y) = MvGridSlot {
            available: true,
            is_intra: false,
            ref_idx_l0_8x8: [ref_idx; 4],
            mv_l0_8x8: mvs,
        };
        let s = intra_grid.slot_mut(mb_x, mb_y);
        s.available = true;
        s.is_i_nxn = false;

        // 10. Per-4x4 nonzero mask + per-partition MVs for the §8.7
        //     deblock walker. Each 8x8 partition maps to four 4x4 blocks
        //     all sharing the same MV.
        let luma_nonzero_4x4 = luma_nz_mask_from_blocks(&blk_has_nz);
        let cb_nz: [bool; 4] =
            std::array::from_fn(|i| cbp_chroma == 2 && u_ac_levels[i].iter().any(|&v| v != 0));
        let cr_nz: [bool; 4] =
            std::array::from_fn(|i| cbp_chroma == 2 && v_ac_levels[i].iter().any(|&v| v != 0));

        let mut mv_l0 = [(0i16, 0i16); 16];
        for blk in 0..16usize {
            let (bx, by) = LUMA_4X4_BLK[blk];
            let sub_idx = 2 * (by / 2) + (bx / 2);
            let mv = mvs[sub_idx];
            mv_l0[blk] = (
                mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            );
        }

        MbDeblockInfo {
            is_intra: false,
            // §7.4.5 chain — see encode_p_mb.
            qp_y: qp_tracker.cur,
            luma_nonzero_4x4,
            chroma_nonzero_4x4: chroma_nz_mask_from_blocks(&cb_nz, &cr_nz),
            mv_l0,
            ref_idx_l0: [ref_idx as i8; 4],
            ref_poc_l0: [ref_key; 4],
            ..Default::default()
        }
    }

    /// Round-29 — encode one P-slice MB with optional **Intra_16x16
    /// fallback** RDO (per §7.3.5 Table 7-13 mb_type values 6..=29).
    ///
    /// When [`EncoderConfig::intra_in_inter`] is true, snapshot the
    /// pre-state, run the inter pipeline (`encode_p_mb`), measure
    /// `J_inter = D_inter + λ·R_inter`, snapshot the post-state, restore
    /// pre-state, run an Intra_16x16 trial, measure `J_intra` the same
    /// way, and install the lower-J winner. When false, just call the
    /// inter pipeline directly.
    ///
    /// The intra trial reuses the already-reconstructed prior MBs from
    /// `recon_y` for §8.3.3 neighbour samples — same as the IDR path.
    /// On winner-is-intra the encoder skips emitting `mvd_l0` and
    /// updates `mv_grid` with `is_intra = true` so subsequent inter MBs'
    /// §8.4.1.3.2 step-2 collapse fires.
    #[allow(clippy::too_many_arguments)]
    fn encode_p_mb_with_intra_fallback(
        &self,
        frame: &YuvFrame<'_>,
        prev: &EncodedFrameRef<'_>,
        me_luma: &[u8],
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid: &mut MvGrid,
        pending_skip: &mut u32,
        qp_tracker: &mut MbQpTracker,
    ) -> MbDeblockInfo {
        // Round-397 — the Intra_16x16-in-inter trial body is
        // 4:2:0-only (its chroma trial + snapshot windows are 8x8);
        // 4:2:2 / 4:4:4 P-slices take the pure-inter path.
        if !self.cfg.intra_in_inter || self.cfg.chroma_format_idc != 1 {
            return self.encode_p_mb(
                frame,
                prev,
                me_luma,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                chroma_height,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mv_grid,
                pending_skip,
                qp_tracker,
            );
        }

        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;

        // -- Snapshot pre-state. --
        let snap_pre = InterMbStateSnapshot::capture_p(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mv_grid,
            mb_addr,
            width_mbs,
            *pending_skip,
        );
        let pre_bits = sw.bits_emitted();
        // The trial writes advance the §7.4.5 QP chain; snapshot it
        // alongside the other rollback state.
        let qp_tracker_pre = *qp_tracker;

        // -- Trial 1: inter (P_Skip / P_L0_16x16 / P_8x8). --
        let inter_dbl = self.encode_p_mb(
            frame,
            prev,
            me_luma,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mv_grid,
            pending_skip,
            qp_tracker,
        );
        let inter_bits = sw.bits_emitted() - pre_bits;
        let inter_d = ssd_16x16(frame.y, width, mb_x * 16, mb_y * 16, &{
            let mut buf = [0i32; 256];
            for j in 0..16usize {
                for i in 0..16usize {
                    buf[j * 16 + i] = recon_y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
                }
            }
            buf
        });
        let lambda = lambda_ssd(qp_y, false);
        let j_inter = cost_combined(inter_d, inter_bits as u64, lambda);

        // Capture post-inter state.
        let snap_inter = InterMbStateSnapshot::capture_p(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mv_grid,
            mb_addr,
            width_mbs,
            *pending_skip,
        );

        let qp_tracker_inter = *qp_tracker;

        // -- Restore pre-state for the intra trial. --
        snap_pre.restore_p(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mv_grid,
            mb_addr,
            pending_skip,
        );
        *qp_tracker = qp_tracker_pre;

        // -- Trial 2: Intra_16x16 in P-slice. --
        let intra_dbl = self.encode_p_mb_intra16x16(
            qp_tracker,
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mv_grid,
            pending_skip,
        );
        let intra_bits = sw.bits_emitted() - pre_bits;
        let intra_d = ssd_16x16(frame.y, width, mb_x * 16, mb_y * 16, &{
            let mut buf = [0i32; 256];
            for j in 0..16usize {
                for i in 0..16usize {
                    buf[j * 16 + i] = recon_y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
                }
            }
            buf
        });
        let j_intra = cost_combined(intra_d, intra_bits as u64, lambda);

        // -- Pick winner. --
        if j_inter <= j_intra {
            // Roll back the intra trial; install the inter results.
            snap_pre.restore_p(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mv_grid,
                mb_addr,
                pending_skip,
            );
            snap_inter.restore_p(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mv_grid,
                mb_addr,
                pending_skip,
            );
            *qp_tracker = qp_tracker_inter;
            inter_dbl
        } else {
            intra_dbl
        }
    }

    /// Round-29 — Intra_16x16 fallback for a P-slice MB. Picks the best
    /// §8.3.3 mode by SAD against the reconstructed neighbour samples
    /// (top/left of the current frame's already-encoded MBs), forward
    /// 4x4 + Hadamard + quantize, encodes chroma, and emits the MB syntax
    /// via [`write_intra16x16_mb_in_inter_slice`] with `mb_type_offset =
    /// 5` (Table 7-13). Updates `mv_grid` with `is_intra = true` so
    /// subsequent inter MBs' §8.4.1.3.2 step-2 collapses.
    ///
    /// Round-29 scope: 4:2:0 only (encode_p / encode_b are 4:2:0-only).
    #[allow(clippy::too_many_arguments)]
    fn encode_p_mb_intra16x16(
        &self,
        qp_tracker: &mut MbQpTracker,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid: &mut MvGrid,
        pending_skip: &mut u32,
    ) -> MbDeblockInfo {
        // Flush any pending P_Skip run before emitting a coded MB.
        sw.ue(*pending_skip);
        *pending_skip = 0;
        qp_tracker.write_pending_mbaff_flag(sw);

        // §7.3.5 — Intra_16x16 always codes the luma DC block, so
        // mb_qp_delta is always present: emit the step from the
        // decoder's current QP_Y to this MB's QP and advance the
        // tracker.
        let mb_qp_delta = qp_y - qp_tracker.cur;
        qp_tracker.cur = qp_y;

        // Delegate the heavy lifting to a writer that targets the
        // P-slice mb_type table (offset = 5).
        self.encode_intra16x16_in_inter_slice(
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            5,
            mb_qp_delta,
            qp_tracker.intra_nb,
        );

        // Update MV grid: intra MB contributes (mv=0, ref=-1) per
        // §8.4.1.3.2 step 2.
        *mv_grid.slot_mut(mb_x, mb_y) = MvGridSlot {
            available: true,
            is_intra: true,
            ref_idx_l0_8x8: [-1; 4],
            mv_l0_8x8: [Mv::ZERO; 4],
        };

        // §8.7.2.1 — per-4x4 deblock mask. For Intra_16x16, when
        // cbp_luma == 15 every 4x4 block carries AC; when cbp_luma == 0
        // only the DC plane is sent. We approximate by setting all 16
        // bits when any AC coefficient exists post-quantize, mirroring
        // the IDR Intra_16x16 path. Look up the actual bit from the
        // nc_grid we just populated.
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;
        let any_nz = nc_grid.mbs[mb_addr]
            .luma_total_coeff
            .iter()
            .any(|&v| v != 0);
        let luma_nonzero_4x4: u16 = if any_nz {
            let mut nz = [false; 16];
            for (blkz, slot) in nz.iter_mut().enumerate() {
                *slot = nc_grid.mbs[mb_addr].luma_total_coeff[blkz] != 0;
            }
            luma_nz_mask_from_blocks(&nz)
        } else {
            0
        };

        MbDeblockInfo {
            is_intra: true,
            // Intra_16x16 always emitted mb_qp_delta, so the chain QP
            // equals qp_y here.
            qp_y: qp_tracker.cur,
            luma_nonzero_4x4,
            chroma_nonzero_4x4: 0,
            ..Default::default()
        }
    }

    /// Round-29 — shared Intra_16x16 emitter used by both the P-slice
    /// (`mb_type_offset = 5`) and B-slice (`mb_type_offset = 23`)
    /// fallback paths. Picks the best §8.3.3 luma mode + best §8.3.4
    /// chroma mode by Lagrangian RDO (luma) / SAD (chroma), runs the
    /// forward + quantize + inverse pipeline, writes the MB syntax via
    /// [`write_intra16x16_mb_in_inter_slice`], and updates `recon_*`,
    /// `nc_grid`, `intra_grid`. Caller is responsible for `mv_grid`
    /// updates, `pending_skip` flush, and the deblock-info return.
    #[allow(clippy::too_many_arguments)]
    fn encode_intra16x16_in_inter_slice(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mb_type_offset: u32,
        mb_qp_delta: i32,
        nb: Option<(bool, bool, bool)>,
    ) {
        let width = self.cfg.width as usize;
        let height = self.cfg.height as usize;
        let lambda = lambda_ssd(qp_y, true);
        // §8.5.9 — an intra MB in a P/B slice quantises / dequantises
        // under the INTRA weightScale lists (round-391).
        let wq = self.cfg.scaling_matrix.intra_weights();

        // Pick best luma mode by RDO (mirrors encode_mb_intra16x16's
        // luma-mode loop, with neighbour reads against `recon_y` which
        // has already been populated by prior MBs).
        let mut best_luma_mode = I16x16Mode::Dc;
        let mut best_luma_pred = [0i32; 256];
        let mut best_luma_cost = u64::MAX;
        for &mode in &[
            I16x16Mode::Vertical,
            I16x16Mode::Horizontal,
            I16x16Mode::Dc,
            I16x16Mode::Plane,
        ] {
            let Some(pred) = predict_16x16_avail(mode, recon_y, width, height, mb_x, mb_y, nb)
            else {
                continue;
            };
            let cost = trial_intra16x16_cost(frame, &pred, mb_x, mb_y, qp_y, width, lambda, &wq.w4);
            if cost < best_luma_cost {
                best_luma_cost = cost;
                best_luma_mode = mode;
                best_luma_pred = pred;
            }
        }

        // Build luma residual against chosen predictor.
        let mut residual = [0i32; 256];
        for j in 0..16usize {
            for i in 0..16usize {
                let s = frame.y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
                residual[j * 16 + i] = s - best_luma_pred[j * 16 + i];
            }
        }
        let mut coeffs_4x4 = [[0i32; 16]; 16];
        for (blk, slot) in coeffs_4x4.iter_mut().enumerate() {
            let bx = blk % 4;
            let by = blk / 4;
            let mut block = [0i32; 16];
            for j in 0..4 {
                for i in 0..4 {
                    block[j * 4 + i] = residual[(by * 4 + j) * 16 + bx * 4 + i];
                }
            }
            *slot = forward_core_4x4(&block);
        }
        let mut dc_coeffs = [0i32; 16];
        for (blk, c) in coeffs_4x4.iter().enumerate() {
            let bx = blk % 4;
            let by = blk / 4;
            dc_coeffs[by * 4 + bx] = c[0];
        }
        let dc_t = forward_hadamard_4x4(&dc_coeffs);
        let dc_levels = quantize_luma_dc_w(&dc_t, qp_y, true, wq.w4[0]);

        // Per-block AC quantize.
        let mut luma_ac_levels = [[0i32; 16]; 16];
        let mut luma_ac_quant_raster = [[0i32; 16]; 16];
        let mut any_luma_ac_nz = false;
        for blkz in 0..16usize {
            let (bx, by) = LUMA_4X4_BLK[blkz];
            let raster = by * 4 + bx;
            let z = quantize_4x4_ac_w(&coeffs_4x4[raster], qp_y, true, &wq.w4);
            luma_ac_quant_raster[raster] = z;
            let scan_ac = zigzag_scan_4x4_ac(&z);
            luma_ac_levels[blkz] = scan_ac;
            if scan_ac.iter().any(|&v| v != 0) {
                any_luma_ac_nz = true;
            }
        }
        let cbp_luma: u8 = if any_luma_ac_nz { 15 } else { 0 };

        // Inverse path → recon_y.
        let inv_dc =
            inverse_hadamard_luma_dc_16x16(&dc_levels, qp_y, &wq.w4, 8).expect("luma DC inverse");
        #[allow(clippy::needless_range_loop)]
        for blk in 0..16usize {
            let bx = blk % 4;
            let by = blk / 4;
            let mut coeffs_in = if cbp_luma == 15 {
                luma_ac_quant_raster[blk]
            } else {
                [0i32; 16]
            };
            coeffs_in[0] = inv_dc[by * 4 + bx];
            let r = inverse_transform_4x4_dc_preserved(&coeffs_in, qp_y, &wq.w4, 8)
                .expect("inverse 4x4");
            for j in 0..4 {
                for i in 0..4 {
                    let px = mb_x * 16 + bx * 4 + i;
                    let py = mb_y * 16 + by * 4 + j;
                    let p = best_luma_pred[(by * 4 + j) * 16 + bx * 4 + i];
                    let raw = p + r[j * 4 + i];
                    recon_y[py * width + px] = raw.clamp(0, 255) as u8;
                }
            }
        }

        // Chroma path (4:2:0 only on this round).
        let chroma_block = encode_chroma_block(
            self.cfg.chroma_format_idc,
            frame.u,
            frame.v,
            recon_u,
            recon_v,
            chroma_width,
            chroma_height,
            mb_x,
            mb_y,
            qp_c,
            &wq.w4,
            nb,
        );
        let cbp_chroma = chroma_block.cbp_chroma;
        let best_chroma_mode_u8 = chroma_block.pred_mode.as_u8();
        install_chroma_recon(
            self.cfg.chroma_format_idc,
            chroma_width,
            mb_x,
            mb_y,
            &chroma_block,
            recon_u,
            recon_v,
        );
        let _ = chroma_height;

        let mut u_dc_levels = [0i32; 4];
        let mut v_dc_levels = [0i32; 4];
        let mut u_ac_levels = [[0i32; 16]; 4];
        let mut v_ac_levels = [[0i32; 16]; 4];
        u_dc_levels.copy_from_slice(&chroma_block.dc_cb[..4]);
        v_dc_levels.copy_from_slice(&chroma_block.dc_cr[..4]);
        u_ac_levels.copy_from_slice(&chroma_block.ac_cb[..4]);
        v_ac_levels.copy_from_slice(&chroma_block.ac_cr[..4]);

        // CAVLC neighbour-grid update for this MB (Intra16x16 → mark as
        // intra so subsequent MBs' nC derivation reads the correct
        // TotalCoeff). Done before per-block nC derivation so internal
        // neighbours within the MB read the freshly-zeroed totals.
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;
        {
            let cur = &mut nc_grid.mbs[mb_addr];
            cur.is_available = true;
            cur.is_intra = true;
            cur.is_skip = false;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }
        let nc_dc = derive_nc_luma(
            nc_grid,
            mb_addr as u32,
            0,
            LumaNcKind::Intra16x16Dc,
            true,
            false,
        );
        let mut luma_ac_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blkz in 0..16u8 {
            nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(nc_grid, mb_addr as u32, blkz, LumaNcKind::Ac, true, false);
            luma_ac_nc[blkz as usize] = nc;
            if cbp_luma == 15 {
                let tc = luma_ac_levels[blkz as usize]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8;
                own_totals[blkz as usize] = tc;
            }
        }
        nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;

        // §9.2.1.1 — per-block chroma-AC nC + grid totals commit.
        let (chroma_nc_cb, chroma_nc_cr) = derive_chroma_ac_nc_and_commit_totals(
            nc_grid,
            mb_addr as u32,
            true,
            cbp_chroma,
            &u_ac_levels,
            &v_ac_levels,
            1,
        );

        // Emit MB syntax.
        let mb_cfg = I16x16McbConfig {
            pred_mode: best_luma_mode.as_u8(),
            intra_chroma_pred_mode: best_chroma_mode_u8,
            cbp_luma,
            cbp_chroma,
            mb_qp_delta,
            luma_dc_levels_raster: dc_levels,
            luma_ac_levels,
            luma_ac_nc,
            chroma_dc_cb: u_dc_levels,
            chroma_dc_cr: v_dc_levels,
            chroma_ac_cb: u_ac_levels,
            chroma_ac_cr: v_ac_levels,
            chroma_ac_nc_cb: chroma_nc_cb,
            chroma_ac_nc_cr: chroma_nc_cr,
        };
        write_intra16x16_mb_in_inter_slice(
            sw,
            &mb_cfg,
            mb_type_offset,
            CoeffTokenContext::Numeric(nc_dc),
        )
        .expect("write Intra_16x16 in inter slice");

        // Mark intra grid: available + not-i_nxn so subsequent I_NxN
        // neighbour lookups fall to DC (mode = 2).
        let s = intra_grid.slot_mut(mb_x, mb_y);
        s.available = true;
        s.is_i_nxn = false;

        // Suppress unused.
        let _ = best_luma_cost;
    }
}

/// Borrowed view of a previously-encoded frame's reconstruction. Used as
/// the reference for [`Encoder::encode_p`] and [`Encoder::encode_b`].
///
/// `partition_mvs` carries per-8x8 colocated MV / refIdx data when this
/// reference is being used as the **L1 anchor** of a B-slice (round-21
/// spatial direct mode needs it for §8.4.1.2.2 step 7 colZeroFlag).
/// For non-B-slice users (`encode_p`) the field is ignored. An empty
/// slice is treated as "all intra colocated" (colZeroFlag = 0).
///
/// `pic_order_cnt` (round-24) is the picture order count this reference
/// was assigned at encode time, needed by §8.4.1.2.3 temporal direct
/// derivation (the POCs of pic0 = L0[refIdxL0] and pic1 = L1[0] feed
/// the `tb` / `td` distance computation). For IDR derived from
/// `EncodedIdr` it defaults to 0 (POC type 0, IDR's
/// `pic_order_cnt_lsb` is forced to 0). For P derived from
/// `EncodedP` it is `2 * pic_order_cnt_lsb` matching the encoder's
/// frame-coding convention (`TopFieldOrderCnt = pic_order_cnt_lsb`,
/// frame POC = min(top, bottom) = top in our setup).
pub struct EncodedFrameRef<'a> {
    pub width: u32,
    pub height: u32,
    pub recon_y: &'a [u8],
    pub recon_u: &'a [u8],
    pub recon_v: &'a [u8],
    /// Per-8x8 partition MVs, length = `(width / 16) * (height / 16) * 4`,
    /// or empty when no MV data is available (IDR / treat as all-intra).
    pub partition_mvs: &'a [FrameRefPartitionMv],
    /// §8.2.1 picture order count of this reference. Used by §8.4.1.2.3
    /// temporal direct (round 24); ignored by spatial direct.
    pub pic_order_cnt: i32,
}

impl<'a> From<&'a EncodedIdr> for EncodedFrameRef<'a> {
    fn from(e: &'a EncodedIdr) -> Self {
        Self {
            width: e.recon_width,
            height: e.recon_height,
            recon_y: &e.recon_y,
            recon_u: &e.recon_u,
            recon_v: &e.recon_v,
            partition_mvs: &e.partition_mvs,
            pic_order_cnt: 0, // §8.2.1.1 / §7.4.3 — IDR's pic_order_cnt_lsb is 0.
        }
    }
}

impl<'a> From<&'a EncodedP> for EncodedFrameRef<'a> {
    fn from(e: &'a EncodedP) -> Self {
        Self {
            width: e.recon_width,
            height: e.recon_height,
            recon_y: &e.recon_y,
            recon_u: &e.recon_u,
            recon_v: &e.recon_v,
            partition_mvs: &e.partition_mvs,
            pic_order_cnt: e.pic_order_cnt_lsb as i32,
        }
    }
}

/// Forward-quantize-inverse output for one inter MB's luma residual.
///
/// * `levels_scan[blk]` — the 16 coefficients in zig-zag scan order for
///   CAVLC emit.
/// * `quant_raster[blk]` — the same coefficients in 4x4 raster (for
///   inverse path / debug).
/// * `blk_has_nz[blk]` — true iff the block has at least one non-zero
///   coefficient (drives cbp_luma quadrant decision).
/// * `recon_residual[blk]` — the reconstructed 16 sample residuals for
///   this 4x4 block (post-inverse), ready to be added to the predictor.
#[derive(Default)]
struct InterLumaForward {
    levels_scan: [[i32; 16]; 16],
    quant_raster: [[i32; 16]; 16],
    blk_has_nz: [bool; 16],
    recon_residual: [[i32; 16]; 16],
}

/// Round-382 — §8.6.4 forward 8x8 transform + §8.5.13.1 quantisation of
/// an inter MB's luma residual (one transform per 8x8 quadrant instead
/// of sixteen 4x4s). Outputs use the same per-4x4-Z-index layout as
/// [`InterLumaForward`] so the caller's recon / CAVLC / nC machinery is
/// shared between the two transform sizes:
///
/// * `levels_scan[blk8*4 + i4x4]` — the §7.4.5.3.3 de-interleaved
///   four-4x4 CAVLC split of quadrant `blk8`'s 8x8 zig-zag scan list.
/// * `blk_has_nz[blk]` — every 4x4 of a quadrant inherits the
///   quadrant's nonzero status (mirrors the decoder's §8.7.2.1 mask).
/// * `recon_residual[blk]` — the §8.5.13 reconstructed residual of the
///   4x4 sub-tile at Z-index `blk`, sliced from the quadrant's 8x8
///   inverse transform.
#[allow(clippy::too_many_arguments)]
fn forward_inter_luma_8x8(
    src_y: &[u8],
    src_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 256],
    qp_y: i32,
    w8: &[i32; 64],
    field_scan: bool,
) -> InterLumaForward {
    let mut levels_scan = [[0i32; 16]; 16];
    let mut blk_has_nz = [false; 16];
    let mut recon_residual = [[0i32; 16]; 16];

    for blk8 in 0..4usize {
        let qx = (blk8 % 2) * 8;
        let qy = (blk8 / 2) * 8;
        let mut res = [0i32; 64];
        for j in 0..8 {
            for i in 0..8 {
                let s = src_y[(mb_y * 16 + qy + j) * src_stride + (mb_x * 16 + qx + i)] as i32;
                res[j * 8 + i] = s - pred[(qy + j) * 16 + qx + i];
            }
        }
        let w = forward_core_8x8(&res);
        let z = quantize_8x8_w(&w, qp_y, false, w8);
        let any_nz = z.iter().any(|&v| v != 0);
        let scan = scan_8x8_for_cavlc(&z, field_scan);
        let subs = deinterleave_8x8_to_4x4(&scan);
        for (i4x4, sub) in subs.iter().enumerate() {
            levels_scan[blk8 * 4 + i4x4] = *sub;
            blk_has_nz[blk8 * 4 + i4x4] = any_nz;
        }
        let r = inverse_transform_8x8(&z, qp_y, w8, 8).expect("inv 8x8");
        // Slice the 8x8 residual into the quadrant's four 4x4 Z-index
        // sub-tiles (§6.4.3: within a quadrant, Z order is TL, TR, BL,
        // BR 4x4 tiles).
        for sub in 0..4usize {
            let sx = (sub % 2) * 4;
            let sy = (sub / 2) * 4;
            let mut tile = [0i32; 16];
            for j in 0..4 {
                for i in 0..4 {
                    tile[j * 4 + i] = r[(sy + j) * 8 + sx + i];
                }
            }
            recon_residual[blk8 * 4 + sub] = tile;
        }
    }
    InterLumaForward {
        levels_scan,
        quant_raster: [[0i32; 16]; 16],
        blk_has_nz,
        recon_residual,
    }
}

/// Round-382 — luma Lagrangian cost `J = D + λ·R` of one inter-MB luma
/// coding alternative (4x4 vs 8x8 transform). `D` is the SSD between
/// the source MB and `pred + recon_residual` with non-transmitted
/// quadrants (cbp bit 0) contributing `pred + 0`; `R` is the trial
/// CAVLC bit count of the transmitted blocks at nC = 0 (stable
/// estimate, same policy as the intra mode trials).
#[allow(clippy::too_many_arguments)]
fn inter_luma_transform_cost(
    src_y: &[u8],
    src_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 256],
    fwd: &InterLumaForward,
    cbp_luma: u8,
    lambda: f64,
) -> u64 {
    let mut d: u64 = 0;
    for (blk, &(bx, by)) in LUMA_4X4_BLK.iter().enumerate() {
        let send = (cbp_luma >> (blk / 4)) & 1 == 1;
        for j in 0..4usize {
            for i in 0..4usize {
                let p = pred[(by * 4 + j) * 16 + bx * 4 + i];
                let r = if send {
                    fwd.recon_residual[blk][j * 4 + i]
                } else {
                    0
                };
                let recon = (p + r).clamp(0, 255);
                let s =
                    src_y[(mb_y * 16 + by * 4 + j) * src_stride + (mb_x * 16 + bx * 4 + i)] as i32;
                let e = (s - recon) as i64;
                d += (e * e) as u64;
            }
        }
    }
    let mut trial_w = BitWriter::new();
    for blk in 0..16usize {
        if (cbp_luma >> (blk / 4)) & 1 == 1 {
            let _ = encode_residual_block_cavlc(
                &mut trial_w,
                CoeffTokenContext::Numeric(0),
                16,
                &fwd.levels_scan[blk],
            );
        }
    }
    cost_combined(d, trial_w.bits_emitted() as u64, lambda)
}

/// Forward 4x4 + AC quantization for an inter MB's luma residual. Inter
/// MBs do NOT use the Intra_16x16 luma DC Hadamard — every 4x4 block is
/// transmitted as a full DC+AC residual block.
fn forward_inter_luma(
    src_y: &[u8],
    src_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 256],
    qp_y: i32,
    w4: &[i32; 16],
) -> InterLumaForward {
    // Build sample residual against the predictor.
    let mut residual = [0i32; 256];
    for j in 0..16usize {
        for i in 0..16usize {
            let s = src_y[(mb_y * 16 + j) * src_stride + (mb_x * 16 + i)] as i32;
            residual[j * 16 + i] = s - pred[j * 16 + i];
        }
    }

    let mut levels_scan = [[0i32; 16]; 16];
    let mut quant_raster = [[0i32; 16]; 16];
    let mut blk_has_nz = [false; 16];
    let mut recon_residual = [[0i32; 16]; 16];

    for blkz in 0..16usize {
        let (bx, by) = LUMA_4X4_BLK[blkz];
        let mut block = [0i32; 16];
        for j in 0..4 {
            for i in 0..4 {
                block[j * 4 + i] = residual[(by * 4 + j) * 16 + bx * 4 + i];
            }
        }
        // Forward 4x4 + full quantize (includes DC; inter uses the
        // standard quantizer per §8.5.10).
        let w = forward_core_4x4(&block);
        let z = quantize_4x4_w(&w, qp_y, false, w4);
        let scan = zigzag_scan_4x4(&z);
        levels_scan[blkz] = scan;
        quant_raster[blkz] = z;
        blk_has_nz[blkz] = z.iter().any(|&v| v != 0);

        // Inverse path (§8.5.9 weightScale-aware — round-391) so we
        // know the recon's residual for the block.
        let r = inverse_transform_4x4(&z, qp_y, w4, 8).expect("inv 4x4");
        recon_residual[blkz] = r;
    }
    InterLumaForward {
        levels_scan,
        quant_raster,
        blk_has_nz,
        recon_residual,
    }
}

// ---------------------------------------------------------------------------
// Round 20 — B-slice support (B_L0_16x16 / B_L1_16x16 / B_Bi_16x16).
// Round 21 — B_Skip / B_Direct_16x16 (spatial direct mode).
//
// Round-20 scope: explicit-inter only; one 16x16 partition per MB; no
// B_Skip / B_Direct; one reference per list (L0 = the IDR, L1 = the prior
// P-frame), `weighted_bipred_idc = 0` so bipred uses default
// `(L0+L1+1)>>1` per §8.4.2.3.1 eq. 8-273.
//
// Round-21 adds **spatial direct mode**:
//   * `B_Direct_16x16` (raw mb_type 0): no mvd_lN / ref_idx_lN in the
//     bitstream; decoder derives MVs per §8.4.1.2.2 from the encoder's
//     L0 / L1 MV grids + the colocated picture's L0 MV.
//   * `B_Skip` (signalled by `mb_skip_run`): same MV derivation as
//     B_Direct_16x16 but with cbp_luma = cbp_chroma = 0 and no MB syntax
//     at all — pure run-length skip.
//
// The encoder mirrors the decoder's §8.4.1.2.2 derivation locally and
// emits B_Direct / B_Skip when:
//   1. The derived predictor's SAD beats the round-20 explicit-inter
//      (B_L0 / B_L1 / B_Bi) candidates, AND
//   2. (For B_Skip) the residual quantises to all-zero (cbp == 0).
//
// `colZeroFlag` (§8.4.1.2.2 step 7) requires the colocated picture's
// per-block L0 MV. The L1 reference (a prior P-frame) supplies these
// via `EncodedFrameRef::partition_mvs`. For an IDR L1 (all-intra), the
// step-7 check returns colZeroFlag = 0 for every block.
//
// Spec sections cited:
//   §7.3.3                 — slice_header() (B-slice fields)
//   §7.3.4                 — slice_data() with mb_skip_run (B_Skip)
//   §7.3.5.1               — mb_pred() with mvd_l0 / mvd_l1
//   §7.4.5 Table 7-14      — B-slice mb_type ∈ {0..=3} mapping
//   §8.4.1.2               — direct-mode predicted MV derivation entry
//   §8.4.1.2.1             — colocated block selection (L0 vs L1 MV)
//   §8.4.1.2.2             — spatial direct MV derivation (5..7)
//   §8.4.1.3               — derivation of mvpLX (separate for L0 / L1)
//   §8.4.1.3.1             — median MV prediction
//   §8.4.1.3.2             — C→D substitution
//   §8.4.2.3.1 eq. 8-273   — default weighted bi-prediction average
//   §8.4.2.2.1             — luma 6-tap fractional sample interpolation
//   §8.4.1.4               — chroma MV derivation from luma (4:2:0)
//   §8.7.2.1 NOTE 2        — bipred edge bS derivation (drives deblock)
//   §A.2                   — profile_idc must be ≥ 77 for B-slices
// ---------------------------------------------------------------------------

/// §8.4.1.2.2 — encoder-side spatial direct derivation result.
///
/// Each MB's direct mode produces one (refIdxL0, refIdxL1, mvL0, mvL1)
/// per 8x8 sub-partition (when `direct_8x8_inference_flag = 1`). When all
/// four 8x8 partitions resolve to the same `(ref, ref, mv, mv)` we can
/// build a single 16x16 predictor; otherwise we'd need per-partition
/// motion compensation. Round-21 only emits B_Direct / B_Skip when all
/// four partitions agree (the common case under directZeroPredictionFlag
/// or when neighbours are zero-MV propagating).
#[derive(Debug, Clone, Copy)]
struct BDirectDerivation {
    ref_idx_l0: i32,
    ref_idx_l1: i32,
    /// Per-8x8 MV (4 entries) for L0. `Mv::ZERO` when `ref_idx_l0 < 0`.
    mv_l0_per_8x8: [Mv; 4],
    /// Per-8x8 MV (4 entries) for L1. `Mv::ZERO` when `ref_idx_l1 < 0`.
    mv_l1_per_8x8: [Mv; 4],
    /// True when `directZeroPredictionFlag` fired (§8.4.1.2.2 step 5).
    direct_zero: bool,
}

impl BDirectDerivation {
    /// True iff every 8x8 partition shares the same MV (and thus the
    /// 16x16 predictor is uniform across the MB). Round-21 only emits
    /// `B_Direct_16x16` / `B_Skip` for this case.
    fn is_uniform(&self) -> bool {
        let l0_uniform = self
            .mv_l0_per_8x8
            .iter()
            .all(|m| *m == self.mv_l0_per_8x8[0]);
        let l1_uniform = self
            .mv_l1_per_8x8
            .iter()
            .all(|m| *m == self.mv_l1_per_8x8[0]);
        l0_uniform && l1_uniform
    }

    /// Read the uniform per-MB L0 MV (only meaningful when `is_uniform()`).
    fn mv_l0(&self) -> Mv {
        self.mv_l0_per_8x8[0]
    }

    /// Read the uniform per-MB L1 MV (only meaningful when `is_uniform()`).
    fn mv_l1(&self) -> Mv {
        self.mv_l1_per_8x8[0]
    }
}

/// §8.4.1.2.2 step 7 — colZeroFlag check.
///
/// Returns true iff the colocated 8x8 partition (from L1's
/// `partition_mvs`) is short-term-coded with `refIdxCol == 0` and
/// `|mvCol| <= 1` in both components.
///
/// Per §8.4.1.2.1, when the colocated MB is intra mvCol=0 / refIdxCol=-1,
/// and colZeroFlag is forced to 0 (the `is_intra` branch). When
/// `partition_mvs` is empty (e.g. an IDR L1 anchor with no MV data
/// recorded), we treat all colocated blocks as intra → colZeroFlag = 0.
fn col_zero_flag(
    l1_partition_mvs: &[FrameRefPartitionMv],
    width_mbs: usize,
    mb_x: usize,
    mb_y: usize,
    part_8x8: usize,
) -> bool {
    let idx = (mb_y * width_mbs + mb_x) * 4 + part_8x8;
    let Some(slot) = l1_partition_mvs.get(idx) else {
        // No MV data → treat as intra → colZeroFlag = 0.
        return false;
    };
    if slot.is_intra {
        return false;
    }
    // §8.4.1.2.1 step 1.2 — picks L0's MV by default when refIdxL0Col >= 0.
    // Our encoder's L1 anchor is a P-slice with single L0 ref so this is
    // always the available data.
    if slot.ref_idx_l0 != 0 {
        return false;
    }
    // §8.4.1.2.2 step 7 — colZeroFlag iff |mvCol| <= 1 in both components.
    slot.mv_l0.0.abs() <= 1 && slot.mv_l0.1.abs() <= 1
}

/// §8.4.1.2.2 — encoder-side spatial direct MV / refIdx derivation for
/// the current MB. Mirrors the decoder's `build_spatial_direct_partitions`
/// using the encoder's (`mv_grid_l0`, `mv_grid_l1`) state and the L1
/// anchor's `partition_mvs` for the step-7 colZeroFlag check.
///
/// Implements:
///   * step 4 — MinPositive(refIdxL0A, refIdxL0B, refIdxL0C) for both
///     lists, with §8.4.1.3.2 C→D substitution applied first.
///   * step 5 — `directZeroPredictionFlag` when both lists' MinPositive
///     output is < 0; both refs collapse to 0, both MVs to (0, 0).
///   * step 6 — per-partition MV derivation: median MVpred from the
///     A/B/C neighbours unless `direct_zero` or `refIdxLX < 0`.
///   * step 7 — per-8x8 colZeroFlag short-circuit: when refIdxLX == 0
///     AND colZeroFlag fires, that list's MV for that partition is 0.
///
/// `direct_8x8_inference_flag = 1` is hard-wired in our SPS so the
/// granularity is 8x8 (4 partitions per MB).
fn b_spatial_direct_derive(
    mv_grid_l0: &MvGrid,
    mv_grid_l1: &MvGrid,
    l1_partition_mvs: &[FrameRefPartitionMv],
    width_mbs: usize,
    mb_x: usize,
    mb_y: usize,
) -> BDirectDerivation {
    // §8.4.1.2.2 step 2-3 — MB-level (A, B, C, D) for both lists.
    let (a_l0, b_l0, c_l0, d_l0) = neighbour_mvs_16x16(mv_grid_l0, mb_x, mb_y);
    let (a_l1, b_l1, c_l1, d_l1) = neighbour_mvs_16x16(mv_grid_l1, mb_x, mb_y);

    // Run the §8.4.1.2.2 step 4-5 derivation through the helper to get
    // ref_idx_l0/l1 + the MB-level mvL0/mvL1 (subject to step 7
    // override below). The helper returns refIdx >= 0 for both lists
    // when directZero fires, but with `direct_zero = (mv == 0)` the
    // caller can detect the fallback by re-checking the MinPositive
    // result independently.
    let (ref_idx_l0_helper, mv_l0_mb, ref_idx_l1_helper, mv_l1_mb) =
        crate::mv_deriv::derive_b_spatial_direct_with_d(
            a_l0, a_l1, b_l0, b_l1, c_l0, c_l1, d_l0, d_l1,
        );

    // Repeat the step-4 MinPositive chain locally to detect directZero
    // (the helper folds it into the output).
    let c_l0_eff = if !c_l0.partition_available && d_l0.partition_available {
        d_l0
    } else {
        c_l0
    };
    let c_l1_eff = if !c_l1.partition_available && d_l1.partition_available {
        d_l1
    } else {
        c_l1
    };
    let min_pos = |x: i32, y: i32| -> i32 {
        if x >= 0 && y >= 0 {
            x.min(y)
        } else {
            x.max(y)
        }
    };
    let r0_minp = min_pos(a_l0.ref_idx, min_pos(b_l0.ref_idx, c_l0_eff.ref_idx));
    let r1_minp = min_pos(a_l1.ref_idx, min_pos(b_l1.ref_idx, c_l1_eff.ref_idx));
    let direct_zero = r0_minp < 0 && r1_minp < 0;

    let ref_idx_l0_final: i32 = if direct_zero {
        0
    } else if r0_minp < 0 {
        -1
    } else {
        ref_idx_l0_helper
    };
    let ref_idx_l1_final: i32 = if direct_zero {
        0
    } else if r1_minp < 0 {
        -1
    } else {
        ref_idx_l1_helper
    };

    // §8.4.1.2.2 step 6/7 — per 8x8 partition MV derivation.
    let mut mv_l0_per_8x8 = [Mv::ZERO; 4];
    let mut mv_l1_per_8x8 = [Mv::ZERO; 4];
    for part in 0..4usize {
        let cz = col_zero_flag(l1_partition_mvs, width_mbs, mb_x, mb_y, part);
        // §8.4.1.2.2 step 6/7 — three forced-zero conditions per list
        // (directZero, refIdx<0, refIdx==0 AND colZeroFlag); otherwise
        // the MB-level median MV applies.
        let l0_force_zero = direct_zero || ref_idx_l0_final < 0 || (ref_idx_l0_final == 0 && cz);
        let l1_force_zero = direct_zero || ref_idx_l1_final < 0 || (ref_idx_l1_final == 0 && cz);
        mv_l0_per_8x8[part] = if l0_force_zero { Mv::ZERO } else { mv_l0_mb };
        mv_l1_per_8x8[part] = if l1_force_zero { Mv::ZERO } else { mv_l1_mb };
    }

    BDirectDerivation {
        ref_idx_l0: ref_idx_l0_final,
        ref_idx_l1: ref_idx_l1_final,
        mv_l0_per_8x8,
        mv_l1_per_8x8,
        direct_zero,
    }
}

// ---------------------------------------------------------------------------
// Round 24 — §8.4.1.2.3 B-slice **temporal direct** derivation (encoder side).
//
// Temporal direct mode (`direct_spatial_mv_pred_flag = 0`) replaces the
// §8.4.1.2.2 spatial MV / refIdx derivation with a POC-distance-driven
// scaling of the colocated picture's L0 motion vectors:
//
//   pic1 = colocated picture = RefPicList1[0]   (the L1 anchor)
//   pic0 = RefPicList0[refIdxL0]                 (the L0 reference picked by
//                                                 MapColToList0(refIdxCol))
//   td = Clip3(-128, 127, DiffPicOrderCnt(pic1, pic0))
//   tb = Clip3(-128, 127, DiffPicOrderCnt(currPicOrField, pic0))
//   tx = (16384 + |td/2|) / td
//   DistScaleFactor = Clip3(-1024, 1023, (tb*tx + 32) >> 6)
//   mvL0 = (DistScaleFactor*mvCol + 128) >> 8
//   mvL1 = mvL0 - mvCol
//
// `MapColToList0` (eq. 8-191) maps the colocated block's `refIdxCol` (an
// index into the colocated picture's RefPicList0) into the current
// slice's RefPicList0 by **picture identity (POC)**. Our encoder uses a
// single L0 reference per B-slice (the IDR), so MapColToList0 collapses
// to "the current slice's RefPicList0[0] = the IDR" whenever the
// colocated MB's refIdxCol == 0, and to refIdxL0 = 0 when refIdxCol < 0
// (the "directZero" fallback per eq. 8-191's first branch).
//
// `direct_8x8_inference_flag = 1` in our SPS, so the granularity is
// 4 partitions per MB (one (mvL0, mvL1) per 8x8). The 4x4 sub-grid
// within each 8x8 carries the same MV — same convention the spatial
// path uses.
//
// Spec sections cited:
//   §8.4.1.2.1     — colocated block / picture selection (Table 8-6)
//   §8.4.1.2.3     — temporal direct MV derivation (eq. 8-191..8-202)
//   §8.4.1.2 NOTE 3 — direct_8x8_inference_flag = 1 → per-8x8 granularity
//   §8.2.1         — DiffPicOrderCnt (frame coding ⇒ POC subtract)
// ---------------------------------------------------------------------------

/// §8.4.1.2.3 — encoder-side temporal direct derivation for one MB.
///
/// Mirrors the decoder's `derive_temporal_direct_mvs_for_block` for our
/// constrained encoder setup:
///   * Single L0 reference per B-slice (the IDR / older anchor).
///   * Single L1 reference per B-slice (the prior P-frame).
///   * `direct_8x8_inference_flag = 1` → 4 partitions per MB.
///   * `MapColToList0` collapses to identity when refIdxCol == 0 (the
///     IDR is at index 0 of both the L1 anchor's RefPicList0 and the
///     current B's RefPicList0); else falls back to refIdxL0 = 0.
///   * Long-term refs not used (encoder emits only short-term) — the
///     long-term shortcut never fires.
///
/// `curr_poc` / `pic0_poc` / `pic1_poc` are picture order counts.
/// For our POC type 0 frame-coded encoder these equal the
/// `pic_order_cnt_lsb` values shipped in the slice headers.
fn b_temporal_direct_derive(
    l1_partition_mvs: &[FrameRefPartitionMv],
    width_mbs: usize,
    mb_x: usize,
    mb_y: usize,
    curr_poc: i32,
    pic0_poc: i32,
    pic1_poc: i32,
) -> BDirectDerivation {
    // §8.4.1.2.3 / eq. 8-192 — refIdxL1 is always 0 for direct mode
    // (the colocated picture itself is RefPicList1[0]).
    //
    // refIdxL0: see eq. 8-191. Our encoder has a single L0 reference,
    // so MapColToList0(refIdxCol) collapses to 0 whenever the colocated
    // L0 reference matches the IDR (which it always does in our IPB
    // setup — the L1 P-frame's only L0 ref is the IDR). When the
    // colocated block is intra (refIdxCol < 0), eq. 8-191 forces
    // refIdxL0 = 0 as well. Either way refIdxL0 = 0 across the MB.
    let mut mv_l0_per_8x8 = [Mv::ZERO; 4];
    let mut mv_l1_per_8x8 = [Mv::ZERO; 4];

    for part in 0..4usize {
        let idx = (mb_y * width_mbs + mb_x) * 4 + part;
        // Default colocated mv = (0, 0) when no L1 partition data is
        // available (e.g. an IDR L1 anchor — recall §8.4.1.2.1 NOTE
        // for intra colocated MBs: mvCol = 0 / refIdxCol = -1).
        let (mv_col, is_intra) = match l1_partition_mvs.get(idx) {
            Some(slot) if !slot.is_intra => {
                (Mv::new(slot.mv_l0.0 as i32, slot.mv_l0.1 as i32), false)
            }
            _ => (Mv::ZERO, true),
        };
        // §8.4.1.2.3 eq. 8-195/8-196 short-circuit when the colocated
        // block is intra (or when DiffPicOrderCnt(pic1, pic0) == 0,
        // handled inside `derive_b_temporal_direct`): mvL0 = mvCol = 0,
        // mvL1 = 0. Same numerical result either way.
        if is_intra {
            mv_l0_per_8x8[part] = Mv::ZERO;
            mv_l1_per_8x8[part] = Mv::ZERO;
            continue;
        }
        // Forward to the shared §8.4.1.2.3 scaling helper (eq. 8-197..8-200).
        // The helper handles the td == 0 → mvL0 = mvCol / mvL1 = 0
        // shortcut internally.
        let (mv_l0, mv_l1) =
            crate::mv_deriv::derive_b_temporal_direct(mv_col, pic1_poc, curr_poc, pic0_poc);
        mv_l0_per_8x8[part] = mv_l0;
        mv_l1_per_8x8[part] = mv_l1;
    }

    // Both refIdxL0 and refIdxL1 are 0 in our single-ref-per-list setup.
    BDirectDerivation {
        ref_idx_l0: 0,
        ref_idx_l1: 0,
        mv_l0_per_8x8,
        mv_l1_per_8x8,
        direct_zero: false,
    }
}

/// Output of [`Encoder::encode_b`] — a single B-slice access unit and the
/// matching reconstruction. Same layout as [`EncodedP`]; B-frames are
/// non-reference (`nal_ref_idc = 0`) so they do not feed any further
/// inter-coding pass — but we publish the recon anyway for measurement
/// (PSNR vs source) and ffmpeg-interop testing.
pub struct EncodedB {
    pub annex_b: Vec<u8>,
    pub recon_y: Vec<u8>,
    pub recon_u: Vec<u8>,
    pub recon_v: Vec<u8>,
    pub recon_width: u32,
    pub recon_height: u32,
    /// `frame_num` of this B-frame. Per §7.4.3 this matches the B's
    /// position in decode order (NOT display order).
    pub frame_num: u32,
    /// `pic_order_cnt_lsb` of this B-frame — used by the decoder's
    /// §8.2.4 list construction to determine which ref is "before" and
    /// which is "after" in display order.
    pub pic_order_cnt_lsb: u32,
    /// Per-8x8-partition MV state. B-frames are non-reference so this
    /// is normally unused, but is provided for API symmetry.
    pub partition_mvs: Vec<FrameRefPartitionMv>,
    /// Round-382 — number of macroblocks coded with
    /// `transform_size_8x8_flag = 1` (High-profile 8x8 transform).
    /// Always 0 unless [`EncoderConfig::transform_8x8`] is set.
    pub i8x8_mb_count: u32,
}

impl<'a> From<&'a EncodedB> for EncodedFrameRef<'a> {
    fn from(e: &'a EncodedB) -> Self {
        Self {
            width: e.recon_width,
            height: e.recon_height,
            recon_y: &e.recon_y,
            recon_u: &e.recon_u,
            recon_v: &e.recon_v,
            partition_mvs: &e.partition_mvs,
            pic_order_cnt: e.pic_order_cnt_lsb as i32,
        }
    }
}

/// Per-MB chosen B-prediction descriptor — what `encode_b_mb` decides
/// before emitting the macroblock syntax + recon. `mvd_lN` already
/// accounts for the §8.4.1.3 `mvpLN` predictor of the chosen list.
#[derive(Debug, Clone, Copy)]
struct BMbDecision {
    /// Which list(s) this MB references.
    pred: BPred16x16,
    /// Chosen L0 MV (1/4-pel). Always Mv::ZERO when `pred == L1`.
    mv_l0: Mv,
    /// Chosen L1 MV (1/4-pel). Always Mv::ZERO when `pred == L0`.
    mv_l1: Mv,
    /// L0 mvd against the §8.4.1.3 mvp. Zero when L0 unused.
    mvd_l0_x: i32,
    mvd_l0_y: i32,
    /// L1 mvd against the §8.4.1.3 mvp.
    mvd_l1_x: i32,
    mvd_l1_y: i32,
    /// Combined luma predictor (post-§8.4.2.3 weighted-pred merge for
    /// bipred, or one list verbatim for L0-only / L1-only).
    pred_y: [i32; 256],
    /// Combined chroma Cb predictor.
    pred_u: [i32; 64],
    /// Combined chroma Cr predictor.
    pred_v: [i32; 64],
}

/// Round-26 — explicit weighted-bipred merge parameters (luma only).
///
/// When `Some`, `build_b_predictors` replaces the §8.4.2.3.1 default
/// `(L0 + L1 + 1) >> 1` luma merge with the §8.4.2.3.2 explicit formula
/// (eq. 8-276) using these `(weight, offset)` pairs and `log2_wd` denom.
/// Chroma keeps the default merge — our `pred_weight_table()` writer
/// signals `chroma_weight_lN_flag = 0` for every ref so the decoder
/// matches.
#[derive(Debug, Clone, Copy)]
struct WeightedBipredLuma {
    log2_wd: u32,
    weight_l0: i32,
    offset_l0: i32,
    weight_l1: i32,
    offset_l1: i32,
    /// Round-440 — apply the same (w0, w1) pair to the CHROMA merges
    /// too. §8.4.2.3.3 IMPLICIT weighting weights every plane with the
    /// POC-derived pair; the round-26 explicit path keeps chroma on
    /// the §8.4.2.3.1 default average (its pred_weight_table signals
    /// `chroma_weight_lN_flag = 0`).
    apply_chroma: bool,
}

/// §8.4.2.3.2 eq. 8-276 — merge two predictor slices with the
/// (w0, w1, logWD) triple (offsets folded by the caller; the implicit
/// path has none per eq. 8-278/8-279).
#[inline]
fn weighted_bipred_merge(a: i32, b: i32, wp: &WeightedBipredLuma) -> i32 {
    let round = 1i32 << wp.log2_wd;
    let off_avg = (wp.offset_l0 + wp.offset_l1 + 1) >> 1;
    let v = (a * wp.weight_l0 + b * wp.weight_l1 + round) >> (wp.log2_wd + 1);
    (v + off_avg).clamp(0, 255)
}

/// Round-26 — slice-wide weight selector for explicit weighted bipred.
///
/// Models the source luma plane as
///   `src[k] ≈ ((w0 * L0[k] + w1 * L1[k] + 2^logWD) >> (logWD+1)) +
///             ((o0 + o1 + 1) >> 1)`
/// (the §8.4.2.3.2 eq. 8-276 prediction). For a slice-wide constant fit
/// we collapse to a 2-parameter least-squares problem in (α, β):
///   `src ≈ α * L0 + (1 - α) * L1 + β`
/// then quantise α to a denom-32 fraction (`logWD = 5`):
///   `w0 = round(α * 32)`, `w1 = 32 - w0`
/// Offsets are split symmetrically: `o0 = o1 = round(β / 2)`. The fit
/// uses the encoder's mb-aligned regions only — no MV-aware sample
/// matching — which is sufficient for cross-fade content where the two
/// references share spatial structure (no per-MB motion).
///
/// Picks the (w0, w1) pair on a coarse grid `{0, 4, 8, 12, ..., 32}`
/// (9 candidates) by sum-of-squared-error against the source after the
/// §8.4.2.3.2 round-and-clip is applied. Offsets are constrained to
/// the integer least-squares optimum, clamped to ±127 per spec.
///
/// Falls back to the default (16, 16, 0, 0) when the chosen weights
/// don't beat the default merge by at least 1% on SSD — that ensures
/// the bit cost of pred_weight_table doesn't backfire on neutral
/// content. Returns `None`-equivalent default in that case.
#[allow(clippy::too_many_arguments)]
fn compute_explicit_bipred_weights(
    src_y: &[u8],
    ref_l0_y: &[u8],
    ref_l1_y: &[u8],
    width: usize,
    height: usize,
    ref_l0_stride: usize,
    ref_l1_stride: usize,
) -> ExplicitBipredWeightTable {
    const LOG2_WD: u32 = 5; // denom = 32; w0+w1 = 64 for the canonical "α + (1-α) = 1"
    const DENOM: i32 = 1 << (LOG2_WD + 1); // 64

    // Default weights: w0 = w1 = 32 (sum = 64 → α = 0.5 → eq. 8-273).
    let default_table = ExplicitBipredWeightTable {
        luma_log2_weight_denom: LOG2_WD,
        luma_weight_l0: 32,
        luma_offset_l0: 0,
        luma_weight_l1: 32,
        luma_offset_l1: 0,
    };

    // Round-and-clip the §8.4.2.3.2 prediction for a given (w0, w1, o)
    // combo and return the SSE against `src`. `o` is the per-list offset
    // (symmetric: o0 = o1 = o so `(o0+o1+1)>>1` is just o). Used both
    // for the candidate search and for the default-vs-explicit decision.
    let sse_for = |w0: i32, w1: i32, o: i32| -> u64 {
        let mut sse: u64 = 0;
        let logwd_plus1 = LOG2_WD + 1;
        let round = 1i32 << LOG2_WD;
        let off_avg = (o + o + 1) >> 1;
        for j in 0..height {
            for i in 0..width {
                let p0 = ref_l0_y[j * ref_l0_stride + i] as i32;
                let p1 = ref_l1_y[j * ref_l1_stride + i] as i32;
                let v = ((p0 * w0 + p1 * w1 + round) >> logwd_plus1) + off_avg;
                let pred = v.clamp(0, 255);
                let s = src_y[j * width + i] as i32;
                let d = s - pred;
                sse = sse.saturating_add((d * d) as u64);
            }
        }
        sse
    };

    // Coarse grid over α at 1/16 granularity (sum w0+w1 == DENOM = 64).
    // For every candidate w0, also pick the integer offset o that
    // minimises SSE (closed-form: o = round(mean(src - pred_no_offset))).
    let total = (width * height) as f64;
    let mut best_sse = u64::MAX;
    let mut best_w0 = 32i32;
    let mut best_off = 0i32;
    for w0 in (0..=DENOM).step_by(4) {
        let w1 = DENOM - w0;
        // Compute optimal symmetric offset (o0 = o1 = o) by averaging
        // the residual. This is the LS fit for the constant component.
        let mut sum_resid: f64 = 0.0;
        let logwd_plus1 = LOG2_WD + 1;
        let round = 1i32 << LOG2_WD;
        for j in 0..height {
            for i in 0..width {
                let p0 = ref_l0_y[j * ref_l0_stride + i] as i32;
                let p1 = ref_l1_y[j * ref_l1_stride + i] as i32;
                let v = (p0 * w0 + p1 * w1 + round) >> logwd_plus1;
                let s = src_y[j * width + i] as i32;
                sum_resid += (s - v) as f64;
            }
        }
        let o_raw = (sum_resid / total).round() as i32;
        let o = o_raw.clamp(-127, 127);
        let sse = sse_for(w0, w1, o);
        if sse < best_sse {
            best_sse = sse;
            best_w0 = w0;
            best_off = o;
        }
    }

    // Compute the default (16, 16, 0, 0)-equivalent SSE for the
    // accept/reject decision. Note: with w0=w1=32, logWD=5, eq. 8-276
    // simplifies to `(L0 + L1 + 32) >> 6 + 0` which differs from the
    // §8.4.2.3.1 default by one rounding-bit position. To compare
    // apples-to-apples we evaluate the *actual* default merge.
    let mut default_sse: u64 = 0;
    for j in 0..height {
        for i in 0..width {
            let p0 = ref_l0_y[j * ref_l0_stride + i] as i32;
            let p1 = ref_l1_y[j * ref_l1_stride + i] as i32;
            let pred = (p0 + p1 + 1) >> 1;
            let s = src_y[j * width + i] as i32;
            let d = s - pred;
            default_sse = default_sse.saturating_add((d * d) as u64);
        }
    }

    // Accept the chosen weights only if they beat the default by a
    // healthy margin (≥ 1% SSE reduction). This avoids spending the
    // ~30-bit pred_weight_table budget on slices where it doesn't help.
    let margin = default_sse / 100;
    if best_sse + margin >= default_sse {
        return default_table;
    }

    let w1 = DENOM - best_w0;
    ExplicitBipredWeightTable {
        luma_log2_weight_denom: LOG2_WD,
        luma_weight_l0: best_w0,
        luma_offset_l0: best_off,
        luma_weight_l1: w1,
        luma_offset_l1: best_off,
    }
}

/// Build the L0 + L1 luma + chroma predictors for a 16x16 MB given the
/// chosen MVs and the two reference frames. Returns one composite buffer
/// per plane that already incorporates the §8.4.2.3.1 default weighted
/// merge for bipred (`(L0 + L1 + 1) >> 1`). For L0-only / L1-only the
/// returned predictor is just that list's interpolated samples.
///
/// Round-26 — when `weighted` is `Some`, the bipred luma merge instead
/// uses the §8.4.2.3.2 explicit formula (eq. 8-276):
///   `Clip1(((L0*w0 + L1*w1 + 2^logWD) >> (logWD+1)) +
///          ((o0 + o1 + 1) >> 1))`
/// Chroma still uses the default §8.4.2.3.1 average; our slice header
/// emit flags chroma weights as absent so the decoder agrees.
/// Round-453 — slice-wide §8.4.2.3.2 luma weight fit for a P slice
/// with one L0 reference (fade detection).
///
/// Least-squares affine fit of the co-located planes
/// `src ≈ a · ref + b` (no motion compensation — a fade shares
/// spatial structure between the frames), quantised to
/// `logWD = 5`: `w = round(a · 32)`, `o = round(b)`, both clamped to
/// the §7.4.3.2 `-128..=127` range. The pair is elected only when the
/// eq. 8-274 prediction (round + clip applied) beats the identity
/// weighting by at least 1% SSD on the co-located planes; otherwise
/// the table codes `luma_weight_l0_flag = 0` (identity).
fn compute_explicit_p_weight(
    src_y: &[u8],
    ref_y: &[u8],
    width: usize,
    height: usize,
) -> ExplicitPredWeightTableL0 {
    const LOG2_WD: u32 = 5;
    let identity = ExplicitPredWeightTableL0 {
        luma_log2_weight_denom: LOG2_WD,
        luma: None,
    };
    let n = (width * height) as f64;
    if n == 0.0 {
        return identity;
    }
    let (mut sx, mut sr, mut srr, mut sxr) = (0f64, 0f64, 0f64, 0f64);
    for (&x, &r) in src_y.iter().zip(ref_y.iter()) {
        let (x, r) = (x as f64, r as f64);
        sx += x;
        sr += r;
        srr += r * r;
        sxr += x * r;
    }
    let var_r = srr - sr * sr / n;
    let a = if var_r.abs() < 1e-9 {
        1.0
    } else {
        (sxr - sx * sr / n) / var_r
    };
    let b = (sx - a * sr) / n;
    let w = ((a * (1u32 << LOG2_WD) as f64).round() as i32).clamp(-128, 127);
    let o = (b.round() as i32).clamp(-128, 127);
    if w == (1i32 << LOG2_WD) && o == 0 {
        return identity;
    }
    let cand = WeightedPredL0 {
        log2_wd: LOG2_WD,
        weight: w,
        offset: o,
    };
    let (mut ssd_id, mut ssd_w) = (0u64, 0u64);
    let mut buf = [0i32; 1];
    for (&x, &r) in src_y.iter().zip(ref_y.iter()) {
        buf[0] = r as i32;
        cand.apply(&mut buf);
        let d_id = x as i64 - r as i64;
        let d_w = x as i64 - buf[0] as i64;
        ssd_id += (d_id * d_id) as u64;
        ssd_w += (d_w * d_w) as u64;
    }
    if ssd_w * 100 <= ssd_id * 99 {
        ExplicitPredWeightTableL0 {
            luma_log2_weight_denom: LOG2_WD,
            luma: Some((w, o)),
        }
    } else {
        identity
    }
}

#[allow(clippy::too_many_arguments)]
fn build_b_predictors(
    pred: BPred16x16,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    mv_l0: Mv,
    mv_l1: Mv,
    weighted: Option<WeightedBipredLuma>,
) -> ([i32; 256], [i32; 64], [i32; 64]) {
    // Always interpolate from each list it uses; the §8.4.2.3.1 average
    // is bit-equivalent to the sum-then-shift the decoder applies.
    let chroma_w_l0 = ref_l0.width / 2;
    let chroma_h_l0 = ref_l0.height / 2;
    let chroma_w_l1 = ref_l1.width / 2;
    let chroma_h_l1 = ref_l1.height / 2;

    let p_y_l0 = if pred.uses_l0() {
        Some(build_inter_pred_luma(
            ref_l0.recon_y,
            ref_l0.width,
            ref_l0.height,
            mb_x,
            mb_y,
            mv_l0,
        ))
    } else {
        None
    };
    let p_y_l1 = if pred.uses_l1() {
        Some(build_inter_pred_luma(
            ref_l1.recon_y,
            ref_l1.width,
            ref_l1.height,
            mb_x,
            mb_y,
            mv_l1,
        ))
    } else {
        None
    };
    let p_u_l0 = if pred.uses_l0() {
        Some(build_inter_pred_chroma(
            ref_l0.recon_u,
            chroma_w_l0,
            chroma_h_l0,
            mb_x,
            mb_y,
            mv_l0,
        ))
    } else {
        None
    };
    let p_u_l1 = if pred.uses_l1() {
        Some(build_inter_pred_chroma(
            ref_l1.recon_u,
            chroma_w_l1,
            chroma_h_l1,
            mb_x,
            mb_y,
            mv_l1,
        ))
    } else {
        None
    };
    let p_v_l0 = if pred.uses_l0() {
        Some(build_inter_pred_chroma(
            ref_l0.recon_v,
            chroma_w_l0,
            chroma_h_l0,
            mb_x,
            mb_y,
            mv_l0,
        ))
    } else {
        None
    };
    let p_v_l1 = if pred.uses_l1() {
        Some(build_inter_pred_chroma(
            ref_l1.recon_v,
            chroma_w_l1,
            chroma_h_l1,
            mb_x,
            mb_y,
            mv_l1,
        ))
    } else {
        None
    };

    // Merge per pred mode.
    let mut pred_y = [0i32; 256];
    let mut pred_u = [0i32; 64];
    let mut pred_v = [0i32; 64];
    match pred {
        BPred16x16::L0 => {
            pred_y = p_y_l0.unwrap();
            pred_u = p_u_l0.unwrap();
            pred_v = p_v_l0.unwrap();
        }
        BPred16x16::L1 => {
            pred_y = p_y_l1.unwrap();
            pred_u = p_u_l1.unwrap();
            pred_v = p_v_l1.unwrap();
        }
        BPred16x16::Bi => {
            let l0_y = p_y_l0.unwrap();
            let l1_y = p_y_l1.unwrap();
            if let Some(wp) = weighted {
                // §8.4.2.3.2 eq. 8-276 — explicit weighted bipred:
                //   Clip1Y(((L0*w0 + L1*w1 + 2^logWD) >> (logWD+1)) +
                //          ((o0 + o1 + 1) >> 1))
                let logwd = wp.log2_wd;
                let off_avg = (wp.offset_l0 + wp.offset_l1 + 1) >> 1;
                let round = 1i32 << logwd;
                for i in 0..256 {
                    let v =
                        (l0_y[i] * wp.weight_l0 + l1_y[i] * wp.weight_l1 + round) >> (logwd + 1);
                    pred_y[i] = (v + off_avg).clamp(0, 255);
                }
            } else {
                // §8.4.2.3.1 eq. 8-273 — default `(L0 + L1 + 1) >> 1`.
                for i in 0..256 {
                    pred_y[i] = (l0_y[i] + l1_y[i] + 1) >> 1;
                }
            }
            let l0_u = p_u_l0.unwrap();
            let l1_u = p_u_l1.unwrap();
            let l0_v = p_v_l0.unwrap();
            let l1_v = p_v_l1.unwrap();
            match weighted {
                Some(wp) if wp.apply_chroma => {
                    // §8.4.2.3.3 — implicit weights apply to chroma too.
                    for i in 0..64 {
                        pred_u[i] = weighted_bipred_merge(l0_u[i], l1_u[i], &wp);
                        pred_v[i] = weighted_bipred_merge(l0_v[i], l1_v[i], &wp);
                    }
                }
                _ => {
                    for i in 0..64 {
                        pred_u[i] = (l0_u[i] + l1_u[i] + 1) >> 1;
                        pred_v[i] = (l0_v[i] + l1_v[i] + 1) >> 1;
                    }
                }
            }
        }
    }
    (pred_y, pred_u, pred_v)
}

/// Round-23 — per-8x8 prediction kind for a `B_8x8` MB whose four
/// sub-MBs are all `B_Direct_8x8`. Each 8x8 partition gets its own
/// (refIdxL0, refIdxL1, mvL0, mvL1) per §8.4.1.2.2 step 4-7, and the
/// (refIdxL0 >= 0, refIdxL1 >= 0) pair maps to one of the same three
/// merge modes the 16x16 path uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DirectPart8x8 {
    /// L0-only — `refIdxL0 >= 0`, `refIdxL1 == -1`.
    L0,
    /// L1-only — `refIdxL0 == -1`, `refIdxL1 >= 0`.
    L1,
    /// Both lists, default weighted average `(L0 + L1 + 1) >> 1` per
    /// §8.4.2.3.1 eq. 8-273.
    Bi,
    /// Neither list (would only arise for an all-intra colocated source
    /// without `directZeroPredictionFlag` correction). Not expected in
    /// practice — the spatial-direct derivation forces both refs to 0
    /// when neighbours are all unavailable. We treat this as L0-only with
    /// mv=0 to keep a single defined predictor in scope.
    None,
}

impl DirectPart8x8 {
    fn uses_l0(self) -> bool {
        matches!(self, Self::L0 | Self::Bi)
    }
    fn uses_l1(self) -> bool {
        matches!(self, Self::L1 | Self::Bi)
    }
}

/// Round-23 — derive the per-8x8 prediction kind for each of the four
/// sub-MBs of a `B_8x8` macroblock from the §8.4.1.2.2 spatial-direct
/// derivation result.
///
/// With `direct_8x8_inference_flag = 1` (hard-wired in our SPS), the
/// derivation produces one (mvL0, mvL1, refIdxL0, refIdxL1) per 8x8
/// partition. The current `BDirectDerivation` shape carries a single
/// (refIdxL0, refIdxL1) for the whole MB (matching the spec — refIdxLX
/// is MB-level, not per-partition), so the per-8x8 prediction kind only
/// varies when the per-8x8 MV grid disagrees AND we want to honour
/// per-list "off" status when refIdx == -1.
fn direct_per_8x8_kinds(d: &BDirectDerivation) -> [DirectPart8x8; 4] {
    let l0_used = d.ref_idx_l0 >= 0;
    let l1_used = d.ref_idx_l1 >= 0;
    // §8.4.1.2.2 step 7 colZeroFlag can drive a per-list MV to (0,0)
    // even when refIdxLX >= 0; that does NOT change predFlagLX, so
    // L0/L1 still apply at the merge stage. We honour predFlagLX
    // exactly via refIdxLX sign.
    let kind = match (l0_used, l1_used) {
        (true, true) => DirectPart8x8::Bi,
        (true, false) => DirectPart8x8::L0,
        (false, true) => DirectPart8x8::L1,
        (false, false) => DirectPart8x8::None,
    };
    [kind; 4]
}

/// Round-23 — build per-8x8 luma + chroma predictors for a `B_8x8`
/// macroblock with all-`B_Direct_8x8` sub-MBs. Each 8x8 quadrant uses
/// its own (mvL0, mvL1) pair from the §8.4.1.2.2 derivation; the
/// composite is stitched into a 16x16 luma buffer + two 8x8 chroma
/// buffers (matching the `build_b_predictors` shape so the existing
/// residual / reconstruction code works unchanged).
///
/// For each 8x8 quadrant index `q ∈ 0..4` (raster Z-order: top-left,
/// top-right, bottom-left, bottom-right), the per-list 8x8 luma + 4x4
/// chroma predictors are computed via `build_inter_pred_luma_8x8` /
/// `build_inter_pred_chroma_4x4`. Bi-pred uses the same §8.4.2.3.1
/// default weighted average `(L0+L1+1)>>1` as 16x16 / 16x8 / 8x16.
#[allow(clippy::too_many_arguments)]
fn build_b_direct_8x8_predictors(
    weighted: Option<WeightedBipredLuma>,
    kinds: [DirectPart8x8; 4],
    mv_l0_per_8x8: [Mv; 4],
    mv_l1_per_8x8: [Mv; 4],
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
) -> ([i32; 256], [i32; 64], [i32; 64]) {
    let mut pred_y = [0i32; 256];
    let mut pred_u = [0i32; 64];
    let mut pred_v = [0i32; 64];

    let chroma_w_l0 = ref_l0.width / 2;
    let chroma_h_l0 = ref_l0.height / 2;
    let chroma_w_l1 = ref_l1.width / 2;
    let chroma_h_l1 = ref_l1.height / 2;

    // §6.4.3 raster-Z order across the four 8x8 quadrants of an MB:
    //   q=0 → (sub_x=0, sub_y=0)  top-left
    //   q=1 → (sub_x=1, sub_y=0)  top-right
    //   q=2 → (sub_x=0, sub_y=1)  bottom-left
    //   q=3 → (sub_x=1, sub_y=1)  bottom-right
    for q in 0..4usize {
        let sub_x = q % 2;
        let sub_y = q / 2;
        let kind = kinds[q];
        let mv0 = mv_l0_per_8x8[q];
        let mv1 = mv_l1_per_8x8[q];

        // Luma 8x8 predictor for this quadrant.
        let l0_y = if kind.uses_l0() {
            Some(build_inter_pred_luma_8x8(
                ref_l0.recon_y,
                ref_l0.width,
                ref_l0.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv0,
            ))
        } else {
            None
        };
        let l1_y = if kind.uses_l1() {
            Some(build_inter_pred_luma_8x8(
                ref_l1.recon_y,
                ref_l1.width,
                ref_l1.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv1,
            ))
        } else {
            None
        };
        let q_y: [i32; 64] = match kind {
            DirectPart8x8::L0 => l0_y.unwrap(),
            DirectPart8x8::L1 => l1_y.unwrap(),
            DirectPart8x8::Bi => {
                let l0 = l0_y.unwrap();
                let l1 = l1_y.unwrap();
                let mut out = [0i32; 64];
                match weighted {
                    // §8.4.2.3.2/.3.3 — weighted bipred merge.
                    Some(wp) => {
                        for i in 0..64 {
                            out[i] = weighted_bipred_merge(l0[i], l1[i], &wp);
                        }
                    }
                    None => {
                        for i in 0..64 {
                            out[i] = (l0[i] + l1[i] + 1) >> 1;
                        }
                    }
                }
                out
            }
            DirectPart8x8::None => {
                // Defensive fallback — predict from L0 with mv=0.
                build_inter_pred_luma_8x8(
                    ref_l0.recon_y,
                    ref_l0.width,
                    ref_l0.height,
                    mb_x,
                    mb_y,
                    sub_x,
                    sub_y,
                    Mv::ZERO,
                )
            }
        };

        // Chroma 4x4 predictor (4:2:0) for this quadrant.
        let l0_u = if kind.uses_l0() {
            Some(build_inter_pred_chroma_4x4(
                ref_l0.recon_u,
                chroma_w_l0,
                chroma_h_l0,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv0,
            ))
        } else {
            None
        };
        let l0_v = if kind.uses_l0() {
            Some(build_inter_pred_chroma_4x4(
                ref_l0.recon_v,
                chroma_w_l0,
                chroma_h_l0,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv0,
            ))
        } else {
            None
        };
        let l1_u = if kind.uses_l1() {
            Some(build_inter_pred_chroma_4x4(
                ref_l1.recon_u,
                chroma_w_l1,
                chroma_h_l1,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv1,
            ))
        } else {
            None
        };
        let l1_v = if kind.uses_l1() {
            Some(build_inter_pred_chroma_4x4(
                ref_l1.recon_v,
                chroma_w_l1,
                chroma_h_l1,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv1,
            ))
        } else {
            None
        };
        let merge_chroma = |c0: Option<[i32; 16]>, c1: Option<[i32; 16]>| -> [i32; 16] {
            match kind {
                DirectPart8x8::L0 => c0.unwrap(),
                DirectPart8x8::L1 => c1.unwrap(),
                DirectPart8x8::Bi => {
                    let a = c0.unwrap();
                    let b = c1.unwrap();
                    let mut out = [0i32; 16];
                    match weighted {
                        // §8.4.2.3.3 — implicit weights every plane.
                        Some(wp) if wp.apply_chroma => {
                            for i in 0..16 {
                                out[i] = weighted_bipred_merge(a[i], b[i], &wp);
                            }
                        }
                        _ => {
                            for i in 0..16 {
                                out[i] = (a[i] + b[i] + 1) >> 1;
                            }
                        }
                    }
                    out
                }
                DirectPart8x8::None => c0.unwrap_or([0; 16]),
            }
        };
        let q_u = merge_chroma(l0_u, l1_u);
        let q_v = merge_chroma(l0_v, l1_v);

        // Stitch the 8x8 luma + 4x4 chroma quadrants into the 16x16 /
        // 8x8 plane buffers.
        for j in 0..8usize {
            for i in 0..8usize {
                let dst_y = (sub_y * 8 + j) * 16 + sub_x * 8 + i;
                pred_y[dst_y] = q_y[j * 8 + i];
            }
        }
        for j in 0..4usize {
            for i in 0..4usize {
                let dst_c = (sub_y * 4 + j) * 8 + sub_x * 4 + i;
                pred_u[dst_c] = q_u[j * 4 + i];
                pred_v[dst_c] = q_v[j * 4 + i];
            }
        }
    }
    (pred_y, pred_u, pred_v)
}

// ---------------------------------------------------------------------------
// Round 25 — B_8x8 with mixed sub_mb_type per cell.
//
// Each of the four 8x8 quadrants of a B_8x8 MB picks independently from
// {Direct (§8.4.1.2.2 / §8.4.1.2.3), L0-only, L1-only, Bi}. The cell's
// MB-syntax cost varies — Direct is free (no MVs / refs), L0/L1 each
// cost ~12 bits of mvd (one mvd_l0 or mvd_l1 pair plus the sub_mb_type
// ue(v) overhead vs Direct), and Bi costs ~20 bits.
//
// Spec sections cited:
//   §7.3.5.2          — sub_mb_pred() syntax with sub_mb_type[i]
//   §7.4.5 Table 7-18 — sub_mb_type ∈ {0..3} for the four single-partition
//                       cell types (B_Direct_8x8 / B_L0_8x8 / B_L1_8x8 /
//                       B_Bi_8x8).
//   §8.4.1.2.2        — spatial direct derivation (mvL0, mvL1 per 8x8)
//   §8.4.2.3.1 eq. 8-273 — default weighted bipred (L0 + L1 + 1) >> 1
// ---------------------------------------------------------------------------

/// SAD between an 8x8 source block (at MB-relative offset `(off_x,
/// off_y)` ∈ {0, 8}² of MB `(mb_x, mb_y)` in `src_y`) and an 8x8 luma
/// predictor buffer (row-major i32, length 64). Predictor samples are
/// clipped to 0..=255 to match the decoder.
pub(crate) fn sad_8x8_pred(
    src_y: &[u8],
    src_stride: usize,
    mb_x: usize,
    mb_y: usize,
    off_x: usize,
    off_y: usize,
    pred: &[i32; 64],
) -> u32 {
    let mut s = 0u32;
    for j in 0..8usize {
        for i in 0..8usize {
            let src = src_y[(mb_y * 16 + off_y + j) * src_stride + mb_x * 16 + off_x + i] as i32;
            let p = pred[j * 8 + i].clamp(0, 255);
            s = s.saturating_add((src - p).unsigned_abs());
        }
    }
    s
}

/// Round-25 — build one 8x8 luma cell predictor for an explicit-inter
/// `B_8x8` cell (`B_L0_8x8` / `B_L1_8x8` / `B_Bi_8x8`). Bi uses the
/// §8.4.2.3.1 default weighted average `(L0 + L1 + 1) >> 1`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_b_explicit_8x8_cell_luma(
    cell: BSubMbCell,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    sub_x: usize,
    sub_y: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> [i32; 64] {
    match cell {
        BSubMbCell::L0 => build_inter_pred_luma_8x8(
            ref_l0.recon_y,
            ref_l0.width,
            ref_l0.height,
            mb_x,
            mb_y,
            sub_x,
            sub_y,
            mv_l0,
        ),
        BSubMbCell::L1 => build_inter_pred_luma_8x8(
            ref_l1.recon_y,
            ref_l1.width,
            ref_l1.height,
            mb_x,
            mb_y,
            sub_x,
            sub_y,
            mv_l1,
        ),
        BSubMbCell::Bi => {
            let a = build_inter_pred_luma_8x8(
                ref_l0.recon_y,
                ref_l0.width,
                ref_l0.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv_l0,
            );
            let b = build_inter_pred_luma_8x8(
                ref_l1.recon_y,
                ref_l1.width,
                ref_l1.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv_l1,
            );
            let mut out = [0i32; 64];
            for i in 0..64 {
                out[i] = (a[i] + b[i] + 1) >> 1;
            }
            out
        }
        BSubMbCell::Direct => {
            // Caller is responsible for using `build_inter_pred_luma_8x8`
            // with the §8.4.1.2.2 derived per-8x8 MVs for Direct cells.
            // Defensive fallback: L0 with mv=0.
            build_inter_pred_luma_8x8(
                ref_l0.recon_y,
                ref_l0.width,
                ref_l0.height,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                Mv::ZERO,
            )
        }
    }
}

/// Round-25 — build one 4x4 chroma cell predictor (4:2:0) for an
/// explicit-inter `B_8x8` cell. Symmetric with `build_b_explicit_8x8_cell_luma`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_b_explicit_4x4_cell_chroma(
    cell: BSubMbCell,
    ref_plane_l0: &[u8],
    ref_plane_l1: &[u8],
    chroma_w_l0: u32,
    chroma_h_l0: u32,
    chroma_w_l1: u32,
    chroma_h_l1: u32,
    mb_x: usize,
    mb_y: usize,
    sub_x: usize,
    sub_y: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> [i32; 16] {
    match cell {
        BSubMbCell::L0 => build_inter_pred_chroma_4x4(
            ref_plane_l0,
            chroma_w_l0,
            chroma_h_l0,
            mb_x,
            mb_y,
            sub_x,
            sub_y,
            mv_l0,
        ),
        BSubMbCell::L1 => build_inter_pred_chroma_4x4(
            ref_plane_l1,
            chroma_w_l1,
            chroma_h_l1,
            mb_x,
            mb_y,
            sub_x,
            sub_y,
            mv_l1,
        ),
        BSubMbCell::Bi => {
            let a = build_inter_pred_chroma_4x4(
                ref_plane_l0,
                chroma_w_l0,
                chroma_h_l0,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv_l0,
            );
            let b = build_inter_pred_chroma_4x4(
                ref_plane_l1,
                chroma_w_l1,
                chroma_h_l1,
                mb_x,
                mb_y,
                sub_x,
                sub_y,
                mv_l1,
            );
            let mut out = [0i32; 16];
            for i in 0..16 {
                out[i] = (a[i] + b[i] + 1) >> 1;
            }
            out
        }
        BSubMbCell::Direct => build_inter_pred_chroma_4x4(
            ref_plane_l0,
            chroma_w_l0,
            chroma_h_l0,
            mb_x,
            mb_y,
            sub_x,
            sub_y,
            Mv::ZERO,
        ),
    }
}

/// Round-25 — pick the best per-cell `BSubMbCell` for one 8x8 quadrant
/// of a `B_8x8` MB by minimising a Lagrangian SAD with rate cost
/// approximations:
///
///   * Direct: 0-bit headroom (no MVs / refs / sub_mb_type overhead vs
///     B_Direct_8x8 baseline).
///   * L0: ~6 bits worth of SAD penalty (sub_mb_type overhead +
///     mvd_l0 (.x, .y) at se(0) = 2 bits, plus typical small se).
///   * L1: ~6 bits.
///   * Bi:  ~12 bits (two mvds + larger sub_mb_type).
///
/// The penalty multiplier scales with QP via λ. We use the same
/// `λ = (qp_y / 6).clamp(0, 8)` family as the round-21..24 selectors.
#[allow(clippy::too_many_arguments)]
pub(crate) fn pick_best_b8x8_cell(
    src_y: &[u8],
    src_stride: usize,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    sub_x: usize,
    sub_y: usize,
    direct_pred: &[i32; 64],
    me_l0: Mv,
    me_l1: Mv,
    qp_y: i32,
) -> (BSubMbCell, Mv, Mv, [i32; 64], u32) {
    let off_x = sub_x * 8;
    let off_y = sub_y * 8;

    // Direct candidate — caller-supplied predictor (already built from
    // the §8.4.1.2.2 derivation's per-8x8 MVs).
    let sad_direct = sad_8x8_pred(src_y, src_stride, mb_x, mb_y, off_x, off_y, direct_pred);

    // L0/L1/Bi candidates.
    let pred_l0 = build_b_explicit_8x8_cell_luma(
        BSubMbCell::L0,
        ref_l0,
        ref_l1,
        mb_x,
        mb_y,
        sub_x,
        sub_y,
        me_l0,
        me_l1,
    );
    let sad_l0 = sad_8x8_pred(src_y, src_stride, mb_x, mb_y, off_x, off_y, &pred_l0);

    let pred_l1 = build_b_explicit_8x8_cell_luma(
        BSubMbCell::L1,
        ref_l0,
        ref_l1,
        mb_x,
        mb_y,
        sub_x,
        sub_y,
        me_l0,
        me_l1,
    );
    let sad_l1 = sad_8x8_pred(src_y, src_stride, mb_x, mb_y, off_x, off_y, &pred_l1);

    let pred_bi = build_b_explicit_8x8_cell_luma(
        BSubMbCell::Bi,
        ref_l0,
        ref_l1,
        mb_x,
        mb_y,
        sub_x,
        sub_y,
        me_l0,
        me_l1,
    );
    let sad_bi = sad_8x8_pred(src_y, src_stride, mb_x, mb_y, off_x, off_y, &pred_bi);

    // Rate cost approximations (bits) per cell, vs the all-Direct baseline.
    let lambda = (qp_y / 6).clamp(0, 8) as u32;
    let cost_direct = 0u32;
    let cost_l0 = (lambda + 1) * 6;
    let cost_l1 = (lambda + 1) * 6;
    let cost_bi = (lambda + 1) * 12;

    let j_direct = sad_direct.saturating_add(cost_direct);
    let j_l0 = sad_l0.saturating_add(cost_l0);
    let j_l1 = sad_l1.saturating_add(cost_l1);
    let j_bi = sad_bi.saturating_add(cost_bi);

    // Tie-break order: Direct → L0 → L1 → Bi (mirrors round-21 / round-22
    // selector preferences for cheaper syntax).
    let mut best = (
        BSubMbCell::Direct,
        Mv::ZERO,
        Mv::ZERO,
        *direct_pred,
        j_direct,
        sad_direct,
    );
    if j_l0 < best.4 {
        best = (BSubMbCell::L0, me_l0, Mv::ZERO, pred_l0, j_l0, sad_l0);
    }
    if j_l1 < best.4 {
        best = (BSubMbCell::L1, Mv::ZERO, me_l1, pred_l1, j_l1, sad_l1);
    }
    if j_bi < best.4 {
        best = (BSubMbCell::Bi, me_l0, me_l1, pred_bi, j_bi, sad_bi);
    }
    (best.0, best.1, best.2, best.3, best.5)
}

/// SAD between a 16x16 source block (at MB `(mb_x, mb_y)` of `src_y`) and
/// a 16x16 luma predictor buffer in row-major i32 (clamped to 0..=255 to
/// match what the decoder writes after weighted-pred clipping).
fn sad_16x16_pred(
    src_y: &[u8],
    src_stride: usize,
    mb_x: usize,
    mb_y: usize,
    pred: &[i32; 256],
) -> u32 {
    let mut s = 0u32;
    for j in 0..16usize {
        for i in 0..16usize {
            let src = src_y[(mb_y * 16 + j) * src_stride + mb_x * 16 + i] as i32;
            let p = pred[j * 16 + i].clamp(0, 255);
            s = s.saturating_add((src - p).unsigned_abs());
        }
    }
    s
}

// ---------------------------------------------------------------------------
// Round 22 — B-slice 16x8 / 8x16 partition predictors and MVP helpers.
// ---------------------------------------------------------------------------

/// Round-22 — build a luma inter predictor for one 16x8 partition (top
/// or bottom) of a B MB, optionally combining L0 and L1 per
/// `BPartPred`. Output is `[i32; 128]` in row-major (8 rows of 16
/// samples). `partition_y_off` ∈ {0, 8} selects the half within the MB.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_b_partition_pred_luma_16x8(
    pred: BPartPred,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    partition_y_off: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> [i32; 128] {
    let mut out = [0i32; 128];
    let l0 = if pred.uses_l0() {
        Some(build_inter_pred_luma_partition(
            ref_l0.recon_y,
            ref_l0.width,
            ref_l0.height,
            mb_x,
            mb_y,
            0,
            partition_y_off,
            16,
            8,
            mv_l0,
        ))
    } else {
        None
    };
    let l1 = if pred.uses_l1() {
        Some(build_inter_pred_luma_partition(
            ref_l1.recon_y,
            ref_l1.width,
            ref_l1.height,
            mb_x,
            mb_y,
            0,
            partition_y_off,
            16,
            8,
            mv_l1,
        ))
    } else {
        None
    };
    match pred {
        BPartPred::L0 => out.copy_from_slice(&l0.unwrap()),
        BPartPred::L1 => out.copy_from_slice(&l1.unwrap()),
        BPartPred::Bi => {
            // §8.4.2.3.1 eq. 8-273.
            let a = l0.unwrap();
            let b = l1.unwrap();
            for i in 0..128 {
                out[i] = (a[i] + b[i] + 1) >> 1;
            }
        }
    }
    out
}

/// Round-22 — build a luma inter predictor for one 8x16 partition (left
/// or right) of a B MB. Output is `[i32; 128]` in row-major (16 rows of
/// 8 samples). `partition_x_off` ∈ {0, 8} selects the half within the
/// MB.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_b_partition_pred_luma_8x16(
    pred: BPartPred,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    partition_x_off: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> [i32; 128] {
    let mut out = [0i32; 128];
    let l0 = if pred.uses_l0() {
        Some(build_inter_pred_luma_partition(
            ref_l0.recon_y,
            ref_l0.width,
            ref_l0.height,
            mb_x,
            mb_y,
            partition_x_off,
            0,
            8,
            16,
            mv_l0,
        ))
    } else {
        None
    };
    let l1 = if pred.uses_l1() {
        Some(build_inter_pred_luma_partition(
            ref_l1.recon_y,
            ref_l1.width,
            ref_l1.height,
            mb_x,
            mb_y,
            partition_x_off,
            0,
            8,
            16,
            mv_l1,
        ))
    } else {
        None
    };
    match pred {
        BPartPred::L0 => out.copy_from_slice(&l0.unwrap()),
        BPartPred::L1 => out.copy_from_slice(&l1.unwrap()),
        BPartPred::Bi => {
            let a = l0.unwrap();
            let b = l1.unwrap();
            for i in 0..128 {
                out[i] = (a[i] + b[i] + 1) >> 1;
            }
        }
    }
    out
}

/// Round-22 — generic luma inter-pred helper for an arbitrary
/// rectangular partition of an MB. `(off_x, off_y)` is the partition's
/// top-left within the MB in luma samples; `(w, h)` is the partition
/// dimensions (one of (16, 8), (8, 16), (16, 16), (8, 8)). Output is
/// `[i32; w*h]` packed row-major into a `Vec<i32>` (length 128 for the
/// 16x8/8x16 cases used here).
#[allow(clippy::too_many_arguments)]
fn build_inter_pred_luma_partition(
    ref_y: &[u8],
    ref_w: u32,
    ref_h: u32,
    mb_x: usize,
    mb_y: usize,
    off_x: usize,
    off_y: usize,
    w: u32,
    h: u32,
    mv: Mv,
) -> Vec<i32> {
    let stride = ref_w as usize;
    let h_us = ref_h as usize;
    let ref_i32: Vec<i32> = ref_y
        .iter()
        .take(stride * h_us)
        .map(|&v| v as i32)
        .collect();

    let mv_int_x = mv.x >> 2;
    let mv_int_y = mv.y >> 2;
    let x_frac = (mv.x & 3) as u8;
    let y_frac = (mv.y & 3) as u8;
    let int_x = (mb_x * 16 + off_x) as i32 + mv_int_x;
    let int_y = (mb_y * 16 + off_y) as i32 + mv_int_y;

    let mut dst = vec![0i32; (w * h) as usize];
    interpolate_luma(
        &ref_i32, stride, stride, h_us, int_x, int_y, x_frac, y_frac, w, h, 8, &mut dst, w as usize,
    )
    .expect("luma interpolation partition");
    dst
}

/// Round-22 — generic chroma inter-pred for an arbitrary partition.
/// `(off_x, off_y)` is the partition's top-left in luma samples; `(w,
/// h)` is the partition's chroma dimensions (so a 16x8 luma partition
/// gives an 8x4 chroma partition). 4:2:0 only.
#[allow(clippy::too_many_arguments)]
fn build_inter_pred_chroma_partition(
    ref_c: &[u8],
    ref_cw: u32,
    ref_ch: u32,
    mb_x: usize,
    mb_y: usize,
    off_x_luma: usize,
    off_y_luma: usize,
    w_chroma: u32,
    h_chroma: u32,
    mv: Mv,
) -> Vec<i32> {
    let stride = ref_cw as usize;
    let h_us = ref_ch as usize;
    let ref_i32: Vec<i32> = ref_c
        .iter()
        .take(stride * h_us)
        .map(|&v| v as i32)
        .collect();

    // §8.4.1.4 — 4:2:0 chroma uses luma MV directly with 1/8-pel
    // fractional positions.
    let int_x = (mb_x * 8 + off_x_luma / 2) as i32 + (mv.x >> 3);
    let int_y = (mb_y * 8 + off_y_luma / 2) as i32 + (mv.y >> 3);
    let x_frac = (mv.x & 7) as u8;
    let y_frac = (mv.y & 7) as u8;

    let mut dst = vec![0i32; (w_chroma * h_chroma) as usize];
    interpolate_chroma(
        &ref_i32,
        stride,
        stride,
        h_us,
        int_x,
        int_y,
        x_frac,
        y_frac,
        w_chroma,
        h_chroma,
        8,
        &mut dst,
        w_chroma as usize,
    )
    .expect("chroma interpolation partition");
    dst
}

/// Round-22 — build chroma predictors for one B-slice 16x8 partition
/// (Cb + Cr). 4:2:0 → chroma partition is 8x4 (`[i32; 32]` row-major).
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_b_partition_pred_chroma_16x8(
    pred: BPartPred,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    partition_y_off_luma: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> ([i32; 32], [i32; 32]) {
    let cw_l0 = ref_l0.width / 2;
    let ch_l0 = ref_l0.height / 2;
    let cw_l1 = ref_l1.width / 2;
    let ch_l1 = ref_l1.height / 2;
    let make = |plane_l0: &[u8], plane_l1: &[u8]| -> [i32; 32] {
        let mut out = [0i32; 32];
        let a = if pred.uses_l0() {
            Some(build_inter_pred_chroma_partition(
                plane_l0,
                cw_l0,
                ch_l0,
                mb_x,
                mb_y,
                0,
                partition_y_off_luma,
                8,
                4,
                mv_l0,
            ))
        } else {
            None
        };
        let b = if pred.uses_l1() {
            Some(build_inter_pred_chroma_partition(
                plane_l1,
                cw_l1,
                ch_l1,
                mb_x,
                mb_y,
                0,
                partition_y_off_luma,
                8,
                4,
                mv_l1,
            ))
        } else {
            None
        };
        match pred {
            BPartPred::L0 => out.copy_from_slice(&a.unwrap()),
            BPartPred::L1 => out.copy_from_slice(&b.unwrap()),
            BPartPred::Bi => {
                let a = a.unwrap();
                let b = b.unwrap();
                for i in 0..32 {
                    out[i] = (a[i] + b[i] + 1) >> 1;
                }
            }
        }
        out
    };
    (
        make(ref_l0.recon_u, ref_l1.recon_u),
        make(ref_l0.recon_v, ref_l1.recon_v),
    )
}

/// Round-22 — build chroma predictors for one B-slice 8x16 partition
/// (Cb + Cr). 4:2:0 → chroma partition is 4x8 (`[i32; 32]` row-major).
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_b_partition_pred_chroma_8x16(
    pred: BPartPred,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    partition_x_off_luma: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> ([i32; 32], [i32; 32]) {
    let cw_l0 = ref_l0.width / 2;
    let ch_l0 = ref_l0.height / 2;
    let cw_l1 = ref_l1.width / 2;
    let ch_l1 = ref_l1.height / 2;
    let make = |plane_l0: &[u8], plane_l1: &[u8]| -> [i32; 32] {
        let mut out = [0i32; 32];
        let a = if pred.uses_l0() {
            Some(build_inter_pred_chroma_partition(
                plane_l0,
                cw_l0,
                ch_l0,
                mb_x,
                mb_y,
                partition_x_off_luma,
                0,
                4,
                8,
                mv_l0,
            ))
        } else {
            None
        };
        let b = if pred.uses_l1() {
            Some(build_inter_pred_chroma_partition(
                plane_l1,
                cw_l1,
                ch_l1,
                mb_x,
                mb_y,
                partition_x_off_luma,
                0,
                4,
                8,
                mv_l1,
            ))
        } else {
            None
        };
        match pred {
            BPartPred::L0 => out.copy_from_slice(&a.unwrap()),
            BPartPred::L1 => out.copy_from_slice(&b.unwrap()),
            BPartPred::Bi => {
                let a = a.unwrap();
                let b = b.unwrap();
                for i in 0..32 {
                    out[i] = (a[i] + b[i] + 1) >> 1;
                }
            }
        }
        out
    };
    (
        make(ref_l0.recon_u, ref_l1.recon_u),
        make(ref_l0.recon_v, ref_l1.recon_v),
    )
}

/// SAD between an arbitrary-sized source block (at MB-relative offset
/// `(off_x, off_y)` of the MB at `(mb_x, mb_y)`) and a `w*h` luma
/// predictor buffer (row-major i32 with stride = w, clamped to
/// 0..=255).
#[allow(clippy::too_many_arguments)]
pub(crate) fn sad_partition_pred(
    src_y: &[u8],
    src_stride: usize,
    mb_x: usize,
    mb_y: usize,
    off_x: usize,
    off_y: usize,
    w: usize,
    h: usize,
    pred: &[i32],
) -> u32 {
    let mut s = 0u32;
    for j in 0..h {
        for i in 0..w {
            let src = src_y[(mb_y * 16 + off_y + j) * src_stride + mb_x * 16 + off_x + i] as i32;
            let p = pred[j * w + i].clamp(0, 255);
            s = s.saturating_add((src - p).unsigned_abs());
        }
    }
    s
}

/// Round-22 — derive the §8.4.1.3 mvpLX for one 16x8 partition (top or
/// bottom) of a B MB at `(mb_x, mb_y)` against list `list_idx` ∈
/// {0, 1}. `is_top` selects which 16x8 half. Within-MB neighbour reads
/// use `inflight_*` arrays that carry the already-decoded partitions
/// of the **current** MB.
///
/// The shape directs the §8.4.1.3 directional shortcut:
/// `Partition16x8Top` for top, `Partition16x8Bottom` for bottom. The
/// `derive_mvpred_with_d` median fallback consults A/B/C neighbours of
/// the partition's top-left 4x4 plus the optional D (above-left).
#[allow(clippy::too_many_arguments)]
fn mvp_for_b_16x8_partition(
    grid: &MvGrid,
    mb_x: usize,
    mb_y: usize,
    is_top: bool,
    ref_idx: i32,
    inflight_avail: [bool; 4],
    mv_inflight: [Mv; 4],
    ref_inflight: [i32; 4],
) -> Mv {
    // Partition top-left in 4x4 units. Top: (0, 0); bottom: (0, 2).
    let by = if is_top { 0i32 } else { 2 };
    // A at (-1, by); B at (0, by - 1); C at (4, by - 1); D at (-1, by - 1).
    // Partition width = 16 px = 4 4x4 → C at column index 4 (above-right
    // neighbour MB). Partition height irrelevant for 16x8 neighbours.
    let a = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        -1,
        by,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let b = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        0,
        by - 1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let c = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        4,
        by - 1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let d = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        -1,
        by - 1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let shape = if is_top {
        crate::mv_deriv::MvpredShape::Partition16x8Top
    } else {
        crate::mv_deriv::MvpredShape::Partition16x8Bottom
    };
    let inputs = MvpredInputs::from_abc(a, b, c, ref_idx, shape);
    crate::mv_deriv::derive_mvpred_with_d(&inputs, d)
}

/// Round-22 — derive the §8.4.1.3 mvpLX for one 8x16 partition (left
/// or right). Mirrors [`mvp_for_b_16x8_partition`].
#[allow(clippy::too_many_arguments)]
fn mvp_for_b_8x16_partition(
    grid: &MvGrid,
    mb_x: usize,
    mb_y: usize,
    is_left: bool,
    ref_idx: i32,
    inflight_avail: [bool; 4],
    mv_inflight: [Mv; 4],
    ref_inflight: [i32; 4],
) -> Mv {
    // Partition top-left in 4x4 units. Left: (0, 0); right: (2, 0).
    let bx = if is_left { 0i32 } else { 2 };
    // A at (bx - 1, 0); B at (bx, -1); C at (bx + 2, -1); D at (bx - 1, -1).
    // Partition width = 8 px = 2 4x4 → C at column (bx + 2) (above MB
    // for left, above-right MB for right).
    let a = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx - 1,
        0,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let b = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx,
        -1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let c = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx + 2,
        -1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let d = neighbour_8x8_partition_mv(
        grid,
        mb_x,
        mb_y,
        bx - 1,
        -1,
        inflight_avail,
        mv_inflight,
        ref_inflight,
    );
    let shape = if is_left {
        crate::mv_deriv::MvpredShape::Partition8x16Left
    } else {
        crate::mv_deriv::MvpredShape::Partition8x16Right
    };
    let inputs = MvpredInputs::from_abc(a, b, c, ref_idx, shape);
    crate::mv_deriv::derive_mvpred_with_d(&inputs, d)
}

/// Round-22 — per-partition ME for one 16x8 or 8x16 partition (any
/// list). Runs `search_quarter_pel_8x8` on each of the (up to 2) 8x8
/// cells covered by the partition, and picks the candidate MV (one of
/// `mv_16x16` or per-cell-best) that gives the lowest partition-wide
/// SAD against `ref_y`. Returns the best partition MV.
///
/// The encoder tries three candidates per (partition, list):
///   * The 16x16 ME result (`mv_16x16`).
///   * The first 8x8 cell's qpel ME result.
///   * The second 8x8 cell's qpel ME result.
///
/// SAD is measured over the full partition area against the qpel-
/// interpolated predictor. This costs 3 partition-SADs per (partition,
/// list) but reuses ME results we already need anyway.
#[allow(clippy::too_many_arguments)]
fn best_partition_mv(
    src_y: &[u8],
    src_stride: usize,
    src_w: u32,
    src_h: u32,
    ref_y: &[u8],
    ref_stride: usize,
    ref_w: u32,
    ref_h: u32,
    mb_x: usize,
    mb_y: usize,
    off_x: usize,
    off_y: usize,
    part_w: u32,
    part_h: u32,
    candidates: &[Mv],
) -> (Mv, u32) {
    let mut best_mv = candidates[0];
    let mut best_sad = u32::MAX;
    for &mv in candidates {
        let pred = build_inter_pred_luma_partition(
            ref_y, ref_w, ref_h, mb_x, mb_y, off_x, off_y, part_w, part_h, mv,
        );
        let sad = sad_partition_pred(
            src_y,
            src_stride,
            mb_x,
            mb_y,
            off_x,
            off_y,
            part_w as usize,
            part_h as usize,
            &pred,
        );
        let _ = (src_w, src_h, ref_stride);
        if sad < best_sad {
            best_sad = sad;
            best_mv = mv;
        }
    }
    (best_mv, best_sad)
}

/// Round-22 — per-partition SAD for a given (mode, mv_l0, mv_l1).
/// Builds the partition's L0/L1/Bi predictor, returns its SAD against
/// source.
#[allow(clippy::too_many_arguments)]
pub(crate) fn partition_sad_b_16x8(
    pred: BPartPred,
    src_y: &[u8],
    src_stride: usize,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    off_y: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> u32 {
    let p = build_b_partition_pred_luma_16x8(pred, ref_l0, ref_l1, mb_x, mb_y, off_y, mv_l0, mv_l1);
    sad_partition_pred(src_y, src_stride, mb_x, mb_y, 0, off_y, 16, 8, &p)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn partition_sad_b_8x16(
    pred: BPartPred,
    src_y: &[u8],
    src_stride: usize,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
    off_x: usize,
    mv_l0: Mv,
    mv_l1: Mv,
) -> u32 {
    let p = build_b_partition_pred_luma_8x16(pred, ref_l0, ref_l1, mb_x, mb_y, off_x, mv_l0, mv_l1);
    sad_partition_pred(src_y, src_stride, mb_x, mb_y, off_x, 0, 8, 16, &p)
}

/// Round-22 — choose the best per-partition (mode, mv_l0, mv_l1) for
/// one 16x8 or 8x16 partition given pre-computed per-list candidate MVs.
pub(crate) fn best_partition_mode_b(
    candidates_l0: &[Mv],
    candidates_l1: &[Mv],
    eval_sad: impl Fn(BPartPred, Mv, Mv) -> u32,
) -> (BPartPred, Mv, Mv, u32) {
    let mut best = (BPartPred::L0, Mv::ZERO, Mv::ZERO, u32::MAX);
    // L0-only — try each L0 candidate.
    for &mv0 in candidates_l0 {
        let s = eval_sad(BPartPred::L0, mv0, Mv::ZERO);
        if s < best.3 {
            best = (BPartPred::L0, mv0, Mv::ZERO, s);
        }
    }
    // L1-only — try each L1 candidate.
    for &mv1 in candidates_l1 {
        let s = eval_sad(BPartPred::L1, Mv::ZERO, mv1);
        if s < best.3 {
            best = (BPartPred::L1, Mv::ZERO, mv1, s);
        }
    }
    // Bi — try each L0 × L1 combination.
    for &mv0 in candidates_l0 {
        for &mv1 in candidates_l1 {
            let s = eval_sad(BPartPred::Bi, mv0, mv1);
            if s < best.3 {
                best = (BPartPred::Bi, mv0, mv1, s);
            }
        }
    }
    best
}

/// Round-22 — which partition shape was picked for a B MB.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PartitionShape {
    /// Two 16x8 halves stacked vertically (top, bottom).
    P16x8,
    /// Two 8x16 halves side-by-side (left, right).
    P8x16,
}

/// Round-22 — captured per-partition decision for a B 16x8 / 8x16 MB.
/// `mode_a` / `mv_*_a` is the first partition (top for 16x8, left for
/// 8x16); `mode_b` / `mv_*_b` is the second (bottom / right).
#[derive(Debug, Clone, Copy)]
struct PartitionChoiceB {
    shape: PartitionShape,
    mode_a: BPartPred,
    mode_b: BPartPred,
    mv_l0_a: Mv,
    mv_l1_a: Mv,
    mv_l0_b: Mv,
    mv_l1_b: Mv,
}

/// Round-22 — build a 16x16 composite predictor (luma + Cb + Cr) from a
/// partition decision, by stitching the two per-partition predictors
/// into the relevant halves of a 16x16 buffer.
fn build_partition_composite_b(
    pc: &PartitionChoiceB,
    ref_l0: &EncodedFrameRef<'_>,
    ref_l1: &EncodedFrameRef<'_>,
    mb_x: usize,
    mb_y: usize,
) -> ([i32; 256], [i32; 64], [i32; 64]) {
    let mut pred_y = [0i32; 256];
    let mut pred_u = [0i32; 64];
    let mut pred_v = [0i32; 64];
    match pc.shape {
        PartitionShape::P16x8 => {
            let py0 = build_b_partition_pred_luma_16x8(
                pc.mode_a, ref_l0, ref_l1, mb_x, mb_y, 0, pc.mv_l0_a, pc.mv_l1_a,
            );
            let py1 = build_b_partition_pred_luma_16x8(
                pc.mode_b, ref_l0, ref_l1, mb_x, mb_y, 8, pc.mv_l0_b, pc.mv_l1_b,
            );
            for j in 0..8usize {
                for i in 0..16usize {
                    pred_y[j * 16 + i] = py0[j * 16 + i];
                    pred_y[(8 + j) * 16 + i] = py1[j * 16 + i];
                }
            }
            // Chroma 4:2:0 → 8x4 each half.
            let (cb0, cr0) = build_b_partition_pred_chroma_16x8(
                pc.mode_a, ref_l0, ref_l1, mb_x, mb_y, 0, pc.mv_l0_a, pc.mv_l1_a,
            );
            let (cb1, cr1) = build_b_partition_pred_chroma_16x8(
                pc.mode_b, ref_l0, ref_l1, mb_x, mb_y, 8, pc.mv_l0_b, pc.mv_l1_b,
            );
            for j in 0..4usize {
                for i in 0..8usize {
                    pred_u[j * 8 + i] = cb0[j * 8 + i];
                    pred_v[j * 8 + i] = cr0[j * 8 + i];
                    pred_u[(4 + j) * 8 + i] = cb1[j * 8 + i];
                    pred_v[(4 + j) * 8 + i] = cr1[j * 8 + i];
                }
            }
        }
        PartitionShape::P8x16 => {
            let py0 = build_b_partition_pred_luma_8x16(
                pc.mode_a, ref_l0, ref_l1, mb_x, mb_y, 0, pc.mv_l0_a, pc.mv_l1_a,
            );
            let py1 = build_b_partition_pred_luma_8x16(
                pc.mode_b, ref_l0, ref_l1, mb_x, mb_y, 8, pc.mv_l0_b, pc.mv_l1_b,
            );
            for j in 0..16usize {
                for i in 0..8usize {
                    pred_y[j * 16 + i] = py0[j * 8 + i];
                    pred_y[j * 16 + 8 + i] = py1[j * 8 + i];
                }
            }
            // Chroma 4:2:0 → 4x8 each half.
            let (cb0, cr0) = build_b_partition_pred_chroma_8x16(
                pc.mode_a, ref_l0, ref_l1, mb_x, mb_y, 0, pc.mv_l0_a, pc.mv_l1_a,
            );
            let (cb1, cr1) = build_b_partition_pred_chroma_8x16(
                pc.mode_b, ref_l0, ref_l1, mb_x, mb_y, 8, pc.mv_l0_b, pc.mv_l1_b,
            );
            for j in 0..8usize {
                for i in 0..4usize {
                    pred_u[j * 8 + i] = cb0[j * 4 + i];
                    pred_v[j * 8 + i] = cr0[j * 4 + i];
                    pred_u[j * 8 + 4 + i] = cb1[j * 4 + i];
                    pred_v[j * 8 + 4 + i] = cr1[j * 4 + i];
                }
            }
        }
    }
    (pred_y, pred_u, pred_v)
}

/// Round-22 — derive per-partition MVDs for a B 16x8 / 8x16 MB using
/// the §8.4.1.3 partition-shape MVP derivation. Returns
/// `(mvd_l0[2], mvd_l1[2])`.
///
/// For the second partition (bottom of 16x8 / right of 8x16) the §8.4.1.3
/// MVP can read from the first partition's MVs (which are part of the
/// SAME MB, already decoded in raster order). We surface those via
/// `inflight_*` arrays so the within-MB neighbour lookup in
/// `mvp_for_b_*_partition` finds them.
/// Per-partition MVD tuple (one (x, y) per of the two partitions).
type PartitionMvds = [(i32, i32); 2];

fn partition_mvds_b(
    pc: &PartitionChoiceB,
    mv_grid_l0: &MvGrid,
    mv_grid_l1: &MvGrid,
    mb_x: usize,
    mb_y: usize,
) -> (PartitionMvds, PartitionMvds) {
    let mut mvd_l0 = [(0i32, 0i32); 2];
    let mut mvd_l1 = [(0i32, 0i32); 2];
    let inflight_avail = [false; 4];
    let mv_inflight = [Mv::ZERO; 4];
    let ref_inflight = [-1i32; 4];
    match pc.shape {
        PartitionShape::P16x8 => {
            // Partition 0 (top).
            if pc.mode_a.uses_l0() {
                let mvp = mvp_for_b_16x8_partition(
                    mv_grid_l0,
                    mb_x,
                    mb_y,
                    true,
                    0,
                    inflight_avail,
                    mv_inflight,
                    ref_inflight,
                );
                mvd_l0[0] = (pc.mv_l0_a.x - mvp.x, pc.mv_l0_a.y - mvp.y);
            }
            if pc.mode_a.uses_l1() {
                let mvp = mvp_for_b_16x8_partition(
                    mv_grid_l1,
                    mb_x,
                    mb_y,
                    true,
                    0,
                    inflight_avail,
                    mv_inflight,
                    ref_inflight,
                );
                mvd_l1[0] = (pc.mv_l1_a.x - mvp.x, pc.mv_l1_a.y - mvp.y);
            }
            // Partition 1 (bottom) — top covers 8x8 #0 and #1.
            let inflight_avail_bot = [true, true, false, false];
            let mv_inflight_bot_l0 = [pc.mv_l0_a, pc.mv_l0_a, Mv::ZERO, Mv::ZERO];
            let mv_inflight_bot_l1 = [pc.mv_l1_a, pc.mv_l1_a, Mv::ZERO, Mv::ZERO];
            let ref_inflight_bot_l0 = [
                if pc.mode_a.uses_l0() { 0 } else { -1 },
                if pc.mode_a.uses_l0() { 0 } else { -1 },
                -1,
                -1,
            ];
            let ref_inflight_bot_l1 = [
                if pc.mode_a.uses_l1() { 0 } else { -1 },
                if pc.mode_a.uses_l1() { 0 } else { -1 },
                -1,
                -1,
            ];
            if pc.mode_b.uses_l0() {
                let mvp = mvp_for_b_16x8_partition(
                    mv_grid_l0,
                    mb_x,
                    mb_y,
                    false,
                    0,
                    inflight_avail_bot,
                    mv_inflight_bot_l0,
                    ref_inflight_bot_l0,
                );
                mvd_l0[1] = (pc.mv_l0_b.x - mvp.x, pc.mv_l0_b.y - mvp.y);
            }
            if pc.mode_b.uses_l1() {
                let mvp = mvp_for_b_16x8_partition(
                    mv_grid_l1,
                    mb_x,
                    mb_y,
                    false,
                    0,
                    inflight_avail_bot,
                    mv_inflight_bot_l1,
                    ref_inflight_bot_l1,
                );
                mvd_l1[1] = (pc.mv_l1_b.x - mvp.x, pc.mv_l1_b.y - mvp.y);
            }
        }
        PartitionShape::P8x16 => {
            if pc.mode_a.uses_l0() {
                let mvp = mvp_for_b_8x16_partition(
                    mv_grid_l0,
                    mb_x,
                    mb_y,
                    true,
                    0,
                    inflight_avail,
                    mv_inflight,
                    ref_inflight,
                );
                mvd_l0[0] = (pc.mv_l0_a.x - mvp.x, pc.mv_l0_a.y - mvp.y);
            }
            if pc.mode_a.uses_l1() {
                let mvp = mvp_for_b_8x16_partition(
                    mv_grid_l1,
                    mb_x,
                    mb_y,
                    true,
                    0,
                    inflight_avail,
                    mv_inflight,
                    ref_inflight,
                );
                mvd_l1[0] = (pc.mv_l1_a.x - mvp.x, pc.mv_l1_a.y - mvp.y);
            }
            // Partition 1 (right) — left covers 8x8 #0 and #2.
            let inflight_avail_right = [true, false, true, false];
            let mv_inflight_right_l0 = [pc.mv_l0_a, Mv::ZERO, pc.mv_l0_a, Mv::ZERO];
            let mv_inflight_right_l1 = [pc.mv_l1_a, Mv::ZERO, pc.mv_l1_a, Mv::ZERO];
            let ref_inflight_right_l0 = [
                if pc.mode_a.uses_l0() { 0 } else { -1 },
                -1,
                if pc.mode_a.uses_l0() { 0 } else { -1 },
                -1,
            ];
            let ref_inflight_right_l1 = [
                if pc.mode_a.uses_l1() { 0 } else { -1 },
                -1,
                if pc.mode_a.uses_l1() { 0 } else { -1 },
                -1,
            ];
            if pc.mode_b.uses_l0() {
                let mvp = mvp_for_b_8x16_partition(
                    mv_grid_l0,
                    mb_x,
                    mb_y,
                    false,
                    0,
                    inflight_avail_right,
                    mv_inflight_right_l0,
                    ref_inflight_right_l0,
                );
                mvd_l0[1] = (pc.mv_l0_b.x - mvp.x, pc.mv_l0_b.y - mvp.y);
            }
            if pc.mode_b.uses_l1() {
                let mvp = mvp_for_b_8x16_partition(
                    mv_grid_l1,
                    mb_x,
                    mb_y,
                    false,
                    0,
                    inflight_avail_right,
                    mv_inflight_right_l1,
                    ref_inflight_right_l1,
                );
                mvd_l1[1] = (pc.mv_l1_b.x - mvp.x, pc.mv_l1_b.y - mvp.y);
            }
        }
    }
    (mvd_l0, mvd_l1)
}

/// Round-22 — derive (per-8x8 MV, per-8x8 ref_idx, list_used) for the
/// MvGrid update of one list. For partition modes the per-8x8 slots
/// carry per-partition data; for 16x16 / Direct, all slots share the
/// single MV.
fn grid_state_b(
    pc: Option<&PartitionChoiceB>,
    is_l0: bool,
    pred: BPred16x16,
    eff_mv: Mv,
) -> ([Mv; 4], [i32; 4], bool) {
    if let Some(pc) = pc {
        let (mv_a, mv_b, used_a, used_b) = if is_l0 {
            (
                pc.mv_l0_a,
                pc.mv_l0_b,
                pc.mode_a.uses_l0(),
                pc.mode_b.uses_l0(),
            )
        } else {
            (
                pc.mv_l1_a,
                pc.mv_l1_b,
                pc.mode_a.uses_l1(),
                pc.mode_b.uses_l1(),
            )
        };
        let any_used = used_a || used_b;
        let mut mvs = [Mv::ZERO; 4];
        let mut refs = [-1i32; 4];
        match pc.shape {
            PartitionShape::P16x8 => {
                // Top covers 8x8 #0/#1; bottom #2/#3.
                if used_a {
                    mvs[0] = mv_a;
                    mvs[1] = mv_a;
                    refs[0] = 0;
                    refs[1] = 0;
                }
                if used_b {
                    mvs[2] = mv_b;
                    mvs[3] = mv_b;
                    refs[2] = 0;
                    refs[3] = 0;
                }
            }
            PartitionShape::P8x16 => {
                // Left covers 8x8 #0/#2; right #1/#3.
                if used_a {
                    mvs[0] = mv_a;
                    mvs[2] = mv_a;
                    refs[0] = 0;
                    refs[2] = 0;
                }
                if used_b {
                    mvs[1] = mv_b;
                    mvs[3] = mv_b;
                    refs[1] = 0;
                    refs[3] = 0;
                }
            }
        }
        (mvs, refs, any_used)
    } else {
        let used = if is_l0 {
            pred.uses_l0()
        } else {
            pred.uses_l1()
        };
        if used {
            ([eff_mv; 4], [0; 4], true)
        } else {
            ([Mv::ZERO; 4], [-1; 4], false)
        }
    }
}

/// Round-22 — build the per-4x4 MV / per-8x8 ref / per-8x8 POC arrays
/// for the §8.7 deblocker. For partition modes the 4x4 blocks in each
/// half carry that half's MV; for 16x16 / Direct the single MV applies
/// everywhere.
fn deblock_mv_arr_b(
    pc: Option<&PartitionChoiceB>,
    is_l0: bool,
    pred: BPred16x16,
    eff_mv: Mv,
    poc_sentinel: i32,
) -> ([(i16, i16); 16], [i8; 4], [i32; 4]) {
    if let Some(pc) = pc {
        let (mv_a, mv_b, used_a, used_b) = if is_l0 {
            (
                pc.mv_l0_a,
                pc.mv_l0_b,
                pc.mode_a.uses_l0(),
                pc.mode_b.uses_l0(),
            )
        } else {
            (
                pc.mv_l1_a,
                pc.mv_l1_b,
                pc.mode_a.uses_l1(),
                pc.mode_b.uses_l1(),
            )
        };
        let mv_a_t = (
            mv_a.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            mv_a.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        );
        let mv_b_t = (
            mv_b.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            mv_b.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        );
        let mut mvs = [(0i16, 0i16); 16];
        let mut refs = [-1i8; 4];
        let mut pocs = [i32::MIN; 4];
        // The `mvs` array is indexed by §6.4.3 Z-scan position 0..15
        // (matches `MbDeblockInfo::mv_l0` / decoder MbInfo layout). Map
        // each Z-scan index to its (4x4-bx, 4x4-by) coords via
        // `LUMA_4X4_BLK` so we correctly assign top/bottom (16x8) or
        // left/right (8x16) partition MVs.
        match pc.shape {
            PartitionShape::P16x8 => {
                for (blk, slot) in mvs.iter_mut().enumerate() {
                    let (_bx, by) = LUMA_4X4_BLK[blk];
                    *slot = if by < 2 {
                        if used_a {
                            mv_a_t
                        } else {
                            (0, 0)
                        }
                    } else if used_b {
                        mv_b_t
                    } else {
                        (0, 0)
                    };
                }
                refs[0] = if used_a { 0 } else { -1 };
                refs[1] = if used_a { 0 } else { -1 };
                refs[2] = if used_b { 0 } else { -1 };
                refs[3] = if used_b { 0 } else { -1 };
                pocs[0] = if used_a { poc_sentinel } else { i32::MIN };
                pocs[1] = if used_a { poc_sentinel } else { i32::MIN };
                pocs[2] = if used_b { poc_sentinel } else { i32::MIN };
                pocs[3] = if used_b { poc_sentinel } else { i32::MIN };
            }
            PartitionShape::P8x16 => {
                for (blk, slot) in mvs.iter_mut().enumerate() {
                    let (bx, _by) = LUMA_4X4_BLK[blk];
                    *slot = if bx < 2 {
                        if used_a {
                            mv_a_t
                        } else {
                            (0, 0)
                        }
                    } else if used_b {
                        mv_b_t
                    } else {
                        (0, 0)
                    };
                }
                refs[0] = if used_a { 0 } else { -1 };
                refs[2] = if used_a { 0 } else { -1 };
                refs[1] = if used_b { 0 } else { -1 };
                refs[3] = if used_b { 0 } else { -1 };
                pocs[0] = if used_a { poc_sentinel } else { i32::MIN };
                pocs[2] = if used_a { poc_sentinel } else { i32::MIN };
                pocs[1] = if used_b { poc_sentinel } else { i32::MIN };
                pocs[3] = if used_b { poc_sentinel } else { i32::MIN };
            }
        }
        (mvs, refs, pocs)
    } else {
        let used = if is_l0 {
            pred.uses_l0()
        } else {
            pred.uses_l1()
        };
        if used {
            let mv_t = (
                eff_mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                eff_mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            );
            ([mv_t; 16], [0; 4], [poc_sentinel; 4])
        } else {
            ([(0, 0); 16], [-1; 4], [i32::MIN; 4])
        }
    }
}

/// Round-23 — build the per-4x4 MV / per-8x8 ref / per-8x8 POC arrays
/// for the §8.7 deblocker on a `B_8x8` + 4× `B_Direct_8x8` macroblock.
/// Each 8x8 quadrant carries its own per-list MV (from the §8.4.1.2.2
/// derivation); within a quadrant all four 4x4 blocks share the
/// quadrant's MV (`direct_8x8_inference_flag = 1`). When `ref_idx` is
/// negative the list is unused for this MB and all per-4x4 MVs / refs /
/// pocs are zeroed-out / sentinel.
fn deblock_arrays_per_8x8_direct(
    mv_per_8x8: [Mv; 4],
    ref_idx: i32,
    poc_sentinel: i32,
) -> ([(i16, i16); 16], [i8; 4], [i32; 4]) {
    let used = ref_idx >= 0;
    if !used {
        return ([(0, 0); 16], [-1; 4], [i32::MIN; 4]);
    }
    let mut mvs = [(0i16, 0i16); 16];
    // §6.4.3 raster-Z 4x4 indexing; LUMA_4X4_BLK[blk] returns (4x4-bx,
    // 4x4-by) ∈ 0..4 × 0..4. The containing 8x8 quadrant is
    // (bx/2, by/2) → quadrant index = (by/2)*2 + bx/2.
    for (blk, slot) in mvs.iter_mut().enumerate() {
        let (bx, by) = LUMA_4X4_BLK[blk];
        let q = (by / 2) * 2 + (bx / 2);
        let mv = mv_per_8x8[q];
        *slot = (
            mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        );
    }
    let refs = [ref_idx.clamp(i8::MIN as i32, i8::MAX as i32) as i8; 4];
    let pocs = [poc_sentinel; 4];
    (mvs, refs, pocs)
}

/// Round-25 — build the per-4x4 MV / per-8x8 ref / per-8x8 POC arrays
/// for the §8.7 deblocker on a mixed `B_8x8` macroblock. Each 8x8
/// quadrant carries its own per-list MV AND its own per-list ref_idx
/// (an 8x8 cell may be Direct, L0-only, L1-only, or Bi independently
/// from its neighbours). Within a quadrant all four 4x4 blocks share
/// the quadrant's MV.
///
/// Slots whose ref_idx is negative encode "list unused for this 8x8
/// cell" (mv = (0, 0), poc = `i32::MIN` sentinel).
fn deblock_arrays_per_8x8_mixed(
    mv_per_8x8: [Mv; 4],
    ref_idx_per_8x8: [i32; 4],
    poc_sentinel: i32,
) -> ([(i16, i16); 16], [i8; 4], [i32; 4]) {
    let mut mvs = [(0i16, 0i16); 16];
    for (blk, slot) in mvs.iter_mut().enumerate() {
        let (bx, by) = LUMA_4X4_BLK[blk];
        let q = (by / 2) * 2 + (bx / 2);
        if ref_idx_per_8x8[q] >= 0 {
            let mv = mv_per_8x8[q];
            *slot = (
                mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
            );
        } else {
            *slot = (0, 0);
        }
    }
    let mut refs = [-1i8; 4];
    let mut pocs = [i32::MIN; 4];
    for q in 0..4usize {
        if ref_idx_per_8x8[q] >= 0 {
            refs[q] = ref_idx_per_8x8[q].clamp(i8::MIN as i32, i8::MAX as i32) as i8;
            pocs[q] = poc_sentinel;
        }
    }
    (mvs, refs, pocs)
}

impl Encoder {
    /// Round-20 — encode one B-frame using `ref_l0` (typically the IDR /
    /// older anchor) and `ref_l1` (typically the next anchor — the prior
    /// P-frame in our IPB GOP). Emits just the slice NAL; SPS/PPS were
    /// shipped by the IDR. The B-frame is **non-reference**
    /// (`nal_ref_idc = 0`) so the DPB does not retain it, and we never
    /// chain another inter-coded frame off of it.
    ///
    /// Strategy per MB:
    ///   1. Run quarter-pel ME against L0 and against L1 independently.
    ///   2. Build the bipred predictor as `(L0_pred + L1_pred + 1) >> 1`
    ///      and SAD that against source as well.
    ///   3. Pick the minimum-SAD candidate among {L0, L1, Bi} as the
    ///      `pred` for this MB. Tie-break order: Bi → L0 → L1 (Bi first
    ///      because the bit cost of a bipred MB is offset by its lower
    ///      residual rate when L0 and L1 are close).
    ///   4. Emit `B_L0/L1/Bi_16x16` with the appropriate mvd(s),
    ///      residual, recon.
    ///
    /// The encoder never emits B_Skip or B_Direct in round 20 (they
    /// require derivation paths we don't yet exercise). The slice header
    /// still signals `direct_spatial_mv_pred_flag = 1` for spec
    /// completeness.
    pub fn encode_b(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
    ) -> EncodedB {
        self.encode_b_with_qp(
            frame,
            ref_l0,
            ref_l1,
            frame_num,
            pic_order_cnt_lsb,
            self.cfg.qp,
        )
    }

    /// [`encode_b`](Self::encode_b) with a per-frame QP override —
    /// same §7.4.3 `slice_qp_delta` mechanics as
    /// [`encode_idr_with_qp`](Self::encode_idr_with_qp).
    pub fn encode_b_with_qp(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
        frame_qp: i32,
    ) -> EncodedB {
        self.encode_b_impl(
            frame,
            ref_l0,
            ref_l1,
            frame_num,
            pic_order_cnt_lsb,
            frame_qp,
            None,
        )
    }

    /// [`encode_b_with_qp`](Self::encode_b_with_qp) plus **MB-row QP
    /// modulation** toward a whole-slice bit budget (round-443) —
    /// the B-picture sibling of
    /// [`encode_p_rate_adaptive`](Self::encode_p_rate_adaptive):
    /// identical row controller (asymmetric ±2-per-row stepping
    /// bounded to `frame_qp − 2 ..= frame_qp + 6`), with the QP
    /// changes riding §7.4.5 `mb_qp_delta` on MBs with coded
    /// residual; B_Skip and cbp==0 MBs inherit the previous MB's
    /// QP_Y exactly as the decoder derives it (the §8.7 deblock
    /// strengths follow the same chain).
    ///
    /// 4:2:0 only (the modulated writers' §7.3.5 mb_qp_delta gating
    /// is exercised at ChromaArrayType == 1).
    #[allow(clippy::too_many_arguments)]
    pub fn encode_b_rate_adaptive(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
        frame_qp: i32,
        frame_budget_bits: u64,
    ) -> EncodedB {
        assert_eq!(
            self.cfg.chroma_format_idc, 1,
            "encode_b_rate_adaptive requires 4:2:0"
        );
        self.encode_b_impl(
            frame,
            ref_l0,
            ref_l1,
            frame_num,
            pic_order_cnt_lsb,
            frame_qp,
            Some(frame_budget_bits),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn encode_b_impl(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        frame_num: u32,
        pic_order_cnt_lsb: u32,
        frame_qp: i32,
        row_budget_bits: Option<u64>,
    ) -> EncodedB {
        assert!(
            (0..=51).contains(&frame_qp),
            "frame_qp {frame_qp} out of 0..=51"
        );
        assert_eq!(frame.width, self.cfg.width);
        assert_eq!(frame.height, self.cfg.height);
        assert_eq!(ref_l0.width, self.cfg.width);
        assert_eq!(ref_l0.height, self.cfg.height);
        assert_eq!(ref_l1.width, self.cfg.width);
        assert_eq!(ref_l1.height, self.cfg.height);
        assert!(
            self.cfg.profile_idc >= 77,
            "B-slices require Main profile or higher (§A.2.2 — Baseline forbids B)"
        );
        // Round-382 — inside a transform_8x8_mode_flag=1 stream every
        // coded B MB shape used by this encoder passes the §7.3.5
        // second gate (no sub-partition below 8x8;
        // direct_8x8_inference_flag = 1 in our SPS), so each B writer
        // codes the mandatory transform_size_8x8_flag as 0 when
        // cbp_luma > 0 (`emit_transform_size_8x8_zero`). The B residual
        // itself stays on the 4x4 transform — an 8x8-residual RDO trial
        // for B MBs is a follow-up.

        let width = self.cfg.width as usize;
        let width_mbs = self.cfg.width / 16;
        let height_mbs = self.cfg.height / 16;
        // §6.2 Table 6-1 — chroma plane dimensions per chroma format
        // (round-397: encode_b runs at 4:2:0, 4:2:2 and 4:4:4;
        // round-448 adds 4:0:0).
        let chroma_width = match self.cfg.chroma_format_idc {
            0 => 0usize,
            3 => self.cfg.width as usize,
            _ => (self.cfg.width / 2) as usize,
        };
        let chroma_height = match self.cfg.chroma_format_idc {
            0 => 0usize,
            2 | 3 => self.cfg.height as usize,
            _ => (self.cfg.height / 2) as usize,
        };

        // SPS/PPS are not re-emitted for non-IDR slices.
        let mut stream: Vec<u8> = Vec::new();

        let log2_max_frame_num_minus4: u32 = 4;
        let log2_max_poc_lsb_minus4: u32 = 4;
        let chroma_qp_index_offset: i32 = 0;

        // Round-24 — direct_spatial_mv_pred_flag follows the encoder
        // configuration: 1 = §8.4.1.2.2 spatial direct (rounds 21/23),
        // 0 = §8.4.1.2.3 temporal direct (round 24). The slice header
        // signals the choice; the encoder's per-MB direct path picks
        // the matching derivation below.
        let direct_spatial = !self.cfg.direct_temporal_mv_pred;

        // Round-26 — explicit weighted-bipred weight selection.
        //
        // When `cfg.explicit_weighted_bipred` is set, fit a single
        // (w0, w1, o0, o1) at log2_wd = 5 against the two reference
        // recon planes and the source. The fit is a slice-wide constant
        // — a finer per-MB selection would need its own pred_weight
        // table per ref index, which is out of scope. The chosen weights
        // are then carried in the slice header's `pred_weight_table()`
        // and applied by the decoder via §8.4.2.3.2 explicit bipred.
        //
        // We accept the chosen weights only if they materially diverge
        // from the default (32, 32, 0, 0); otherwise the bit cost of
        // the pred_weight_table outweighs any gain and we leave the
        // table absent (decoder falls back to default merge).
        let weighted_table = if self.cfg.explicit_weighted_bipred {
            Some(compute_explicit_bipred_weights(
                frame.y,
                ref_l0.recon_y,
                ref_l1.recon_y,
                self.cfg.width as usize,
                self.cfg.height as usize,
                ref_l0.width as usize,
                ref_l1.width as usize,
            ))
        } else {
            None
        };
        let weighted_luma_for_mb: Option<WeightedBipredLuma> =
            weighted_table.map(|t| WeightedBipredLuma {
                log2_wd: t.luma_log2_weight_denom,
                weight_l0: t.luma_weight_l0,
                offset_l0: t.luma_offset_l0,
                weight_l1: t.luma_weight_l1,
                offset_l1: t.luma_offset_l1,
                apply_chroma: false,
            });

        let mut sw = BitWriter::new();
        write_b_slice_header(
            &mut sw,
            &BSliceHeaderConfig {
                first_mb_in_slice: 0,
                slice_type_raw: 6, // B, all-same-type
                pic_parameter_set_id: 0,
                colour_plane_id: self.cfg.colour_plane_id,
                frame_num,
                frame_num_bits: log2_max_frame_num_minus4 + 4,
                pic_order_cnt_lsb,
                poc_lsb_bits: log2_max_poc_lsb_minus4 + 4,
                direct_spatial_mv_pred_flag: direct_spatial,
                slice_qp_delta: frame_qp - self.cfg.qp,
                // 4:4:4 mirrors encode_idr / encode_p: deblocking
                // disabled per §7.4.3 (the §8.7 luma-filter-on-chroma
                // path for ChromaArrayType == 3 is not wired).
                disable_deblocking_filter_idc: if self.cfg.chroma_format_idc == 3 {
                    1
                } else {
                    0
                },
                slice_alpha_c0_offset_div2: 0,
                slice_beta_offset_div2: 0,
                nal_ref_idc: 0, // non-reference B
                pred_weight_table: weighted_table,
                cabac: None,
                field: FieldPicSignal::FrameMbsOnly,
            },
        );

        // Reconstruction state for THIS picture.
        let mut recon_y = vec![0u8; (self.cfg.width * self.cfg.height) as usize];
        let mut recon_u = vec![0u8; chroma_width * chroma_height];
        let mut recon_v = vec![0u8; chroma_width * chroma_height];

        // §8.5.8 BD-aware chroma-QP — see encode_idr; identical reasoning.
        let qp_bd_offset_c = qp_bd_offset(self.cfg.bit_depth_chroma_minus8);

        let mut nc_grid = CavlcNcGrid::new(width_mbs, height_mbs);
        let mut intra_grid = IntraGrid::new(width_mbs as usize, height_mbs as usize);
        // Two MV-pred grids — one per reference list. §8.4.1.3 derives
        // mvpLX from neighbours' refIdxLX / mvLX of the *same* list, so
        // the L0 and L1 predictors are derived independently from each
        // other.
        let mut mv_grid_l0 = MvGrid::new(width_mbs as usize, height_mbs as usize);
        let mut mv_grid_l1 = MvGrid::new(width_mbs as usize, height_mbs as usize);

        let mut mb_deblock_infos: Vec<MbDeblockInfo> =
            vec![MbDeblockInfo::default(); (width_mbs * height_mbs) as usize];

        // §7.3.4 CAVLC B-slice walker — `mb_skip_run` ue(v) accumulates
        // consecutive B_Skip MBs and is flushed before every coded MB
        // (and once at end-of-slice). Round-21 enables B_Skip when the
        // §8.4.1.2.2 spatial-direct predictor agrees with the encoder's
        // chosen MVs and the residual quantises to all-zero.
        let mut pending_skip: u32 = 0;
        let mut i8x8_mb_count = 0u32;
        // §7.4.5 decoded-QP chain: starts at SliceQP_Y (§7.4.3).
        let mut qp_tracker = MbQpTracker::new(frame_qp);
        let mut want_qp = frame_qp;
        for mb_y in 0..height_mbs as usize {
            // Round-443 — MB-row QP modulation, identical controller
            // to `encode_p_impl` (round 420): compare bits spent so
            // far to the pro-rata share of the slice budget and step
            // the working QP, asymmetrically (overshoot climbs up to
            // +2 per row toward frame_qp + 6, undershoot descends one
            // step toward frame_qp - 2 and only once most of the
            // slice has proven cheap).
            if let Some(budget) = row_budget_bits {
                if mb_y > 0 && budget > 0 {
                    let frac = mb_y as f64 / height_mbs as f64;
                    let spent = sw.bits_emitted() as f64;
                    let expected = (budget as f64 * frac).max(1.0);
                    let ratio = spent.max(1.0) / expected;
                    let adj = if ratio >= 1.0 {
                        (6.0 * ratio.log2()).round() as i32
                    } else {
                        (3.0 * ratio.log2()).round() as i32
                    };
                    let mut new_want = frame_qp + adj;
                    if new_want < frame_qp && frac < 0.6 {
                        new_want = frame_qp;
                    }
                    want_qp = new_want
                        .clamp(want_qp - 1, want_qp + 2)
                        .clamp(frame_qp - 2, frame_qp + 6)
                        .clamp(0, 51);
                }
            }
            let qp_y = want_qp;
            let qp_c = qp_y_to_qp_c_with_bd_offset(qp_y, chroma_qp_index_offset, qp_bd_offset_c);

            for mb_x in 0..width_mbs as usize {
                let mb_addr = mb_y * (width_mbs as usize) + mb_x;
                // Round-29: Intra fallback in B-slice via RDO wrapper.
                let dbl = self.encode_b_mb_with_intra_fallback(
                    frame,
                    ref_l0,
                    ref_l1,
                    mb_x,
                    mb_y,
                    qp_y,
                    qp_c,
                    chroma_width,
                    chroma_height,
                    width,
                    &mut recon_y,
                    &mut recon_u,
                    &mut recon_v,
                    &mut sw,
                    &mut nc_grid,
                    &mut intra_grid,
                    &mut mv_grid_l0,
                    &mut mv_grid_l1,
                    &mut pending_skip,
                    pic_order_cnt_lsb as i32,
                    weighted_luma_for_mb,
                    &mut qp_tracker,
                );
                if dbl.transform_size_8x8_flag {
                    i8x8_mb_count += 1;
                }
                mb_deblock_infos[mb_addr] = dbl;
            }
        }
        // §7.3.4 — flush any trailing skip run (mb_skip_run for the
        // final group of skips at end-of-slice).
        sw.ue(pending_skip);

        // §7.3.2.8 — slice_data trailing bits.
        sw.rbsp_trailing_bits();
        let slice_rbsp = sw.into_bytes();
        // nal_ref_idc = 0 (non-reference B).
        stream.extend_from_slice(&build_nal_unit(0, NalUnitType::SliceNonIdr, &slice_rbsp));

        // §8.7 — picture-level in-loop deblocking. The B picture itself
        // is not used as a reference but we run the filter so the
        // exported recon matches what the decoder will output (and so
        // any test comparing against ffmpeg's decoded YUV measures the
        // post-filter samples). 4:4:4 skips the pass (slice header set
        // disable_deblocking_filter_idc = 1).
        if self.cfg.chroma_format_idc != 3 {
            crate::encoder::deblock::deblock_recon_with_chroma_array_type(
                self.cfg.width,
                self.cfg.height,
                chroma_width as u32,
                chroma_height as u32,
                &mut recon_y,
                &mut recon_u,
                &mut recon_v,
                &mb_deblock_infos,
                chroma_qp_index_offset,
                width_mbs,
                height_mbs,
                self.cfg.chroma_format_idc,
            );
        }

        // Capture per-8x8 MV state from the L0 grid (B-frames are
        // non-reference so this is normally unused; provided for API
        // symmetry with EncodedP / EncodedIdr).
        let n_parts = (width_mbs as usize) * (height_mbs as usize) * 4;
        let mut partition_mvs = Vec::with_capacity(n_parts);
        for slot in &mv_grid_l0.slots {
            for part in 0..4usize {
                // Both "not available" and "intra" map to (mv=0,
                // ref=-1, is_intra=true) per §8.4.1.2.1: an intra
                // colocated MB has refIdxCol=-1, and an unencoded slot
                // is treated identically to "intra" by the colocated
                // probe.
                let (mv, ref_idx, is_intra) = if !slot.available || slot.is_intra {
                    (Mv::ZERO, -1, true)
                } else {
                    (slot.mv_l0_8x8[part], slot.ref_idx_l0_8x8[part], false)
                };
                partition_mvs.push(FrameRefPartitionMv {
                    mv_l0: (
                        mv.x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                        mv.y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
                    ),
                    ref_idx_l0: ref_idx.clamp(-1, 127) as i8,
                    is_intra,
                });
            }
        }

        EncodedB {
            annex_b: stream,
            recon_y,
            recon_u,
            recon_v,
            recon_width: self.cfg.width,
            recon_height: self.cfg.height,
            frame_num,
            pic_order_cnt_lsb,
            partition_mvs,
            i8x8_mb_count,
        }
    }

    /// Encode one B-slice macroblock. Mirrors [`Encoder::encode_p_mb`]
    /// but with two-list ME and the §8.4.2.3 weighted-pred merge for
    /// bipred.
    ///
    /// Round-21 adds the **spatial direct** path:
    ///   * Compute the §8.4.1.2.2 derived MVs / refIdxs for this MB's
    ///     neighbour configuration.
    ///   * Build the corresponding predictor and trial-quantise its
    ///     residual.
    ///   * If the result has `cbp_luma == cbp_chroma == 0`, emit the MB
    ///     as **B_Skip** (extends `pending_skip`). Otherwise compare its
    ///     SAD against the explicit-inter candidates (L0/L1/Bi) and
    ///     prefer **B_Direct_16x16** when its SAD is competitive (it
    ///     saves the mvds + ref_idx in the bitstream).
    #[allow(clippy::too_many_arguments)]
    fn encode_b_mb(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        _chroma_height: usize,
        src_stride: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid_l0: &mut MvGrid,
        mv_grid_l1: &mut MvGrid,
        pending_skip: &mut u32,
        // Round-24 — picture order count of the current B-frame, used by
        // §8.4.1.2.3 temporal direct (with `ref_l0.pic_order_cnt` =
        // pic0 POC and `ref_l1.pic_order_cnt` = pic1 POC). Ignored
        // when the encoder is configured for spatial direct.
        curr_poc: i32,
        // Round-26 — explicit weighted-bipred parameters (luma) for
        // this B slice. `Some` when the slice header carries a
        // `pred_weight_table()`; the bipred merge in `build_b_predictors`
        // then uses §8.4.2.3.2 eq. 8-276 instead of the default average.
        weighted: Option<WeightedBipredLuma>,
        // Round-443 — §7.4.5 decoded-QP chain for MB-row modulation
        // (`encode_b_rate_adaptive`); at frame-constant QP the chain
        // always equals `qp_y` and every emitted delta is 0.
        qp_tracker: &mut MbQpTracker,
    ) -> MbDeblockInfo {
        // Round-397 — 4:2:2 / 4:4:4 B MBs take a dedicated body with
        // the {B_Skip, B_Direct_16x16, B_L0/L1/Bi_16x16, 16x8 / 8x16
        // partitions} mode set and per-format chroma MC + residual
        // coding. B_8x8 remains a 4:2:0-only encoder choice. Row
        // modulation is 4:2:0-only, so the chain is degenerate here.
        if self.cfg.chroma_format_idc != 1 {
            debug_assert_eq!(
                qp_tracker.cur, qp_y,
                "row modulation (non-zero mb_qp_delta) is 4:2:0-only"
            );
            return self.encode_b_mb_multifmt(
                frame,
                ref_l0,
                ref_l1,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                _chroma_height,
                src_stride,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mv_grid_l0,
                mv_grid_l1,
                pending_skip,
                curr_poc,
                weighted,
            );
        }
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;

        // 1. Per-list quarter-pel ME (integer + ½-pel + ¼-pel). Exact
        //    same routine the P encoder uses; only the reference plane
        //    differs.
        let me_l0 = search_quarter_pel_16x16(
            frame.y,
            src_stride,
            self.cfg.width,
            self.cfg.height,
            ref_l0.recon_y,
            ref_l0.width as usize,
            ref_l0.width,
            ref_l0.height,
            mb_x,
            mb_y,
            16,
            16,
        );
        let me_l1 = search_quarter_pel_16x16(
            frame.y,
            src_stride,
            self.cfg.width,
            self.cfg.height,
            ref_l1.recon_y,
            ref_l1.width as usize,
            ref_l1.width,
            ref_l1.height,
            mb_x,
            mb_y,
            16,
            16,
        );
        let mv_l0 = Mv::new(me_l0.mv_x, me_l0.mv_y);
        let mv_l1 = Mv::new(me_l1.mv_x, me_l1.mv_y);

        // 2. Build the L0-only / L1-only / bipred predictors and SAD them
        //    against the source. The predictors are built once and then
        //    re-used for the chosen mode.
        let (pred_y_l0, pred_u_l0, pred_v_l0) = build_b_predictors(
            BPred16x16::L0,
            ref_l0,
            ref_l1,
            mb_x,
            mb_y,
            mv_l0,
            mv_l1,
            weighted,
        );
        let (pred_y_l1, pred_u_l1, pred_v_l1) = build_b_predictors(
            BPred16x16::L1,
            ref_l0,
            ref_l1,
            mb_x,
            mb_y,
            mv_l0,
            mv_l1,
            weighted,
        );
        let (pred_y_bi, pred_u_bi, pred_v_bi) = build_b_predictors(
            BPred16x16::Bi,
            ref_l0,
            ref_l1,
            mb_x,
            mb_y,
            mv_l0,
            mv_l1,
            weighted,
        );

        let sad_l0 = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &pred_y_l0);
        let sad_l1 = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &pred_y_l1);
        let sad_bi = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &pred_y_bi);

        // 2.5 Round-21 / Round-24 — direct mode trial.
        //
        // Mirror the decoder's derivation locally to learn what MVs /
        // refIdxs the decoder would compute if we emitted B_Direct here.
        // Build that predictor, trial-quantise its residual, and compare
        // against the explicit-inter candidates.
        //
        // The encoder's `cfg.direct_temporal_mv_pred` flag chooses
        // between two spec-defined paths:
        //   * `false` (default) — §8.4.1.2.2 SPATIAL direct (rounds 21
        //     / 23). MVs/refIdxs derived from the (A, B, C) MB-level
        //     neighbour mvs/refs of the current B-frame's grids, with
        //     a per-8x8 step-7 colZeroFlag override probing the L1
        //     anchor's colocated motion.
        //   * `true` — §8.4.1.2.3 TEMPORAL direct (round 24). MVs are
        //     POC-distance scalings of the L1 anchor's per-partition
        //     L0 motion vectors; refIdxs collapse to (0, 0) for our
        //     single-ref-per-list setup.
        //
        // Round-21 only emits B_Direct / B_Skip when the derivation
        // produces a uniform MV across all 4 8x8 partitions; round-23
        // adds B_8x8+all-Direct for the per-partition case. Same set
        // of writers serves both spatial and temporal — only the
        // derivation differs.
        let direct = if self.cfg.direct_temporal_mv_pred {
            b_temporal_direct_derive(
                ref_l1.partition_mvs,
                width_mbs,
                mb_x,
                mb_y,
                curr_poc,
                ref_l0.pic_order_cnt,
                ref_l1.pic_order_cnt,
            )
        } else {
            b_spatial_direct_derive(
                mv_grid_l0,
                mv_grid_l1,
                ref_l1.partition_mvs,
                width_mbs,
                mb_x,
                mb_y,
            )
        };
        let direct_uniform = direct.is_uniform();
        // Round-440 — under `b_l0_bi_only` a direct derivation whose
        // refIdxL0 collapsed below 0 (L1-only prediction) is not
        // representable in the L0-only colocated snapshot this
        // picture's consumers read; drop the direct candidates for
        // this MB (legal mode-choice restriction).
        let direct_l0_ok = !(self.cfg.b_l0_bi_only && direct.ref_idx_l0 < 0);
        // Map (refIdxL0 >= 0, refIdxL1 >= 0) onto the same BPred16x16
        // enum the explicit-inter writer uses, so the predictor builder
        // is shared. Direct mode where neither list is used should not
        // happen (directZeroPredictionFlag forces both refs to 0), but
        // if it did we fall back to L0-only with mv=0.
        let direct_pred_kind: Option<BPred16x16> =
            match (direct.ref_idx_l0 >= 0, direct.ref_idx_l1 >= 0) {
                (true, true) => Some(BPred16x16::Bi),
                (true, false) => Some(BPred16x16::L0),
                (false, true) => Some(BPred16x16::L1),
                (false, false) => None,
            };

        // Compute the direct predictor + SAD only when the configuration
        // is exploitable (uniform across 8x8 partitions and at least one
        // list is used).
        let (direct_competitive, direct_pred_y, direct_pred_u, direct_pred_v, direct_sad) =
            match (direct_uniform && direct_l0_ok, direct_pred_kind) {
                (true, Some(dpk)) => {
                    let (dy, du, dv) = build_b_predictors(
                        dpk,
                        ref_l0,
                        ref_l1,
                        mb_x,
                        mb_y,
                        direct.mv_l0(),
                        direct.mv_l1(),
                        weighted,
                    );
                    let dsad = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &dy);
                    (true, dy, du, dv, dsad)
                }
                _ => (false, [0i32; 256], [0i32; 64], [0i32; 64], u32::MAX),
            };

        // 2.6 Round-23 — `B_8x8` with all four sub_mb_type =
        // `B_Direct_8x8`. This honours the per-8x8 MVs produced by the
        // §8.4.1.2.2 step-7 colZeroFlag override (which can drive
        // individual partitions' MVs to (0,0) while leaving others on
        // the median MVpred), as well as any future per-8x8 refIdx
        // disagreement. Compute the per-8x8 stitched predictor and its
        // SAD whenever direct_pred_kind is well-defined; the BMode
        // selector below picks among {direct uniform, direct per-8x8,
        // explicit, partition} on Lagrangian cost.
        let direct_8x8_kinds = direct_per_8x8_kinds(&direct);
        let (
            direct_8x8_competitive,
            direct_8x8_pred_y,
            direct_8x8_pred_u,
            direct_8x8_pred_v,
            direct_8x8_sad,
        ) = match direct_pred_kind.filter(|_| direct_l0_ok) {
            Some(_) => {
                let (dy, du, dv) = build_b_direct_8x8_predictors(
                    weighted,
                    direct_8x8_kinds,
                    direct.mv_l0_per_8x8,
                    direct.mv_l1_per_8x8,
                    ref_l0,
                    ref_l1,
                    mb_x,
                    mb_y,
                );
                let dsad = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &dy);
                (true, dy, du, dv, dsad)
            }
            None => (false, [0i32; 256], [0i32; 64], [0i32; 64], u32::MAX),
        };

        // 2.7 Round-25 — `B_8x8` with **mixed** per-cell sub_mb_type.
        // Per-cell qpel ME on each list (re-using `search_quarter_pel_8x8`),
        // then per-cell pick of {Direct, L0, L1, Bi} on Lagrangian SAD.
        // The Direct cell predictor is sliced from the round-23
        // `direct_8x8_pred_y` 16x16 buffer at the appropriate quadrant.
        // The mixed predictor is stitched from the per-cell winners. If
        // every cell ends up Direct we collapse to the round-23 path
        // (the all-Direct writer is a tighter syntax than the round-25
        // mixed writer when no MVs are emitted).
        let mut mixed_me_l0_cells: [Mv; 4] = [Mv::ZERO; 4];
        let mut mixed_me_l1_cells: [Mv; 4] = [Mv::ZERO; 4];
        for cell in 0..4usize {
            let sx = cell % 2;
            let sy = cell / 2;
            let r0 = search_quarter_pel_8x8(
                frame.y,
                src_stride,
                self.cfg.width,
                self.cfg.height,
                ref_l0.recon_y,
                ref_l0.width as usize,
                ref_l0.width,
                ref_l0.height,
                mb_x,
                mb_y,
                sx,
                sy,
                4,
                4,
            );
            let r1 = search_quarter_pel_8x8(
                frame.y,
                src_stride,
                self.cfg.width,
                self.cfg.height,
                ref_l1.recon_y,
                ref_l1.width as usize,
                ref_l1.width,
                ref_l1.height,
                mb_x,
                mb_y,
                sx,
                sy,
                4,
                4,
            );
            mixed_me_l0_cells[cell] = Mv::new(r0.mv_x, r0.mv_y);
            mixed_me_l1_cells[cell] = Mv::new(r1.mv_x, r1.mv_y);
        }

        let mut mixed_cells = [BSubMbCell::Direct; 4];
        let mut mixed_cell_mv_l0 = [Mv::ZERO; 4];
        let mut mixed_cell_mv_l1 = [Mv::ZERO; 4];
        let mut mixed_cell_pred_y_per_cell = [[0i32; 64]; 4];
        let mut mixed_total_sad = 0u32;
        let mixed_competitive = direct_pred_kind.is_some();
        if mixed_competitive {
            for cell in 0..4usize {
                let sub_x = cell % 2;
                let sub_y = cell / 2;
                // Slice the Direct cell's 8x8 luma predictor out of the
                // 16x16 buffer.
                let mut direct_cell_pred = [0i32; 64];
                for j in 0..8usize {
                    for i in 0..8usize {
                        direct_cell_pred[j * 8 + i] =
                            direct_8x8_pred_y[(sub_y * 8 + j) * 16 + sub_x * 8 + i];
                    }
                }
                let (cell_kind, cell_mv0, cell_mv1, cell_pred, cell_sad) = pick_best_b8x8_cell(
                    frame.y,
                    src_stride,
                    ref_l0,
                    ref_l1,
                    mb_x,
                    mb_y,
                    sub_x,
                    sub_y,
                    &direct_cell_pred,
                    mixed_me_l0_cells[cell],
                    mixed_me_l1_cells[cell],
                    qp_y,
                );
                mixed_cells[cell] = cell_kind;
                mixed_cell_mv_l0[cell] = cell_mv0;
                mixed_cell_mv_l1[cell] = cell_mv1;
                mixed_cell_pred_y_per_cell[cell] = cell_pred;
                mixed_total_sad = mixed_total_sad.saturating_add(cell_sad);
            }
        } else {
            mixed_total_sad = u32::MAX;
        }

        // The mixed mode is only worth emitting when at least one cell
        // picked a non-Direct kind (otherwise the round-23 all-Direct
        // writer is tighter and produces the same predictor).
        let mixed_has_non_direct = mixed_cells.iter().any(|&c| c != BSubMbCell::Direct);
        // Round-440 — the Mixed8x8 per-cell merges are not wired for
        // the §8.4.2.3.3 implicit weighted combine, and its cells may
        // pick L1-only prediction; drop the candidate under the
        // implicit-weight axis and under `b_l0_bi_only` (a legal
        // encoder mode-choice restriction — the emitted syntax stays
        // fully conforming).
        let mixed_competitive_for_pick = mixed_competitive
            && mixed_has_non_direct
            && !weighted.map(|w| w.apply_chroma).unwrap_or(false)
            && !self.cfg.b_l0_bi_only;

        // Stitch the per-cell mixed luma + chroma composite predictors.
        let (mixed_pred_y, mixed_pred_u, mixed_pred_v) = if mixed_competitive_for_pick {
            let mut py = [0i32; 256];
            let mut pu = [0i32; 64];
            let mut pv = [0i32; 64];
            let chroma_w_l0 = ref_l0.width / 2;
            let chroma_h_l0 = ref_l0.height / 2;
            let chroma_w_l1 = ref_l1.width / 2;
            let chroma_h_l1 = ref_l1.height / 2;
            for cell in 0..4usize {
                let sub_x = cell % 2;
                let sub_y = cell / 2;
                let cell_pred_y = mixed_cell_pred_y_per_cell[cell];
                for j in 0..8usize {
                    for i in 0..8usize {
                        py[(sub_y * 8 + j) * 16 + sub_x * 8 + i] = cell_pred_y[j * 8 + i];
                    }
                }
                // Chroma predictor for this cell. Direct cells use the
                // §8.4.1.2.2-derived per-8x8 MVs; explicit cells use the
                // per-cell ME MVs. The chroma kind for Direct cells
                // honours the §8.4.1.2.2 derived (refIdxL0, refIdxL1)
                // status (both >= 0 → Bi; only one >= 0 → L0/L1).
                let (mv0, mv1) = if mixed_cells[cell] == BSubMbCell::Direct {
                    (direct.mv_l0_per_8x8[cell], direct.mv_l1_per_8x8[cell])
                } else {
                    (mixed_cell_mv_l0[cell], mixed_cell_mv_l1[cell])
                };
                let chroma_kind = match mixed_cells[cell] {
                    BSubMbCell::Direct => {
                        match (direct.ref_idx_l0 >= 0, direct.ref_idx_l1 >= 0) {
                            (true, true) => BSubMbCell::Bi,
                            (true, false) => BSubMbCell::L0,
                            (false, true) => BSubMbCell::L1,
                            (false, false) => BSubMbCell::L0, // defensive
                        }
                    }
                    other => other,
                };
                let cu = build_b_explicit_4x4_cell_chroma(
                    chroma_kind,
                    ref_l0.recon_u,
                    ref_l1.recon_u,
                    chroma_w_l0,
                    chroma_h_l0,
                    chroma_w_l1,
                    chroma_h_l1,
                    mb_x,
                    mb_y,
                    sub_x,
                    sub_y,
                    mv0,
                    mv1,
                );
                let cv = build_b_explicit_4x4_cell_chroma(
                    chroma_kind,
                    ref_l0.recon_v,
                    ref_l1.recon_v,
                    chroma_w_l0,
                    chroma_h_l0,
                    chroma_w_l1,
                    chroma_h_l1,
                    mb_x,
                    mb_y,
                    sub_x,
                    sub_y,
                    mv0,
                    mv1,
                );
                for j in 0..4usize {
                    for i in 0..4usize {
                        pu[(sub_y * 4 + j) * 8 + sub_x * 4 + i] = cu[j * 4 + i];
                        pv[(sub_y * 4 + j) * 8 + sub_x * 4 + i] = cv[j * 4 + i];
                    }
                }
            }
            (py, pu, pv)
        } else {
            ([0i32; 256], [0i32; 64], [0i32; 64])
        };

        // 3. Pick the candidate that minimises a Lagrangian cost
        //    `J = SAD_luma + λ · R_syntax`. Direct mode emits the
        //    smallest syntax block (just `mb_type=0 + cbp`, or nothing
        //    at all when B_Skip), so it gets a SAD allowance that
        //    reflects its rate savings.
        //
        // We approximate R_syntax with simple constants:
        //   * Direct (cbp != 0): ~2 bits (`mb_type=0` ue + `cbp_codenum`
        //     ue=0 if cbp small).
        //   * Direct + cbp == 0 (would emit B_Skip): 0 bits (run-length).
        //   * Explicit L0 / L1: ~3 + 2·avg_mvd_bits ≈ ~12 bits.
        //   * Explicit Bi:      ~3 + 4·avg_mvd_bits ≈ ~20 bits.
        //
        // The "SAD-equivalent" of one bit at QP_Y is roughly
        //   λ · 1 ≈ 0.85 · 2^((QP-12)/3) bits-to-SAD scaling.
        // For QP=26 this gives λ ≈ 22, and the explicit-vs-direct
        // syntax delta is ~10-20 bits → an equivalent SAD margin of
        // ~200-440. Empirically a fixed margin of 16 bits' worth on
        // top of the explicit candidate's SAD is sufficient for static
        // / smooth content where ME is searching a flat SAD landscape.
        #[derive(Debug, Clone, Copy)]
        enum BMode {
            Direct,
            /// Round-23: `B_8x8` with all four sub_mb_type=B_Direct_8x8.
            /// Same MV / ref derivation as Direct (§8.4.1.2.2), but with
            /// per-8x8 motion compensation honouring the colZeroFlag
            /// step-7 per-partition overrides. Bigger MB syntax than
            /// `B_Direct_16x16` (mb_type=22 ue(9 bits) + 4× sub_mb_type
            /// ue(1 bit) = 13 bits before cbp), so only chosen when
            /// direct_8x8_sad beats direct_uniform_sad by more than the
            /// extra-syntax cost.
            DirectPer8x8,
            /// Round-25: `B_8x8` with mixed per-cell sub_mb_type (some
            /// cells Direct, others L0/L1/Bi). Each non-Direct cell adds
            /// ~6-12 bits of MB syntax (sub_mb_type overhead + per-cell
            /// mvds), so only chosen when the per-cell motion materially
            /// beats the all-Direct (round-23) candidate.
            Mixed8x8,
            Explicit(BPred16x16),
        }
        // Per-MB Lagrangian penalty applied to explicit candidates
        // relative to Direct, in SAD units. Tuned conservatively so
        // round-20 fixtures still see Bi pick when it materially beats
        // Direct (the round-20 midpoint test has direct_sad far above
        // bi_sad on every MB → Bi still wins there).
        let direct_bias_sad: u32 = {
            // λ · bit-savings, scaled coarsely. For QP 0..51 this
            // ranges from ~1 (low QP) to ~64 (QP 51). The bit savings
            // (Direct vs Explicit Bi) are ~20 bits, so a typical
            // smooth-motion B-slice gets a few hundred SAD units of
            // headroom in favour of Direct.
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 16
        };
        // Round-23 — extra cost for B_8x8+all-Direct relative to
        // B_Direct_16x16: ~13 - 1 = ~12 bits of MB header (mb_type 22 +
        // 4× sub_mb_type=0 = 13 bits, vs B_Direct_16x16's 1 bit
        // mb_type=0). Bias the selector against per-8x8 direct so we
        // only switch when the per-8x8 motion materially beats the
        // single-MV uniform predictor.
        let direct_8x8_bias_sad: u32 = {
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 12
        };
        // Best direct candidate (between uniform B_Direct_16x16 and
        // per-8x8 B_8x8+all-Direct). Pick uniform when its SAD plus the
        // per-8x8 syntax-cost bias still beats the per-8x8 SAD.
        let prefer_per_8x8 = direct_8x8_competitive
            && (!direct_competitive
                || direct_8x8_sad.saturating_add(direct_8x8_bias_sad) < direct_sad);
        let (best_direct_competitive, best_direct_sad, best_direct_is_per_8x8) = if prefer_per_8x8 {
            (direct_8x8_competitive, direct_8x8_sad, true)
        } else {
            (direct_competitive, direct_sad, false)
        };
        // Round-25 — mixed `B_8x8` candidate. The per-cell pick already
        // factored in a per-cell Lagrangian rate cost (in
        // `pick_best_b8x8_cell`), so `mixed_total_sad` already includes
        // the per-non-Direct-cell sub_mb_type+mvd bit penalty.
        //
        // Mixed8x8 vs B_Direct_16x16: Mixed costs +12 bits of MB header
        // (mb_type 22 ue(9) + 4× sub_mb_type ue(≥1) ≥ 4 bits, vs
        // B_Direct_16x16's 1-bit mb_type=0).
        //
        // Mixed8x8 vs DirectPer8x8: same MB header (both mb_type=22),
        // but Mixed's sub_mb_type entries cost ≥3 extra bits each for
        // non-Direct cells (ue(1)/ue(2)/ue(3) = 3/3/5 bits vs ue(0) = 1
        // bit) — that overhead is the per-cell `(lambda+1)*6` term in
        // `pick_best_b8x8_cell`'s rate cost.
        //
        // To gate Mixed vs DirectPer8x8 / B_Direct_16x16 fairly:
        //   * If best_direct is the 16x16 form, add the +12-bit MB
        //     header penalty to Mixed's J score.
        //   * If best_direct is DirectPer8x8, no extra penalty (same MB
        //     header).
        //
        // Plus a small extra "tie-break" margin so Mixed only fires when
        // it materially beats the simpler all-Direct candidate.
        let mixed_mb_header_bias_sad: u32 = if best_direct_is_per_8x8 {
            0
        } else {
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 12
        };
        let mixed_tiebreak_bias_sad: u32 = {
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 8
        };
        let prefer_mixed = mixed_competitive_for_pick
            && best_direct_competitive
            && mixed_total_sad
                .saturating_add(mixed_mb_header_bias_sad)
                .saturating_add(mixed_tiebreak_bias_sad)
                < best_direct_sad;
        let chosen_mode: BMode = if prefer_mixed {
            BMode::Mixed8x8
        } else if best_direct_competitive
            && best_direct_sad <= sad_bi.saturating_add(direct_bias_sad)
            && best_direct_sad <= sad_l0.saturating_add(direct_bias_sad)
            && best_direct_sad <= sad_l1.saturating_add(direct_bias_sad)
        {
            if best_direct_is_per_8x8 {
                BMode::DirectPer8x8
            } else {
                BMode::Direct
            }
        } else if sad_bi <= sad_l0 && (sad_bi <= sad_l1 || self.cfg.b_l0_bi_only) {
            BMode::Explicit(BPred16x16::Bi)
        } else if sad_l0 <= sad_l1 || self.cfg.b_l0_bi_only {
            // Round-440 — `b_l0_bi_only` keeps every coded MB's motion
            // representable in the L0-only colocated snapshot a later
            // temporal-direct derivation reads (§8.4.1.2.1 prefers the
            // colocated L0 motion; an L1-only macroblock would make
            // the co-located read fall through to L1).
            BMode::Explicit(BPred16x16::L0)
        } else {
            BMode::Explicit(BPred16x16::L1)
        };
        let (pred, pred_y, pred_u, pred_v, eff_mv_l0, eff_mv_l1) = match chosen_mode {
            BMode::Direct => {
                // Direct's effective MVs are the §8.4.1.2.2 derivation's
                // outputs (used for downstream grid updates + deblocker
                // mv-identity). The explicit `pred` enum carries which
                // list(s) the predictor reads; for the writer we'll use
                // the dedicated B_Direct_16x16 path (no mvd / ref_idx).
                (
                    direct_pred_kind.expect("Direct chosen → direct_pred_kind set"),
                    direct_pred_y,
                    direct_pred_u,
                    direct_pred_v,
                    direct.mv_l0(),
                    direct.mv_l1(),
                )
            }
            BMode::DirectPer8x8 => {
                // The MB-level (eff_mv_l0, eff_mv_l1) returned here is
                // only used for downstream grid + deblock setup when
                // partition_choice is None (the per-8x8 path patches its
                // own per-8x8 MVs into the grid further below), so we
                // hand back the top-left 8x8's MV as a representative —
                // the real per-8x8 grid update happens in the explicit
                // per-8x8 branch after `partition_choice` is settled.
                (
                    direct_pred_kind.expect("DirectPer8x8 chosen → direct_pred_kind set"),
                    direct_8x8_pred_y,
                    direct_8x8_pred_u,
                    direct_8x8_pred_v,
                    direct.mv_l0_per_8x8[0],
                    direct.mv_l1_per_8x8[0],
                )
            }
            BMode::Mixed8x8 => {
                // Round-25 — `B_8x8` with mixed sub_mb_type cells. The
                // composite predictor was stitched above. The MB-level
                // `pred` enum is a coarse summary used by downstream
                // grid / deblock helpers when no per-cell override
                // overrides them; the per-cell branch below patches the
                // grid with the per-cell MVs / refs directly.
                let any_l0 = mixed_cells.iter().any(|&c| c.writes_l0()) || direct.ref_idx_l0 >= 0;
                let any_l1 = mixed_cells.iter().any(|&c| c.writes_l1()) || direct.ref_idx_l1 >= 0;
                let summary = match (any_l0, any_l1) {
                    (true, true) => BPred16x16::Bi,
                    (true, false) => BPred16x16::L0,
                    (false, true) => BPred16x16::L1,
                    (false, false) => BPred16x16::L0, // defensive
                };
                (
                    summary,
                    mixed_pred_y,
                    mixed_pred_u,
                    mixed_pred_v,
                    mixed_cell_mv_l0[0],
                    mixed_cell_mv_l1[0],
                )
            }
            BMode::Explicit(BPred16x16::Bi) => (
                BPred16x16::Bi,
                pred_y_bi,
                pred_u_bi,
                pred_v_bi,
                mv_l0,
                mv_l1,
            ),
            BMode::Explicit(BPred16x16::L0) => (
                BPred16x16::L0,
                pred_y_l0,
                pred_u_l0,
                pred_v_l0,
                mv_l0,
                Mv::ZERO,
            ),
            BMode::Explicit(BPred16x16::L1) => (
                BPred16x16::L1,
                pred_y_l1,
                pred_u_l1,
                pred_v_l1,
                Mv::ZERO,
                mv_l1,
            ),
        };
        let mut is_direct = matches!(chosen_mode, BMode::Direct);
        // Round-23 — when DirectPer8x8 is chosen, we still want the
        // partition-mode override below to be DISABLED (Direct paths
        // never pair with explicit 16x8 / 8x16 partition shapes).
        let is_direct_per_8x8 = matches!(chosen_mode, BMode::DirectPer8x8);
        // Round-25 — Mixed8x8 also bypasses the 16x8 / 8x16 partition
        // override (mb_type=22 is mutually exclusive with raws 4..=21).
        let is_mixed_8x8 = matches!(chosen_mode, BMode::Mixed8x8);

        // ---- Round-22: try 16x8 / 8x16 partition modes ----
        //
        // For each of the 4 partition shapes, pick the best (per-list
        // MV, mode) pair. Then compare the joint partition-shape SAD
        // against the winning 16x16 / Direct candidate above. Use a
        // Lagrangian rate cost: a partition MB pays ~10-30 extra bits
        // over 16x16 (single-ref → no extra ref_idx fields, just the
        // larger mb_type ue(v) and the duplicated mvds).
        let mut me_l0_cells: [Mv; 4] = [Mv::ZERO; 4];
        let mut me_l1_cells: [Mv; 4] = [Mv::ZERO; 4];
        for cell in 0..4usize {
            let sx = cell % 2;
            let sy = cell / 2;
            let r0 = search_quarter_pel_8x8(
                frame.y,
                src_stride,
                self.cfg.width,
                self.cfg.height,
                ref_l0.recon_y,
                ref_l0.width as usize,
                ref_l0.width,
                ref_l0.height,
                mb_x,
                mb_y,
                sx,
                sy,
                4,
                4,
            );
            let r1 = search_quarter_pel_8x8(
                frame.y,
                src_stride,
                self.cfg.width,
                self.cfg.height,
                ref_l1.recon_y,
                ref_l1.width as usize,
                ref_l1.width,
                ref_l1.height,
                mb_x,
                mb_y,
                sx,
                sy,
                4,
                4,
            );
            me_l0_cells[cell] = Mv::new(r0.mv_x, r0.mv_y);
            me_l1_cells[cell] = Mv::new(r1.mv_x, r1.mv_y);
        }

        // Best 16x16 SAD = the SAD of the chosen 16x16-mode predictor.
        // (For Mixed8x8 / DirectPer8x8 we still pass the SAD of their
        // composite into the partition-mode comparison even though the
        // partition path will be skipped — `is_mixed_8x8` /
        // `is_direct_per_8x8` are checked directly in the gate below.)
        let best_16x16_sad = match chosen_mode {
            BMode::Direct => direct_sad,
            BMode::DirectPer8x8 => direct_8x8_sad,
            BMode::Mixed8x8 => mixed_total_sad,
            BMode::Explicit(BPred16x16::Bi) => sad_bi,
            BMode::Explicit(BPred16x16::L0) => sad_l0,
            BMode::Explicit(BPred16x16::L1) => sad_l1,
        };

        // 16x8 candidates: top uses cells 0/1; bottom uses 2/3.
        let cand_top_l0 = [mv_l0, me_l0_cells[0], me_l0_cells[1]];
        let cand_top_l1 = [mv_l1, me_l1_cells[0], me_l1_cells[1]];
        let cand_bot_l0 = [mv_l0, me_l0_cells[2], me_l0_cells[3]];
        let cand_bot_l1 = [mv_l1, me_l1_cells[2], me_l1_cells[3]];
        let (top_mode, top_mv_l0, top_mv_l1, sad_top) =
            best_partition_mode_b(&cand_top_l0, &cand_top_l1, |pred, mv0, mv1| {
                partition_sad_b_16x8(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 0, mv0, mv1,
                )
            });
        let (bot_mode, bot_mv_l0, bot_mv_l1, sad_bot) =
            best_partition_mode_b(&cand_bot_l0, &cand_bot_l1, |pred, mv0, mv1| {
                partition_sad_b_16x8(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 8, mv0, mv1,
                )
            });
        let sad_16x8_total = sad_top.saturating_add(sad_bot);

        // 8x16 candidates: left = cells 0/2; right = cells 1/3.
        let cand_left_l0 = [mv_l0, me_l0_cells[0], me_l0_cells[2]];
        let cand_left_l1 = [mv_l1, me_l1_cells[0], me_l1_cells[2]];
        let cand_right_l0 = [mv_l0, me_l0_cells[1], me_l0_cells[3]];
        let cand_right_l1 = [mv_l1, me_l1_cells[1], me_l1_cells[3]];
        let (left_mode, left_mv_l0, left_mv_l1, sad_left) =
            best_partition_mode_b(&cand_left_l0, &cand_left_l1, |pred, mv0, mv1| {
                partition_sad_b_8x16(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 0, mv0, mv1,
                )
            });
        let (right_mode, right_mv_l0, right_mv_l1, sad_right) =
            best_partition_mode_b(&cand_right_l0, &cand_right_l1, |pred, mv0, mv1| {
                partition_sad_b_8x16(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 8, mv0, mv1,
                )
            });
        let sad_8x16_total = sad_left.saturating_add(sad_right);

        // Lagrangian rate penalty for partition modes vs 16x16. For QP=26
        // this gives ~40 SAD units of headroom — partition wins only when
        // its SAD beats 16x16 by more than that.
        let part_bias_sad: u32 = {
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 8
        };
        let part_threshold = best_16x16_sad.saturating_sub(part_bias_sad);
        let (part_winner, part_winner_sad) = if sad_16x8_total <= sad_8x16_total {
            (PartitionShape::P16x8, sad_16x8_total)
        } else {
            (PartitionShape::P8x16, sad_8x16_total)
        };
        let mut partition_choice: Option<PartitionChoiceB> = None;
        // Don't override Direct: it may collapse to B_Skip (0 bits of MB
        // syntax) once the residual quantises to zero, beating any
        // partition mode by a large margin. Same for DirectPer8x8 / Mixed8x8 —
        // both emit `mb_type=22` (B_8x8) which is mutually exclusive
        // with the explicit 16x8 / 8x16 partition shapes (mb_type 4..=21).
        // Partition mode override only applies to explicit-inter 16x16
        // candidates.
        // Round-440 — the 16x8 / 8x16 partition composites merge Bi
        // halves with the §8.4.2.3.1 default average and may pick
        // L1-only halves: drop the candidate under the §8.4.2.3.3
        // implicit-weight axis (the decoder would weight those merges)
        // and under `b_l0_bi_only` (an L1-only half is not
        // representable in the L0-only colocated snapshot). Both are
        // legal encoder mode-choice restrictions.
        let partitions_allowed =
            !weighted.map(|w| w.apply_chroma).unwrap_or(false) && !self.cfg.b_l0_bi_only;
        if partitions_allowed
            && !is_direct
            && !is_direct_per_8x8
            && !is_mixed_8x8
            && part_winner_sad < part_threshold
        {
            partition_choice = Some(match part_winner {
                PartitionShape::P16x8 => PartitionChoiceB {
                    shape: PartitionShape::P16x8,
                    mode_a: top_mode,
                    mode_b: bot_mode,
                    mv_l0_a: top_mv_l0,
                    mv_l1_a: top_mv_l1,
                    mv_l0_b: bot_mv_l0,
                    mv_l1_b: bot_mv_l1,
                },
                PartitionShape::P8x16 => PartitionChoiceB {
                    shape: PartitionShape::P8x16,
                    mode_a: left_mode,
                    mode_b: right_mode,
                    mv_l0_a: left_mv_l0,
                    mv_l1_a: left_mv_l1,
                    mv_l0_b: right_mv_l0,
                    mv_l1_b: right_mv_l1,
                },
            });
            // Direct mode is incompatible with partition shapes — clear it.
            is_direct = false;
        }

        // Override the working predictor with the partition composite
        // when a partition mode was chosen.
        let (pred_y, pred_u, pred_v) = if let Some(pc) = partition_choice.as_ref() {
            build_partition_composite_b(pc, ref_l0, ref_l1, mb_x, mb_y)
        } else {
            (pred_y, pred_u, pred_v)
        };

        // 4. mvds against the §8.4.1.3 mvp for each used list. For 16x16
        //    explicit, this is a single pair; for partition modes we
        //    derive per-partition MVDs further below.
        let mvp_l0 = mvp_for_16x16(mv_grid_l0, mb_x, mb_y, 0);
        let mvp_l1 = mvp_for_16x16(mv_grid_l1, mb_x, mb_y, 0);
        let (mvd_l0_x, mvd_l0_y) = if !is_direct
            && !is_direct_per_8x8
            && !is_mixed_8x8
            && partition_choice.is_none()
            && pred.uses_l0()
        {
            (eff_mv_l0.x - mvp_l0.x, eff_mv_l0.y - mvp_l0.y)
        } else {
            (0, 0)
        };
        let (mvd_l1_x, mvd_l1_y) = if !is_direct
            && !is_direct_per_8x8
            && !is_mixed_8x8
            && partition_choice.is_none()
            && pred.uses_l1()
        {
            (eff_mv_l1.x - mvp_l1.x, eff_mv_l1.y - mvp_l1.y)
        } else {
            (0, 0)
        };

        // Per-partition MVDs against the §8.4.1.3 partition-shape mvp.
        // Only populated when `partition_choice` is set.
        let (mvd_l0_parts, mvd_l1_parts) = if let Some(pc) = partition_choice.as_ref() {
            partition_mvds_b(pc, mv_grid_l0, mv_grid_l1, mb_x, mb_y)
        } else {
            ([(0, 0); 2], [(0, 0); 2])
        };

        // Round-25 — per-cell MVDs for the Mixed8x8 mode. For each
        // non-Direct cell, compute the mvd against the §8.4.1.3 mvpLX
        // for that 8x8 partition (using the within-MB inflight neighbour
        // states as cells decode in raster Z-order 0→1→2→3). Direct
        // cells emit no MVDs.
        let (mixed_mvd_l0_per_cell, mixed_mvd_l1_per_cell) = if is_mixed_8x8 {
            let mut mvd0 = [(0i32, 0i32); 4];
            let mut mvd1 = [(0i32, 0i32); 4];
            // Inflight per-cell L0 / L1 state for §8.4.1.3 within-MB
            // neighbour reads (mirrors the round-19 P_8x8 path). Each
            // cell sees the previously-decoded cells of this same MB.
            let mut inflight_avail = [false; 4];
            let mut mv_inflight_l0 = [Mv::ZERO; 4];
            let mut ref_inflight_l0 = [-1i32; 4];
            let mut mv_inflight_l1 = [Mv::ZERO; 4];
            let mut ref_inflight_l1 = [-1i32; 4];
            for cell in 0..4usize {
                let kind = mixed_cells[cell];
                if kind.writes_l0() {
                    let mvp = mvp_for_p_8x8_partition(
                        mv_grid_l0,
                        mb_x,
                        mb_y,
                        cell,
                        0,
                        inflight_avail,
                        mv_inflight_l0,
                        ref_inflight_l0,
                    );
                    let mv = mixed_cell_mv_l0[cell];
                    mvd0[cell] = (mv.x - mvp.x, mv.y - mvp.y);
                }
                if kind.writes_l1() {
                    let mvp = mvp_for_p_8x8_partition(
                        mv_grid_l1,
                        mb_x,
                        mb_y,
                        cell,
                        0,
                        inflight_avail,
                        mv_inflight_l1,
                        ref_inflight_l1,
                    );
                    let mv = mixed_cell_mv_l1[cell];
                    mvd1[cell] = (mv.x - mvp.x, mv.y - mvp.y);
                }
                // Update inflight per-cell state for downstream cells.
                inflight_avail[cell] = true;
                // For Direct cells, the inflight state must reflect the
                // §8.4.1.2.2 derivation result (so subsequent cells'
                // §8.4.1.3 neighbour reads see the correct MV / ref).
                let (cell_mv0_ifl, cell_ref0_ifl) = match kind {
                    BSubMbCell::Direct => (direct.mv_l0_per_8x8[cell], direct.ref_idx_l0),
                    BSubMbCell::L0 | BSubMbCell::Bi => (mixed_cell_mv_l0[cell], 0),
                    BSubMbCell::L1 => (Mv::ZERO, -1),
                };
                let (cell_mv1_ifl, cell_ref1_ifl) = match kind {
                    BSubMbCell::Direct => (direct.mv_l1_per_8x8[cell], direct.ref_idx_l1),
                    BSubMbCell::L1 | BSubMbCell::Bi => (mixed_cell_mv_l1[cell], 0),
                    BSubMbCell::L0 => (Mv::ZERO, -1),
                };
                mv_inflight_l0[cell] = cell_mv0_ifl;
                ref_inflight_l0[cell] = cell_ref0_ifl;
                mv_inflight_l1[cell] = cell_mv1_ifl;
                ref_inflight_l1[cell] = cell_ref1_ifl;
            }
            (mvd0, mvd1)
        } else {
            ([(0, 0); 4], [(0, 0); 4])
        };

        let _ = BMbDecision {
            pred,
            mv_l0: eff_mv_l0,
            mv_l1: eff_mv_l1,
            mvd_l0_x,
            mvd_l0_y,
            mvd_l1_x,
            mvd_l1_y,
            pred_y,
            pred_u,
            pred_v,
        }; // (struct kept for forward documentation; the values are read directly below)

        // 5. Forward + quantize the luma residual against the chosen
        //    predictor (re-using the inter forward path; §8.5.9 inter
        //    weightScale — round-391).
        let wq = self.cfg.scaling_matrix.inter_weights();
        let inter_luma = forward_inter_luma(frame.y, src_stride, mb_x, mb_y, &pred_y, qp_y, &wq.w4);
        let mut luma_4x4_levels_scan = inter_luma.levels_scan;
        let mut blk_has_nz = inter_luma.blk_has_nz;
        let mut recon_block_residual = inter_luma.recon_residual;

        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            let any_nz = (0..4).any(|sub| blk_has_nz[blk8 * 4 + sub]);
            if any_nz {
                cbp_luma |= 1u8 << blk8;
            }
        }

        // 5b. Round-382 — 8x8-transform alternative for the B MB's luma
        // residual (same trial as encode_p_mb; every B shape this
        // encoder emits passes the §7.3.5 second gate, so the flag is
        // codable for whichever writer wins below).
        let mut transform_size_8x8 = false;
        if self.cfg.transform_8x8 {
            let inter_luma8 = forward_inter_luma_8x8(
                frame.y,
                src_stride,
                mb_x,
                mb_y,
                &pred_y,
                qp_y,
                &wq.w8,
                sw.field_scan(),
            );
            let mut cbp_luma8: u8 = 0;
            for blk8 in 0..4usize {
                if inter_luma8.blk_has_nz[blk8 * 4] {
                    cbp_luma8 |= 1u8 << blk8;
                }
            }
            let lambda = lambda_ssd(qp_y, false);
            let j4 = inter_luma_transform_cost(
                frame.y,
                src_stride,
                mb_x,
                mb_y,
                &pred_y,
                &inter_luma,
                cbp_luma,
                lambda,
            );
            let j8 = inter_luma_transform_cost(
                frame.y,
                src_stride,
                mb_x,
                mb_y,
                &pred_y,
                &inter_luma8,
                cbp_luma8,
                lambda,
            );
            if j8 < j4 {
                transform_size_8x8 = true;
                luma_4x4_levels_scan = inter_luma8.levels_scan;
                blk_has_nz = inter_luma8.blk_has_nz;
                recon_block_residual = inter_luma8.recon_residual;
                cbp_luma = cbp_luma8;
            }
        }
        // Flag value handed to whichever B writer is selected in the
        // emit step: absent (None) when the PPS doesn't carry the tool.
        let b_t8x8_flag = if self.cfg.transform_8x8 {
            Some(transform_size_8x8)
        } else {
            None
        };

        // 6. Forward + quantize chroma residual.
        let (u_dc_levels, u_ac_levels, u_recon_residual) =
            encode_chroma_residual_inter(frame.u, chroma_width, mb_x, mb_y, &pred_u, qp_c, &wq.w4);
        let (v_dc_levels, v_ac_levels, v_recon_residual) =
            encode_chroma_residual_inter(frame.v, chroma_width, mb_x, mb_y, &pred_v, qp_c, &wq.w4);
        let any_dc_nz = u_dc_levels.iter().any(|&v| v != 0) || v_dc_levels.iter().any(|&v| v != 0);
        let any_ac_nz = u_ac_levels.iter().any(|blk| blk.iter().any(|&v| v != 0))
            || v_ac_levels.iter().any(|blk| blk.iter().any(|&v| v != 0));
        let cbp_chroma: u8 = if any_ac_nz {
            2
        } else if any_dc_nz {
            1
        } else {
            0
        };

        // 7. Apply luma reconstruction (pred + residual or pred-only on
        //    cbp_luma=0 quadrants). Same pattern as encode_p_mb.
        let width = self.cfg.width as usize;
        for blk8 in 0..4usize {
            let send = (cbp_luma >> blk8) & 1 == 1;
            for sub in 0..4usize {
                let blk = blk8 * 4 + sub;
                let (bx, by) = LUMA_4X4_BLK[blk];
                let bx_pix = bx * 4;
                let by_pix = by * 4;
                for j in 0..4usize {
                    for i in 0..4usize {
                        let p = pred_y[(by_pix + j) * 16 + bx_pix + i];
                        let r = if send {
                            recon_block_residual[blk][j * 4 + i]
                        } else {
                            0
                        };
                        let py = mb_y * 16 + by_pix + j;
                        let px = mb_x * 16 + bx_pix + i;
                        recon_y[py * width + px] = (p + r).clamp(0, 255) as u8;
                    }
                }
            }
        }
        for j in 0..8usize {
            for i in 0..8usize {
                let cy = mb_y * 8 + j;
                let cx = mb_x * 8 + i;
                let pu = pred_u[j * 8 + i];
                let pv = pred_v[j * 8 + i];
                let res_u = if cbp_chroma == 0 {
                    0
                } else {
                    u_recon_residual[j * 8 + i]
                };
                let res_v = if cbp_chroma == 0 {
                    0
                } else {
                    v_recon_residual[j * 8 + i]
                };
                recon_u[cy * chroma_width + cx] = (pu + res_u).clamp(0, 255) as u8;
                recon_v[cy * chroma_width + cx] = (pv + res_v).clamp(0, 255) as u8;
            }
        }

        // 8. CAVLC neighbour-grid update + per-block nC.
        //
        // §9.2.1.1 step 6 — a B_Skip neighbour contributes nN=0 (same as
        // P_Skip). For B_Direct_16x16 with cbp_luma=0 the slots are also
        // 0 but `is_skip` stays false (the MB is coded, just with no
        // residual).
        let mb_is_skip = is_direct && cbp_luma == 0 && cbp_chroma == 0;
        {
            let cur = &mut nc_grid.mbs[mb_addr];
            cur.is_available = true;
            cur.is_intra = false;
            cur.is_skip = mb_is_skip;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
        }

        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(
                nc_grid,
                mb_addr as u32,
                blk as u8,
                LumaNcKind::Ac,
                true,
                false,
            );
            luma_4x4_nc[blk] = nc;
            if (cbp_luma >> blk8) & 1 == 1 {
                let tc = luma_4x4_levels_scan[blk]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8;
                own_totals[blk] = tc;
            } else {
                own_totals[blk] = 0;
            }
        }
        nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;

        // §9.2.1.1 — per-block chroma-AC nC + grid totals commit.
        let (chroma_nc_cb, chroma_nc_cr) = derive_chroma_ac_nc_and_commit_totals(
            nc_grid,
            mb_addr as u32,
            false,
            cbp_chroma,
            &u_ac_levels,
            &v_ac_levels,
            1,
        );

        // 9. Emit the MB syntax.
        //
        // §7.3.4 — four bitstream layouts:
        //   * B_Skip            : no MB syntax — pending_skip += 1.
        //   * B_Direct_16x16    : mb_type=0 + cbp + (mb_qp_delta) + residuals.
        //   * Explicit 16x16    : mb_type∈{1,2,3} + ref_idxs + mvds + cbp + …
        //   * 16x8 / 8x16 (r22) : mb_type∈{4..21} + per-partition ref_idxs
        //                        + per-partition mvds + cbp + …
        // Skips never flush their own ue(v); they are folded into the
        // run that precedes the next coded MB (or the trailing flush).
        // Round-443 — §7.4.5 mb_qp_delta: present only on coded MBs
        // with residual (cbp != 0); B_Skip and cbp==0 MBs inherit the
        // previous MB's QP_Y (the deblock info below records the
        // decoder's chain value either way).
        let mb_qp_delta = if !mb_is_skip && (cbp_luma > 0 || cbp_chroma > 0) {
            let d = qp_y - qp_tracker.cur;
            qp_tracker.cur = qp_y;
            d
        } else {
            0
        };
        if mb_is_skip {
            *pending_skip += 1;
        } else {
            sw.ue(*pending_skip);
            *pending_skip = 0;

            if is_direct {
                let dcfg = crate::encoder::macroblock::BDirect16x16McbConfig {
                    transform_size_8x8_flag: b_t8x8_flag,
                    cbp_luma,
                    cbp_chroma,
                    mb_qp_delta,
                    luma_4x4_levels: luma_4x4_levels_scan,
                    luma_4x4_nc,
                    chroma_dc_cb: u_dc_levels,
                    chroma_dc_cr: v_dc_levels,
                    chroma_ac_cb: u_ac_levels,
                    chroma_ac_cr: v_ac_levels,
                    chroma_ac_nc_cb: chroma_nc_cb,
                    chroma_ac_nc_cr: chroma_nc_cr,
                };
                crate::encoder::macroblock::write_b_direct_16x16_mb(sw, &dcfg)
                    .expect("write B_Direct_16x16 mb");
            } else if is_direct_per_8x8 {
                // Round-23 — `B_8x8` with all four sub_mb_type =
                // `B_Direct_8x8`. The decoder re-derives all four
                // (mvL0, mvL1, refIdxL0, refIdxL1) per §8.4.1.2.2 (we
                // already mirror that derivation in
                // `b_spatial_direct_derive`), so no MV / refIdx fields
                // appear in the bitstream — only cbp + residuals.
                let dcfg = crate::encoder::macroblock::B8x8AllDirectMcbConfig {
                    transform_size_8x8_flag: b_t8x8_flag,
                    cbp_luma,
                    cbp_chroma,
                    mb_qp_delta,
                    luma_4x4_levels: luma_4x4_levels_scan,
                    luma_4x4_nc,
                    chroma_dc_cb: u_dc_levels,
                    chroma_dc_cr: v_dc_levels,
                    chroma_ac_cb: u_ac_levels,
                    chroma_ac_cr: v_ac_levels,
                    chroma_ac_nc_cb: chroma_nc_cb,
                    chroma_ac_nc_cr: chroma_nc_cr,
                };
                crate::encoder::macroblock::write_b_8x8_all_direct_mb(sw, &dcfg)
                    .expect("write B_8x8 + 4× B_Direct_8x8 mb");
            } else if is_mixed_8x8 {
                // Round-25 — `B_8x8` with mixed per-cell sub_mb_type.
                // Direct cells emit only their sub_mb_type; explicit
                // cells emit their (mvd_l0, mvd_l1) pair as appropriate
                // (§7.3.5.2 gating; ref_idx absent in single-ref setup).
                let mcfg = B8x8MixedMcbConfig {
                    transform_size_8x8_flag: b_t8x8_flag,
                    cells: mixed_cells,
                    mvd_l0: mixed_mvd_l0_per_cell,
                    mvd_l1: mixed_mvd_l1_per_cell,
                    cbp_luma,
                    cbp_chroma,
                    mb_qp_delta,
                    luma_4x4_levels: luma_4x4_levels_scan,
                    luma_4x4_nc,
                    chroma_dc_cb: u_dc_levels,
                    chroma_dc_cr: v_dc_levels,
                    chroma_ac_cb: u_ac_levels,
                    chroma_ac_cr: v_ac_levels,
                    chroma_ac_nc_cb: chroma_nc_cb,
                    chroma_ac_nc_cr: chroma_nc_cr,
                };
                write_b_8x8_mixed_mb(sw, &mcfg, 0, 0).expect("write B_8x8 mixed mb");
            } else if let Some(pc) = partition_choice.as_ref() {
                use crate::encoder::macroblock::{
                    write_b_16x8_mb, write_b_8x16_mb, B16x8McbConfig, B8x16McbConfig,
                };
                match pc.shape {
                    PartitionShape::P16x8 => {
                        let cfg = B16x8McbConfig {
                            transform_size_8x8_flag: b_t8x8_flag,
                            top: pc.mode_a,
                            bottom: pc.mode_b,
                            mvd_l0: mvd_l0_parts,
                            mvd_l1: mvd_l1_parts,
                            cbp_luma,
                            cbp_chroma,
                            mb_qp_delta,
                            luma_4x4_levels: luma_4x4_levels_scan,
                            luma_4x4_nc,
                            chroma_dc_cb: u_dc_levels,
                            chroma_dc_cr: v_dc_levels,
                            chroma_ac_cb: u_ac_levels,
                            chroma_ac_cr: v_ac_levels,
                            chroma_ac_nc_cb: chroma_nc_cb,
                            chroma_ac_nc_cr: chroma_nc_cr,
                        };
                        write_b_16x8_mb(sw, &cfg, 0, 0).expect("write B_*_16x8 mb");
                    }
                    PartitionShape::P8x16 => {
                        let cfg = B8x16McbConfig {
                            transform_size_8x8_flag: b_t8x8_flag,
                            left: pc.mode_a,
                            right: pc.mode_b,
                            mvd_l0: mvd_l0_parts,
                            mvd_l1: mvd_l1_parts,
                            cbp_luma,
                            cbp_chroma,
                            mb_qp_delta,
                            luma_4x4_levels: luma_4x4_levels_scan,
                            luma_4x4_nc,
                            chroma_dc_cb: u_dc_levels,
                            chroma_dc_cr: v_dc_levels,
                            chroma_ac_cb: u_ac_levels,
                            chroma_ac_cr: v_ac_levels,
                            chroma_ac_nc_cb: chroma_nc_cb,
                            chroma_ac_nc_cr: chroma_nc_cr,
                        };
                        write_b_8x16_mb(sw, &cfg, 0, 0).expect("write B_*_8x16 mb");
                    }
                }
            } else {
                let mb_cfg = B16x16McbConfig {
                    transform_size_8x8_flag: b_t8x8_flag,
                    pred,
                    mvd_l0_x,
                    mvd_l0_y,
                    mvd_l1_x,
                    mvd_l1_y,
                    cbp_luma,
                    cbp_chroma,
                    mb_qp_delta,
                    luma_4x4_levels: luma_4x4_levels_scan,
                    luma_4x4_nc,
                    chroma_dc_cb: u_dc_levels,
                    chroma_dc_cr: v_dc_levels,
                    chroma_ac_cb: u_ac_levels,
                    chroma_ac_cr: v_ac_levels,
                    chroma_ac_nc_cb: chroma_nc_cb,
                    chroma_ac_nc_cr: chroma_nc_cr,
                };
                write_b_16x16_mb(sw, &mb_cfg, 0, 0).expect("write B_*_16x16 mb");
            }
        }

        // 10. Update the L0 and L1 mv-pred grids. For partition modes,
        //     the per-8x8 slots carry per-partition MVs (top half =
        //     slots 0/1, bottom = 2/3 for 16x8; left = 0/2, right = 1/3
        //     for 8x16). For 16x16 / Direct, all four slots share the
        //     single MV. For Round-23 DirectPer8x8, every slot carries
        //     its own (mvL0, mvL1, refIdxL0, refIdxL1) per the
        //     §8.4.1.2.2 derivation.
        let (l0_mvs_8x8, l0_refs_8x8, l0_used) = if is_direct_per_8x8 {
            let used = direct.ref_idx_l0 >= 0;
            (
                direct.mv_l0_per_8x8,
                if used {
                    [direct.ref_idx_l0; 4]
                } else {
                    [-1; 4]
                },
                used,
            )
        } else if is_mixed_8x8 {
            // Round-25 — per-cell L0 (mv, ref). Direct cells take their
            // §8.4.1.2.2 derivation result; explicit L0/Bi cells take
            // their explicit MV with refIdxL0=0; L1 cells leave L0 unset.
            let mut mvs = [Mv::ZERO; 4];
            let mut refs = [-1i32; 4];
            let mut any_used = false;
            for cell in 0..4usize {
                let kind = mixed_cells[cell];
                match kind {
                    BSubMbCell::Direct => {
                        if direct.ref_idx_l0 >= 0 {
                            mvs[cell] = direct.mv_l0_per_8x8[cell];
                            refs[cell] = direct.ref_idx_l0;
                            any_used = true;
                        }
                    }
                    BSubMbCell::L0 | BSubMbCell::Bi => {
                        mvs[cell] = mixed_cell_mv_l0[cell];
                        refs[cell] = 0;
                        any_used = true;
                    }
                    BSubMbCell::L1 => {}
                }
            }
            (mvs, refs, any_used)
        } else {
            grid_state_b(
                partition_choice.as_ref(),
                true, // L0
                pred,
                eff_mv_l0,
            )
        };
        let (l1_mvs_8x8, l1_refs_8x8, l1_used) = if is_direct_per_8x8 {
            let used = direct.ref_idx_l1 >= 0;
            (
                direct.mv_l1_per_8x8,
                if used {
                    [direct.ref_idx_l1; 4]
                } else {
                    [-1; 4]
                },
                used,
            )
        } else if is_mixed_8x8 {
            let mut mvs = [Mv::ZERO; 4];
            let mut refs = [-1i32; 4];
            let mut any_used = false;
            for cell in 0..4usize {
                let kind = mixed_cells[cell];
                match kind {
                    BSubMbCell::Direct => {
                        if direct.ref_idx_l1 >= 0 {
                            mvs[cell] = direct.mv_l1_per_8x8[cell];
                            refs[cell] = direct.ref_idx_l1;
                            any_used = true;
                        }
                    }
                    BSubMbCell::L1 | BSubMbCell::Bi => {
                        mvs[cell] = mixed_cell_mv_l1[cell];
                        refs[cell] = 0;
                        any_used = true;
                    }
                    BSubMbCell::L0 => {}
                }
            }
            (mvs, refs, any_used)
        } else {
            grid_state_b(
                partition_choice.as_ref(),
                false, // L1
                pred,
                eff_mv_l1,
            )
        };
        *mv_grid_l0.slot_mut(mb_x, mb_y) = if l0_used {
            MvGridSlot {
                available: true,
                is_intra: false,
                ref_idx_l0_8x8: l0_refs_8x8,
                mv_l0_8x8: l0_mvs_8x8,
            }
        } else {
            MvGridSlot {
                available: true,
                is_intra: true,
                ref_idx_l0_8x8: [-1; 4],
                mv_l0_8x8: [Mv::ZERO; 4],
            }
        };
        *mv_grid_l1.slot_mut(mb_x, mb_y) = if l1_used {
            MvGridSlot {
                available: true,
                is_intra: false,
                ref_idx_l0_8x8: l1_refs_8x8,
                mv_l0_8x8: l1_mvs_8x8,
            }
        } else {
            MvGridSlot {
                available: true,
                is_intra: true,
                ref_idx_l0_8x8: [-1; 4],
                mv_l0_8x8: [Mv::ZERO; 4],
            }
        };
        let s = intra_grid.slot_mut(mb_x, mb_y);
        s.available = true;
        s.is_i_nxn = false;

        // 11. Per-4x4 nonzero mask + per-list MVs/refs/POCs for the §8.7
        //     deblock walker. For partition modes the per-4x4 MVs follow
        //     the §8.7.2.1 partition layout. POCs use the same anchor-
        //     layout sentinel as the 16x16 path. For Round-23
        //     DirectPer8x8 each 4x4 carries its containing 8x8's MV.
        let luma_nonzero_4x4 = luma_nz_mask_from_blocks(&blk_has_nz);
        let cb_nz: [bool; 4] =
            std::array::from_fn(|i| cbp_chroma == 2 && u_ac_levels[i].iter().any(|&v| v != 0));
        let cr_nz: [bool; 4] =
            std::array::from_fn(|i| cbp_chroma == 2 && v_ac_levels[i].iter().any(|&v| v != 0));

        let (mv_l0_arr, ref_idx_l0, ref_poc_l0) = if is_direct_per_8x8 {
            deblock_arrays_per_8x8_direct(direct.mv_l0_per_8x8, direct.ref_idx_l0, 0i32)
        } else if is_mixed_8x8 {
            deblock_arrays_per_8x8_mixed(l0_mvs_8x8, l0_refs_8x8, 0i32)
        } else {
            deblock_mv_arr_b(partition_choice.as_ref(), true, pred, eff_mv_l0, 0i32)
        };
        let (mv_l1_arr, ref_idx_l1, ref_poc_l1) = if is_direct_per_8x8 {
            deblock_arrays_per_8x8_direct(direct.mv_l1_per_8x8, direct.ref_idx_l1, 1000i32)
        } else if is_mixed_8x8 {
            deblock_arrays_per_8x8_mixed(l1_mvs_8x8, l1_refs_8x8, 1000i32)
        } else {
            deblock_mv_arr_b(partition_choice.as_ref(), false, pred, eff_mv_l1, 1000i32)
        };

        MbDeblockInfo {
            is_intra: false,
            // §7.4.5 chain: qp_tracker.cur is qp_y when this MB coded
            // a residual (delta emitted above), else the inherited
            // predecessor QP — the value the decoder's §8.7 deblock
            // will use.
            qp_y: qp_tracker.cur,
            luma_nonzero_4x4,
            chroma_nonzero_4x4: chroma_nz_mask_from_blocks(&cb_nz, &cr_nz),
            transform_size_8x8_flag: transform_size_8x8,
            mv_l0: mv_l0_arr,
            ref_idx_l0,
            ref_poc_l0,
            mv_l1: mv_l1_arr,
            ref_idx_l1,
            ref_poc_l1,
            is_intra_4x4: false,
        }
    }

    /// Round-397 — encode one B-slice MB at **4:2:2 / 4:4:4** (CAVLC).
    ///
    /// Mode set: `B_Skip`, `B_Direct_16x16` (spatial §8.4.1.2.2 or
    /// temporal §8.4.1.2.3 per the slice header, uniform-derivation
    /// gate as in round 21), the explicit `B_L0_16x16` / `B_L1_16x16`
    /// / `B_Bi_16x16` set, and the 16x8 / 8x16 partition shapes
    /// (Table 7-14 raw 4..=21) with per-format chroma-rect MC.
    /// `B_8x8` (all-direct / mixed) stays a 4:2:0-only encoder choice
    /// — the bitstream cell is fully decodable either way, the
    /// multi-format body just never picks it.
    ///
    /// Chroma per format (§8.4.1.4 / §8.4.2.2):
    ///   * 4:2:2 — x subsampled, y full height (`mvC.y = mvL.y·2` in
    ///     1/8-pel); §8.5.11.2 2x4-Hadamard residual chain.
    ///   * 4:4:4 — the §8.4.2.2.1 LUMA 6-tap process per chroma plane
    ///     with mvC = mvL; §7.3.5.3 coded-like-luma residual with the
    ///     shared CBP quadrant bits (Table 9-4(b)).
    #[allow(clippy::too_many_arguments)]
    fn encode_b_mb_multifmt(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        _chroma_height: usize,
        src_stride: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid_l0: &mut MvGrid,
        mv_grid_l1: &mut MvGrid,
        pending_skip: &mut u32,
        curr_poc: i32,
        weighted: Option<WeightedBipredLuma>,
    ) -> MbDeblockInfo {
        let chroma_array_type = self.cfg.chroma_format_idc;
        debug_assert!(matches!(chroma_array_type, 0 | 2 | 3));
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;
        let chroma_w = chroma_width as u32;
        let chroma_h = _chroma_height as u32;

        // 1. Per-list quarter-pel ME — same routine as encode_b_mb.
        let me_l0 = search_quarter_pel_16x16(
            frame.y,
            src_stride,
            self.cfg.width,
            self.cfg.height,
            ref_l0.recon_y,
            ref_l0.width as usize,
            ref_l0.width,
            ref_l0.height,
            mb_x,
            mb_y,
            16,
            16,
        );
        let me_l1 = search_quarter_pel_16x16(
            frame.y,
            src_stride,
            self.cfg.width,
            self.cfg.height,
            ref_l1.recon_y,
            ref_l1.width as usize,
            ref_l1.width,
            ref_l1.height,
            mb_x,
            mb_y,
            16,
            16,
        );
        let mv_l0 = Mv::new(me_l0.mv_x, me_l0.mv_y);
        let mv_l1 = Mv::new(me_l1.mv_x, me_l1.mv_y);

        // 2. Per-format predictor builders. Luma is shared with the
        //    4:2:0 path; chroma dispatches per §8.4.1.4 / §8.4.2.2.
        let chroma_plane_pred = |plane: &[u8], mv: Mv| -> Vec<i32> {
            match chroma_array_type {
                // Round-448 — 4:0:0: no chroma planes to predict.
                0 => Vec::new(),
                3 => build_inter_pred_luma(plane, chroma_w, chroma_h, mb_x, mb_y, mv).to_vec(),
                _ => cabac_path::build_inter_pred_chroma_local_422(
                    plane, chroma_w, chroma_h, mb_x, mb_y, mv,
                )
                .to_vec(),
            }
        };
        // Merge two per-list predictor tiles per §8.4.2.3.1 (default
        // average). Explicit weighted bipred (round-26) applies to the
        // LUMA merge only, mirroring `build_b_predictors`.
        let build_luma = |kind: BPred16x16, l0mv: Mv, l1mv: Mv| -> [i32; 256] {
            match kind {
                BPred16x16::L0 => build_inter_pred_luma(
                    ref_l0.recon_y,
                    ref_l0.width,
                    ref_l0.height,
                    mb_x,
                    mb_y,
                    l0mv,
                ),
                BPred16x16::L1 => build_inter_pred_luma(
                    ref_l1.recon_y,
                    ref_l1.width,
                    ref_l1.height,
                    mb_x,
                    mb_y,
                    l1mv,
                ),
                BPred16x16::Bi => {
                    let a = build_inter_pred_luma(
                        ref_l0.recon_y,
                        ref_l0.width,
                        ref_l0.height,
                        mb_x,
                        mb_y,
                        l0mv,
                    );
                    let b = build_inter_pred_luma(
                        ref_l1.recon_y,
                        ref_l1.width,
                        ref_l1.height,
                        mb_x,
                        mb_y,
                        l1mv,
                    );
                    let mut out = [0i32; 256];
                    if let Some(wp) = weighted {
                        // §8.4.2.3.2 eq. 8-276 — explicit weighted bipred.
                        let logwd = wp.log2_wd;
                        let off_avg = (wp.offset_l0 + wp.offset_l1 + 1) >> 1;
                        let round = 1i32 << logwd;
                        for i in 0..256 {
                            let v =
                                (a[i] * wp.weight_l0 + b[i] * wp.weight_l1 + round) >> (logwd + 1);
                            out[i] = (v + off_avg).clamp(0, 255);
                        }
                    } else {
                        for i in 0..256 {
                            out[i] = (a[i] + b[i] + 1) >> 1;
                        }
                    }
                    out
                }
            }
        };
        let build_chroma = |kind: BPred16x16, l0mv: Mv, l1mv: Mv| -> (Vec<i32>, Vec<i32>) {
            match kind {
                BPred16x16::L0 => (
                    chroma_plane_pred(ref_l0.recon_u, l0mv),
                    chroma_plane_pred(ref_l0.recon_v, l0mv),
                ),
                BPred16x16::L1 => (
                    chroma_plane_pred(ref_l1.recon_u, l1mv),
                    chroma_plane_pred(ref_l1.recon_v, l1mv),
                ),
                BPred16x16::Bi => {
                    let au = chroma_plane_pred(ref_l0.recon_u, l0mv);
                    let bu = chroma_plane_pred(ref_l1.recon_u, l1mv);
                    let av = chroma_plane_pred(ref_l0.recon_v, l0mv);
                    let bv = chroma_plane_pred(ref_l1.recon_v, l1mv);
                    (
                        au.iter()
                            .zip(&bu)
                            .map(|(&x, &y)| (x + y + 1) >> 1)
                            .collect(),
                        av.iter()
                            .zip(&bv)
                            .map(|(&x, &y)| (x + y + 1) >> 1)
                            .collect(),
                    )
                }
            }
        };

        let pred_y_l0 = build_luma(BPred16x16::L0, mv_l0, mv_l1);
        let pred_y_l1 = build_luma(BPred16x16::L1, mv_l0, mv_l1);
        let pred_y_bi = build_luma(BPred16x16::Bi, mv_l0, mv_l1);
        let sad_l0 = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &pred_y_l0);
        let sad_l1 = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &pred_y_l1);
        let sad_bi = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &pred_y_bi);

        // 2.5 Direct-mode trial (uniform-derivation gate, round 21).
        let direct = if self.cfg.direct_temporal_mv_pred {
            b_temporal_direct_derive(
                ref_l1.partition_mvs,
                width_mbs,
                mb_x,
                mb_y,
                curr_poc,
                ref_l0.pic_order_cnt,
                ref_l1.pic_order_cnt,
            )
        } else {
            b_spatial_direct_derive(
                mv_grid_l0,
                mv_grid_l1,
                ref_l1.partition_mvs,
                width_mbs,
                mb_x,
                mb_y,
            )
        };
        let direct_pred_kind: Option<BPred16x16> =
            match (direct.ref_idx_l0 >= 0, direct.ref_idx_l1 >= 0) {
                (true, true) => Some(BPred16x16::Bi),
                (true, false) => Some(BPred16x16::L0),
                (false, true) => Some(BPred16x16::L1),
                (false, false) => None,
            };
        let (direct_competitive, direct_pred_y, direct_sad) =
            match (direct.is_uniform(), direct_pred_kind) {
                (true, Some(dpk)) => {
                    let dy = build_luma(dpk, direct.mv_l0(), direct.mv_l1());
                    let dsad = sad_16x16_pred(frame.y, src_stride, mb_x, mb_y, &dy);
                    (true, dy, dsad)
                }
                _ => (false, [0i32; 256], u32::MAX),
            };

        // 3. Mode pick — same Lagrangian direct bias as encode_b_mb.
        let direct_bias_sad: u32 = {
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 16
        };
        let is_direct = direct_competitive
            && direct_sad <= sad_bi.saturating_add(direct_bias_sad)
            && direct_sad <= sad_l0.saturating_add(direct_bias_sad)
            && direct_sad <= sad_l1.saturating_add(direct_bias_sad);
        let (pred, pred_y, eff_mv_l0, eff_mv_l1) = if is_direct {
            (
                direct_pred_kind.expect("Direct chosen → direct_pred_kind set"),
                direct_pred_y,
                direct.mv_l0(),
                direct.mv_l1(),
            )
        } else if sad_bi <= sad_l0 && sad_bi <= sad_l1 {
            (BPred16x16::Bi, pred_y_bi, mv_l0, mv_l1)
        } else if sad_l0 <= sad_l1 {
            (BPred16x16::L0, pred_y_l0, mv_l0, Mv::ZERO)
        } else {
            (BPred16x16::L1, pred_y_l1, Mv::ZERO, mv_l1)
        };

        // ---- Round-397: 16x8 / 8x16 partition trial (round-22 logic
        // with per-format chroma). Direct is never overridden — B_Skip
        // dominates any partition mode rate-wise. ----
        let mut me_l0_cells: [Mv; 4] = [Mv::ZERO; 4];
        let mut me_l1_cells: [Mv; 4] = [Mv::ZERO; 4];
        for cell in 0..4usize {
            let sx = cell % 2;
            let sy = cell / 2;
            let r0 = search_quarter_pel_8x8(
                frame.y,
                src_stride,
                self.cfg.width,
                self.cfg.height,
                ref_l0.recon_y,
                ref_l0.width as usize,
                ref_l0.width,
                ref_l0.height,
                mb_x,
                mb_y,
                sx,
                sy,
                4,
                4,
            );
            let r1 = search_quarter_pel_8x8(
                frame.y,
                src_stride,
                self.cfg.width,
                self.cfg.height,
                ref_l1.recon_y,
                ref_l1.width as usize,
                ref_l1.width,
                ref_l1.height,
                mb_x,
                mb_y,
                sx,
                sy,
                4,
                4,
            );
            me_l0_cells[cell] = Mv::new(r0.mv_x, r0.mv_y);
            me_l1_cells[cell] = Mv::new(r1.mv_x, r1.mv_y);
        }
        let cand_top_l0 = [mv_l0, me_l0_cells[0], me_l0_cells[1]];
        let cand_top_l1 = [mv_l1, me_l1_cells[0], me_l1_cells[1]];
        let cand_bot_l0 = [mv_l0, me_l0_cells[2], me_l0_cells[3]];
        let cand_bot_l1 = [mv_l1, me_l1_cells[2], me_l1_cells[3]];
        let (top_mode, top_mv_l0, top_mv_l1, sad_top) =
            best_partition_mode_b(&cand_top_l0, &cand_top_l1, |pred, mv0, mv1| {
                partition_sad_b_16x8(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 0, mv0, mv1,
                )
            });
        let (bot_mode, bot_mv_l0, bot_mv_l1, sad_bot) =
            best_partition_mode_b(&cand_bot_l0, &cand_bot_l1, |pred, mv0, mv1| {
                partition_sad_b_16x8(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 8, mv0, mv1,
                )
            });
        let sad_16x8_total = sad_top.saturating_add(sad_bot);
        let cand_left_l0 = [mv_l0, me_l0_cells[0], me_l0_cells[2]];
        let cand_left_l1 = [mv_l1, me_l1_cells[0], me_l1_cells[2]];
        let cand_right_l0 = [mv_l0, me_l0_cells[1], me_l0_cells[3]];
        let cand_right_l1 = [mv_l1, me_l1_cells[1], me_l1_cells[3]];
        let (left_mode, left_mv_l0, left_mv_l1, sad_left) =
            best_partition_mode_b(&cand_left_l0, &cand_left_l1, |pred, mv0, mv1| {
                partition_sad_b_8x16(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 0, mv0, mv1,
                )
            });
        let (right_mode, right_mv_l0, right_mv_l1, sad_right) =
            best_partition_mode_b(&cand_right_l0, &cand_right_l1, |pred, mv0, mv1| {
                partition_sad_b_8x16(
                    pred, frame.y, src_stride, ref_l0, ref_l1, mb_x, mb_y, 8, mv0, mv1,
                )
            });
        let sad_8x16_total = sad_left.saturating_add(sad_right);

        let best_16x16_sad = if is_direct {
            direct_sad
        } else {
            sad_bi.min(sad_l0).min(sad_l1)
        };
        let part_bias_sad: u32 = {
            let lambda = (qp_y / 6).clamp(0, 8) as u32;
            (lambda + 1) * 8
        };
        let part_threshold = best_16x16_sad.saturating_sub(part_bias_sad);
        let (part_winner, part_winner_sad) = if sad_16x8_total <= sad_8x16_total {
            (PartitionShape::P16x8, sad_16x8_total)
        } else {
            (PartitionShape::P8x16, sad_8x16_total)
        };
        let mut partition_choice: Option<PartitionChoiceB> = None;
        if !is_direct && part_winner_sad < part_threshold {
            partition_choice = Some(match part_winner {
                PartitionShape::P16x8 => PartitionChoiceB {
                    shape: PartitionShape::P16x8,
                    mode_a: top_mode,
                    mode_b: bot_mode,
                    mv_l0_a: top_mv_l0,
                    mv_l1_a: top_mv_l1,
                    mv_l0_b: bot_mv_l0,
                    mv_l1_b: bot_mv_l1,
                },
                PartitionShape::P8x16 => PartitionChoiceB {
                    shape: PartitionShape::P8x16,
                    mode_a: left_mode,
                    mode_b: right_mode,
                    mv_l0_a: left_mv_l0,
                    mv_l1_a: left_mv_l1,
                    mv_l0_b: right_mv_l0,
                    mv_l1_b: right_mv_l1,
                },
            });
        }

        // Composite predictor: partition override or the 16x16 pick.
        let (ct_w, ct_h) = chroma_tile_dims(chroma_array_type);
        let (pred_y, pred_u, pred_v) = if let Some(pc) = partition_choice.as_ref() {
            let mut py = [0i32; 256];
            let mut pu = vec![0i32; ct_w * ct_h];
            let mut pv = vec![0i32; ct_w * ct_h];
            // Luma halves via the shared partition predictors.
            match pc.shape {
                PartitionShape::P16x8 => {
                    let py0 = build_b_partition_pred_luma_16x8(
                        pc.mode_a, ref_l0, ref_l1, mb_x, mb_y, 0, pc.mv_l0_a, pc.mv_l1_a,
                    );
                    let py1 = build_b_partition_pred_luma_16x8(
                        pc.mode_b, ref_l0, ref_l1, mb_x, mb_y, 8, pc.mv_l0_b, pc.mv_l1_b,
                    );
                    for j in 0..8usize {
                        for i in 0..16usize {
                            py[j * 16 + i] = py0[j * 16 + i];
                            py[(8 + j) * 16 + i] = py1[j * 16 + i];
                        }
                    }
                }
                PartitionShape::P8x16 => {
                    let py0 = build_b_partition_pred_luma_8x16(
                        pc.mode_a, ref_l0, ref_l1, mb_x, mb_y, 0, pc.mv_l0_a, pc.mv_l1_a,
                    );
                    let py1 = build_b_partition_pred_luma_8x16(
                        pc.mode_b, ref_l0, ref_l1, mb_x, mb_y, 8, pc.mv_l0_b, pc.mv_l1_b,
                    );
                    for j in 0..16usize {
                        for i in 0..8usize {
                            py[j * 16 + i] = py0[j * 8 + i];
                            py[j * 16 + 8 + i] = py1[j * 8 + i];
                        }
                    }
                }
            }
            // Chroma halves via the per-format rect MC (§8.4.1.4 /
            // §8.4.2.2): a 16x8 luma half maps to a ct_w × ct_h/2
            // chroma rect, an 8x16 half to ct_w/2 × ct_h.
            for (half, (mode, hmv0, hmv1)) in [
                (pc.mode_a, pc.mv_l0_a, pc.mv_l1_a),
                (pc.mode_b, pc.mv_l0_b, pc.mv_l1_b),
            ]
            .into_iter()
            .enumerate()
            {
                let (cx0, cy0, rw, rh) = match pc.shape {
                    PartitionShape::P16x8 => {
                        (mb_x * ct_w, mb_y * ct_h + half * (ct_h / 2), ct_w, ct_h / 2)
                    }
                    PartitionShape::P8x16 => {
                        (mb_x * ct_w + half * (ct_w / 2), mb_y * ct_h, ct_w / 2, ct_h)
                    }
                };
                let ru = build_b_partition_chroma_rect_fmt(
                    mode,
                    ref_l0.recon_u,
                    ref_l1.recon_u,
                    chroma_w,
                    chroma_h,
                    cx0,
                    cy0,
                    rw,
                    rh,
                    hmv0,
                    hmv1,
                    chroma_array_type,
                );
                let rv = build_b_partition_chroma_rect_fmt(
                    mode,
                    ref_l0.recon_v,
                    ref_l1.recon_v,
                    chroma_w,
                    chroma_h,
                    cx0,
                    cy0,
                    rw,
                    rh,
                    hmv0,
                    hmv1,
                    chroma_array_type,
                );
                let ox = cx0 - mb_x * ct_w;
                let oy = cy0 - mb_y * ct_h;
                for j in 0..rh {
                    for i in 0..rw {
                        pu[(oy + j) * ct_w + ox + i] = ru[j * rw + i];
                        pv[(oy + j) * ct_w + ox + i] = rv[j * rw + i];
                    }
                }
            }
            (py, pu, pv)
        } else {
            let (pu, pv) = build_chroma(pred, eff_mv_l0, eff_mv_l1);
            (pred_y, pu, pv)
        };

        // 4. mvds against the §8.4.1.3 mvp. 16x16 shapes derive a
        //    single pair per used list; partition shapes derive
        //    per-partition mvds via the shared §8.4.1.3 helper.
        let mvp_l0 = mvp_for_16x16(mv_grid_l0, mb_x, mb_y, 0);
        let mvp_l1 = mvp_for_16x16(mv_grid_l1, mb_x, mb_y, 0);
        let (mvd_l0_x, mvd_l0_y) = if !is_direct && partition_choice.is_none() && pred.uses_l0() {
            (eff_mv_l0.x - mvp_l0.x, eff_mv_l0.y - mvp_l0.y)
        } else {
            (0, 0)
        };
        let (mvd_l1_x, mvd_l1_y) = if !is_direct && partition_choice.is_none() && pred.uses_l1() {
            (eff_mv_l1.x - mvp_l1.x, eff_mv_l1.y - mvp_l1.y)
        } else {
            (0, 0)
        };
        let (mvd_l0_parts, mvd_l1_parts) = if let Some(pc) = partition_choice.as_ref() {
            partition_mvds_b(pc, mv_grid_l0, mv_grid_l1, mb_x, mb_y)
        } else {
            ([(0, 0); 2], [(0, 0); 2])
        };

        // 5. Luma residual (+ optional §8.6.4 8x8-transform trial).
        let wq = self.cfg.scaling_matrix.inter_weights();
        let inter_luma = forward_inter_luma(frame.y, src_stride, mb_x, mb_y, &pred_y, qp_y, &wq.w4);
        let mut luma_4x4_levels_scan = inter_luma.levels_scan;
        let mut blk_has_nz = inter_luma.blk_has_nz;
        let mut recon_block_residual = inter_luma.recon_residual;
        let mut cbp_luma: u8 = 0;
        for blk8 in 0..4usize {
            if (0..4).any(|sub| blk_has_nz[blk8 * 4 + sub]) {
                cbp_luma |= 1u8 << blk8;
            }
        }
        let mut transform_size_8x8 = false;
        if self.cfg.transform_8x8 {
            let inter_luma8 = forward_inter_luma_8x8(
                frame.y,
                src_stride,
                mb_x,
                mb_y,
                &pred_y,
                qp_y,
                &wq.w8,
                sw.field_scan(),
            );
            let mut cbp_luma8: u8 = 0;
            for blk8 in 0..4usize {
                if inter_luma8.blk_has_nz[blk8 * 4] {
                    cbp_luma8 |= 1u8 << blk8;
                }
            }
            let lambda = lambda_ssd(qp_y, false);
            let j4 = inter_luma_transform_cost(
                frame.y,
                src_stride,
                mb_x,
                mb_y,
                &pred_y,
                &inter_luma,
                cbp_luma,
                lambda,
            );
            let j8 = inter_luma_transform_cost(
                frame.y,
                src_stride,
                mb_x,
                mb_y,
                &pred_y,
                &inter_luma8,
                cbp_luma8,
                lambda,
            );
            if j8 < j4 {
                transform_size_8x8 = true;
                luma_4x4_levels_scan = inter_luma8.levels_scan;
                blk_has_nz = inter_luma8.blk_has_nz;
                recon_block_residual = inter_luma8.recon_residual;
                cbp_luma = cbp_luma8;
            }
        }

        // 6. Chroma residual — per-format dispatch (mirror of the
        //    round-397 encode_p_mb structure).
        let mut u_dc8 = [0i32; 8];
        let mut v_dc8 = [0i32; 8];
        let mut u_ac8 = [[0i32; 16]; 8];
        let mut v_ac8 = [[0i32; 16]; 8];
        let mut u_recon_res_422 = [0i32; 128];
        let mut v_recon_res_422 = [0i32; 128];
        let mut cb444 = InterLumaForward::default();
        let mut cr444 = InterLumaForward::default();
        let mut cbp_chroma: u8 = 0;
        match chroma_array_type {
            // Round-448 — 4:0:0: no chroma residual exists
            // (§7.3.5.3 residual() is luma-only); cbp_chroma stays 0.
            0 => {}
            3 => {
                let pu: &[i32; 256] = pred_u[..256].try_into().expect("pred tile");
                let pv: &[i32; 256] = pred_v[..256].try_into().expect("pred tile");
                if transform_size_8x8 {
                    cb444 = forward_inter_luma_8x8(
                        frame.u,
                        chroma_width,
                        mb_x,
                        mb_y,
                        pu,
                        qp_c,
                        &wq.w8,
                        sw.field_scan(),
                    );
                    cr444 = forward_inter_luma_8x8(
                        frame.v,
                        chroma_width,
                        mb_x,
                        mb_y,
                        pv,
                        qp_c,
                        &wq.w8,
                        sw.field_scan(),
                    );
                } else {
                    cb444 = forward_inter_luma(frame.u, chroma_width, mb_x, mb_y, pu, qp_c, &wq.w4);
                    cr444 = forward_inter_luma(frame.v, chroma_width, mb_x, mb_y, pv, qp_c, &wq.w4);
                }
                // §7.4.5.1 at ChromaArrayType == 3 — shared CBP quadrant
                // bits cover all three planes.
                for blk8 in 0..4usize {
                    let cb_nz = (0..4).any(|sub| cb444.blk_has_nz[blk8 * 4 + sub]);
                    let cr_nz = (0..4).any(|sub| cr444.blk_has_nz[blk8 * 4 + sub]);
                    if cb_nz || cr_nz {
                        cbp_luma |= 1u8 << blk8;
                    }
                }
                if cbp_luma == 0 {
                    transform_size_8x8 = false;
                }
            }
            _ => {
                let pu: &[i32; 128] = pred_u[..128].try_into().expect("pred tile");
                let pv: &[i32; 128] = pred_v[..128].try_into().expect("pred tile");
                let (dcu, acu, ru) =
                    encode_chroma_residual_422(frame.u, chroma_width, mb_x, mb_y, pu, qp_c, &wq.w4);
                let (dcv, acv, rv) =
                    encode_chroma_residual_422(frame.v, chroma_width, mb_x, mb_y, pv, qp_c, &wq.w4);
                u_dc8 = dcu;
                v_dc8 = dcv;
                u_ac8 = acu;
                v_ac8 = acv;
                u_recon_res_422 = ru;
                v_recon_res_422 = rv;
                let any_dc_nz = u_dc8.iter().any(|&v| v != 0) || v_dc8.iter().any(|&v| v != 0);
                let any_ac_nz = u_ac8.iter().any(|b| b.iter().any(|&v| v != 0))
                    || v_ac8.iter().any(|b| b.iter().any(|&v| v != 0));
                cbp_chroma = if any_ac_nz {
                    2
                } else if any_dc_nz {
                    1
                } else {
                    0
                };
            }
        }
        // Normalise the second-gate flag when nothing is coded.
        if cbp_luma == 0 && self.cfg.transform_8x8 {
            transform_size_8x8 = false;
        }
        // Flag value handed to the writer (after the 4:4:4 CBP merge /
        // normalisation): absent when the PPS doesn't carry the tool.
        let b_t8x8_flag = if self.cfg.transform_8x8 {
            Some(transform_size_8x8)
        } else {
            None
        };

        // 7. Reconstruction (pred + residual on coded quadrants).
        let width = self.cfg.width as usize;
        for blk8 in 0..4usize {
            let send = (cbp_luma >> blk8) & 1 == 1;
            for sub in 0..4usize {
                let blk = blk8 * 4 + sub;
                let (bx, by) = LUMA_4X4_BLK[blk];
                for j in 0..4usize {
                    for i in 0..4usize {
                        let p = pred_y[(by * 4 + j) * 16 + bx * 4 + i];
                        let r = if send {
                            recon_block_residual[blk][j * 4 + i]
                        } else {
                            0
                        };
                        let py = mb_y * 16 + by * 4 + j;
                        let px = mb_x * 16 + bx * 4 + i;
                        recon_y[py * width + px] = (p + r).clamp(0, 255) as u8;
                    }
                }
            }
        }
        match chroma_array_type {
            // Round-448 — 4:0:0: nothing to reconstruct.
            0 => {}
            3 => {
                for (pred_c, fwd, recon) in [
                    (&pred_u, &cb444, &mut *recon_u),
                    (&pred_v, &cr444, &mut *recon_v),
                ] {
                    for blk8 in 0..4usize {
                        let send = (cbp_luma >> blk8) & 1 == 1;
                        for sub in 0..4usize {
                            let blk = blk8 * 4 + sub;
                            let (bx, by) = LUMA_4X4_BLK[blk];
                            for j in 0..4usize {
                                for i in 0..4usize {
                                    let p = pred_c[(by * 4 + j) * 16 + bx * 4 + i];
                                    let r = if send {
                                        fwd.recon_residual[blk][j * 4 + i]
                                    } else {
                                        0
                                    };
                                    let cy = mb_y * 16 + by * 4 + j;
                                    let cx = mb_x * 16 + bx * 4 + i;
                                    recon[cy * chroma_width + cx] = (p + r).clamp(0, 255) as u8;
                                }
                            }
                        }
                    }
                }
            }
            _ => {
                for j in 0..16usize {
                    for i in 0..8usize {
                        let cy = mb_y * 16 + j;
                        let cx = mb_x * 8 + i;
                        let pu = pred_u[j * 8 + i];
                        let pv = pred_v[j * 8 + i];
                        let res_u = if cbp_chroma == 0 {
                            0
                        } else {
                            u_recon_res_422[j * 8 + i]
                        };
                        let res_v = if cbp_chroma == 0 {
                            0
                        } else {
                            v_recon_res_422[j * 8 + i]
                        };
                        recon_u[cy * chroma_width + cx] = (pu + res_u).clamp(0, 255) as u8;
                        recon_v[cy * chroma_width + cx] = (pv + res_v).clamp(0, 255) as u8;
                    }
                }
            }
        }

        // 8. CAVLC neighbour-grid update + per-block nC. All plane
        //    totals start at 0; the emit branch below re-commits the
        //    real values for coded MBs (a skipped MB keeps the zeros,
        //    matching §9.2.1.1 step 6).
        let mb_is_skip = is_direct && cbp_luma == 0 && cbp_chroma == 0;
        {
            let cur = &mut nc_grid.mbs[mb_addr];
            cur.is_available = true;
            cur.is_intra = false;
            cur.is_skip = mb_is_skip;
            cur.is_i_pcm = false;
            cur.luma_total_coeff = [0u8; 16];
            cur.cb_total_coeff = [0u8; 8];
            cur.cr_total_coeff = [0u8; 8];
            cur.cb_luma_total_coeff = [0u8; 16];
            cur.cr_luma_total_coeff = [0u8; 16];
        }
        let mut luma_4x4_nc = [0i32; 16];
        let mut own_totals = [0u8; 16];
        for blk in 0..16usize {
            let blk8 = blk / 4;
            nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;
            let nc = derive_nc_luma(
                nc_grid,
                mb_addr as u32,
                blk as u8,
                LumaNcKind::Ac,
                true,
                false,
            );
            luma_4x4_nc[blk] = nc;
            own_totals[blk] = if (cbp_luma >> blk8) & 1 == 1 {
                luma_4x4_levels_scan[blk]
                    .iter()
                    .filter(|&&v| v != 0)
                    .count() as u8
            } else {
                0
            };
        }
        nc_grid.mbs[mb_addr].luma_total_coeff = own_totals;

        // 9. Emit the MB syntax (B_Skip folds into `pending_skip`).
        if mb_is_skip {
            *pending_skip += 1;
        } else {
            sw.ue(*pending_skip);
            *pending_skip = 0;
            // Per-format chroma writer payload + §9.2.1.1 nC commits.
            enum BChromaEmit {
                Mono,
                C422 { nc_cb: [i32; 8], nc_cr: [i32; 8] },
                C444 { cb_nc: [i32; 16], cr_nc: [i32; 16] },
            }
            let emit = if chroma_array_type == 0 {
                // Round-448 — 4:0:0: no chroma payload, no chroma nC
                // commits (§7.3.5.3 residual() is luma-only).
                BChromaEmit::Mono
            } else if chroma_array_type == 3 {
                BChromaEmit::C444 {
                    cb_nc: derive_plane_nc_444_inter(
                        nc_grid,
                        mb_addr as u32,
                        false,
                        cbp_luma,
                        &cb444.levels_scan,
                    ),
                    cr_nc: derive_plane_nc_444_inter(
                        nc_grid,
                        mb_addr as u32,
                        true,
                        cbp_luma,
                        &cr444.levels_scan,
                    ),
                }
            } else {
                let (nc_cb, nc_cr) = derive_chroma_ac_nc_and_commit_totals(
                    nc_grid,
                    mb_addr as u32,
                    false,
                    cbp_chroma,
                    &u_ac8,
                    &v_ac8,
                    2,
                );
                BChromaEmit::C422 { nc_cb, nc_cr }
            };
            let chroma_kind = match &emit {
                BChromaEmit::Mono => crate::encoder::macroblock::ChromaWriteKind::Mono,
                BChromaEmit::C444 { cb_nc, cr_nc } => {
                    crate::encoder::macroblock::ChromaWriteKind::Yuv444Inter {
                        cb_levels: &cb444.levels_scan,
                        cr_levels: &cr444.levels_scan,
                        cb_nc,
                        cr_nc,
                        cbp_luma,
                    }
                }
                BChromaEmit::C422 { nc_cb, nc_cr } => {
                    crate::encoder::macroblock::ChromaWriteKind::Yuv422 {
                        chroma_dc_cb: &u_dc8,
                        chroma_dc_cr: &v_dc8,
                        chroma_ac_cb: &u_ac8,
                        chroma_ac_cr: &v_ac8,
                        cb_ac_nc: nc_cb,
                        cr_ac_nc: nc_cr,
                    }
                }
            };
            if is_direct {
                let dcfg = crate::encoder::macroblock::BDirect16x16McbConfig {
                    transform_size_8x8_flag: b_t8x8_flag,
                    cbp_luma,
                    cbp_chroma,
                    mb_qp_delta: 0,
                    luma_4x4_levels: luma_4x4_levels_scan,
                    luma_4x4_nc,
                    chroma_dc_cb: [0; 4],
                    chroma_dc_cr: [0; 4],
                    chroma_ac_cb: [[0; 16]; 4],
                    chroma_ac_cr: [[0; 16]; 4],
                    chroma_ac_nc_cb: [0; 8],
                    chroma_ac_nc_cr: [0; 8],
                };
                crate::encoder::macroblock::write_b_direct_16x16_mb_chroma(
                    sw,
                    &dcfg,
                    chroma_array_type,
                    chroma_kind,
                )
                .expect("write B_Direct_16x16 mb (4:2:2/4:4:4)");
            } else if let Some(pc) = partition_choice.as_ref() {
                match pc.shape {
                    PartitionShape::P16x8 => {
                        let cfg = crate::encoder::macroblock::B16x8McbConfig {
                            transform_size_8x8_flag: b_t8x8_flag,
                            top: pc.mode_a,
                            bottom: pc.mode_b,
                            mvd_l0: mvd_l0_parts,
                            mvd_l1: mvd_l1_parts,
                            cbp_luma,
                            cbp_chroma,
                            mb_qp_delta: 0,
                            luma_4x4_levels: luma_4x4_levels_scan,
                            luma_4x4_nc,
                            chroma_dc_cb: [0; 4],
                            chroma_dc_cr: [0; 4],
                            chroma_ac_cb: [[0; 16]; 4],
                            chroma_ac_cr: [[0; 16]; 4],
                            chroma_ac_nc_cb: [0; 8],
                            chroma_ac_nc_cr: [0; 8],
                        };
                        crate::encoder::macroblock::write_b_16x8_mb_chroma(
                            sw,
                            &cfg,
                            0,
                            0,
                            chroma_array_type,
                            chroma_kind,
                        )
                        .expect("write B_*_16x8 mb (4:2:2/4:4:4)");
                    }
                    PartitionShape::P8x16 => {
                        let cfg = crate::encoder::macroblock::B8x16McbConfig {
                            transform_size_8x8_flag: b_t8x8_flag,
                            left: pc.mode_a,
                            right: pc.mode_b,
                            mvd_l0: mvd_l0_parts,
                            mvd_l1: mvd_l1_parts,
                            cbp_luma,
                            cbp_chroma,
                            mb_qp_delta: 0,
                            luma_4x4_levels: luma_4x4_levels_scan,
                            luma_4x4_nc,
                            chroma_dc_cb: [0; 4],
                            chroma_dc_cr: [0; 4],
                            chroma_ac_cb: [[0; 16]; 4],
                            chroma_ac_cr: [[0; 16]; 4],
                            chroma_ac_nc_cb: [0; 8],
                            chroma_ac_nc_cr: [0; 8],
                        };
                        crate::encoder::macroblock::write_b_8x16_mb_chroma(
                            sw,
                            &cfg,
                            0,
                            0,
                            chroma_array_type,
                            chroma_kind,
                        )
                        .expect("write B_*_8x16 mb (4:2:2/4:4:4)");
                    }
                }
            } else {
                let mb_cfg = B16x16McbConfig {
                    transform_size_8x8_flag: b_t8x8_flag,
                    pred,
                    mvd_l0_x,
                    mvd_l0_y,
                    mvd_l1_x,
                    mvd_l1_y,
                    cbp_luma,
                    cbp_chroma,
                    mb_qp_delta: 0,
                    luma_4x4_levels: luma_4x4_levels_scan,
                    luma_4x4_nc,
                    chroma_dc_cb: [0; 4],
                    chroma_dc_cr: [0; 4],
                    chroma_ac_cb: [[0; 16]; 4],
                    chroma_ac_cr: [[0; 16]; 4],
                    chroma_ac_nc_cb: [0; 8],
                    chroma_ac_nc_cr: [0; 8],
                };
                crate::encoder::macroblock::write_b_16x16_mb_chroma(
                    sw,
                    &mb_cfg,
                    0,
                    0,
                    chroma_array_type,
                    chroma_kind,
                )
                .expect("write B_*_16x16 mb (4:2:2/4:4:4)");
            }
        }
        // 10. Grids. 16x16 / Direct shapes share the MB-level state
        //     across the four 8x8 slots; partition shapes carry
        //     per-half MVs (top = slots 0/1, bottom = 2/3 for 16x8;
        //     left = 0/2, right = 1/3 for 8x16).
        let (l0_mvs_8x8, l0_refs_8x8, l0_used) =
            grid_state_b(partition_choice.as_ref(), true, pred, eff_mv_l0);
        let (l1_mvs_8x8, l1_refs_8x8, l1_used) =
            grid_state_b(partition_choice.as_ref(), false, pred, eff_mv_l1);
        *mv_grid_l0.slot_mut(mb_x, mb_y) = if l0_used {
            MvGridSlot {
                available: true,
                is_intra: false,
                ref_idx_l0_8x8: l0_refs_8x8,
                mv_l0_8x8: l0_mvs_8x8,
            }
        } else {
            MvGridSlot {
                available: true,
                is_intra: true,
                ref_idx_l0_8x8: [-1; 4],
                mv_l0_8x8: [Mv::ZERO; 4],
            }
        };
        *mv_grid_l1.slot_mut(mb_x, mb_y) = if l1_used {
            MvGridSlot {
                available: true,
                is_intra: false,
                ref_idx_l0_8x8: l1_refs_8x8,
                mv_l0_8x8: l1_mvs_8x8,
            }
        } else {
            MvGridSlot {
                available: true,
                is_intra: true,
                ref_idx_l0_8x8: [-1; 4],
                mv_l0_8x8: [Mv::ZERO; 4],
            }
        };
        let s = intra_grid.slot_mut(mb_x, mb_y);
        s.available = true;
        s.is_i_nxn = false;

        // 11. §8.7 deblock info. 4:2:2 packs the 8-block per-plane AC
        //     mask (bits 0..=7 Cb, 8..=15 Cr); 4:4:4 has deblocking
        //     disabled so the mask is unused.
        let luma_nonzero_4x4 = luma_nz_mask_from_blocks(&blk_has_nz);
        let chroma_nonzero_4x4: u16 = match chroma_array_type {
            0 | 3 => 0,
            _ => {
                let mut m = 0u16;
                for blk in 0..8usize {
                    if cbp_chroma == 2 && u_ac8[blk].iter().any(|&v| v != 0) {
                        m |= 1 << blk;
                    }
                    if cbp_chroma == 2 && v_ac8[blk].iter().any(|&v| v != 0) {
                        m |= 1 << (8 + blk);
                    }
                }
                m
            }
        };
        let (mv_l0_arr, ref_idx_l0, ref_poc_l0) =
            deblock_mv_arr_b(partition_choice.as_ref(), true, pred, eff_mv_l0, 0);
        let (mv_l1_arr, ref_idx_l1, ref_poc_l1) =
            deblock_mv_arr_b(partition_choice.as_ref(), false, pred, eff_mv_l1, 1000);
        MbDeblockInfo {
            is_intra: false,
            qp_y,
            luma_nonzero_4x4,
            chroma_nonzero_4x4,
            transform_size_8x8_flag: transform_size_8x8,
            mv_l0: mv_l0_arr,
            ref_idx_l0,
            ref_poc_l0,
            mv_l1: mv_l1_arr,
            ref_idx_l1,
            ref_poc_l1,
            is_intra_4x4: false,
        }
    }

    /// Round-29 — encode one B-slice MB with optional **Intra_16x16
    /// fallback** RDO (per §7.3.5 Table 7-14 mb_type values 24..=47).
    /// Mirrors [`Encoder::encode_p_mb_with_intra_fallback`] but on the
    /// two-list B-slice context.
    #[allow(clippy::too_many_arguments)]
    fn encode_b_mb_with_intra_fallback(
        &self,
        frame: &YuvFrame<'_>,
        ref_l0: &EncodedFrameRef<'_>,
        ref_l1: &EncodedFrameRef<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        src_stride: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid_l0: &mut MvGrid,
        mv_grid_l1: &mut MvGrid,
        pending_skip: &mut u32,
        curr_poc: i32,
        weighted: Option<WeightedBipredLuma>,
        qp_tracker: &mut MbQpTracker,
    ) -> MbDeblockInfo {
        // Round-397 — the Intra_16x16-in-inter trial body is
        // 4:2:0-only (its chroma trial + snapshot windows are 8x8);
        // 4:2:2 / 4:4:4 B-slices take the pure-inter path.
        if !self.cfg.intra_in_inter || self.cfg.chroma_format_idc != 1 {
            return self.encode_b_mb(
                frame,
                ref_l0,
                ref_l1,
                mb_x,
                mb_y,
                qp_y,
                qp_c,
                chroma_width,
                chroma_height,
                src_stride,
                recon_y,
                recon_u,
                recon_v,
                sw,
                nc_grid,
                intra_grid,
                mv_grid_l0,
                mv_grid_l1,
                pending_skip,
                curr_poc,
                weighted,
                qp_tracker,
            );
        }

        let width = self.cfg.width as usize;
        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;

        // -- Snapshot pre-state. --
        let snap_pre = InterMbStateSnapshot::capture_b(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mv_grid_l0,
            mv_grid_l1,
            mb_addr,
            width_mbs,
            *pending_skip,
        );
        let pre_bits = sw.bits_emitted();
        // §7.4.5 chain state must be trialled + restored alongside the
        // bitstream snapshot: each trial may or may not emit an
        // mb_qp_delta (mirrors `encode_p_mb_with_intra_fallback`).
        let qp_tracker_pre = *qp_tracker;

        // -- Trial 1: inter (B_Skip / B_Direct / B_L0/L1/Bi / partitions / 8x8). --
        let inter_dbl = self.encode_b_mb(
            frame,
            ref_l0,
            ref_l1,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            src_stride,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mv_grid_l0,
            mv_grid_l1,
            pending_skip,
            curr_poc,
            weighted,
            qp_tracker,
        );
        let inter_bits = sw.bits_emitted() - pre_bits;
        let inter_d = ssd_16x16(frame.y, width, mb_x * 16, mb_y * 16, &{
            let mut buf = [0i32; 256];
            for j in 0..16usize {
                for i in 0..16usize {
                    buf[j * 16 + i] = recon_y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
                }
            }
            buf
        });
        let lambda = lambda_ssd(qp_y, false);
        let j_inter = cost_combined(inter_d, inter_bits as u64, lambda);

        // Capture post-inter state.
        let snap_inter = InterMbStateSnapshot::capture_b(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mv_grid_l0,
            mv_grid_l1,
            mb_addr,
            width_mbs,
            *pending_skip,
        );

        let qp_tracker_inter = *qp_tracker;

        // -- Restore pre-state for the intra trial. --
        snap_pre.restore_b(
            recon_y,
            recon_u,
            recon_v,
            width,
            chroma_width,
            mb_x,
            mb_y,
            sw,
            nc_grid,
            intra_grid,
            mv_grid_l0,
            mv_grid_l1,
            mb_addr,
            pending_skip,
        );
        *qp_tracker = qp_tracker_pre;

        // -- Trial 2: Intra_16x16 in B-slice. --
        let intra_dbl = self.encode_b_mb_intra16x16(
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            mv_grid_l0,
            mv_grid_l1,
            pending_skip,
            qp_tracker,
        );
        let intra_bits = sw.bits_emitted() - pre_bits;
        let intra_d = ssd_16x16(frame.y, width, mb_x * 16, mb_y * 16, &{
            let mut buf = [0i32; 256];
            for j in 0..16usize {
                for i in 0..16usize {
                    buf[j * 16 + i] = recon_y[(mb_y * 16 + j) * width + (mb_x * 16 + i)] as i32;
                }
            }
            buf
        });
        let j_intra = cost_combined(intra_d, intra_bits as u64, lambda);

        // -- Pick winner. --
        if j_inter <= j_intra {
            snap_pre.restore_b(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mv_grid_l0,
                mv_grid_l1,
                mb_addr,
                pending_skip,
            );
            snap_inter.restore_b(
                recon_y,
                recon_u,
                recon_v,
                width,
                chroma_width,
                mb_x,
                mb_y,
                sw,
                nc_grid,
                intra_grid,
                mv_grid_l0,
                mv_grid_l1,
                mb_addr,
                pending_skip,
            );
            *qp_tracker = qp_tracker_inter;
            inter_dbl
        } else {
            intra_dbl
        }
    }

    /// Round-29 — Intra_16x16 fallback for a B-slice MB. Mirrors
    /// [`Encoder::encode_p_mb_intra16x16`] but updates *both* L0 and L1
    /// MV grids (intra contribution for either list).
    #[allow(clippy::too_many_arguments)]
    fn encode_b_mb_intra16x16(
        &self,
        frame: &YuvFrame<'_>,
        mb_x: usize,
        mb_y: usize,
        qp_y: i32,
        qp_c: i32,
        chroma_width: usize,
        chroma_height: usize,
        recon_y: &mut [u8],
        recon_u: &mut [u8],
        recon_v: &mut [u8],
        sw: &mut BitWriter,
        nc_grid: &mut CavlcNcGrid,
        intra_grid: &mut IntraGrid,
        mv_grid_l0: &mut MvGrid,
        mv_grid_l1: &mut MvGrid,
        pending_skip: &mut u32,
        qp_tracker: &mut MbQpTracker,
    ) -> MbDeblockInfo {
        // Flush any pending B_Skip run.
        sw.ue(*pending_skip);
        *pending_skip = 0;
        qp_tracker.write_pending_mbaff_flag(sw);

        // §7.3.5 — Intra_16x16 always codes mb_qp_delta (the luma DC
        // block is unconditional): emit the step from the decoder's
        // running predictor (round-443 row modulation).
        let mb_qp_delta = qp_y - qp_tracker.cur;
        qp_tracker.cur = qp_y;
        self.encode_intra16x16_in_inter_slice(
            frame,
            mb_x,
            mb_y,
            qp_y,
            qp_c,
            chroma_width,
            chroma_height,
            recon_y,
            recon_u,
            recon_v,
            sw,
            nc_grid,
            intra_grid,
            23,
            mb_qp_delta,
            None,
        );

        // Update both MV grids for the intra MB.
        let intra_slot = MvGridSlot {
            available: true,
            is_intra: true,
            ref_idx_l0_8x8: [-1; 4],
            mv_l0_8x8: [Mv::ZERO; 4],
        };
        *mv_grid_l0.slot_mut(mb_x, mb_y) = intra_slot;
        *mv_grid_l1.slot_mut(mb_x, mb_y) = intra_slot;

        let width_mbs = (self.cfg.width / 16) as usize;
        let mb_addr = mb_y * width_mbs + mb_x;
        let any_nz = nc_grid.mbs[mb_addr]
            .luma_total_coeff
            .iter()
            .any(|&v| v != 0);
        let luma_nonzero_4x4: u16 = if any_nz {
            let mut nz = [false; 16];
            for (blkz, slot) in nz.iter_mut().enumerate() {
                *slot = nc_grid.mbs[mb_addr].luma_total_coeff[blkz] != 0;
            }
            luma_nz_mask_from_blocks(&nz)
        } else {
            0
        };

        MbDeblockInfo {
            is_intra: true,
            qp_y,
            luma_nonzero_4x4,
            chroma_nonzero_4x4: 0,
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod weighted_bipred_tests {
    use super::*;

    /// Hand-built fade fixture: textured frames at two brightness
    /// levels with a true linear cross-fade. Texture (not just brightness)
    /// rules out the degenerate "all-on-L1, offset compensates" solution
    /// — the weights have to honour the per-sample mixing to keep SSE
    /// low. The selector should land on weights near (45, 19) at
    /// log2_wd = 5, i.e. α ≈ 0.7 toward L0.
    #[test]
    fn weight_selector_finds_alpha_07_on_textured_fade() {
        let w = 16usize;
        let h = 16usize;
        let mut l0 = vec![0u8; w * h];
        let mut l1 = vec![0u8; w * h];
        let mut src = vec![0u8; w * h];
        for j in 0..h {
            for i in 0..w {
                // L0 and L1 have *different* texture scales so an offset
                // alone cannot disguise itself as a weight choice. With
                // L0 amplitude 60 and L1 amplitude 20, only the right α
                // can match the source's mixed texture amplitude
                // 0.7 * 60 + 0.3 * 20 = 42.
                let tex_a = (((i * 13 + j * 7) % 16) as i32) * 4; // 0..=60
                let tex_b = ((i * 13 + j * 7) % 16) as i32; // 0..=15
                let a = 30 + tex_a;
                let b = 180 + tex_b;
                let v = (0.7 * a as f64 + 0.3 * b as f64).round() as i32;
                l0[j * w + i] = a.clamp(0, 255) as u8;
                l1[j * w + i] = b.clamp(0, 255) as u8;
                src[j * w + i] = v.clamp(0, 255) as u8;
            }
        }
        let table = compute_explicit_bipred_weights(&src, &l0, &l1, w, h, w, w);
        assert_eq!(table.luma_log2_weight_denom, 5);
        // w0 + w1 must sum to 64 (denom for log2_wd = 5).
        assert_eq!(
            table.luma_weight_l0 + table.luma_weight_l1,
            64,
            "weights must sum to 2^(logwd+1)"
        );
        // Coarse grid step is 4 → α=0.7 lands on w0 ∈ {44, 48}; we expect
        // the selector to pick the better neighbour.
        assert!(
            (40..=48).contains(&table.luma_weight_l0),
            "expected w0 ≈ 45 (α=0.7), got {}",
            table.luma_weight_l0,
        );
    }

    /// On content where the source IS the linear midpoint of L0 and L1
    /// the selector should fall back to the default (32, 32, 0, 0)
    /// because the explicit table wouldn't beat the default merge.
    #[test]
    fn weight_selector_returns_default_on_midpoint_fade() {
        let w = 16usize;
        let h = 16usize;
        let l0 = vec![60u8; w * h];
        let l1 = vec![160u8; w * h];
        // Midpoint: (60+160+1)>>1 = 110.
        let src = vec![110u8; w * h];
        let table = compute_explicit_bipred_weights(&src, &l0, &l1, w, h, w, w);
        assert_eq!(table.luma_weight_l0, 32);
        assert_eq!(table.luma_weight_l1, 32);
        assert_eq!(table.luma_offset_l0, 0);
        assert_eq!(table.luma_offset_l1, 0);
    }
}

#[cfg(test)]
mod level_derivation_tests {
    use super::*;

    /// Annex A Table A-1 — `min_level_idc_for_picture_size` walks the
    /// MaxFS column low→high and picks the first entry whose `MaxFS`
    /// is at least the picture's `width_in_mbs * height_in_mbs`.
    #[test]
    fn min_level_idc_picks_smallest_covering_level() {
        // QCIF 176x144 → 99 mb → Level 1 (MaxFS = 99).
        assert_eq!(min_level_idc_for_picture_size(11, 9), 10);
        // CIF 352x288 → 396 mb → Level 1.1 (first 396-bucket entry).
        assert_eq!(min_level_idc_for_picture_size(22, 18), 11);
        // 4CIF 704x576 → 1584 mb → Level 2.2 (MaxFS = 1620, first 1620
        // bucket since 2.1 has 792 and 2 has 396).
        assert_eq!(min_level_idc_for_picture_size(44, 36), 22);
        // SD 720x576 → 1620 mb → Level 2.2 (1620 = MaxFS exact).
        assert_eq!(min_level_idc_for_picture_size(45, 36), 22);
        // 720p 1280x720 → 3600 mb → Level 3.1 (MaxFS = 3600 exact).
        assert_eq!(min_level_idc_for_picture_size(80, 45), 31);
        // 1080p 1920x1080 → 8160 mb → Level 4 (MaxFS = 8192).
        assert_eq!(min_level_idc_for_picture_size(120, 68), 40);
        // 4K UHD 3840x2160 → 32400 mb → Level 5.1 (MaxFS = 36864).
        assert_eq!(min_level_idc_for_picture_size(240, 135), 51);
        // 8K UHD 7680x4320 → 129600 mb → Level 6 (MaxFS = 139264).
        assert_eq!(min_level_idc_for_picture_size(480, 270), 60);
        // Pathological huge picture beyond every standardised level
        // (e.g. 16K-equivalent) → cap at Level 6.2.
        assert_eq!(min_level_idc_for_picture_size(1024, 1024), 62);
    }

    /// Default-derived encoder config picks the level via
    /// [`min_level_idc_for_picture_size`]. Pre-fix the constructor
    /// always emitted `level_idc = 30` regardless of size.
    #[test]
    fn encoder_config_default_level_matches_picture_size() {
        // 64x64 (the synthetic test fixture) → 16 mb → Level 1.
        let cfg = EncoderConfig::new(64, 64);
        assert_eq!(cfg.level_idc, 10);

        // 720p
        let cfg = EncoderConfig::new(1280, 720);
        assert_eq!(cfg.level_idc, 31);

        // 1080p
        let cfg = EncoderConfig::new(1920, 1080);
        assert_eq!(cfg.level_idc, 40);

        // 4K UHD
        let cfg = EncoderConfig::new(3840, 2160);
        assert_eq!(cfg.level_idc, 51);
    }

    /// Non-multiple-of-16 dimensions round up to whole MBs (the SPS
    /// field is `pic_width_in_mbs_minus1`, which is in MB units).
    #[test]
    fn non_aligned_dimensions_round_up_to_whole_mbs() {
        // 1920x1088 should equal 1920x1080 (both round to 120x68 mb).
        assert_eq!(EncoderConfig::new(1920, 1088).level_idc, 40);
        // 1920x1081 still rounds to 120x68 → Level 4.
        assert_eq!(EncoderConfig::new(1920, 1081).level_idc, 40);
    }
}