rusty_h264-decoder 0.12.0

Pure-Rust H.264 decoder (Baseline + B-slices + most of High profile, CAVLC + CABAC) — bit-exact vs Cisco openh264, pixel-exact vs ffmpeg, fuzzed panic-free. forbid(unsafe) core; portable Rust SIMD on by default. BSD-2.
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
//! I_16x16 macroblock decoding — the mirror of the encoder's `mb16`.
//!
//! Parses each macroblock's residuals and reconstructs it with the exact same
//! prediction + inverse-transform helpers the encoder uses, so decoder output
//! matches encoder reconstruction bit-for-bit.
#![allow(clippy::needless_range_loop)]

use rusty_h264_common::bit_reader::OutOfData;
use rusty_h264_common::cavlc::{
    decode_residual_block_with, read_cbp_inter, read_cbp_intra, un_scan_4x4_ac_into,
    un_scan_4x4_dcac, vlc_tables,
};
use rusty_h264_common::inter::{
    inter_partitions, mc_chroma_padded, mc_luma_padded, predict_mv, predict_partition_mv,
    MvNeighbor,
};
use rusty_h264_common::predict::{
    add_residual_8x8, chroma8x8_pred, chroma_qp, intra4x4_pred, intra8x8_pred, luma16x16_pred,
    reconstruct_4x4_dc_into, reconstruct_4x4_into, I16Mode,
    CHROMA_4X4_SCAN_XY, LUMA_4X4_SCAN_XY,
};
use rusty_h264_common::transform::{
    dequant_scatter_4x4, dequantize, dequantize_weighted, inverse_quant_8x8,
    inverse_quant_chroma_dc,
    inverse_quant_chroma_dc_weighted, inverse_quant_luma_dc, inverse_quant_luma_dc_weighted,
};
use rusty_h264_common::{BitReader, YuvFrame};

/// One frame's motion field, in 4x4-block raster (`mb_w*4` wide).
///
/// Captured from any conformant stream this decoder parses — including x264's —
/// so a harness can compare motion fields between encoders without depending on
/// external MV-export tooling.
pub struct MvField {
    pub mb_w: usize,
    pub mb_h: usize,
    pub mv: Vec<(i32, i32)>,
    pub ref_idx: Vec<i32>,
    pub inter: Vec<bool>,
}

/// Frames captured in decode order when `RFF_MV_DUMP=1`. Diagnostic only.
pub static MV_DUMP: std::sync::Mutex<Vec<MvField>> = std::sync::Mutex::new(Vec::new());

pub fn mv_dump_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("RFF_MV_DUMP").map_or(false, |v| v != "0"))
}

/// Copy filtered MB rows `[prev..mb_rows)` from coded-size planes into a
/// Frame-MT progress slot's live padded planes, then bump `ready_rows`.
/// Coarser publish: only advance the watermark every 2 MB rows (and always
/// on the last row) to cut lock/notify traffic.
fn publish_filtered_rows_to_slot(
    slot: &crate::RefFrame,
    rec_y: &[u8],
    rec_u: &[u8],
    rec_v: &[u8],
    cw: usize,
    ccw: usize,
    ch: usize,
    mb_rows: usize,
) {
    if mb_rows == 0 || slot.frozen.get().is_some() {
        return;
    }
    if !crate::frame_mt::row_publish_on() {
        return;
    }
    let mb_h = (ch + 15) / 16;
    // Batch: defer watermark until even MB rows (or picture end).
    if mb_rows < mb_h && (mb_rows & 1) != 0 {
        return;
    }
    let Some(live) = &slot.live else {
        slot.publish_ready_rows(mb_rows * 16);
        return;
    };
    let cch = ch / 2;
    let prev = slot.ready_rows.load(std::sync::atomic::Ordering::Acquire) / 16;
    if mb_rows <= prev {
        return;
    }
    let mut py = live.py.write().unwrap();
    let mut pu = live.pu.write().unwrap();
    let mut pv = live.pv.write().unwrap();
    let ls = cw + 2 * crate::LPAD;
    let cs = ccw + 2 * crate::CPAD;
    for mr in prev..mb_rows {
        for dy in 0..16 {
            let y = mr * 16 + dy;
            if y >= ch {
                break;
            }
            let src = &rec_y[y * cw..(y + 1) * cw];
            let dst_y = y + crate::LPAD;
            // ONE row segment covering pad+picture+pad, then `split_at_mut` and
            // two fills — the edge reads and the 2*LPAD writes were separate
            // whole-plane indexes. Same shape as `expand_plane`.
            let seg = &mut py[dst_y * ls..][..2 * crate::LPAD + cw];
            let (lpad, rest) = seg.split_at_mut(crate::LPAD);
            let (mid, rpad) = rest.split_at_mut(cw);
            mid.copy_from_slice(src);
            let (Some(&left), Some(&right)) = (mid.first(), mid.last()) else {
                continue;
            };
            lpad.fill(left);
            rpad[..crate::LPAD].fill(right);
        }
        for dy in 0..8 {
            let cy = mr * 8 + dy;
            if cy >= cch {
                break;
            }
            for (rec, plane) in [(rec_u, &mut *pu), (rec_v, &mut *pv)] {
                let src = &rec[cy * ccw..(cy + 1) * ccw];
                let dst_y = cy + crate::CPAD;
                let seg = &mut plane[dst_y * cs..][..2 * crate::CPAD + ccw];
                let (lpad, rest) = seg.split_at_mut(crate::CPAD);
                let (mid, rpad) = rest.split_at_mut(ccw);
                mid.copy_from_slice(src);
                let (Some(&left), Some(&right)) = (mid.first(), mid.last()) else {
                    continue;
                };
                lpad.fill(left);
                rpad[..crate::CPAD].fill(right);
            }
        }
    }
    if prev == 0 {
        // Copy the whole first picture ROW upward instead of walking columns:
        // `split_at_mut` at the pad boundary proves both sides at once.
        let (pad, rest) = py.split_at_mut(crate::LPAD * ls);
        if let Some(first) = rest.get(..ls) {
            for row in pad.chunks_mut(ls) {
                row.copy_from_slice(first);
            }
        }
        for plane in [&mut *pu, &mut *pv] {
            let (pad, rest) = plane.split_at_mut(crate::CPAD * cs);
            if let Some(first) = rest.get(..cs) {
                for row in pad.chunks_mut(cs) {
                    row.copy_from_slice(first);
                }
            }
        }
    }
    slot.publish_ready_rows(mb_rows * 16);
}

/// Reconstructed coded-size planes plus CAVLC `nnz` context grids.
pub struct FrameDecoder {
    mb_w: usize,
    mb_h: usize,
    /// Slice QP (`SliceQPy`) — the deblock filter's frame-level QP.
    qp: u8,
    /// Running luma QP (`QPy`), carried across macroblocks and stepped by each
    /// `mb_qp_delta` (spec §7.4.5). Equals `qp` on constant-QP streams.
    cur_qp: u8,
    /// `chroma_qp_index_offset` from the active PPS (§8.5.8).
    chroma_qp_offset: i32,
    cw: usize,
    ch: usize,
    ccw: usize,
    cch: usize,
    rec_y: Vec<u8>,
    rec_u: Vec<u8>,
    rec_v: Vec<u8>,
    /// Per-macroblock luma QP (`QPy`), for per-edge deblock strength.
    mb_qp: Vec<u8>,
    /// First macroblock address of the slice currently being decoded. Neighbors
    /// with a lower address belong to an earlier slice and are "not available"
    /// for prediction (spec §8.3/§8.4). Slices are contiguous raster ranges (we
    /// reject FMO/slice-groups), so address ≥ this ⇔ same slice.
    slice_first_mb: usize,
    nnz_y: Vec<u8>,
    nnz_c: [Vec<u8>; 2],
    modes_y: Vec<u8>,
    coded_y: Vec<bool>,
    /// Per-4×4-block List-0 motion (mv + ref index, `-1` = no L0). For P slices
    /// this is the only motion; B slices add the List-1 grids below.
    mv_y: Vec<(i32, i32)>,
    inter_y: Vec<bool>,
    ref_idx_y: Vec<i32>,
    /// Per-4×4-block List-1 motion for B slices (`ref_idx1 = -1` = no L1).
    mv1: Vec<(i32, i32)>,
    ref_idx1: Vec<i32>,
    /// `RefPicList1` and B-slice flags (unused outside B slices).
    refs1: Vec<crate::Ref>,
    num_ref_active1: usize,
    is_b: bool,
    /// True if the stream's profile permits B-slices (`profile_idc != 66`). When
    /// false (Baseline / Constrained Baseline), `as_reference_pooled` skips the per-block
    /// motion (mv/ref_idx/ref_poc) that only B temporal/spatial direct ever reads.
    b_possible: bool,
    direct_spatial: bool,
    nnz_l_cache: [u8; 25],
    nnz_c_cache: [[u8; 9]; 2],
    /// Decoded-picture buffer (most-recent first); empty in I-slices. `ref_idx`
    /// indexes into this list.
    refs: Vec<crate::Ref>,
    /// `num_ref_idx_l0_active` for the current slice — drives whether `ref_idx`
    /// is coded (active > 1) and its te(v)/ue(v) form, independently of how many
    /// reference pictures actually exist (spec §7.4.5.1, §9.1).
    num_ref_active: usize,
    /// `constrained_intra_pred_flag`: when set, intra prediction may only use
    /// samples from intra-coded neighbors (inter neighbors are "not available").
    constrained_intra: bool,
    /// High-profile 4×4 scaling matrices in **raster** order, indexed by
    /// `[Y-intra, Cb-intra, Cr-intra, Y-inter, Cb-inter, Cr-inter]`. `None` = flat.
    scaling: Option<[[i32; 16]; 6]>,
    /// High-profile 8×8 luma scaling matrices in raster order `[Y-intra, Y-inter]`
    /// (4:2:0 has only these two). `None` = flat.
    scaling8: Option<[[i32; 64]; 2]>,
    /// `transform_8x8_mode_flag` from the PPS: enables `transform_size_8x8_flag`.
    transform_8x8_mode: bool,
    /// SPS `qpprime_y_zero_transform_bypass_flag` — refusal gate in `step_qp`.
    transform_bypass: bool,
    /// GATE 1 router counters (big-oppy-decoder §2): skip MBs and
    /// residual-coded MBs this picture. Two integer adds per MB, no atomics.
    route_skip_mbs: u32,
    route_coded_mbs: u32,
    /// Per-slice `(first_mb, idc == 2)` in decode order — drives the
    /// `disable_deblocking_filter_idc == 2` cross-slice-edge suppression.
    slice_bounds: Vec<(usize, bool)>,
    /// The CURRENT slice's `disable_deblocking_filter_idc == 2`, latched by
    /// `set_deblock_params` and recorded per slice by the decode loops.
    cur_idc2: bool,
    /// Per-macroblock `transform_size_8x8_flag` (for deblocking: internal 4×4
    /// luma edges of 8×8-transform MBs are not filtered).
    mb_t8x8: Vec<bool>,
    // ---- Row-interleaved deblocking state (docs/row-interleave-plan.md) ----
    /// Per-MB boundary strengths, filled row-by-row as decode completes rows.
    bs_frame: Vec<rusty_h264_common::deblock::MbBs>,
    /// Rows whose bS is derived (watermark).
    bs_rows: usize,
    /// Rows already deblock-FILTERED (watermark; R3).
    flt_rows: usize,
    /// Two-row rolling window of packed records (prev = row r-1, cur = row r).
    pk_prev: Vec<rusty_h264_common::deblock::MbPack>,
    pk_cur: Vec<rusty_h264_common::deblock::MbPack>,
    /// Transform-block coded mask (nnz with the 8x8 OR applied), filled per row.
    nnz_dbr: Vec<u8>,
    /// Unfiltered bottom rows of the last-filtered MB row (intra reads these).
    bak_y: Vec<u8>,
    bak_u: Vec<u8>,
    bak_v: Vec<u8>,
    /// Entropy-decouple: deferred pixel jobs + the per-slice activation flag
    /// (CABAC slices only — the CAVLC loop has no flush hooks).
    edc_jobs: Vec<EdcJob>,
    edc_active: bool,
    // ---- E2: the worker-thread plumbing (all None outside a threaded slice) ----
    edc_tx: Option<std::sync::mpsc::SyncSender<EdcMsg>>,
    edc_ctx_rx: Option<std::sync::mpsc::Receiver<PixelCtx>>,
    edc_back_tx: Option<std::sync::mpsc::Sender<PixelCtx>>,
    /// While the parse thread holds the pixel context for an intra macroblock
    /// (planes moved into `self`), the rest of the context parks here.
    edc_parked: Option<PixelCtx>,
    /// E3: while parsing a B macroblock in threaded mode, its MC regions
    /// accumulate here instead of executing (the pixel side is the worker's).
    edc_regions: Option<Vec<BRegion>>,
    /// Measurement only: previous full-MB single-rect direct (x, y, refi0,
    /// refi1, m0, m1) for run-adjacency counting. No decode behavior.
    bsk_last: Option<(usize, usize, i32, i32, (i32, i32), (i32, i32))>,
    /// D10: jobs accumulated for the current row, sent as ONE message.
    edc_batch: Vec<EdcJob>,
    /// D12: bits/MB carried in from previous slices (0 = not yet known).
    bits_per_mb: f64,
    /// Current slice's deblock parameters (set per slice by the caller).
    db_ena: bool,
    db_oa: i32,
    db_ob: i32,
    /// Per-macroblock deblock derivation CLASS (`MB_KIND_*`), so the loop filter
    /// can skip the 24-block neighbourhood gather on macroblocks whose strengths
    /// are determined by syntax alone. Starts UNSET; anything left UNSET simply
    /// takes the blind path, so a missed producer site costs speed, not
    /// correctness. Only classes that are uniform BY SYNTAX are written — notably
    /// NOT `B_Skip`/`B_Direct`, whose direct-derived motion varies per 4×4.
    mb_kind: Vec<u8>,
    /// Explicit weighted-prediction tables, when active for this slice.
    weights: Option<WeightTable>,
    /// `frame_mt::row_progress_on()` cached at construction (see
    /// wait_refs_for_mb).
    row_wait: bool,
    /// Colocated-picture fast-probe cache (set_b_context): true when refs1[0]
    /// is frozen (1T), short-term, with motion grids — col_zero then skips
    /// the Option + live + long_term + w4 branch chain per probe.
    col_ok: bool,
    col_w4: usize,
    /// Measurement knobs cached at construction — these were OnceLock derefs
    /// on EVERY skip macroblock (no_bskipfast per B skip, no_runmv per P
    /// skip); one field test now.
    k_no_bskipfast: bool,
    k_no_runmv: bool,
    /// rowdb_on()/rowhook_eager() cached at construction — these were atomic
    /// loads inside row_hook_at on EVERY macroblock.
    k_rowdb: bool,
    k_roweager: bool,
    /// MEASUREMENT KNOB, cached. `kind_loads()` is a `OnceLock` deref and was
    /// evaluated as a MATCH GUARD on every Skip/InterUniform macroblock in
    /// `derive_bs_row` — the dominant class. The census (DBSDERIVE kindarm=0 on
    /// 6/6 corpus streams) shows the arm it guards never fires by default, so
    /// every one of those derefs was pure tax. Same treatment `k_rowdb` /
    /// `k_roweager` already had.
    k_kindloads: bool,
    /// True once ANY macroblock in this picture used the 8x8 transform. The
    /// `nnz_dbr` row copy + the per-row t8 scan in `derive_bs_row` exist ONLY
    /// to apply the 8x8 coded-status OR; with no t8 macroblock `nnz_dbr` is a
    /// byte-for-byte copy of `nnz_y`, so both are skipped and the derivation
    /// reads `nnz_y` directly. Census: t8mb=0 on every cavlc/main stream.
    any_t8: bool,
    /// True once any slice in this picture carries
    /// `disable_deblocking_filter_idc == 2`. Replaces a per-ROW
    /// `slice_bounds.iter().any(..)` scan (census: idc2row=0 on the corpus).
    any_idc2: bool,
    /// Raster address whose P_Skip MV is FORCED (0,0): the previous
    /// decode_p_skip was at addr-1 and committed (0,0), so this MB's left
    /// neighbor either fires §8.4.1.1's zero-MV rule (in-slice: ref 0,
    /// (0,0)) or is unavailable (out-of-slice — same rule). Interior MBs of
    /// a skip run skip the 3-neighbor gather entirely.
    skip_zero_next: usize,
    /// Pending B_Skip grid+recon span: (mb row, x0, n, kind) of CONSECUTIVE
    /// fast B_Skips with IDENTICAL committed values, deferred and range-
    /// filled/band-reconned at flush. Flushed before ANY grid or pixel
    /// reader runs — see span_flush callers.
    bzspan: Option<(usize, usize, usize, BzKind)>,
    /// Pending P_Skip (0,0) grid-commit span — the P mirror of `bzspan`
    /// (values: ref 0 list-0, mv (0,0), inter, coded, DC mode, kind SKIP).
    /// The bool records whether the RECON is deferred too (1T, identity/no
    /// weights) — decided at push time, not re-derived at flush (begin_slice
    /// may have changed the fields in between).
    pzspan: Option<(usize, usize, usize, bool)>,
    /// Per-picture bitmap: MB decoded as a ref0/(0,0)-both-lists zero-bi fast
    /// B_Skip. Never cleared mid-picture — false only ever means "derive
    /// normally" — so no MB path carries a clearing duty.
    bzero: Vec<bool>,
    /// Pooled CABAC slice scratch — refilled (not reallocated) at slice entry;
    /// carried across pictures via `GridPool`. Taken out of `self` at
    /// `decode_slice_cabac_inner` entry and put back at its normal exit (an
    /// error exit simply forfeits the pooled allocation).
    sc_cat: Vec<u8>,
    sc_cbp: Vec<u8>,
    sc_cmode: Vec<i32>,
    sc_nzc: Vec<[u8; 24]>,
    sc_cbfdc: Vec<u16>,
    sc_skip: Vec<bool>,
    sc_ref: Vec<[i8; 16]>,
    sc_mvd: Vec<[[i16; 2]; 16]>,
    sc_ref1: Vec<[i8; 16]>,
    sc_mvd1: Vec<[[i16; 2]; 16]>,
    sc_direct: Vec<bool>,
    /// Lazily cached `implicit_weights(0, 0)` — slice-constant (POCs of
    /// refs[0]/refs1[0] and cur don't change within a slice). Reset in
    /// set_b_context.
    iw00: Option<Option<(i32, i32)>>,
    /// Cached `weights.list_identity(0)` — all list-0 refs identity; gates the
    /// whole weight_partition pass for P inter (one choke point, all sites).
    weights_l0id: bool,
    /// Cached `weights.ref0_identity()` — identity tables (the x264 weightp=2
    /// common case) make every ref-0 weighting pass an exact no-op, and the
    /// skip fast paths check this per MB, so it is computed once per slice.
    weights_id0: bool,
    /// Current picture's `PicOrderCnt` (for temporal direct + implicit weighting).
    cur_poc: i32,
    /// `weighted_bipred_idc` (0 = none/average, 1 = explicit, 2 = implicit).
    weighted_bipred_idc: u8,
    /// `direct_8x8_inference_flag` (B direct co-located sub-block selection).
    direct_8x8_inference: bool,
    /// Frame-MT Phase B: shared progress Arc for the picture being decoded.
    progress: Option<crate::Ref>,
    /// Slice-stable ref→POC tables for bS (≤16 entries). `derive_bs_row` used
    /// to `collect()` these every row — same values for the whole slice.
    ref_poc0: Vec<i32>,
    ref_poc1: Vec<i32>,
}

/// Explicit weighted-prediction tables (spec §7.4.3.2 / §8.4.2.3.2). Per
/// reference list, per ref index: a luma `(weight, offset)` and two chroma
/// `(weight, offset)` (Cb, Cr). `log2` denominators are shared.
#[derive(Clone, Default)]
pub struct WeightTable {
    pub luma_log2_denom: i32,
    pub chroma_log2_denom: i32,
    /// `[list][ref_idx] = (weight, offset)`.
    pub luma: [Vec<(i32, i32)>; 2],
    /// `[list][ref_idx][cb=0/cr=1] = (weight, offset)`.
    pub chroma: [Vec<[(i32, i32); 2]>; 2],
}

impl WeightTable {
    /// True when list-0 ref-0 carries identity weights (w == 1<<denom, offset 0)
    /// for luma and both chroma planes. x264's weightp=2 puts a pred_weight_table
    /// in EVERY P slice, but outside fades the entries are identity — and the
    /// identity weight is an EXACT no-op ((s*2^d + 2^(d-1))>>d + 0 == s), so a
    /// P_Skip recon may bypass the weighting pass byte-identically.
    fn ref0_identity(&self) -> bool {
        self.luma[0].first().is_some_and(|&(w, o)| w == 1 << self.luma_log2_denom && o == 0)
            && self.chroma[0].first().is_some_and(|c| {
                c.iter().all(|&(w, o)| w == 1 << self.chroma_log2_denom && o == 0)
            })
    }

    /// True when EVERY entry of `list` (all refs, luma + both chroma) is the
    /// identity weight — the x264 weightp=2 shape outside fades. Identity is
    /// an exact per-pixel no-op (see ref0_identity), so the whole per-ref
    /// weighting pass may be skipped for this list.
    fn list_identity(&self, list: usize) -> bool {
        self.luma[list].iter().all(|&(w, o)| w == 1 << self.luma_log2_denom && o == 0)
            && self.chroma[list].iter().all(|c| {
                c.iter().all(|&(w, o)| w == 1 << self.chroma_log2_denom && o == 0)
            })
    }

    /// Applies a single-list (uni-prediction) luma weight (spec §8.4.2.3.2).
    /// Resolves a list/ref slot's (weight, offset) ONCE. `list` is 0..1 and the
    /// fallback is the IDENTITY weight, which is what an absent entry means.
    #[inline]
    fn luma_wo(&self, list: usize, refi: usize) -> (i32, i32) {
        self.luma[list & 1].get(refi).copied().unwrap_or((1 << self.luma_log2_denom, 0))
    }

    /// Ditto for chroma component `cc`.
    #[inline]
    fn chroma_wo(&self, list: usize, refi: usize, cc: usize) -> (i32, i32) {
        self.chroma[list & 1]
            .get(refi)
            .map(|c| c[cc & 1])
            .unwrap_or((1 << self.chroma_log2_denom, 0))
    }

    /// [`Self::apply_luma`] with the weight already resolved — the form the
    /// per-sample loops use, so the lookup is not repeated 256 times.
    #[inline]
    fn apply_luma_wo(&self, sample: u8, w: i32, o: i32) -> u8 {
        let lwd = self.luma_log2_denom;
        let v = if lwd >= 1 {
            ((sample as i32 * w + (1 << (lwd - 1))) >> lwd) + o
        } else {
            sample as i32 * w + o
        };
        v.clamp(0, 255) as u8
    }

    /// [`Self::apply_chroma`] with the weight already resolved.
    #[inline]
    fn apply_chroma_wo(&self, sample: u8, w: i32, o: i32) -> u8 {
        let cwd = self.chroma_log2_denom;
        let v = if cwd >= 1 {
            ((sample as i32 * w + (1 << (cwd - 1))) >> cwd) + o
        } else {
            sample as i32 * w + o
        };
        v.clamp(0, 255) as u8
    }

    fn apply_luma(&self, sample: u8, list: usize, refi: usize) -> u8 {
        let (w, o) = self.luma_wo(list, refi);
        let lwd = self.luma_log2_denom;
        let v = if lwd >= 1 {
            ((sample as i32 * w + (1 << (lwd - 1))) >> lwd) + o
        } else {
            sample as i32 * w + o
        };
        v.clamp(0, 255) as u8
    }

    /// Applies a single-list (uni-prediction) chroma weight for component `cc`.
    fn apply_chroma(&self, sample: u8, list: usize, refi: usize, cc: usize) -> u8 {
        let (w, o) = self.chroma_wo(list, refi, cc);
        let cwd = self.chroma_log2_denom;
        let v = if cwd >= 1 {
            ((sample as i32 * w + (1 << (cwd - 1))) >> cwd) + o
        } else {
            sample as i32 * w + o
        };
        v.clamp(0, 255) as u8
    }
}

/// Why a macroblock could not be decoded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MbError {
    Truncated,
    Unsupported(&'static str),
}

impl From<OutOfData> for MbError {
    fn from(_: OutOfData) -> Self {
        MbError::Truncated
    }
}

/// Recycled per-picture scratch grids.
///
/// `FrameDecoder::new` used to allocate ~1.65 MB of frame-wide grids for EVERY
/// coded picture and drop them when the picture finished. The sampled profiler
/// prices that (stage `dec-setup`) at 6.7% of decode — larger than dequant,
/// reconstruct and intra prediction combined, and none of it is codec work.
///
/// Two costs are being paid, and the allocation is the bigger one. A ~460 KB
/// `Vec` goes straight to the OS, so every page is a fresh zero page and the
/// decoder takes a soft page fault on FIRST TOUCH of each 4 KB — a cost charged
/// to whatever per-macroblock stage happens to touch it first, not to the
/// allocation. Handing the same buffers back keeps the pages mapped and warm.
///
/// The initialising fill is NOT skipped: these grids are read as neighbour
/// context (`modes_y` must read 2/DC, `ref_idx_y` must read -1) before every
/// block that writes them, so a stale value from the previous picture is a
/// correctness bug, not a performance trade. `clear()` + `resize()` keeps the
/// fill and drops only the allocation.
///
/// The reconstruction planes are deliberately NOT pooled: `into_frame` MOVES
/// them out as the caller's output frame, so there is nothing to hand back.
#[derive(Default)]
pub struct GridPool {
    /// D12: running bits-per-macroblock of decoded slices, the E2 dispatch's
    /// density signal. Lives here because `GridPool` is the only state that
    /// survives a picture (`FrameDecoder` is rebuilt per picture).
    bits_per_mb: f64,
    mb_qp: Vec<u8>,
    bs_frame: Vec<rusty_h264_common::deblock::MbBs>,
    pk_prev: Vec<rusty_h264_common::deblock::MbPack>,
    pk_cur: Vec<rusty_h264_common::deblock::MbPack>,
    nnz_dbr: Vec<u8>,
    bak_y: Vec<u8>,
    bak_u: Vec<u8>,
    bak_v: Vec<u8>,
    nnz_y: Vec<u8>,
    nnz_c0: Vec<u8>,
    nnz_c1: Vec<u8>,
    modes_y: Vec<u8>,
    coded_y: Vec<bool>,
    mv_y: Vec<(i32, i32)>,
    inter_y: Vec<bool>,
    ref_idx_y: Vec<i32>,
    mv1: Vec<(i32, i32)>,
    ref_idx1: Vec<i32>,
    mb_t8x8: Vec<bool>,
    mb_kind: Vec<u8>,
    bzero: Vec<bool>,
    // CABAC slice scratch (D13 follow-through): these were fresh `vec![..]`
    // allocations at EVERY slice entry — ~407 KB per P slice, ~700 KB per B
    // slice at 720p, the same fresh-page class GridPool exists to kill.
    sc_cat: Vec<u8>,
    sc_cbp: Vec<u8>,
    sc_cmode: Vec<i32>,
    sc_nzc: Vec<[u8; 24]>,
    sc_cbfdc: Vec<u16>,
    sc_skip: Vec<bool>,
    sc_ref: Vec<[i8; 16]>,
    sc_mvd: Vec<[[i16; 2]; 16]>,
    sc_ref1: Vec<[i8; 16]>,
    sc_mvd1: Vec<[[i16; 2]; 16]>,
    sc_direct: Vec<bool>,
    // D24 (inline-execution.md 11.10): the ref-POC mirrors were the only
    // per-picture Vecs NOT recycled - a fresh alloc + collect per picture each.
    ref_poc0: Vec<i32>,
    ref_poc1: Vec<i32>,
}


/// Reuse `v`'s allocation for `n` copies of `val`. Identical OBSERVABLE result to
/// `vec![val; n]`; differs only in that it reuses the existing allocation when the
/// capacity already suffices.
#[inline]
fn refill<T: Clone>(mut v: Vec<T>, n: usize, val: T) -> Vec<T> {
    v.clear();
    v.resize(n, val);
    v
}

impl FrameDecoder {
    /// Non-pooled ctor — tests only; production always enters via `with_pool`
    /// (`GridPool` recycling, see lib.rs).
    #[cfg(test)]
    pub fn new(
        mb_w: usize,
        mb_h: usize,
        qp: u8,
        chroma_qp_offset: i32,
        refs: Vec<crate::Ref>,
        num_ref_active: usize,
        constrained_intra: bool,
        transform_8x8_mode: bool,
        b_possible: bool,
    ) -> Self {
        Self::with_pool(
            mb_w,
            mb_h,
            qp,
            chroma_qp_offset,
            refs,
            num_ref_active,
            constrained_intra,
            transform_8x8_mode,
            b_possible,
            GridPool::default(),
        )
    }

    /// As `new`, but reusing a previous picture's grid allocations. See `GridPool`.
    #[allow(clippy::too_many_arguments)]
    pub fn with_pool(
        mb_w: usize,
        mb_h: usize,
        qp: u8,
        chroma_qp_offset: i32,
        refs: Vec<crate::Ref>,
        num_ref_active: usize,
        constrained_intra: bool,
        transform_8x8_mode: bool,
        b_possible: bool,
        pool: GridPool,
    ) -> Self {
        let (cw, ch) = (mb_w * 16, mb_h * 16);
        let (ccw, cch) = (cw / 2, ch / 2);
        let bits_per_mb = pool.bits_per_mb;
        let ref_poc0 = {
            let mut v = pool.ref_poc0;
            v.clear();
            v.extend(refs.iter().map(|f| f.pic_poc()));
            v
        };
        Self {
            mb_w,
            mb_h,
            qp,
            cur_qp: qp,
            chroma_qp_offset,
            cw,
            ch,
            ccw,
            cch,
            rec_y: vec![0; cw * ch],
            rec_u: vec![0; ccw * cch],
            rec_v: vec![0; ccw * cch],
            mb_qp: refill(pool.mb_qp, mb_w * mb_h, qp),
            slice_first_mb: 0,
            nnz_y: refill(pool.nnz_y, (mb_w * 4) * (mb_h * 4), 0),
            nnz_c: [
                refill(pool.nnz_c0, (mb_w * 2) * (mb_h * 2), 0),
                refill(pool.nnz_c1, (mb_w * 2) * (mb_h * 2), 0),
            ],
            modes_y: refill(pool.modes_y, (mb_w * 4) * (mb_h * 4), 2),
            coded_y: refill(pool.coded_y, (mb_w * 4) * (mb_h * 4), false),
            mv_y: refill(pool.mv_y, (mb_w * 4) * (mb_h * 4), (0, 0)),
            inter_y: refill(pool.inter_y, (mb_w * 4) * (mb_h * 4), false),
            ref_idx_y: refill(pool.ref_idx_y, (mb_w * 4) * (mb_h * 4), -1),
            mv1: refill(pool.mv1, (mb_w * 4) * (mb_h * 4), (0, 0)),
            ref_idx1: refill(pool.ref_idx1, (mb_w * 4) * (mb_h * 4), -1),
            refs1: Vec::new(),
            num_ref_active1: 0,
            is_b: false,
            b_possible,
            direct_spatial: true,
            nnz_l_cache: [0x80; 25],
            nnz_c_cache: [[0x80; 9]; 2],
            refs,
            num_ref_active,
            constrained_intra,
            scaling: None,
            scaling8: None,
            transform_8x8_mode,
            transform_bypass: false,
            route_skip_mbs: 0,
            route_coded_mbs: 0,
            slice_bounds: Vec::new(),
            cur_idc2: false,
            mb_t8x8: refill(pool.mb_t8x8, mb_w * mb_h, false),
            bs_frame: refill(pool.bs_frame, mb_w * mb_h, Default::default()),
            bs_rows: 0,
            flt_rows: 0,
            pk_prev: {
                let mut v = pool.pk_prev;
                v.clear();
                v
            },
            pk_cur: {
                let mut v = pool.pk_cur;
                v.clear();
                v
            },
            nnz_dbr: refill(pool.nnz_dbr, (mb_w * 4) * (mb_h * 4), 0),
            bak_y: refill(pool.bak_y, cw, 0),
            bak_u: refill(pool.bak_u, ccw, 0),
            bak_v: refill(pool.bak_v, ccw, 0),
            edc_jobs: Vec::new(),
            edc_active: false,
            edc_tx: None,
            edc_ctx_rx: None,
            edc_back_tx: None,
            edc_parked: None,
            edc_regions: None,
            bsk_last: None,
            edc_batch: Vec::new(),
            bits_per_mb,
            db_ena: false,
            db_oa: 0,
            db_ob: 0,
            mb_kind: refill(
                pool.mb_kind,
                mb_w * mb_h,
                rusty_h264_common::deblock::MB_KIND_UNSET,
            ),
            weights: None,
            row_wait: crate::frame_mt::row_progress_on(),
            col_ok: false,
            col_w4: 0,
            k_no_bskipfast: no_bskipfast(),
            k_no_runmv: no_runmv(),
            k_rowdb: rowdb_on(),
            k_roweager: rowhook_eager(),
            k_kindloads: kind_loads(),
            any_t8: false,
            any_idc2: false,
            skip_zero_next: usize::MAX,
            bzero: refill(pool.bzero, mb_w * mb_h, false),
            sc_cat: pool.sc_cat,
            sc_cbp: pool.sc_cbp,
            sc_cmode: pool.sc_cmode,
            sc_nzc: pool.sc_nzc,
            sc_cbfdc: pool.sc_cbfdc,
            sc_skip: pool.sc_skip,
            sc_ref: pool.sc_ref,
            sc_mvd: pool.sc_mvd,
            sc_ref1: pool.sc_ref1,
            sc_mvd1: pool.sc_mvd1,
            sc_direct: pool.sc_direct,
            bzspan: None,
            pzspan: None,
            iw00: None,
            weights_id0: false,
            weights_l0id: false,
            cur_poc: 0,
            weighted_bipred_idc: 0,
            direct_8x8_inference: false,
            progress: None,
            ref_poc0,
            ref_poc1: {
                let mut v = pool.ref_poc1;
                v.clear();
                v
            },
        }
    }

    fn refresh_ref_pocs(&mut self) {
        self.ref_poc0.clear();
        self.ref_poc0.extend(self.refs.iter().map(|f| f.pic_poc()));
        self.ref_poc1.clear();
        self.ref_poc1.extend(self.refs1.iter().map(|f| f.pic_poc()));
    }

    /// Frame-MT Phase B: attach the shared progress Arc for row watermarks.
    pub fn set_progress_slot(&mut self, slot: crate::Ref) {
        self.progress = Some(slot);
    }

    /// Wait until every L0/L1 ref has enough ready luma rows for MB row `mb_y`
    /// (pad conservatively for MV overshoot).
    #[inline(always)]
    fn wait_refs_for_mb(&self, mb_y: usize) {
        // Cached at construction: in 1T (row-progress off, the default) this
        // is one field test instead of a fn call + OnceLock read per MB.
        if !self.row_wait {
            return;
        }
        let need = crate::RefFrame::rows_needed_for_mb(mb_y, self.ch);
        crate::RefFrame::set_mc_row_need(mb_y, self.ch);
        for r in self.refs.iter().chain(self.refs1.iter()) {
            // Only pay the wait when the ref may still be in-flight (Phase B).
            if r.live.is_some() && r.frozen.get().is_none() {
                r.wait_ready_rows(need);
            }
        }
    }

    fn publish_progress(&mut self) {
        let Some(slot) = &self.progress else {
            return;
        };
        // Under EDC the worker publishes (PixelCtx::publish_progress_rows).
        if self.edc_tx.is_some() {
            return;
        }
        // Cached field, not the knob function: this runs per ROW.
        if !self.k_rowdb || !self.db_ena || self.flt_rows == 0 {
            return;
        }
        publish_filtered_rows_to_slot(
            slot,
            &self.rec_y,
            &self.rec_u,
            &self.rec_v,
            self.cw,
            self.ccw,
            self.ch,
            self.flt_rows,
        );
    }

    /// Sets the explicit weighted-prediction tables for this slice.
    pub fn set_weights(&mut self, weights: WeightTable) {
        self.weights_id0 = weights.ref0_identity();
        self.weights_l0id = weights.list_identity(0);
        self.weights = Some(weights);
    }

    /// Applies explicit uni-prediction weighting to a motion-compensated partition
    /// (luma `pred_y` region + the two chroma planes), if weighting is active.
    /// `list` is the reference list and `refi` the partition's reference index.
    fn weight_partition(
        &self,
        pred_y: &mut [u8; 256],
        c_pred: &mut [[u8; 64]; 2],
        list: usize,
        refi: usize,
        rx: usize,
        ry: usize,
        rw: usize,
        rh: usize,
    ) {
        let Some(wt) = &self.weights else { return };
        // Identity list-0 table (x264 weightp=2 outside fades): the whole pass
        // is an exact per-pixel no-op — skip it. RS_H264_NO_SKIPFP restores it
        // for paired A/B (same knob family as the P_Skip weight skip).
        if list == 0 && self.weights_l0id && !no_skipfp() {
            edcstat::bump(&edcstat::WP_SKIPPED, 1);
            return;
        }
        // REFUTED, reverted: row-slicing these loops measured +28% instructions
        // on `weight_partition` (the extents are runtime values, so the slice
        // bounds cost more than the per-sample checks they replaced). The real
        // win for this function was hoisting the identity test to its CALLERS,
        // which stands.
        // RESOLVE ONCE, APPLY MANY. `apply_luma` re-read `self.luma[list][refi]`
        // — an array index, a Vec deref and an element index, two of them bounds
        // checked — on EVERY sample, up to 256 luma plus 128 chroma per call.
        // The weight is a property of the partition, not of the pixel. (The loop
        // SHAPE is untouched: row-slicing it is refuted above.)
        // MASKED, not row-sliced. `pred_y` is a fixed `[u8; 256]` and `c_pred` a
        // `[[u8; 64]; 2]`, so `& 255` / `& 63` are no-ops that prove the index
        // outright — where SLICING these loops cost +28% (the extents are runtime
        // values, so the slice bounds outweigh the checks). Same lesson as
        // `luma_centre`: the refutation was of one SHAPE, not of the goal.
        let (lw, lo) = wt.luma_wo(list, refi);
        for dy in 0..rh {
            for dx in 0..rw {
                let i = ((ry + dy) * 16 + (rx + dx)) & 255;
                pred_y[i] = wt.apply_luma_wo(pred_y[i], lw, lo);
            }
        }
        let (crx, cry, crw, crh) = (rx / 2, ry / 2, rw / 2, rh / 2);
        for cc in 0..2 {
            let (cw, co) = wt.chroma_wo(list, refi, cc);
            let plane = &mut c_pred[cc & 1];
            for dy in 0..crh {
                for dx in 0..crw {
                    let i = ((cry + dy) * 8 + (crx + dx)) & 63;
                    plane[i] = wt.apply_chroma_wo(plane[i], cw, co);
                }
            }
        }
    }

    /// Sets the High-profile scaling matrices (raster order: six 4×4 lists, two
    /// 8×8 luma lists). The caller un-zig-zags the SPS lists. Flat is the default.
    /// GATE 1 router counters: (skip MBs, residual-coded MBs) this picture.
    pub fn route_counters(&self) -> (u32, u32) {
        (self.route_skip_mbs, self.route_coded_mbs)
    }

    /// SPS `qpprime_y_zero_transform_bypass_flag` — see [`Self::step_qp`].
    pub fn set_transform_bypass(&mut self, on: bool) {
        self.transform_bypass = on;
    }

    pub fn set_scaling(&mut self, scaling: [[i32; 16]; 6], scaling8: [[i32; 64]; 2]) {
        self.scaling = Some(scaling);
        self.scaling8 = Some(scaling8);
    }

    /// Dequantizes a 4×4 AC block with scaling list `list` (flat if none active).
    fn dequant(&self, levels: &[i32; 16], qp: u8, list: usize) -> [i32; 16] {
        match &self.scaling {
            Some(s) => dequantize_weighted(levels, qp, &s[list]),
            None => dequantize(levels, qp),
        }
    }

    /// Single-coefficient twin of `dequant` for position 0 (DC-only fast path).
    fn dequant_dc4(&self, level: i32, qp: u8, list: usize) -> i32 {
        rusty_h264_common::transform::dequantize_dc4(
            level,
            qp,
            self.scaling.as_ref().map(|s| s[list][0]),
        )
    }

    /// Inverse-quantizes the I_16x16 luma DC with scaling list `list`'s DC weight.
    fn dequant_luma_dc(&self, levels: &[i32; 16], qp: u8, list: usize) -> [i32; 16] {
        match &self.scaling {
            Some(s) => inverse_quant_luma_dc_weighted(levels, qp, s[list][0]),
            None => inverse_quant_luma_dc(levels, qp),
        }
    }

    /// Inverse-quantizes a chroma DC block with scaling list `list`'s DC weight.
    fn dequant_chroma_dc(&self, levels: &[i32; 4], qp: u8, list: usize) -> [i32; 4] {
        match &self.scaling {
            Some(s) => inverse_quant_chroma_dc_weighted(levels, qp, s[list][0]),
            None => inverse_quant_chroma_dc(levels, qp),
        }
    }

    /// Sets the B-slice context for the slice about to be decoded: `RefPicList1`,
    /// its active count, and the direct-mode flag.
    #[allow(clippy::too_many_arguments)]
    pub fn set_b_context(
        &mut self,
        refs1: Vec<crate::Ref>,
        num_ref_active1: usize,
        direct_spatial: bool,
        cur_poc: i32,
        weighted_bipred_idc: u8,
        direct_8x8_inference: bool,
    ) {
        self.is_b = true;
        self.refs1 = refs1;
        self.num_ref_active1 = num_ref_active1;
        self.direct_spatial = direct_spatial;
        self.cur_poc = cur_poc;
        self.weighted_bipred_idc = weighted_bipred_idc;
        self.direct_8x8_inference = direct_8x8_inference;
        self.iw00 = None; // slice-scoped cache: lists/POC may have changed
        // Colocated fast-probe cache (see col_zero / col_zero_fast).
        self.col_ok = self.refs1.first().is_some_and(|c| {
            c.live.is_none() && !c.long_term && c.w4 != 0
        });
        self.col_w4 = self.refs1.first().map_or(0, |c| c.w4);
        self.refresh_ref_pocs();
    }

    /// Cached `implicit_weights(0, 0)` — constant within a slice.
    fn iw00(&mut self) -> Option<(i32, i32)> {
        // Read the discriminant ONCE. The `is_none()` + `unwrap()` pair tested it
        // twice and carried an `unwrap_failed` path for a value this very function
        // had just written. `get_or_insert_with` cannot be used here: the closure
        // would need `&mut self` while the `Option` is already borrowed.
        match self.iw00 {
            Some(v) => v,
            None => {
                let v = if self.refs.is_empty() || self.refs1.is_empty() {
                    None
                } else {
                    self.implicit_weights(0, 0)
                };
                self.iw00 = Some(v);
                v
            }
        }
    }

    /// Steps the running luma QP by a `mb_qp_delta` (spec §7.4.5, 8-bit depth):
    /// `QPy = (QPy_prev + delta + 52) % 52`.
    /// Steps QPy by `mb_qp_delta` (spec §7.4.5 modulo). Called exactly for
    /// residual-coded macroblocks (mb_qp_delta presence ⇔ cbp != 0 or I_16x16),
    /// which makes it the one chokepoint for the transform-bypass refusal:
    /// with `qpprime_y_zero_transform_bypass_flag` set and QP'Y == 0 the
    /// residual is LOSSLESS-bypassed (no transform, no quant — and DPCM intra
    /// forms), which this decoder does not implement. Refusing here is loud
    /// and exact: all-PCM lossless streams (no mb_qp_delta) still decode.
    fn step_qp(&mut self, delta: i32) -> Result<(), MbError> {
        // Router counter: step_qp fires exactly once per residual-coded MB.
        self.route_coded_mbs += 1;
        self.cur_qp = (self.cur_qp as i32 + delta + 52).rem_euclid(52) as u8;
        if self.transform_bypass && self.cur_qp == 0 {
            return Err(MbError::Unsupported("transform-bypass (lossless) macroblock"));
        }
        Ok(())
    }

    /// Maps a luma QP to its chroma QP, applying `chroma_qp_index_offset`
    /// (spec §8.5.8): `QPc = qpc_table(Clip3(0, 51, QPy + offset))`.
    fn chroma_qp_for(&self, qp_y: u8) -> u8 {
        let qpi = (qp_y as i32 + self.chroma_qp_offset).clamp(0, 51) as u8;
        chroma_qp(qpi)
    }

    /// Resets per-slice state before decoding a continuation slice of the same
    /// picture: the running QP (each slice carries its own `slice_qp`) and the
    /// reference list (each slice may reorder it).
    pub fn begin_slice(&mut self, slice_qp: u8, refs: Vec<crate::Ref>, num_ref_active: usize) {
        self.cur_qp = slice_qp;
        self.qp = slice_qp;
        self.refs = refs;
        self.num_ref_active = num_ref_active;
        self.weights = None; // re-set per slice if a pred_weight_table is present
        self.weights_id0 = false;
        self.weights_l0id = false;
        self.refresh_ref_pocs();
    }

    /// Whether the neighbor macroblock at `(nbx, nby)` is in the slice currently
    /// being decoded (address ≥ the slice's first MB). For single-slice pictures
    /// `slice_first_mb == 0`, so this is always true and prediction is unchanged.
    #[inline]
    fn nbr_in_slice(&self, nbx: usize, nby: usize) -> bool {
        nby * self.mb_w + nbx >= self.slice_first_mb
    }

    /// Whether the neighbor 4×4 block at `(nbx, nby)` may contribute to intra
    /// prediction. With `constrained_intra_pred`, an inter-coded neighbor is
    /// treated as unavailable (spec §8.3.1.2.{1,2}); otherwise always usable.
    #[inline]
    fn intra_nbr_ok(&self, nbx: usize, nby: usize) -> bool {
        // Fallible read: this is inlined at eleven sites across the intra paths,
        // and `constrained_intra` short-circuits it on nearly every stream, so
        // the check was pure tax on a value that is usually never loaded.
        // `unwrap_or(true)` is the conservative direction — an out-of-range
        // neighbour reads as inter, i.e. UNAVAILABLE, which is what the
        // constrained-intra rule means by a neighbour it cannot use.
        !self.constrained_intra
            || !self.inter_y.get(nby * (self.mb_w * 4) + nbx).copied().unwrap_or(true)
    }

    fn mv_neighbors(&self, mb_x: usize, mb_y: usize) -> [MvNeighbor; 3] {
        let w4 = self.mb_w * 4;
        let get = |avail: bool, bx: isize, by: isize| {
            if avail {
                let idx = by as usize * w4 + bx as usize;
                match (self.mv_y.get(idx), self.ref_idx_y.get(idx)) {
                    (Some(&m), Some(&r)) => MvNeighbor { available: true, mv: m, ref_idx: r },
                    _ => MvNeighbor::NONE,
                }
            } else {
                MvNeighbor::NONE
            }
        };
        let (bx, by) = (mb_x as isize * 4, mb_y as isize * 4);
        let a = get(mb_x > 0 && self.nbr_in_slice(mb_x - 1, mb_y), bx - 1, by);
        let b = get(mb_y > 0 && self.nbr_in_slice(mb_x, mb_y - 1), bx, by - 1);
        let c = if mb_y > 0 && mb_x + 1 < self.mb_w && self.nbr_in_slice(mb_x + 1, mb_y - 1) {
            get(true, bx + 4, by - 1)
        } else {
            get(mb_x > 0 && mb_y > 0 && self.nbr_in_slice(mb_x - 1, mb_y - 1), bx - 1, by - 1)
        };
        [a, b, c]
    }

    fn mv_neighbors_block(&self, pbx: isize, pby: isize, pwb: isize) -> [MvNeighbor; 3] {
        let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Neighbors);
        self.mv_neighbors_block_grid(pbx, pby, pwb, 0)
    }

    fn skip_mv(&self, mb_x: usize, mb_y: usize) -> (i32, i32) {
        let [a, b, c] = self.mv_neighbors(mb_x, mb_y);
        if !a.available
            || !b.available
            || (a.ref_idx == 0 && a.mv == (0, 0))
            || (b.ref_idx == 0 && b.mv == (0, 0))
        {
            (0, 0)
        } else {
            predict_mv(a, b, c, 0)
        }
    }

    fn set_mb_mv(&mut self, mb_x: usize, mb_y: usize, mv: (i32, i32), inter: bool, refi: i32) {
        // ROW FILLS. This wrote all sixteen cells of three grids one indexed
        // store at a time - FORTY-EIGHT separate bounds checks per call - and
        // re-evaluated `if inter` inside the inner loop. Each macroblock row is
        // four CONTIGUOUS cells, so twelve `fill`s cover it.
        let w4 = self.mb_w * 4;
        let r = if inter { refi } else { -1 };
        for dy in 0..4 {
            let a = (mb_y * 4 + dy) * w4 + mb_x * 4;
            self.mv_y[a..a + 4].fill(mv);
            self.inter_y[a..a + 4].fill(inter);
            self.ref_idx_y[a..a + 4].fill(r);
        }
    }

    /// Commit one inter partition's motion into the 4×4 grid (ref 0, 1-ref P).
    /// `(rx,ry,rw,rh)` are MB-relative luma pixels; committing before the next
    /// partition's prediction is what lets a later partition predict from it.
    fn commit_inter_grid(&mut self, mb_x: usize, mb_y: usize, rx: usize, ry: usize, rw: usize, rh: usize, mv: (i32, i32), refi: i8) {
        // Row-range fills instead of the per-4x4 scatter: partitions are
        // rectangles, so each grid row is one contiguous run (same values).
        let w4 = self.mb_w * 4;
        let (bx0, bw) = (mb_x * 4 + rx / 4, rw / 4);
        for by in ry / 4..ry / 4 + rh / 4 {
            let a = (mb_y * 4 + by) * w4 + bx0;
            self.mv_y[a..a + bw].fill(mv);
            self.inter_y[a..a + bw].fill(true);
            self.ref_idx_y[a..a + bw].fill(refi as i32);
            self.coded_y[a..a + bw].fill(true);
        }
    }

    /// Per-slice deblock parameters, needed DURING decode by the row-interleave
    /// path. `ena` is already resolved against `RFF_ABL_DEBLOCK` by the caller.
    pub fn set_deblock_params(&mut self, ena: bool, oa: i32, ob: i32, idc2: bool) {
        // Latch: the FIRST disabling slice turns row filtering off for the rest
        // of the picture (see `row_hook`); rows already filtered stay counted
        // in `flt_rows` and the picture-end tail handles the remainder.
        self.db_ena = ena && (self.flt_rows == 0 || self.db_ena);
        self.db_oa = oa;
        self.db_ob = ob;
        self.cur_idc2 = idc2;
    }

    /// Slice index owning `addr` (slices are raster-contiguous, bounds ascending).
    fn slice_of(&self, addr: usize) -> usize {
        match self.slice_bounds.binary_search_by(|&(f, _)| f.cmp(&addr)) {
            Ok(i) => i,
            Err(i) => i - 1,
        }
    }

    /// Derives bS for macroblock row `r` from the just-decoded (hot) grids into
    /// `bs_frame`, maintaining the two-row rolling record window (R2 of
    /// docs/row-interleave-plan.md).
    fn derive_bs_row(&mut self, r: usize) {
        // bS derivation reads the motion/nnz grids — flush deferred spans.
        self.span_flush();
        // Same stage label the in-filter derivation used, so profiles keep
        // pricing bS derivation wherever it lives.
        let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DebDerive);
        use rusty_h264_common::deblock::{
            derive_mb_kind, derive_mb_records, pack_mb, BlockInfo, MbBs, MbKind,
        };
        let (mb_w, w4) = (self.mb_w, self.mb_w * 4);
        edcstat::bump(&edcstat::DBS_ROWS, 1);
        // Transform-block coded mask for this row: raw nnz, then the 8x8 OR for
        // t8 macroblocks (spec §8.7: the 8x8 transform's coded status is per 8x8).
        //
        // T8 GATE. `nnz_dbr` exists ONLY to carry that OR. With no 8x8
        // macroblock anywhere in the picture it is a byte-for-byte copy of
        // `nnz_y`, so both the 4-row copy and the per-row scan below are pure
        // work: the derivation reads `nnz_y` directly instead. Census
        // (DBSDERIVE) measured t8mb=0 on EVERY cavlc and main stream while
        // nnz_rowcopy ran 10800-16320 sub-rows per decode.
        if self.any_t8 {
            for br in r * 4..r * 4 + 4 {
                let a = br * w4;
                self.nnz_dbr[a..a + w4].copy_from_slice(&self.nnz_y[a..a + w4]);
            }
            edcstat::bump(&edcstat::DBS_NNZ_ROWCOPY, 4);
            // WHOLE-MACROBLOCK ROW SLICES. The 2x2-of-2x2 nest did sixteen
            // bounds-checked reads and sixteen bounds-checked writes per t8
            // macroblock; the same cells are four contiguous runs of four, so
            // four slice reads and four slice writes cover them. The OR is over
            // bytes, so `a | b | c | d > 0` is exactly the old per-cell `> 0`.
            let t8_row_pre = &self.mb_t8x8[r * mb_w..][..mb_w];
            for mb_x in 0..mb_w {
                if !t8_row_pre[mb_x] {
                    continue;
                }
                edcstat::bump(&edcstat::DBS_T8MB, 1);
                let base = r * 4 * w4 + mb_x * 4;
                let mut src = [[0u8; 4]; 4];
                for (k, row) in src.iter_mut().enumerate() {
                    row.copy_from_slice(&self.nnz_y[base + k * w4..][..4]);
                }
                let mut out = [[0u8; 4]; 4];
                for b8 in 0..4usize {
                    let (cx, cy) = ((b8 % 2) * 2, (b8 / 2) * 2);
                    let any = (src[cy][cx] | src[cy][cx + 1] | src[cy + 1][cx] | src[cy + 1][cx + 1])
                        > 0;
                    for sy in 0..2 {
                        for sx in 0..2 {
                            out[cy + sy][cx + sx] = any as u8;
                        }
                    }
                }
                for (k, row) in out.iter().enumerate() {
                    self.nnz_dbr[base + k * w4..][..4].copy_from_slice(row);
                }
            }
        }
        let info = BlockInfo {
            inter: &self.inter_y,
            nnz: if self.any_t8 { &self.nnz_dbr } else { &self.nnz_y },
            mv: &self.mv_y,
            ref_id: &self.ref_idx_y,
            mv1: &self.mv1,
            ref_id1: if self.ref_poc1.is_empty() { &[] } else { &self.ref_idx1 },
            w4,
            t8x8: &self.mb_t8x8,
            bs: &[],
            poc0: &self.ref_poc0,
            poc1: &self.ref_poc1,
            kind: &self.mb_kind,
        };
        let has1 = !info.ref_id1.is_empty();
        std::mem::swap(&mut self.pk_prev, &mut self.pk_cur);
        self.pk_cur.clear();
        let kl = self.k_kindloads;
        // Census gate resolved ONCE per row: `edcstat::on()` is a relaxed atomic
        // load and LLVM will not CSE atomic loads, so a per-MB bump costs a load
        // each. Same rule as hoisting an A/B arm selector out of the loop under
        // test (codec-measurement 15).
        let stats = edcstat::on();
        // ROW SLICES for the three per-macroblock grids. Each was indexed
        // `r * mb_w + mb_x` against a whole-FRAME Vec, which the compiler
        // cannot prove in range; sliced to THIS row, `[mb_x]` is provably
        // `< mb_w`. These are disjoint FIELDS of `self`, so the `&mut` on
        // `bs_frame` coexists with the `&` borrows `info` holds.
        let row0 = r * mb_w;
        let bs_row = &mut self.bs_frame[row0..][..mb_w];
        let t8_row = &self.mb_t8x8[row0..][..mb_w];
        let kind_row: &[u8] = if self.mb_kind.is_empty() {
            &[]
        } else {
            &self.mb_kind[row0..][..mb_w]
        };
        for mb_x in 0..mb_w {
            // Always pack: UNSET / Inter neighbours in this row and the next
            // read left/top MbPack. Kind stores MbBs directly (no i32 hop).
            self.pk_cur.push(pack_mb(&info, has1, mb_x, r));
            let slot = r * mb_w + mb_x;
            if stats {
                edcstat::bump(&edcstat::DBS_MB, 1);
            }
            // KIND ECONOMICS ON THE PACKED PATH: derive_mb_kind(Skip) does 9
            // fresh strided Blk::loads per MB, but pack_mb already ran for this
            // MB (the line above) — the packed `_` arm derives from those
            // records with no further gathers. A B_Skip kind experiment
            // measured kind-arm 1.8% SLOWER (z=-2.69) with +1.07M loads, so
            // Skip/InterUniform route to the packed arm; Intra keeps the kind
            // arm (pure constants, no loads). `RS_H264_KIND_LOADS=1` restores
            // the old routing for paired A/B.
            match kind_row.get(mb_x).copied().and_then(MbKind::from_u8) {
                Some(MbKind::Intra) => {
                    if stats {
                        edcstat::bump(&edcstat::DBS_INTRA, 1);
                    }
                    bs_row[mb_x] = derive_mb_kind(&info, mb_x, r, MbKind::Intra);
                }
                Some(k @ (MbKind::Skip | MbKind::InterUniform)) if kl => {
                    if stats {
                        edcstat::bump(&edcstat::DBS_KINDARM, 1);
                    }
                    bs_row[mb_x] = derive_mb_kind(&info, mb_x, r, k);
                }
                _ => {
                    let Some(cur) = self.pk_cur.get(mb_x) else { continue };
                    let left = if mb_x > 0 { self.pk_cur.get(mb_x - 1) } else { None };
                    let top = if r > 0 { self.pk_prev.get(mb_x) } else { None };
                    let mb_t8 = t8_row[mb_x];
                    let (mut bv, mut bh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]);
                    let flat = derive_mb_records(cur, left, top, mb_t8, &mut bv, &mut bh);
                    if stats {
                        edcstat::bump(&edcstat::DBS_PACKED, 1);
                    }
                    // MEASUREMENT ONLY: sizes the `kind_loads()` match guard that
                    // used to be a OnceLock deref here (now `k_kindloads`).
                    if stats
                        && matches!(
                            self.mb_kind.get(slot).copied().and_then(MbKind::from_u8),
                            Some(MbKind::Skip | MbKind::InterUniform)
                        )
                    {
                        edcstat::bump(&edcstat::DBS_KINDGUARD, 1);
                    }
                    // FLAT-AWARE NARROWING. `derive_mb_records` returns early on a
                    // flat inter macroblock having written ONLY edge 0 of each
                    // orientation; edges 1..4 are still the caller's zero-init, so
                    // widening all 32 entries copies 24 known zeros onto 24 known
                    // zeros - after a `MbBs::default()` that zeroed them a third
                    // time. Census DBSDERIVE flat: 96.8% screen_text, 90.2%
                    // FourPeople, 82.1% akiyo - the dominant class.
                    let m = if flat {
                        if stats {
                            edcstat::bump(&edcstat::DBS_FLAT, 1);
                        }
                        debug_assert!(bv[1..] == [[0i32; 4]; 3] && bh[1..] == [[0i32; 4]; 3]);
                        let mut m = MbBs::default();
                        m.v[0] = std::array::from_fn(|sg| bv[0][sg] as u8);
                        m.h[0] = std::array::from_fn(|sg| bh[0][sg] as u8);
                        m
                    } else {
                        // Written once, not zeroed by `default()` and then written.
                        MbBs {
                            v: std::array::from_fn(|e| std::array::from_fn(|sg| bv[e][sg] as u8)),
                            h: std::array::from_fn(|e| std::array::from_fn(|sg| bh[e][sg] as u8)),
                        }
                    };
                    // MEASUREMENT ONLY: `on()` first, so the 32-byte compare
                    // never runs in a shipped decode (it is not otherwise needed
                    // here — the consumer in filter_frame_rows makes it).
                    if stats && m.v == [[0u8; 4]; 4] && m.h == [[0u8; 4]; 4] {
                        edcstat::bump(&edcstat::DBS_ALLZERO, 1);
                    }
                    bs_row[mb_x] = m;
                }
            }
        }
        // disable_deblocking_filter_idc == 2 (spec §7.4.3): a slice may forbid
        // filtering ITS macroblocks' edges against OTHER slices. bS = 0 on the
        // crossing MB edges kills exactly those filters; interior edges keep
        // their derived strengths. Guarded so single-slice / idc 0-1 pictures
        // pay one branch per row.
        if self.any_idc2 && self.slice_bounds.len() > 1 {
            edcstat::bump(&edcstat::DBS_IDC2ROW, 1);
            for mb_x in 0..mb_w {
                let slot = r * mb_w + mb_x;
                let si = self.slice_of(slot);
                if !self.slice_bounds.get(si).is_some_and(|b| b.1) {
                    continue;
                }
                if mb_x > 0 && self.slice_of(slot - 1) != si {
                    if let Some(b) = self.bs_frame.get_mut(slot) {
                        b.v[0] = [0; 4];
                    }
                }
                if r > 0 && self.slice_of(slot - mb_w) != si {
                    if let Some(b) = self.bs_frame.get_mut(slot) {
                        b.h[0] = [0; 4];
                    }
                }
            }
        }
    }

    /// Decode-loop hook: called at each MB-loop head with the NEXT address to be
    /// decoded; derives AND FILTERS (R3) every fully-decoded row. Filtering a
    /// row here preserves the spec's raster per-MB filter order exactly (every
    /// MB the row's edges touch is already decoded; bottom-adjacent edges
    /// belong to the NEXT row's MBs, which filter later).
    ///
    /// Fast path: mid-row heads (`done <= bs_rows`) do no row work — return
    /// before the profiler scope (this hook is entered once per MB; scoping
    /// every call was measuring the timer, not the filter).
    /// row_hook with the caller's carried row — avoids the per-MB division.
    #[inline(always)]
    fn row_hook_at(&mut self, addr: usize, mby: usize) {
        if self.k_rowdb {
            // ~44/45 of calls are mid-row: one compare, no atomic loads.
            if !self.k_roweager && mby <= self.bs_rows {
                return;
            }
        }
        self.row_hook(addr, mby);
    }

    /// `mby` is the row `addr` sits in. It is a PARAMETER rather than
    /// `addr / self.mb_w` because both callers already carry it: the slice loops
    /// track `(mbx, mby)` with a compare-and-wrap precisely so the per-macroblock
    /// div+mod never runs, and this hook -- entered PER MACROBLOCK on the
    /// non-rowdb arm -- was reconstructing it with an integer divide anyway.
    fn row_hook(&mut self, addr: usize, mby: usize) {
        debug_assert_eq!(mby, addr / self.mb_w, "row_hook: mby must be addr's row");
        // `RS_H264_ROWHOOK_EAGER=1` restores per-MB profiler scoping (A/B oracle).
        // Read from the CACHED fields: `row_hook_at` already gates on
        // `self.k_roweager` / `self.k_rowdb`, and re-reading the knob functions
        // here paid a OnceLock deref plus a relaxed atomic load on every entry -
        // and on the non-rowdb arm this function is entered per MACROBLOCK.
        let eager = self.k_roweager;
        if !self.k_rowdb {
            edcstat::bump(&edcstat::MBS, 1);
            let _rh = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecRowHook);
            self.edc_flush();
            let done = mby;
            if done > self.bs_rows {
                self.bs_rows = done;
                self.publish_progress();
            }
            return;
        }
        let done = mby;
        // ~44/45 of calls are mid-row: no derive/filter/handoff yet.
        if !eager && done <= self.bs_rows {
            return;
        }
        edcstat::bump(&edcstat::MBS, 1);
        let _rh = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecRowHook);
        if done <= self.bs_rows {
            return;
        }
        if self.edc_tx.is_some() {
            // E2: derivation stays here (it reads the syntax grids); filtering
            // is the worker's, fed the row's bs/qp/t8 snapshot. `flt_rows`
            // advances on the worker and comes home with the context.
            self.edc_giveback();
            while self.bs_rows < done {
                let r = self.bs_rows;
                self.derive_bs_row(r);
                self.bs_rows += 1;
                let base = r * self.mb_w;
                // ORDER: this row's pixel jobs must reach the worker BEFORE the
                // filter message for the same row.
                self.edc_flush_batch();
                edcstat::bump(&edcstat::ROWS, 1);
                edcstat::bump(
                    &edcstat::ROWBYTES,
                    (self.mb_w
                        * (std::mem::size_of::<rusty_h264_common::deblock::MbBs>() + 2))
                        as u64,
                );
                let msg = EdcMsg::Row {
                    r,
                    bs: self.bs_frame[base..base + self.mb_w].to_vec(),
                    qp: self.mb_qp[base..base + self.mb_w].to_vec(),
                    t8: self.mb_t8x8[base..base + self.mb_w].to_vec(),
                };
                self.edc_tx.as_ref().unwrap().send(msg).expect("worker alive");
            }
            return;
        }
        self.edc_flush();
        while self.bs_rows < done {
            let r = self.bs_rows;
            self.derive_bs_row(r);
            self.bs_rows += 1;
            // Row filtering requires deblock enabled on EVERY slice so far
            // (`db_ena` latches false once any slice disables it): a mixed
            // picture falls back to the picture-end tail so "latest slice
            // wins" semantics are preserved.
            if self.db_ena {
                self.save_bak(r);
                self.filter_row(r);
                self.flt_rows = r + 1;
            }
            self.publish_progress();
        }
    }

    /// Saves the UNFILTERED bottom pixel rows of MB row `r` before filtering
    /// modifies them: the next row's intra prediction must read pre-deblock
    /// samples (spec §8.3), and filtering touches the bottom three rows while
    /// intra reads exactly the bottom ONE (+ the corner) — so one backup row
    /// per plane suffices, overwritten per row.
    fn save_bak(&mut self, r: usize) {
        let y0 = (r * 16 + 15) * self.cw;
        self.bak_y.copy_from_slice(&self.rec_y[y0..y0 + self.cw]);
        let c0 = (r * 8 + 7) * self.ccw;
        self.bak_u.copy_from_slice(&self.rec_u[c0..c0 + self.ccw]);
        self.bak_v.copy_from_slice(&self.rec_v[c0..c0 + self.ccw]);
    }

    /// Filters one MB row against the stored strengths, using the CURRENT
    /// slice's alpha/beta offsets (single-offset streams — the whole corpus —
    /// are bit-identical to the picture-end call; the plan's risk register
    /// documents the multi-offset divergence).
    fn filter_row(&mut self, r: usize) {
        let info = rusty_h264_common::deblock::BlockInfo {
            inter: &self.inter_y,
            // Same source `derive_bs_row` used (see the T8 GATE there). This
            // path passes a non-empty `bs`, so it takes the PRECOMPUTED arm and
            // never reads `nnz` at all; kept in step so the two cannot diverge.
            nnz: if self.any_t8 { &self.nnz_dbr } else { &self.nnz_y },
            mv: &self.mv_y,
            ref_id: &self.ref_idx_y,
            mv1: &self.mv1,
            ref_id1: &self.ref_idx1,
            w4: self.mb_w * 4,
            t8x8: &self.mb_t8x8,
            bs: &self.bs_frame,
            poc0: &[],
            poc1: &[],
            kind: &self.mb_kind,
        };
        rusty_h264_common::deblock::filter_frame_rows(
            &mut self.rec_y,
            &mut self.rec_u,
            &mut self.rec_v,
            self.mb_w,
            self.mb_h,
            r..r + 1,
            &self.mb_qp,
            self.chroma_qp_offset,
            self.db_oa,
            self.db_ob,
            &info,
        );
    }

    /// Top-neighbour LUMA pixel for intra prediction: reads the unfiltered
    /// backup row when the row above has already been deblock-filtered by the
    /// row-interleave (flt_rows gates it; 0 when the interleave is off, so
    /// this compiles to the plain read on the fallback path).
    #[inline]
    fn top_y_px(&self, py: usize, x: usize) -> u8 {
        // 128 is the spec's value for an unavailable sample (1 << (BitDepth - 1),
        // §8.3.1.2), so the fallback is the one the prediction rules already use
        // — and unreachable anyway, since callers gate on availability first.
        if py % 16 == 0 && self.flt_rows * 16 >= py {
            self.bak_y.get(x).copied().unwrap_or(128)
        } else {
            self.rec_y.get((py - 1) * self.cw + x).copied().unwrap_or(128)
        }
    }

    /// Slice form of [`Self::top_y_px`] for the contiguous 16-wide I16 gather.
    #[inline]
    fn top_y_row(&self, py: usize, x: usize, n: usize) -> &[u8] {
        if py % 16 == 0 && self.flt_rows * 16 >= py {
            &self.bak_y[x..x + n]
        } else {
            &self.rec_y[(py - 1) * self.cw + x..][..n]
        }
    }

    /// Top-neighbour CHROMA pixel (plane `c`: 0 = U, 1 = V).
    #[inline]
    fn top_c_px(&self, c: usize, cy: usize, x: usize) -> u8 {
        // 128 = the spec's unavailable sample, as in `top_y_px`.
        if cy % 8 == 0 && self.flt_rows * 8 >= cy {
            let bak = if c == 0 { &self.bak_u } else { &self.bak_v };
            bak.get(x).copied().unwrap_or(128)
        } else {
            let rec = if c == 0 { &self.rec_u } else { &self.rec_v };
            rec.get((cy - 1) * self.ccw + x).copied().unwrap_or(128)
        }
    }

    /// Slice form of [`Self::top_c_px`] for the 8-wide chroma gather.
    #[inline]
    fn top_c_row(&self, c: usize, cy: usize, x: usize, n: usize) -> &[u8] {
        if cy % 8 == 0 && self.flt_rows * 8 >= cy {
            if c == 0 { &self.bak_u[x..x + n] } else { &self.bak_v[x..x + n] }
        } else {
            let rec = if c == 0 { &self.rec_u } else { &self.rec_v };
            &rec[(cy - 1) * self.ccw + x..][..n]
        }
    }

    /// Snapshots the (deblocked) reconstruction as a reference picture, drawing
    /// its padded-plane allocations from `pool` (recycled
    /// planes of evicted DPB frames — see `Decoder::reclaim_retired`). ~1.9 MB of
    /// fresh allocation per reference picture otherwise (`dpb-clone` stage, 3-4%
    /// of decode, mostly first-touch page faults).
    pub fn as_reference_pooled(&self, pool: &mut Vec<Vec<u8>>) -> crate::RefFrame {
        // MV CAPTURE (`RFF_MV_DUMP=1`) — lets a harness read the motion field any
        // conformant H.264 stream carries, including x264's, using this decoder as
        // the parser. Diagnostic only; inert unless the env var is set.
        if mv_dump_on() {
            MV_DUMP.lock().unwrap().push(MvField {
                mb_w: self.mb_w,
                mb_h: self.mb_h,
                mv: self.mv_y.clone(),
                ref_idx: self.ref_idx_y.clone(),
                inter: self.inter_y.clone(),
            });
        }

        // The per-block motion (mv/ref_idx/ref_poc) is read ONLY by B temporal/spatial
        // direct (`col.mv/ref_idx/ref_poc`, guarded on `w4 != 0` + `idx < len`). On
        // Baseline/Constrained-Baseline streams (no B) it's pure waste — skip the two
        // grid clones + the per-block ref_poc resolve/alloc. `w4 = 0` makes the B
        // readers no-op even on malformed input.
        let (mv, ref_idx, mv1, ref_idx1, ref_poc, w4) = if self.b_possible {
            (
                self.mv_y.clone(),
                self.ref_idx_y.clone(),
                self.mv1.clone(),
                self.ref_idx1.clone(),
                // Resolve each block's List-0 ref index to the referenced picture's
                // POC, so temporal direct can map it into the current list.
                // Via a tiny per-ref LUT: the per-block bounds + Option chain +
                // Ref pointer chase (57k blocks at 720p, once per reference
                // frame) becomes one table index. Identical output: LUT slots
                // past refs.len() hold MIN, exactly what .get() returned.
                {
                    let mut poc_lut = [i32::MIN; 32];
                    for (i, f) in self.refs.iter().take(32).enumerate() {
                poc_lut[i & 31] = f.pic_poc();
                    }
                    self.ref_idx_y
                        .iter()
                        .map(|&r| if (0..32).contains(&r) { poc_lut[r as usize] } else { i32::MIN })
                        .collect()
                },
                self.mb_w * 4,
            )
        } else {
            (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), 0)
        };
        // Pop an exact-size recycled buffer per plane; a miss falls back to a
        // fresh allocation inside `pad_plane_into`.
        let mut take = |len: usize| -> Vec<u8> {
            match pool.iter().position(|v| v.len() == len) {
                Some(i) => pool.swap_remove(i),
                None => Vec::new(),
            }
        };
        let (lpw, lph) = (self.cw + 2 * crate::LPAD, self.ch + 2 * crate::LPAD);
        let (cpw, cph) = (self.ccw + 2 * crate::CPAD, self.ch / 2 + 2 * crate::CPAD);
        crate::RefFrame {
            // Pad once here (ExpandPicture) instead of extracting a clamped tile
            // on every MC call — same copy class as the old plane clone.
            py: rusty_h264_common::inter::pad_plane_into(take(lpw * lph), &self.rec_y, self.cw, self.ch, crate::LPAD),
            pu: rusty_h264_common::inter::pad_plane_into(take(cpw * cph), &self.rec_u, self.ccw, self.ch / 2, crate::CPAD),
            pv: rusty_h264_common::inter::pad_plane_into(take(cpw * cph), &self.rec_v, self.ccw, self.ch / 2, crate::CPAD),
            cw: self.cw,
            ch: self.ch,
            ready_rows: std::sync::atomic::AtomicUsize::new(0),
            live: None,
            frozen: std::sync::OnceLock::new(),
            frame_num: 0, // set by the caller (decode_slice knows frame_num)
            poc: 0,       // set by the caller
            mv,
            ref_idx,
            mv1,
            ref_idx1,
            ref_poc,
            w4,
            long_term: false,
            long_term_idx: 0,
        }
    }

    fn nnz_cache_load(&mut self, mb_x: usize, mb_y: usize) {
        let w4 = self.mb_w * 4;
        let top_unavail = mb_y == 0 || !self.nbr_in_slice(mb_x, mb_y - 1);
        let left_unavail = mb_x == 0 || !self.nbr_in_slice(mb_x - 1, mb_y);
        // The four TOP neighbours are one contiguous run of the nnz grid; only
        // the left column is strided. Hoisting the uniform `top_unavail` test out
        // of the loop turns four checked grid loads into one slice copy.
        if top_unavail {
            self.nnz_l_cache[1..5].fill(0x80);
        } else {
            let src = &self.nnz_y[(mb_y * 4 - 1) * w4 + mb_x * 4..][..4];
            self.nnz_l_cache[1..5].copy_from_slice(src);
        }
        for lby in 0..4 {
            self.nnz_l_cache[(lby + 1) * 5] =
                if left_unavail {
                0x80
            } else {
                self.nnz_y.get((mb_y * 4 + lby) * w4 + (mb_x * 4 - 1)).copied().unwrap_or(0)
            };
        }
    }
    #[inline]
    fn nc_pred(&self, lbx: usize, lby: usize) -> i32 {
        // MASKED, and it pays twice over: this helper and `nnz_cache_set` are
        // inlined into the intra path, the inter path AND both slice loops, so
        // the two unprovable indexes were replicated at every call site. The
        // cache is a 5x5 grid in a `[u8; 25]` and every caller passes a 4x4 block
        // coordinate (`LUMA_4X4_SCAN_XY`, `b8*2 + s`, or a literal), so `& 3` is
        // a no-op that puts the worst case at 4 * 5 + 4 = 24.
        let (lbx, lby) = (lbx & 3, lby & 3);
        let left = self.nnz_l_cache[(lby + 1) * 5 + lbx] as i32;
        let top = self.nnz_l_cache[lby * 5 + (lbx + 1)] as i32;
        let r = left + top;
        if r < 0x80 { (r + 1) >> 1 } else { r & 0x7f }
    }
    #[inline]
    fn nnz_cache_set(&mut self, lbx: usize, lby: usize, total: u8) {
        self.nnz_l_cache[((lby & 3) + 1) * 5 + ((lbx & 3) + 1)] = total;
    }
    fn chroma_cache_load(&mut self, mb_x: usize, mb_y: usize) {
        let w2 = self.mb_w * 2;
        let top_unavail = mb_y == 0 || !self.nbr_in_slice(mb_x, mb_y - 1);
        let left_unavail = mb_x == 0 || !self.nbr_in_slice(mb_x - 1, mb_y);
        for c in 0..2 {
            if top_unavail {
                self.nnz_c_cache[c][1..3].fill(0x80);
            } else {
                let src = &self.nnz_c[c][(mb_y * 2 - 1) * w2 + mb_x * 2..][..2];
                self.nnz_c_cache[c][1..3].copy_from_slice(src);
            }
            for by in 0..2 {
                self.nnz_c_cache[c][(by + 1) * 3] =
                    if left_unavail {
                0x80
            } else {
                self.nnz_c[c & 1].get((mb_y * 2 + by) * w2 + (mb_x * 2 - 1)).copied().unwrap_or(0)
            };
            }
        }
    }
    #[inline]
    fn chroma_nc_pred(&self, c: usize, bx: usize, by: usize) -> i32 {
        // Same shape as `nc_pred`, one size down: a 3x3 grid in `[u8; 9]`, two
        // planes, and every caller passes 0..1 for all three coordinates.
        let (c, bx, by) = (c & 1, bx & 1, by & 1);
        let left = self.nnz_c_cache[c][(by + 1) * 3 + bx] as i32;
        let top = self.nnz_c_cache[c][by * 3 + (bx + 1)] as i32;
        let r = left + top;
        if r < 0x80 { (r + 1) >> 1 } else { r & 0x7f }
    }
    #[inline]
    fn chroma_nnz_cache_set(&mut self, c: usize, bx: usize, by: usize, total: u8) {
        self.nnz_c_cache[c & 1][((by & 1) + 1) * 3 + ((bx & 1) + 1)] = total;
    }

    /// Decodes one slice's macroblocks (raster order) starting at `first_mb`,
    /// until `more_rbsp_data()` is exhausted or the picture is full. Returns the
    /// next macroblock address (= total when the picture is complete). In a
    /// P-slice each macroblock is preceded by `mb_skip_run`.
    /// CABAC slice-data decode (docs/cabac-decode-plan.md), brought up brick by brick
    /// against the instrumented openh264 oracle. Phase 1: verify engine init; the
    /// syntax layer (Phase 2+) is WIP.
    #[allow(clippy::too_many_arguments)]
    pub fn decode_slice_data_cabac(
        &mut self,
        rbsp: &[u8],
        start_byte: usize,
        slice_qp: u8,
        cabac_init_idc: u32,
        is_i: bool,
        is_p: bool,
        first_mb: usize,
    ) -> Result<usize, MbError> {
        // E2: overlap parse (this thread) with pixel reconstruction (a scoped
        // worker owning the planes) for P slices. I slices and B slices keep
        // the inline path (their pixel coupling is per-MB); the ownership
        // ping-pong around intra-in-P macroblocks is `edc_intra_sync`.
        let eligible = edc_on() && rowdb_on() && !is_i && (is_p || self.is_b);
        let threaded = eligible && edc_spawn_worker(self.mb_w, self.mb_h, self.bits_per_mb, true);
        edcstat::bump(&edcstat::DISPATCH_ON, threaded as u64);
        edcstat::bump(&edcstat::DISPATCH_SEEN, eligible as u64);
        if !threaded {
            let r = self.decode_slice_cabac_inner(rbsp, start_byte, slice_qp, cabac_init_idc, is_i, is_p, first_mb);
            self.note_slice_density(rbsp.len().saturating_sub(start_byte), first_mb, &r);
            return r;
        }
        let ctx = self.edc_take_ctx();
        // D7 PROBE: is the CPU overhead PAYLOAD (alloc/copy per job) or
        // SYNCHRONISATION (blocking on a full queue, park/unpark)? The bound
        // separates them: raising it removes send-blocking without changing a
        // single byte copied. `RS_H264_EDC_BOUND` sweeps it.
        let (tx, rx) = std::sync::mpsc::sync_channel::<EdcMsg>(edc_bound());
        let (ctx_tx, ctx_rx) = std::sync::mpsc::channel::<PixelCtx>();
        let (back_tx, back_rx) = std::sync::mpsc::channel::<PixelCtx>();
        let (res, ctx, panicked) = std::thread::scope(|sc| {
            let h = sc.spawn(move || edc_worker(ctx, rx, ctx_tx, back_rx));
            self.edc_tx = Some(tx);
            self.edc_ctx_rx = Some(ctx_rx);
            self.edc_back_tx = Some(back_tx);
            // UNWIND SAFETY (found by the fuzzer as a HANG, not a failure): a
            // panic inside the parse loop would skip the cleanup below — but
            // the sender lives in `self`, which outlives the unwind, so the
            // channel would never close, the worker would never exit, and the
            // scope's join would block forever, converting a diagnosable panic
            // into a silent deadlock under `catch_unwind` harnesses. Catch,
            // clean up, join, restore the planes, THEN resume the panic.
            let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                self.decode_slice_cabac_inner(rbsp, start_byte, slice_qp, cabac_init_idc, is_i, is_p, first_mb)
            }));
            self.edc_flush_batch(); // ORDER: no job may outlive the channel
            self.edc_giveback(); // if an intra macroblock left us holding
            self.edc_tx = None; // closes the channel -> worker drains + returns
            self.edc_ctx_rx = None;
            self.edc_back_tx = None;
            match (r, h.join()) {
                (Ok(res), Ok(ctx)) => (res, Some(ctx), None),
                (Err(p), Ok(ctx)) => (Err(MbError::Truncated), Some(ctx), Some(p)),
                (Ok(_), Err(p)) | (Err(_), Err(p)) => (Err(MbError::Truncated), None, Some(p)),
            }
        });
        if let Some(ctx) = ctx {
            self.edc_restore_ctx(ctx);
        }
        if let Some(p) = panicked {
            std::panic::resume_unwind(p);
        }
        self.note_slice_density(rbsp.len().saturating_sub(start_byte), first_mb, &res);
        res
    }

    /// Feed the D12 dispatch its density signal from a slice just decoded.
    /// Exponentially smoothed so one atypical slice cannot flip the arm, and
    /// only ever read on the NEXT slice — the current one is already committed.
    fn note_slice_density(&mut self, bytes: usize, first_mb: usize, r: &Result<usize, MbError>) {
        let Ok(end) = r else { return };
        let mbs = end.saturating_sub(first_mb);
        if mbs == 0 {
            return;
        }
        let bpm = (bytes * 8) as f64 / mbs as f64;
        self.bits_per_mb = if self.bits_per_mb == 0.0 {
            bpm
        } else {
            0.75 * self.bits_per_mb + 0.25 * bpm
        };
    }

    fn decode_slice_cabac_inner(
        &mut self,
        rbsp: &[u8],
        start_byte: usize,
        slice_qp: u8,
        cabac_init_idc: u32,
        is_i: bool,
        is_p: bool,
        first_mb: usize,
    ) -> Result<usize, MbError> {
        self.edc_active = edc_on();
        let mut cab = crate::cabac::Cabac::new(rbsp, start_byte, slice_qp as i32, cabac_init_idc, is_i);
        let (range, _offset) = cab.dbg_state();
        let trace = std::env::var_os("RH_CABAC_TRACE").is_some();
        debug_assert_eq!(range, 510, "CABAC init range must be 510");

        let mbw = self.mb_w;
        let total = self.mb_w * self.mb_h;
        // Per-MB neighbour state (single-slice assumption: avail == in-bounds).
        // SCOPED: zero-initialised allocations sized by MB count, once per slice.
        // D13: B-only grids (List-1 ref/mvd + direct flags) are ~292 KB at 720p and
        // are ONLY written on the B branch below — allocating them on every P/I
        // slice was the same fresh-page class GridPool fixed for the frame grids.
        // `RS_H264_FAT_SLICE=1` restores the always-alloc path for A/B.
        let _alloc_g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecSliceAlloc);
        // POOLED (was fresh `vec![..]` per slice): refill reuses the pooled
        // allocation with contents identical to a fresh vec, so the body below
        // is untouched. Taken out of `self` here; put back at the normal exit.
        let mut cat = refill(std::mem::take(&mut self.sc_cat), total, 255u8); // 0=I4x4, 2=I16, 255=unavailable
        let mut mb_cbp = refill(std::mem::take(&mut self.sc_cbp), total, 0u8);
        let mut cmode = refill(std::mem::take(&mut self.sc_cmode), total, -1i32); // chroma pred mode
        let mut mb_nzc = refill(std::mem::take(&mut self.sc_nzc), total, [0u8; 24]); // 16 luma raster + 8 chroma
        let mut cbf_dc = refill(std::mem::take(&mut self.sc_cbfdc), total, 0u16);
        let mut mb_skip = refill(std::mem::take(&mut self.sc_skip), total, false);
        let mut mb_ref = refill(std::mem::take(&mut self.sc_ref), total, [-1i8; 16]); // per-4×4-block List-0 ref (-1 = intra)
        let mut mb_mvd = refill(std::mem::take(&mut self.sc_mvd), total, [[0i16; 2]; 16]); // per-block mvd (for mvd ctxInc)
        // D13: B-only grids (~292 KB @720p) only on B slices (or FAT_SLICE A/B).
        let want_b_grids = self.is_b || fat_slice_on();
        let mut mb_ref1 = if want_b_grids {
            refill(std::mem::take(&mut self.sc_ref1), total, [-1i8; 16])
        } else {
            Vec::new()
        };
        let mut mb_mvd1 = if want_b_grids {
            refill(std::mem::take(&mut self.sc_mvd1), total, [[0i16; 2]; 16])
        } else {
            Vec::new()
        };
        let mut mb_direct = if want_b_grids {
            refill(std::mem::take(&mut self.sc_direct), total, false)
        } else {
            Vec::new()
        };
        drop(_alloc_g);
        // Multi-slice availability (spec §6.4.x): a macroblock before this
        // slice's first_mb is NOT available — for pixel-domain prediction
        // (`nbr_in_slice`, like the CAVLC twin sets) AND for every CABAC ctx
        // neighbour below. The per-slice ctx arrays' defaults are not the
        // "unavailable" value (cat 255 reads as available-I16, mb_cbp 0 as
        // all-zero-cbp, mb_t8x8 is a frame grid…), so the `left`/`top`
        // options themselves are gated on slice membership — one gate that
        // every downstream ctxIdxInc read inherits. Confirmed against ffmpeg
        // on an x264 `--slices 4` stream, which desynced without this.
        self.slice_first_mb = first_mb;
        self.slice_bounds.push((first_mb, self.cur_idc2));
        self.any_idc2 |= self.cur_idc2;
        let mut last_delta_qp = 0i32;
        let mut addr = first_mb;

        let _mbloop_g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMbLoop);
        // A new slice's first MBs may read grids a previous slice's deferred
        // spans still owe (P-after-B in one picture included).
        self.span_flush();
        // `mbw` is `pic_width_in_mbs_minus1 + 1` from the SPS. It cannot be 0 in
        // a conformant stream, but it is a runtime value, so this div+rem pair
        // carried a divide-by-zero panic reachable from a MALFORMED header --
        // on the untrusted-input path, at slice entry. `.max(1)` retires both
        // checks and cannot change a conformant decode.
        let mbw_nz = mbw.max(1);
        let (mut mbx, mut mby) = (addr % mbw_nz, addr / mbw_nz);
        // Slice-invariant B properties, formerly re-derived per macroblock.
        if self.is_b {
            self.edc_flush(); // drain anything a preceding P slice queued
        }
        let b_records = self.edc_tx.is_some();
        let b_refs_ok = !self.refs.is_empty() && !self.refs1.is_empty();
        // Loop-invariant: the lowest `addr` whose top neighbour is in this slice.
        let top_lim = first_mb + mbw;
        // Reused across macroblocks: MC overwrites every byte it reads back (all
        // B layouts cover the full macroblock), so the per-MB 384-byte zero-init
        // these used to pay was dead. Byte-identity is the guard.
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        // The loop wraps mbx at entry; bias so the first iteration is exact.
        // BOUND the entropy-coded loop (fuzzer-surfaced): a mutated stream can
        // never produce decode_terminate and the engine zero-fills forever. The
        // bound needs checking ONCE at entry — every in-loop path that advances
        // `addr` already breaks on `addr >= total` before continuing.
        if addr >= total {
            return Err(MbError::Truncated);
        }
        // BIND THE LENGTH FOR THE LOOP. Every grid below is `refill(.., total, ..)`
        // so its length is EXACTLY `total`, and the loop is entered only with
        // `addr < total` (checked above, re-asserted each turn) — but nothing
        // related the two, so every `[addr]` carried a check. Twenty-eight of
        // those became `get_mut` in the previous pass and cost ~2% on CABAC
        // content (crowd_run-main 1.021x, z=+2.11): a branch per write on the
        // decoder's hottest loop. Reborrowing at the literal `total` makes
        // `addr < total` and `addr < len` the SAME fact — no check, no branch.
        // The borrows end with this block, before the grids go back to the pool.
        // `mb_direct`/`mb_ref1`/`mb_mvd1` are deliberately NOT bound here: they
        // are `Vec::new()` on non-B slices, so slicing them to `total` would be
        // the very panic this campaign is removing.
        {
            let cat = &mut cat[..total];
            let mb_cbp = &mut mb_cbp[..total];
            let cmode = &mut cmode[..total];
            let mb_nzc = &mut mb_nzc[..total];
            let cbf_dc = &mut cbf_dc[..total];
            let mb_skip = &mut mb_skip[..total];
            let mb_ref = &mut mb_ref[..total];
            let mb_mvd = &mut mb_mvd[..total];
        loop {
            // A REAL check, not `debug_assert` — which compiles OUT in release,
            // so nothing carried `addr < total` across the loop's back-edge and
            // the reborrows above folded nothing on their own. This cannot fire
            // (every path that advances `addr` already breaks on `addr >= total`,
            // and entry is guarded above), but stating it once per macroblock
            // replaces FIFTEEN per-write branches with one that never taken.
            if addr >= total {
                break;
            }
            // Carried coordinates: one compare-and-wrap replaces the per-MB
            // div+mod pair (and row_hook's own division).
            if mbx == mbw {
                mbx = 0;
                mby += 1;
            }
            self.row_hook_at(addr, mby);
            self.wait_refs_for_mb(mby);
            let left = (mbx > 0 && addr > first_mb).then(|| addr - 1);
            let top = (mby > 0 && addr >= top_lim).then(|| addr - mbw);

            // Brick 3.1/3.2: P-slice mb_skip_flag, then mb_type (P mb_type is neighbour-
            // independent; intra sub-types map to the I dispatch below).
            let mb_type;
            if is_p {
                // Direct bool arithmetic — no Option chain on the hot path.
                let sctx = 11
                    + (left.is_some() && !mb_skip.get(addr - 1).copied().unwrap_or(true)) as usize
                    + (top.is_some()
                        && !mb_skip.get(addr.wrapping_sub(mbw)).copied().unwrap_or(true))
                        as usize;
                if parse_mb_skip_cabac(&mut cab, sctx) {
                    if let Some(p) = mb_skip.get_mut(addr) {
                        *p = true;
                    }
                    last_delta_qp = 0; // skip codes no mb_qp_delta → delta ctxInc resets
                    // P_Skip recon reuses the entropy-free CAVLC primitive verbatim: it
                    // takes no bit-reader (skip has no coded syntax past the flag), just
                    // predicts the skip MV, motion-compensates, and commits the grid.
                    self.decode_p_skip(mbx, mby)?;
                    if let Some(p) = self.mb_qp.get_mut(addr) {
                        *p = self.cur_qp;
                    } // skip inherits QPy
                    let eos = cab.decode_terminate();
                    addr += 1;
                    mbx += 1;
                    if eos || addr >= total {
                        break;
                    }
                    continue;
                }
                let mbt = parse_mb_type_p_cabac(&mut cab);
                // NON-SKIP P MB: the inter arms below predict MVs from the
                // grids (mv_neighbors_block) and the intra arm gathers — flush
                // the deferred P span (B span cannot be pending in a P slice,
                // but span_flush is one Option check each).
                self.span_flush();
                if mbt <= 3 {
                    let _gb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMbP);
                    // noSubMbPartSizeLessThan8x8Flag (spec 7.3.5): P_8x8 permits the
                    // 8x8 transform only when every sub-partition is itself 8x8.
                    let mut allow8 = true;
                    // Inter MB (Bricks 3.3/3.4/3.5). 1-ref stream → ref_idx not coded (ref=0).
                    // Build the 30-entry mvd/ref neighbour cache (openh264 WelsFillCacheInterCabac).
                    let mut mvdc = [[0i16; 2]; 30];
                    let mut refc = [-1i8; 30];
                    // Index the neighbour's RECORD once, then read within it.
                    // `mb_ref[l][bi]` is two bounds checks - one on the Vec, one
                    // on the array - repeated for each of the four entries and
                    // again for `mb_mvd`, i.e. sixteen checks per macroblock for
                    // four neighbours. Binding the record hoists the Vec check
                    // out; the inner index is a literal and folds.
                    if let Some(l) = left {
                        let (Some(lr), Some(lm)) = (mb_ref.get(l), mb_mvd.get(l)) else {
                            return Err(MbError::Truncated);
                        };
                        for (ci, bi) in [(6usize, 3usize), (12, 7), (18, 11), (24, 15)] {
                            refc[ci] = lr[bi];
                            mvdc[ci] = lm[bi];
                        }
                    }
                    if let Some(t) = top {
                        let (Some(tr), Some(tm)) = (mb_ref.get(t), mb_mvd.get(t)) else {
                            return Err(MbError::Truncated);
                        };
                        for (ci, bi) in [(1usize, 12usize), (2, 13), (3, 14), (4, 15)] {
                            refc[ci] = tr[bi];
                            mvdc[ci] = tm[bi];
                        }
                    }
                    if mbx > 0 && mby > 0 {
                        let a = addr - mbw - 1;
                        if let (Some(r), Some(m)) = (mb_ref.get(a), mb_mvd.get(a)) {
                            (refc[0], mvdc[0]) = (r[15], m[15]);
                        }
                    }
                    if mby > 0 && mbx + 1 < mbw {
                        let a = addr - mbw + 1;
                        if let (Some(r), Some(m)) = (mb_ref.get(a), mb_mvd.get(a)) {
                            (refc[5], mvdc[5]) = (r[12], m[12]);
                        }
                    }
                    let mut mmvd = [[0i16; 2]; 16];
                    let mut mref = [0i8; 16];
                    // mb_pred (spec 7.3.5.1): all ref_idx_l0 FIRST (only when >1 active
                    // ref), then all mvd + ref-aware predict + commit. `refidx!` parses one
                    // partition's ref_idx (ctxIdxOffset 54, ctx from neighbour refc) and
                    // seeds refc so a later partition's ref/mvd context sees it — mirror
                    // of the encoder's two-phase emit_mb_cabac_p_inter.
                    macro_rules! refidx {
                        ($pi:expr, $zb:expr) => {{
                            if self.num_ref_active > 1 {
                                let s = CACHE30[$pi & 15].clamp(6, 29);
                                let c0 = (refc[s - 1] > 0) as usize + 2 * (refc[s - 6] > 0) as usize;
                                let r = parse_ref_idx_cabac(&mut cab, c0);
                                for &zb in $zb.iter() {
                                    refc[CACHE30[zb & 15]] = r;
                                }
                                r
                            } else {
                                0i8
                            }
                        }};
                    }
                    macro_rules! part {
                        ($pi:expr, $zb:expr, $pred:expr, $rx:expr, $ry:expr, $rw:expr, $rh:expr, $refi:expr) => {{
                            let (mvx, mvy) = parse_mvd_partition(&mut cab, $pi, $zb, &mut mvdc, &mut refc, &mut mmvd, &mut mref, $refi);
                            let [na, nb, nc] = self.mv_neighbors_block(
                                (mbx * 4 + $rx / 4) as isize,
                                (mby * 4 + $ry / 4) as isize,
                                ($rw / 4) as isize,
                            );
                            let pmv = $pred(na, nb, nc);
                            self.commit_inter_grid(mbx, mby, $rx, $ry, $rw, $rh, (pmv.0 + mvx, pmv.1 + mvy), $refi);
                        }};
                    }
                    match mbt {
                        0 => {
                            // Sibling of CAVLC P_16x16: one (ref, mv) for all 16
                            // blocks → every internal edge is strength 0 (§8.7.2.1).
                            // Without this, CABAC Main/High P_16x16 stayed UNSET and
                            // paid the blind 24-block bS gather.
                            if let Some(k) = self.mb_kind.get_mut(mby * self.mb_w + mbx) {
            *k =
                                rusty_h264_common::deblock::MB_KIND_INTER_UNIFORM;
        }
                            let r0 = refidx!(0, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
                            part!(0, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], |a, b, c| predict_partition_mv(0, 0, a, b, c, r0 as i32), 0, 0, 16, 16, r0);
                        }
                        1 => {
                            let r0 = refidx!(0, &[0, 1, 2, 3, 4, 5, 6, 7]);
                            let r1 = refidx!(8, &[8, 9, 10, 11, 12, 13, 14, 15]);
                            part!(0, &[0, 1, 2, 3, 4, 5, 6, 7], |a, b, c| predict_partition_mv(1, 0, a, b, c, r0 as i32), 0, 0, 16, 8, r0);
                            part!(8, &[8, 9, 10, 11, 12, 13, 14, 15], |a, b, c| predict_partition_mv(1, 1, a, b, c, r1 as i32), 0, 8, 16, 8, r1);
                        }
                        2 => {
                            let r0 = refidx!(0, &[0, 1, 2, 3, 8, 9, 10, 11]);
                            let r1 = refidx!(4, &[4, 5, 6, 7, 12, 13, 14, 15]);
                            part!(0, &[0, 1, 2, 3, 8, 9, 10, 11], |a, b, c| predict_partition_mv(2, 0, a, b, c, r0 as i32), 0, 0, 8, 16, r0);
                            part!(4, &[4, 5, 6, 7, 12, 13, 14, 15], |a, b, c| predict_partition_mv(2, 1, a, b, c, r1 as i32), 8, 0, 8, 16, r1);
                        }
                        _ => {
                            // P_8x8: 4 sub_mb_types, then 4 ref_idx (one per 8×8), then mvd.
                            let mut subt = [0u32; 4];
                            for st in &mut subt {
                                *st = parse_sub_mb_type_p_cabac(&mut cab);
                            }
                            allow8 = subt.iter().all(|&t| t == 0);
                            let mut pr = [0i8; 4];
                            for (i, r) in pr.iter_mut().enumerate() {
                                let b = i * 4;
                                *r = refidx!(b, &[b, b + 1, b + 2, b + 3]);
                            }
                            for i in 0..4usize {
                                let b = i * 4;
                                let (ox, oy) = ((i % 2) * 8, (i / 2) * 8); // 8×8 pixel origin in MB
                                let ri = pr[i];
                                match subt[i] {
                                    0 => part!(b, &[b, b + 1, b + 2, b + 3], |a, b, c| predict_mv(a, b, c, ri as i32), ox, oy, 8, 8, ri),
                                    1 => {
                                        part!(b, &[b, b + 1], |a, b, c| predict_mv(a, b, c, ri as i32), ox, oy, 8, 4, ri);
                                        part!(b + 2, &[b + 2, b + 3], |a, b, c| predict_mv(a, b, c, ri as i32), ox, oy + 4, 8, 4, ri);
                                    }
                                    2 => {
                                        part!(b, &[b, b + 2], |a, b, c| predict_mv(a, b, c, ri as i32), ox, oy, 4, 8, ri);
                                        part!(b + 1, &[b + 1, b + 3], |a, b, c| predict_mv(a, b, c, ri as i32), ox + 4, oy, 4, 8, ri);
                                    }
                                    _ => {
                                        for j in 0..4usize {
                                            let (sx, sy) = ((j % 2) * 4, (j / 2) * 4);
                                            part!(b + j, &[b + j], |a, b, c| predict_mv(a, b, c, ri as i32), ox + sx, oy + sy, 4, 4, ri);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if let Some(p) = mb_ref.get_mut(addr) {
                        *p = mref;
                    }
                    if let Some(p) = mb_mvd.get_mut(addr) {
                        *p = mmvd;
                    }

                    // Inter cbp + residual (is_intra = false → cbf default nA=nB=0).
                    let cbp = parse_cbp_cabac(&mut cab, top.and_then(|a| mb_cbp.get(a).copied()), left.and_then(|a| mb_cbp.get(a).copied()));
                    if let Some(p) = mb_cbp.get_mut(addr) {
                        *p = cbp as u8;
                    }
                    // H-49: an INTER macroblock carries transform_size_8x8_flag AFTER cbp
                    // (spec 7.3.5), present only when CodedBlockPatternLuma > 0 and
                    // noSubMbPartSizeLessThan8x8Flag. Same context as the intra read.
                    let t8 = self.transform_8x8_mode && (cbp & 15) != 0 && allow8 && {
                        let a = left.map_or(0, |x| self.mb_t8x8.get(x).is_some_and(|&f| f) as usize);
                        let b = top.map_or(0, |x| self.mb_t8x8.get(x).is_some_and(|&f| f) as usize);
                        cab.decode_decision(399 + a + b) != 0
                    };
                    if let Some(p) = self.mb_t8x8.get_mut(addr) {
                        *p = t8;
                    }
                    self.any_t8 |= t8;
                    // D9c: cbp==0 never parses residuals — skip the 2.5 KB coeff
                    // zero-init + PInterJob entirely when NORES is on (default).
                    // Current-MB nzc slots stay unset under cbp==0 and export as 0
                    // (same as the 0xff→0 scrub below), so mb_nzc = [0;24] is exact.
                    if cbp == 0 && nores_on() {
                        last_delta_qp = 0;
                        if let Some(p) = self.mb_qp.get_mut(addr) {
                            *p = self.cur_qp;
                        }
                        if let Some(p) = cbf_dc.get_mut(addr) {
                            *p = 0;
                        }
                        if let Some(p) = mb_nzc.get_mut(addr) {
                    *p = [0u8; 24];
                }
                        if self.refs.is_empty() {
                            return Err(MbError::Unsupported("inter without reference"));
                        }
                        let (mut jgmv, mut jgref) = ([(0i32, 0i32); 16], [0u8; 16]);
                        {
                            let w4r = self.mb_w * 4;
                            for by in 0..4usize {
                                // Row-contiguous — see the coded-inter gather.
                                let row = (mby * 4 + by) * w4r + mbx * 4;
                                jgmv[by * 4..by * 4 + 4]
                                    .copy_from_slice(&self.mv_y[row..row + 4]);
                                // Row-slice the ref grid too - it was the only
                                // one still indexed per block.
                                let ridx = &self.ref_idx_y[row..row + 4];
                                for bx in 0..4usize {
                                    jgref[by * 4 + bx] = ridx[bx].clamp(0, 15) as u8;
                                }
                            }
                        }
                        let pj = PInterNoResJob {
                            mbx,
                            mby,
                            t8,
                            gmv: jgmv,
                            gref: jgref,
                        };
                        if self.edc_tx.is_some() {
                            self.edc_giveback();
                            self.edc_commit_nnz(mbx, mby, t8, &[0u8; 24], 0);
                            if edcstat::on() {
                                edcstat::bump(&edcstat::J_INTER, 1);
                                edcstat::bump(&edcstat::J_INTER_NORES, 1);
                            }
                            edcstat::bump(&edcstat::J_NORES_SENT, 1);
                            self.edc_send_job(EdcJob::InterNoRes(Box::new(pj)));
                        } else if self.edc_active {
                            edcstat::bump(&edcstat::J_NORES_SENT, 1);
                            self.edc_jobs.push(EdcJob::InterNoRes(Box::new(pj)));
                        } else {
                            self.recon_p_inter_nores(&pj);
                            if double_recon() {
                                self.recon_p_inter_nores(&pj);
                            }
                        }
                        let eos = cab.decode_terminate();
                        addr += 1;
                    mbx += 1;
                        if eos || addr >= total {
                            break;
                        }
                        continue;
                    }
                    // Zeroed ONLY when the 8x8 transform is in play — this was a
                    // 1KB memset per coded inter MB on non-t8 tiers.
                    let mut luma8: Option<[[i32; 64]; 4]> = None;
                    let (cbp_luma, cbp_chroma) = (cbp & 15, cbp >> 4);
                    let mut nzc = [0xffu8; 48];
                    if let Some(t) = top {
                        let tnz = mb_nzc.get(t).unwrap_or(&ZERO_NZC);
                        nzc[1..5].copy_from_slice(&tnz[12..16]);
                        (nzc[0], nzc[5], nzc[29]) = (0, 0, 0);
                        (nzc[6], nzc[7], nzc[30], nzc[31]) = (tnz[20], tnz[21], tnz[22], tnz[23]);
                    }
                    if let Some(l) = left {
                        let lnz = mb_nzc.get(l).unwrap_or(&ZERO_NZC);
                        (nzc[8], nzc[16], nzc[24], nzc[32]) = (lnz[3], lnz[7], lnz[11], lnz[15]);
                        (nzc[13], nzc[21], nzc[37], nzc[45]) = (lnz[17], lnz[21], lnz[19], lnz[23]);
                    }
                    let mut cbfdc = 0u16;
                    let mut nnzs = [0u8; 24]; // parsed totalCoeff per block (see add_inter_residual)
                    // Materialised ONLY when the parse actually writes them: a
                    // t8 macroblock never touches luma_scan (1 KB), and
                    // cbp_chroma < 2 never touches cac (512 B).
                    let mut luma_scan: Option<[[i32; 16]; 16]> = None; // per z-order 4×4 block
                    let mut cdc = [[0i32; 4]; 2]; // chroma DC per plane (scan order)
                    let mut cac: Option<[[[i32; 16]; 4]; 2]> = None; // chroma AC per plane
                    // A cbp==0 MB codes no mb_qp_delta → the next MB's delta ctxInc sees 0.
                    if cbp == 0 {
                        last_delta_qp = 0;
                    }
                    if cbp != 0 {
                        let ndc = (top.and_then(|a| cbf_dc.get(a).copied()), left.and_then(|a| cbf_dc.get(a).copied()));
                        let qpd = parse_mb_qp_delta_cabac(&mut cab, &mut last_delta_qp);
                        self.step_qp(qpd)?;
                        for id8 in 0..4usize {
                            if cbp_luma & (1 << id8) != 0 {
                                if t8 {
                                    // All four slots carry the 8x8 total: cat 5 has no per-4x4
                                    // counts, and the recon helper now reads one slot
                                    // per 4x4 cell.
                                    let n8 = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, id8 * 4, RP_LUMA_8X8, false, ndc, &mut luma8.get_or_insert_with(|| [[0i32; 64]; 4])[id8]) as u8;
                                    for k in 0..4 {
                                        nnzs[id8 * 4 + k] = n8;
                                    }
                                } else {
                                    let ls = luma_scan.get_or_insert_with(|| [[0i32; 16]; 16]);
                                    for id4 in 0..4usize {
                                        let iz = id8 * 4 + id4;
                                        nnzs[iz] = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, iz, RP_LUMA_4X4, false, ndc, &mut ls[iz]) as u8;
                                    }
                                }
                            } else {
                                for k in 0..4 {
                                    nzc[NZC_CACHE[(id8 * 4 + k).min(23)].min(47)] = 0;
                                }
                            }
                        }
                        if cbp_chroma >= 1 {
                            for i in 0..2usize {
                                parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4, RP_CHROMA_DC + i, false, ndc, &mut cdc[i]);
                            }
                        }
                        if cbp_chroma == 2 {
                            let cacm = cac.get_or_insert_with(|| [[[0i32; 16]; 4]; 2]);
                            for i in 0..2usize {
                                for id4 in 0..4usize {
                                    nnzs[16 + i * 4 + id4] = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4 + id4, RP_CHROMA_AC + i, false, ndc, &mut cacm[i][id4]) as u8;
                                }
                            }
                        }
                    }
                    if let Some(p) = self.mb_qp.get_mut(addr) {
                        *p = self.cur_qp;
                    }
                    if let Some(p) = cbf_dc.get_mut(addr) {
                        *p = cbfdc;
                    }
                    let _sc = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecStateCache);
                    let mut mn = [0u8; 24];
                    for k in 0..4 {
                        mn[k] = nzc[9 + k];
                        mn[4 + k] = nzc[17 + k];
                        mn[8 + k] = nzc[25 + k];
                        mn[12 + k] = nzc[33 + k];
                    }
                    (mn[16], mn[17], mn[20], mn[21]) = (nzc[14], nzc[15], nzc[22], nzc[23]);
                    (mn[18], mn[19], mn[22], mn[23]) = (nzc[38], nzc[39], nzc[46], nzc[47]);
                    // A block whose residual was skipped (cbp bit clear / no chroma AC)
                    // has 0 coeffs, not "unavailable" — export 0 so an intra neighbour's
                    // CBF ctxInc reads 0 (not the 0xff sentinel → is_intra default).
                    for v in mn.iter_mut() {
                        if *v == 0xff {
                            *v = 0;
                        }
                    }
                    if let Some(p) = mb_nzc.get_mut(addr) {
                        *p = mn;
                    }
                    drop(_sc);

                    if self.refs.is_empty() {
                        return Err(MbError::Unsupported("inter without reference"));
                    }
                    // NOTE (measured, do not "optimise" this away): EDC is
                    // DEFAULT ON (`edc_on()`, opt out with RS_H264_EDC=0), so
                    // even single-threaded this job is built and deferred —
                    // that batching is the E1 loop-fission win, not overhead.
                    // A "skip the job in 1T" bypass added here could never fire
                    // and was removed.
                    let (mut jgmv, mut jgref) = ([(0i32, 0i32); 16], [0u8; 16]);
                    {
                        let w4r = self.mb_w * 4;
                        for by in 0..4usize {
                            // Row-contiguous: one slice copy for the MVs
                            // instead of four bounds-checked strided loads.
                            let row = (mby * 4 + by) * w4r + mbx * 4;
                            jgmv[by * 4..by * 4 + 4].copy_from_slice(&self.mv_y[row..row + 4]);
                            // Row-slice the ref grid too - it was the only one
                            // still indexed per block.
                            let ridx = &self.ref_idx_y[row..row + 4];
                            for bx in 0..4usize {
                                jgref[by * 4 + bx] = ridx[bx].clamp(0, 15) as u8;
                            }
                        }
                    }
                    // D9c: when `cbp == 0`, never materialise the 2.5 KB coeff
                    // arrays into a `PInterJob` — ship `InterNoRes` (or call
                    // `recon_p_inter_nores` inline). `RS_H264_NORES=0` keeps the
                    // old full-job path for A/B.
                    let nores = cbp == 0 && nores_on();
                    if nores {
                        let pj = PInterNoResJob {
                            mbx,
                            mby,
                            t8,
                            gmv: jgmv,
                            gref: jgref,
                        };
                        if self.edc_tx.is_some() {
                            self.edc_giveback();
                            self.edc_commit_nnz(mbx, mby, t8, &[0u8; 24], 0);
                            if edcstat::on() {
                                edcstat::bump(&edcstat::J_INTER, 1);
                                edcstat::bump(&edcstat::J_INTER_NORES, 1);
                            }
                            edcstat::bump(&edcstat::J_NORES_SENT, 1);
                            self.edc_send_job(EdcJob::InterNoRes(Box::new(pj)));
                        } else if self.edc_active {
                            edcstat::bump(&edcstat::J_NORES_SENT, 1);
                            self.edc_jobs.push(EdcJob::InterNoRes(Box::new(pj)));
                        } else {
                            self.recon_p_inter_nores(&pj);
                            if double_recon() {
                                self.recon_p_inter_nores(&pj);
                            }
                        }
                        let eos = cab.decode_terminate();
                        addr += 1;
                    mbx += 1;
                        if eos || addr >= total {
                            break;
                        }
                        continue;
                    }
                    let job = PInterJob {
                        mbx,
                        mby,
                        qp: self.cur_qp,
                        cbp_chroma,
                        gmv: jgmv,
                        gref: jgref,
                        luma_scan,
                        luma8,
                        cdc,
                        cac,
                        nnzs,
                    };
                    if self.edc_tx.is_some() {
                        self.edc_giveback();
                        self.edc_commit_nnz(mbx, mby, t8, &nnzs, cbp_chroma);
                        if edcstat::on() {
                            edcstat::bump(&edcstat::J_INTER, 1);
                        }
                        self.edc_send_job(EdcJob::Inter(Box::new(job)));
                    } else if self.edc_active {
                        self.edc_jobs.push(EdcJob::Inter(Box::new(job)));
                    } else {
                        self.recon_p_inter(&job);
                        if double_recon() {
                            self.recon_p_inter(&job);
                        }
                    }

                    let eos = cab.decode_terminate();
                    addr += 1;
                    mbx += 1;
                    if eos || addr >= total {
                        break;
                    }
                    continue;
                }
                mb_type = mbt - 5; // 5→0 (I_4x4), 6..29→1..24 (I_16x16)
            } else if self.is_b {
                // NOTE: the per-macroblock edc_flush() that used to sit here is
                // hoisted to slice entry (see below) — nothing inside a B slice
                // pushes to edc_jobs.
                if b_records {
                    // E3: this B macroblock's MC regions record instead of executing.
                    self.edc_regions = Some(Vec::with_capacity(8));
                }
                let _gb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMbB);
                // noSubMbPartSizeLessThan8x8Flag for B: direct MBs qualify only under
                // direct_8x8_inference_flag; B_8x8 needs every sub-partition 8x8.
                let mut allow8 = true;
                // B-slice: mb_skip_flag (ctx 24 + neighbour-not-skip), then B mb_type.
                let (hl, ht) = (left.is_some(), top.is_some());
                let sctx = 24
                    + (hl && !mb_skip.get(addr - 1).copied().unwrap_or(true)) as usize
                    + (ht && !mb_skip.get(addr.wrapping_sub(mbw)).copied().unwrap_or(true)) as usize;
                if parse_mb_skip_cabac(&mut cab, sctx) {
                    if let (Some(sk), Some(di)) = (mb_skip.get_mut(addr), mb_direct.get_mut(addr)) {
                        (*sk, *di) = (true, true);
                    }
                    last_delta_qp = 0; // skip codes no mb_qp_delta → delta ctxInc resets
                    // B_Skip recon reuses the entropy-free CAVLC primitive (spatial/temporal
                    // direct with no residual), which also commits the motion grid.
                    // Hot prefix inline: forced run continuations skip the call.
                    if !self.b_skip_hot(mbx, mby) {
                        self.decode_b_skip(mbx, mby)?;
                    }
                    if let Some(p) = self.mb_qp.get_mut(addr) {
                        *p = self.cur_qp;
                    }
                    // Skip/direct blocks contribute mvd 0 to a later MB's mvd ctxInc; the
                    // ref stays in-list so |mvd|=0 is summed (same result either way).
                    // mb_ref/mb_ref1 stay at their -1 init: every reader is
                    // either a `> 0` context test (-1 and 0 both false) or the
                    // mvd-sum's `>= 0` gate — and a skip's mvd is (0,0), so
                    // exclusion (-1) and inclusion-of-zero (0) give the same
                    // sum. The 64-byte per-skip zero-fill was pure waste.
                    let eos = cab.decode_terminate();
                    addr += 1;
                    mbx += 1;
                    if eos || addr >= total {
                        break;
                    }
                    continue;
                }
                // NON-SKIP B MB: every arm below reads the grids INLINE
                // (H-48: CABAC never routes through decode_b_mb) — flush
                // the deferred spans. Caught by the tempete ARM-DIFF.
                self.span_flush();
                let bci = (hl && !mb_direct.get(addr - 1).copied().unwrap_or(true)) as usize
                    + (ht && !mb_direct.get(addr.wrapping_sub(mbw)).copied().unwrap_or(true)) as usize;
                let bmt = { let _s = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BTypeParse); parse_mb_type_b_cabac(&mut cab, bci) };
                if bmt < 23 {
                    // ---- B inter: parse motion (mvd L0/L1; ref not coded on this 1-ref
                    // stream) + residual. Recon (b_mc/direct) deferred to B.3. ----
                    let mut mvdc0 = [[0i16; 2]; 30];
                    let mut refc0 = [-1i8; 30];
                    let mut mvdc1 = [[0i16; 2]; 30];
                    let mut refc1 = [-1i8; 30];
                    // WelsFillCacheInterCabac, per list (L0 = mb_ref/mb_mvd, L1 = mb_ref1/mb_mvd1).
                    // The corner addresses and their guards are macroblock
                    // properties, resolved ONCE here rather than rebuilt inside
                    // each list expansion; each neighbour grid row is borrowed
                    // once instead of re-indexed per entry.
                    let tl = (mbx > 0 && mby > 0).then(|| addr - mbw - 1);
                    let tr = (mby > 0 && mbx + 1 < mbw).then(|| addr - mbw + 1);
                    macro_rules! fill {
                        ($mrf:expr, $mmv:expr, $rc:expr, $mc:expr) => {{
                            // `.get` PER PARALLEL GRID. The ref and mvd grids are
                            // separate Vecs indexed by the same macroblock address,
                            // so `$mrf[l]` proved nothing about `$mmv[l]` and each
                            // of the four neighbour slots carried two panic paths —
                            // doubled again because this macro expands once per
                            // list. A `None` here degrades to exactly what the
                            // cache already means by "neighbour unavailable" (the
                            // `-1` ref it is initialised to), so the fallible form
                            // is the honest one as well as the cheap one.
                            if let Some(l) = left {
                                if let (Some(rr), Some(mm)) = ($mrf.get(l), $mmv.get(l)) {
                                    for (ci, bi) in [(6usize, 3usize), (12, 7), (18, 11), (24, 15)] {
                                        $rc[ci] = rr[bi];
                                        $mc[ci] = mm[bi];
                                    }
                                }
                            }
                            if let Some(t) = top {
                                if let (Some(rr), Some(mm)) = ($mrf.get(t), $mmv.get(t)) {
                                    for (ci, bi) in [(1usize, 12usize), (2, 13), (3, 14), (4, 15)] {
                                        $rc[ci] = rr[bi];
                                        $mc[ci] = mm[bi];
                                    }
                                }
                            }
                            if let Some(a) = tl {
                                if let (Some(rr), Some(mm)) = ($mrf.get(a), $mmv.get(a)) {
                                    ($rc[0], $mc[0]) = (rr[15], mm[15]);
                                }
                            }
                            if let Some(a) = tr {
                                if let (Some(rr), Some(mm)) = ($mrf.get(a), $mmv.get(a)) {
                                    ($rc[5], $mc[5]) = (rr[12], mm[12]);
                                }
                            }
                        }};
                    }
                    {
                        let _s = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BFillCache);
                        fill!(mb_ref, mb_mvd, refc0, mvdc0);
                        fill!(mb_ref1, mb_mvd1, refc1, mvdc1);
                    }
                    let mut _smv = Some(rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BMvdParse));
                    let mut mmvd0 = [[0i16; 2]; 16];
                    let mut mref0 = [-1i8; 16];
                    let mut mmvd1 = [[0i16; 2]; 16];
                    let mut mref1 = [-1i8; 16];
                    if !b_refs_ok {
                        return Err(MbError::Unsupported("B without references"));
                    }
                    // Recon (mirrors CAVLC decode_b_mb / decode_b_8x8): predict each list's
                    // MV off the committed grid + the CABAC-parsed mvd, commit, MC (bi-pred
                    // blend), then add the residual. Prediction reads mmvd0/mmvd1 (the mvd
                    // per raster block, splatted during the parse above).
                    // pred_y / c_pred are slice-scope scratch (see the loop head).
                    // Recording is a per-macroblock property — ask once, not per
                    // partition, so the 1T path calls b_mc straight through.
                    let rec_mode = self.edc_regions.is_some();

                    if bmt == 0 {
                        // B_Direct_16x16: no coded motion. A direct block contributes mvd 0
                        // to a later MB's mvd ctxInc with its ref in-list (|0| summed).
                        if let Some(p) = mb_direct.get_mut(addr) {
                            *p = true;
                        }
                        allow8 = self.direct_8x8_inference;
                        (mref0, mref1) = ([0i8; 16], [0i8; 16]);
                        // FORCED derivation via the zero-bi bitmap (same triple
                        // as b_skip_hot): a direct-16 whose left/top/topright are
                        // recorded ref0/(0,0) committers derives (0,0)/(0,0) bi —
                        // skip the gather + derivation, run the region half
                        // directly. Its own commit is zero-bi too, so it EXTENDS
                        // forcing chains through coded direct MBs.
                        // `mbw` is already carried by the loop, and the row-above
                        // address is one subtraction, not three.
                        let up = addr.wrapping_sub(mbw);
                        let forced = !b_records
                            && mbx > 0
                            && mby > 0
                            && mbx + 1 < mbw
                            && up >= self.slice_first_mb
                            && match self.bzero.get(..=addr) {
                                // A slice ENDING at `addr` proves all three
                                // neighbour reads at once — the guards above put
                                // every one of them below `addr`. Same shape as
                                // `b_skip_hot`.
                                Some(bz) => {
                                    bz.get(addr - 1).copied().unwrap_or(false)
                                        && bz.get(up).copied().unwrap_or(false)
                                        && bz.get(up + 1).copied().unwrap_or(false)
                                }
                                None => false,
                            };
                        if forced {
                            self.b_direct_region(mbx, mby, 0, 0, 16, 16, &mut pred_y, &mut c_pred, (0, 0, (0, 0), (0, 0), false));
                            if let Some(b) = self.bzero.get_mut(addr) {
            *b = true;
        }
                        } else {
                            self.decode_b_direct(mbx, mby, 0, 0, 16, 16, &mut pred_y, &mut c_pred);
                        }
                    } else if bmt == 22 {
                        // B_8x8: 4 sub_mb_types, (ref not coded on 1-ref), then mvd
                        // list-major → sub-MB → sub-partition (openh264 order).
                        let mut subt = [0u32; 4];
                        for s in &mut subt {
                            *s = parse_sub_mb_type_b_cabac(&mut cab);
                        }
                        let d8i = self.direct_8x8_inference;
                        allow8 = subt.iter().all(|&t| if t == 0 { d8i } else { (1..=3).contains(&t) });
                        // uses(list) depends only on the sub_mb_type — resolve the
                        // whole 4x2 table once here; the ref_idx, mvd and recon
                        // loops below all read it instead of re-asking.
                        let su = [
                            [b_sub_uses(subt[0], 0), b_sub_uses(subt[0], 1)],
                            [b_sub_uses(subt[1], 0), b_sub_uses(subt[1], 1)],
                            [b_sub_uses(subt[2], 0), b_sub_uses(subt[2], 1)],
                            [b_sub_uses(subt[3], 0), b_sub_uses(subt[3], 1)],
                        ];
                        // A direct sub-partition contributes mvd 0 / ref in-list to the
                        // ctxInc — both the per-MB export and the within-MB 30-cache that a
                        // later (non-direct) sub in this MB reads.
                        for i in 0..4usize {
                            if subt[i] == 0 {
                                let b = i * 4;
                                for zb in b..b + 4 {
                                    // each table read once, not twice
                                    let (g, c) = (G_SCAN4[zb & 15], CACHE30[zb & 15]);
                                    (mref0[g], mref1[g]) = (0, 0);
                                    (refc0[c], refc1[c]) = (0, 0);
                                }
                            }
                        }
                        // ref_idx_l0 for all four 8x8s, then ref_idx_l1, then the mvds
                        // (spec 7.3.5.2 sub_mb_pred). ONE ref per 8x8 -- never per
                        // sub-partition -- and B_Direct_8x8 codes none.
                        let mut sref = [[0i8; 2]; 4]; // [sub-MB][list]
                        for list in 0..2usize {
                            // Single-reference lists code no ref_idx at all.
                            if (if list == 0 { self.num_ref_active } else { self.num_ref_active1 }) <= 1 {
                                continue;
                            }
                            let rc = if list == 0 { &mut refc0 } else { &mut refc1 };
                            for i in 0..4usize {
                                let st = subt[i];
                                if st == 0 || !su[i][list] {
                                    continue;
                                }
                                let b = i * 4;
                                let s = CACHE30[b & 15].clamp(6, 29);
                                let c0 = (rc[s - 1] > 0) as usize + 2 * (rc[s - 6] > 0) as usize;
                                let r = parse_ref_idx_cabac(&mut cab, c0);
                                for &zb in &[b, b + 1, b + 2, b + 3] {
                                    rc[CACHE30[zb]] = r;
                                }
                                sref[i][list] = r;
                            }
                        }
                        for list in 0..2usize {
                            let (mmv, mrf, mc, rc) = if list == 0 {
                                (&mut mmvd0, &mut mref0, &mut mvdc0, &mut refc0)
                            } else {
                                (&mut mmvd1, &mut mref1, &mut mvdc1, &mut refc1)
                            };
                            for i in 0..4usize {
                                let st = subt[i];
                                if st == 0 || !su[i][list] {
                                    continue;
                                }
                                let b = i * 4;
                                for &(sx, sy, sw, sh) in b_sub_parts(st) {
                                    // Shapes are 8x8 / 8x4 / 4x8 / 4x4, so the block
                                    // list is closed-form: `step` is 1 when the part
                                    // spans both columns, 2 when it spans both rows.
                                    let (w4b, h4b) = (sw / 4, sh / 4);
                                    let base = b + (sy / 4) * 2 + sx / 4;
                                    let step = if w4b == 2 { 1 } else { 2 };
                                    let zb = [base, base + step, base + 2, base + 3];
                                    let n = w4b * h4b;
                                    parse_mvd_partition(&mut cab, zb[0], &zb[..n], mc, rc, mmv, mrf, sref[i][list]);
                                }
                            }
                        }
                        // Recon each 8×8: direct sub → decode_b_direct; else per sub-part
                        // predict (median) + commit + MC.
                        // Spatial-direct A/B/C are MB-level — walk once if any sub is
                        // direct. `dmemo=0` rewalks every direct 8×8 (A/B oracle).
                        // Derivation hoist: A/B/C AND the rid/median result are
                        // MB-level — derive once, run only the per-8x8 region half
                        // (czg differs per sub) for every direct sub.
                        let hoisted = if self.direct_spatial
                            && direct_memo_on()
                            && subt.iter().any(|&t| t == 0)
                        {
                            let (n0, n1) = self.b_direct_nbrs(mbx, mby);
                            Some(Self::b_direct_refs_mvs(&n0, &n1))
                        } else {
                            None
                        };
                        for (p, &st) in subt.iter().enumerate() {
                            let (b8x, b8y) = ((p % 2) * 8, (p / 2) * 8);
                            if st == 0 {
                                match hoisted {
                                    Some(derived) => self.b_direct_region(
                                        mbx, mby, b8x, b8y, 8, 8, &mut pred_y, &mut c_pred, derived,
                                    ),
                                    None => self.decode_b_direct(
                                        mbx, mby, b8x, b8y, 8, 8, &mut pred_y, &mut c_pred,
                                    ),
                                }
                                continue;
                            }
                            // From the table built at the top of this arm.
                            let (u0, u1) = (su[p & 3][0], su[p & 3][1]);
                            for &(sx, sy, sw, sh) in b_sub_parts(st) {
                                let (px, py) = (b8x + sx, b8y + sy);
                                let mut mv = [(0i32, 0i32); 2];
                                let (bx4, by4) = ((mbx * 4 + px / 4) as isize, (mby * 4 + py / 4) as isize);
                                let didx = (py / 4) * 4 + px / 4;
                                // A BI sub-part gathers both lists at ONE position, so the
                                // availability work (bounds + coded + slice) is shared —
                                // the fusion the 16x16 layout path already had.
                                if u0 && u1 {
                                    let (n0, n1) = self.mv_neighbors_both(bx4, by4, (sw / 4) as isize);
                                    for (list, nb) in [(0usize, &n0), (1, &n1)] {
                                        let d = (if list == 0 { &mmvd0 } else { &mmvd1 })[didx & 15];
                                        let pmv = predict_mv(nb[0], nb[1], nb[2], sref[p & 3][list & 1] as i32);
                                        mv[list & 1] = (pmv.0 + d[0] as i32, pmv.1 + d[1] as i32);
                                    }
                                } else {
                                    for list in 0..2usize {
                                        if if list == 0 { u0 } else { u1 } {
                                            let d = (if list == 0 { &mmvd0 } else { &mmvd1 })[didx & 15];
                                            let nb = self.mv_neighbors_list(bx4, by4, (sw / 4) as isize, list);
                                            let pmv = predict_mv(nb[0], nb[1], nb[2], sref[p & 3][list & 1] as i32);
                                            mv[list & 1] = (pmv.0 + d[0] as i32, pmv.1 + d[1] as i32);
                                        }
                                    }
                                }
                                let refi0 = if u0 { sref[p & 3][0] as i32 } else { -1 };
                                let refi1 = if u1 { sref[p & 3][1] as i32 } else { -1 };
                                self.b_set_motion(mbx, mby, px, py, sw, sh, refi0, mv[0], refi1, mv[1]);
                                if rec_mode {
                                    self.b_mc_or_record(mbx, mby, px, py, sw, sh, refi0, mv[0], refi1, mv[1], &mut pred_y, &mut c_pred);
                                } else {
                                    self.b_mc(mbx, mby, px, py, sw, sh, refi0, mv[0], refi1, mv[1], &mut pred_y, &mut c_pred);
                                }
                            }
                        }
                    } else {
                        let (layout, mvmode, preds) = b_inter_layout(bmt);
                        let parts: &[(usize, &[usize])] = match mvmode {
                            0 => &[(0, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])],
                            1 => &[(0, &[0, 1, 2, 3, 4, 5, 6, 7]), (8, &[8, 9, 10, 11, 12, 13, 14, 15])],
                            _ => &[(0, &[0, 1, 2, 3, 8, 9, 10, 11]), (4, &[4, 5, 6, 7, 12, 13, 14, 15])],
                        };
                        // ref_idx_l0 for EVERY partition, then ref_idx_l1, then the mvds
                        // (spec 7.3.5.1 macroblock_prediction). This was missing entirely
                        // -- the B path assumed a single reference -- so any B slice with
                        // more than one active reference in either list desynced the
                        // arithmetic decoder at the first partition that codes a ref_idx,
                        // and the slice ended early at a phantom end_of_slice_flag.
                        let mut pref = [[0i8; 2]; 2]; // [partition][list]
                        for list in 0..2usize {
                            let active = if list == 0 { self.num_ref_active } else { self.num_ref_active1 };
                            if active <= 1 {
                                continue;
                            }
                            let rc = if list == 0 { &mut refc0 } else { &mut refc1 };
                            for (p, &(pidx, zb)) in parts.iter().enumerate() {
                                if !preds[p & 1].uses(list) {
                                    continue;
                                }
                                let s = CACHE30[pidx & 15].clamp(6, 29);
                                let c0 = (rc[s - 1] > 0) as usize + 2 * (rc[s - 6] > 0) as usize;
                                let r = parse_ref_idx_cabac(&mut cab, c0);
                                // Seed the cache so a later partition's ref/mvd ctxInc sees it.
                                for &zbi in zb.iter() {
                                    rc[CACHE30[zbi & 15]] = r;
                                }
                                pref[p & 1][list & 1] = r;
                            }
                        }
                        // mvd parse order: list-major, partition-minor (openh264
                        // ParseInterBMotionInfoCabac); the ctxInc reads the same-list cache.
                        for list in 0..2usize {
                            let (mmv, mrf, mc, rc) = if list == 0 {
                                (&mut mmvd0, &mut mref0, &mut mvdc0, &mut refc0)
                            } else {
                                (&mut mmvd1, &mut mref1, &mut mvdc1, &mut refc1)
                            };
                            for (p, &(pidx, zb)) in parts.iter().enumerate() {
                                if preds[p & 1].uses(list) {
                                    parse_mvd_partition(&mut cab, pidx, zb, mc, rc, mmv, mrf, pref[p & 1][list & 1]);
                                }
                            }
                        }
                        // Per-partition recon: predict each list's MV, commit, MC.
                        let (mbb_x, mbb_y) = (mbx * 4, mby * 4);
                        for (p, &(rx, ry, rw, rh)) in layout.iter().enumerate() {
                            let mut mv = [(0i32, 0i32); 2];
                            // uses(list) is a property of the layout — resolve both
                            // once instead of five times per partition, and build
                            // the neighbour coordinates once instead of per list.
                            let (u0, u1) = (preds[p & 1].uses(0), preds[p & 1].uses(1));
                            let (nx, ny) = ((mbb_x + rx / 4) as isize, (mbb_y + ry / 4) as isize);
                            let (nw, didx) = ((rw / 4) as isize, (ry / 4) * 4 + rx / 4);
                            // Bi partitions gather both lists at ONE position —
                            // fuse the availability work (same trick as
                            // b_direct_nbrs); uni partitions keep the single
                            // gather.
                            if u0 && u1 {
                                let (n0, n1) = self.mv_neighbors_both(nx, ny, nw);
                                for (list, n) in [(0usize, &n0), (1, &n1)] {
                                    let d = (if list == 0 { &mmvd0 } else { &mmvd1 })[didx & 15];
                                    let pmv = predict_partition_mv(mvmode, p, n[0], n[1], n[2], pref[p & 1][list & 1] as i32);
                                    mv[list & 1] = (pmv.0 + d[0] as i32, pmv.1 + d[1] as i32);
                                }
                            } else {
                                for list in 0..2usize {
                                    if if list == 0 { u0 } else { u1 } {
                                        let d = (if list == 0 { &mmvd0 } else { &mmvd1 })[didx & 15];
                                        let n = self.mv_neighbors_list(nx, ny, nw, list);
                                        let pmv = predict_partition_mv(mvmode, p, n[0], n[1], n[2], pref[p & 1][list & 1] as i32);
                                        mv[list & 1] = (pmv.0 + d[0] as i32, pmv.1 + d[1] as i32);
                                    }
                                }
                            }
                            let refi0 = if u0 { pref[p & 1][0] as i32 } else { -1 };
                            let refi1 = if u1 { pref[p & 1][1] as i32 } else { -1 };
                            self.b_set_motion(mbx, mby, rx, ry, rw, rh, refi0, mv[0], refi1, mv[1]);
                            // Proper spec bi-prediction (average of L0+L1). NOTE: the CAVLC
                            // decode_b_mb replicates an openh264 bug here for a Bi 16×8/8×16
                            // partition; our pixel gate is ffmpeg (spec-correct), so we do NOT.
                            if rec_mode {
                                self.b_mc_or_record(mbx, mby, rx, ry, rw, rh, refi0, mv[0], refi1, mv[1], &mut pred_y, &mut c_pred);
                            } else {
                                self.b_mc(mbx, mby, rx, ry, rw, rh, refi0, mv[0], refi1, mv[1], &mut pred_y, &mut c_pred);
                            }
                        }
                    }
                    // Paired stores: one index expression per grid pair.
                    // Four per-macroblock grids at one address; each is its own
                    // Vec, so each assignment carried its own check.
                    if let (Some(r0), Some(d0)) = (mb_ref.get_mut(addr), mb_mvd.get_mut(addr)) {
                        (*r0, *d0) = (mref0, mmvd0);
                    }
                    if let (Some(r1), Some(d1)) = (mb_ref1.get_mut(addr), mb_mvd1.get_mut(addr)) {
                        (*r1, *d1) = (mref1, mmvd1);
                    }
                    _smv = None; // close b:mvd-parse; the residual half follows
                    let _sres = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BResid);

                    // Inter cbp + residual (identical to the P path).
                    let cbp = parse_cbp_cabac(&mut cab, top.and_then(|a| mb_cbp.get(a).copied()), left.and_then(|a| mb_cbp.get(a).copied()));
                    if let Some(p) = mb_cbp.get_mut(addr) {
                        *p = cbp as u8;
                    }
                    // H-49: an INTER macroblock carries transform_size_8x8_flag AFTER cbp
                    // (spec 7.3.5), present only when CodedBlockPatternLuma > 0 and
                    // noSubMbPartSizeLessThan8x8Flag. Same context as the intra read.
                    let t8 = self.transform_8x8_mode && (cbp & 15) != 0 && allow8 && {
                        let a = left.map_or(0, |x| self.mb_t8x8.get(x).is_some_and(|&f| f) as usize);
                        let b = top.map_or(0, |x| self.mb_t8x8.get(x).is_some_and(|&f| f) as usize);
                        cab.decode_decision(399 + a + b) != 0
                    };
                    if let Some(p) = self.mb_t8x8.get_mut(addr) {
                        *p = t8;
                    }
                    self.any_t8 |= t8;
                    // D9c-B: coded B with cbp==0 never parses residuals — skip the
                    // ~2.5 KB coeff zero-init + fat BJob when NORES is on (default).
                    // MC already filled pred_y / edc_regions; recon == pred (same as
                    // B_Skip / P InterNoRes). t8 is always false here ((cbp&15)==0).
                    if cbp == 0 && nores_on() {
                        last_delta_qp = 0;
                        if let Some(p) = self.mb_qp.get_mut(addr) {
                            *p = self.cur_qp;
                        }
                        if let Some(p) = cbf_dc.get_mut(addr) {
                            *p = 0;
                        }
                        if let Some(p) = mb_nzc.get_mut(addr) {
                    *p = [0u8; 24];
                }
                        if let Some(regions) = self.edc_regions.take() {
                            self.edc_giveback();
                            self.edc_commit_nnz(mbx, mby, false, &[0u8; 24], 0);
                            edcstat::bump(&edcstat::J_NORES_SENT, 1);
                            self.edc_send_job(EdcJob::BSkip { mbx, mby, regions });
                        } else {
                            // Inline twin of decode_b_skip's plane copy (MC already done).
                            for dy in 0..16 {
                                let d = (mby * 16 + dy) * self.cw + mbx * 16;
                                self.rec_y[d..d + 16]
                                    .copy_from_slice(&pred_y[dy * 16..dy * 16 + 16]);
                            }
                            for c in 0..2 {
                                let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                                for dy in 0..8 {
                                    let d = (mby * 8 + dy) * self.ccw + mbx * 8;
                                    plane[d..d + 8]
                                        .copy_from_slice(&c_pred[c][dy * 8..dy * 8 + 8]);
                                }
                            }
                            let w4 = self.mb_w * 4;
                            for dy in 0..4 {
                                self.nnz_y[(mby * 4 + dy) * w4 + mbx * 4..][..4].fill(0);
                            }
                        }
                        let eos = cab.decode_terminate();
                        addr += 1;
                    mbx += 1;
                        if eos || addr >= total {
                            break;
                        }
                        continue;
                    }
                    // Zeroed ONLY when the 8x8 transform is in play — this was a
                    // 1KB memset per coded inter MB on non-t8 tiers.
                    let mut luma8: Option<[[i32; 64]; 4]> = None;
                    let (cbp_luma, cbp_chroma) = (cbp & 15, cbp >> 4);
                    let mut nzc = [0xffu8; 48];
                    if let Some(t) = top {
                        let tnz = mb_nzc.get(t).unwrap_or(&ZERO_NZC);
                        nzc[1..5].copy_from_slice(&tnz[12..16]);
                        (nzc[0], nzc[5], nzc[29]) = (0, 0, 0);
                        (nzc[6], nzc[7], nzc[30], nzc[31]) = (tnz[20], tnz[21], tnz[22], tnz[23]);
                    }
                    if let Some(l) = left {
                        let lnz = mb_nzc.get(l).unwrap_or(&ZERO_NZC);
                        (nzc[8], nzc[16], nzc[24], nzc[32]) = (lnz[3], lnz[7], lnz[11], lnz[15]);
                        (nzc[13], nzc[21], nzc[37], nzc[45]) = (lnz[17], lnz[21], lnz[19], lnz[23]);
                    }
                    let mut cbfdc = 0u16;
                    let mut nnzs = [0u8; 24]; // parsed totalCoeff per block
                    // See the P arm: materialised only when actually written.
                    let mut luma_scan: Option<[[i32; 16]; 16]> = None;
                    let mut cdc = [[0i32; 4]; 2];
                    let mut cac: Option<[[[i32; 16]; 4]; 2]> = None;
                    if cbp == 0 {
                        last_delta_qp = 0;
                    }
                    if cbp != 0 {
                        let ndc = (top.and_then(|a| cbf_dc.get(a).copied()), left.and_then(|a| cbf_dc.get(a).copied()));
                        let qpd = parse_mb_qp_delta_cabac(&mut cab, &mut last_delta_qp);
                        self.step_qp(qpd)?;
                        for id8 in 0..4usize {
                            if cbp_luma & (1 << id8) != 0 {
                                if t8 {
                                    // All four slots carry the 8x8 total: cat 5 has no per-4x4
                                    // counts, and the recon helper now reads one slot
                                    // per 4x4 cell.
                                    let n8 = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, id8 * 4, RP_LUMA_8X8, false, ndc, &mut luma8.get_or_insert_with(|| [[0i32; 64]; 4])[id8]) as u8;
                                    for k in 0..4 {
                                        nnzs[id8 * 4 + k] = n8;
                                    }
                                } else {
                                    let ls = luma_scan.get_or_insert_with(|| [[0i32; 16]; 16]);
                                    for id4 in 0..4usize {
                                        let iz = id8 * 4 + id4;
                                        nnzs[iz] = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, iz, RP_LUMA_4X4, false, ndc, &mut ls[iz]) as u8;
                                    }
                                }
                            } else {
                                for k in 0..4 {
                                    nzc[NZC_CACHE[(id8 * 4 + k).min(23)].min(47)] = 0;
                                }
                            }
                        }
                        if cbp_chroma >= 1 {
                            for i in 0..2usize {
                                parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4, RP_CHROMA_DC + i, false, ndc, &mut cdc[i]);
                            }
                        }
                        if cbp_chroma == 2 {
                            let cacm = cac.get_or_insert_with(|| [[[0i32; 16]; 4]; 2]);
                            for i in 0..2usize {
                                for id4 in 0..4usize {
                                    nnzs[16 + i * 4 + id4] = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4 + id4, RP_CHROMA_AC + i, false, ndc, &mut cacm[i][id4]) as u8;
                                }
                            }
                        }
                    }
                    if let Some(p) = self.mb_qp.get_mut(addr) {
                        *p = self.cur_qp;
                    }
                    if let Some(p) = cbf_dc.get_mut(addr) {
                        *p = cbfdc;
                    }
                    let _sc = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecStateCache);
                    let mut mn = [0u8; 24];
                    for k in 0..4 {
                        mn[k] = nzc[9 + k];
                        mn[4 + k] = nzc[17 + k];
                        mn[8 + k] = nzc[25 + k];
                        mn[12 + k] = nzc[33 + k];
                    }
                    (mn[16], mn[17], mn[20], mn[21]) = (nzc[14], nzc[15], nzc[22], nzc[23]);
                    (mn[18], mn[19], mn[22], mn[23]) = (nzc[38], nzc[39], nzc[46], nzc[47]);
                    // A block whose residual was skipped (cbp bit clear / no chroma AC)
                    // has 0 coeffs, not "unavailable" — export 0 so an intra neighbour's
                    // CBF ctxInc reads 0 (not the 0xff sentinel → is_intra default).
                    for v in mn.iter_mut() {
                        if *v == 0xff {
                            *v = 0;
                        }
                    }
                    if let Some(p) = mb_nzc.get_mut(addr) {
                        *p = mn;
                    }
                    drop(_sc);
                    if let Some(regions) = self.edc_regions.take() {
                        self.edc_giveback();
                        self.edc_commit_nnz(mbx, mby, t8, &nnzs, cbp_chroma);
                        let job = BJob {
                            mbx,
                            mby,
                            qp: self.cur_qp,
                            cbp_chroma,
                            skip: false,
                            regions,
                            luma_scan,
                            luma8,
                            cdc,
                            cac,
                            nnzs,
                        };
                        self.edc_send_job(EdcJob::B(Box::new(job)));
                    } else {
                        self.add_inter_residual(mbx, mby, &pred_y, &c_pred, luma_scan.as_ref(), luma8.as_ref(), &cdc, cac.as_ref(), cbp_chroma, &nnzs);
                    }

                    let eos = cab.decode_terminate();
                    addr += 1;
                    mbx += 1;
                    if eos || addr >= total {
                        break;
                    }
                    continue;
                }
                mb_type = bmt - 23; // 23→0 (I_4x4), 24..=47→1..24 (I_16x16), 48→25 (PCM)
            } else {
                let li = left.map_or(0, |a| cat.get(a).is_some_and(|&c| c >= 2) as usize);
                let ti = top.map_or(0, |a| cat.get(a).is_some_and(|&c| c >= 2) as usize);
                mb_type = parse_mb_type_i_cabac(&mut cab, li + ti);
            }
            // H-48: the CABAC intra path is INLINED in this loop, not routed through
            // `decode_intra_mb` (which only the CAVLC readers call) — wiring the scope
            // there reported ZERO calls against 480,510 intra-pred calls. All three
            // intra entries (I-slice, P-slice mb_type>3, B-slice bmt>=23) converge
            // here, so this is the one point that sees every intra MB.
            self.edc_intra_sync(); // intra reconstruction reads neighbour PIXELS
            // Intra prediction ALSO reads the coded_y/modes_y/inter_y grids a
            // deferred span still owes (this arm is inline — it never passes
            // decode_b_mb's flush). Caught by the tempete ARM-DIFF.
            self.span_flush();
            let _gi = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMbI);
            // Intra bS is a constant pattern (4 on MB edges, 3 internal) — written
            // here because CABAC inlines I recon and never calls decode_intra_mb.
            if let Some(p) = self.mb_kind.get_mut(mby * self.mb_w + mbx) {
                *p = rusty_h264_common::deblock::MB_KIND_INTRA;
            }
            if mb_type == 25 {
                // ---- I_PCM (spec §7.3.5): 384 raw byte-aligned sample bytes inside
                // the CABAC stream. The PCM marker was a terminate bin, so the engine
                // has stopped; DecodeFlush + pcm_alignment_zero_bit put the samples
                // at `pcm_start_byte()`, and the engine re-initialises after them
                // with its CONTEXTS KEPT (§9.3.1). All three slice types (I, P via
                // mbt 30, B via bmt 48) reach here as mb_type 25.
                let pcm = cab.pcm_start_byte();
                let end = pcm + 384;
                if end > rbsp.len() {
                    return Err(MbError::Truncated);
                }
                let mut pr = BitReader::new(&rbsp[pcm..end]);
                self.decode_ipcm(&mut pr, mbx, mby)?;
                cab.reinit_at(end);
                // Neighbour context (§7.4.5 + §9.3.3.1.1.x inferences): intra, QPy
                // unchanged (no mb_qp_delta — its ctxInc resets), CodedBlockPattern
                // luma/chroma inferred 15/2, every coded_block_flag (incl. DC) 1,
                // nnz 16, chroma pred mode 0.
                if let Some(p) = self.mb_qp.get_mut(addr) {
                    *p = self.cur_qp;
                }
                if let Some(p) = cat.get_mut(addr) {
                    *p = 25;
                }
                if let Some(p) = cmode.get_mut(addr) {
                    *p = 0;
                }
                if let Some(p) = mb_cbp.get_mut(addr) {
                    *p = 0x2f;
                }
                if let Some(p) = cbf_dc.get_mut(addr) {
                    *p = (1 << RP_I16_DC) | (1 << RP_CHROMA_DC) | (1 << (RP_CHROMA_DC + 1));
                }
                if let Some(p) = mb_nzc.get_mut(addr) {
                    *p = [16u8; 24];
                }
                last_delta_qp = 0;
                let eos = cab.decode_terminate();
                addr += 1;
                    mbx += 1;
                if eos || addr >= total {
                    break;
                }
                continue;
            }
            // chroma-pred-mode ctxInc from neighbour chroma modes (1..=3).
            let cci = left.map_or(0, |a| cmode.get(a).is_some_and(|c| (1..=3).contains(c)) as usize)
                + top.map_or(0, |a| cmode.get(a).is_some_and(|c| (1..=3).contains(c)) as usize);

            if mb_type != 0 {
                // ---- I_16x16 (mb_type 1..=24): pred mode & cbp DERIVED from mb_type;
                // luma DC always coded. Syntax order: intra_chroma_pred_mode, mb_qp_delta,
                // luma DC (Hadamard), luma AC (if cbp_luma), chroma DC/AC. Mirrors the CAVLC
                // decode_i16, driven by the CABAC residual. ----
                let mt = mb_type - 1;
                let pred_mode = I16Mode::from_id(mt % 4);
                let cbp_chroma = (mt % 12) / 4;
                let cbp_luma_15 = mt / 12 == 1;
                let chroma_mode = parse_intra_chroma_pred_mode_cabac(&mut cab, cci) as u8;
                if let Some(p) = cmode.get_mut(addr) {
                    *p = chroma_mode as i32;
                }
                if let Some(p) = cat.get_mut(addr) {
                    *p = 2;
                }
                if let Some(p) = mb_cbp.get_mut(addr) {
                    *p = ((cbp_chroma as u8) << 4) | if cbp_luma_15 { 15 } else { 0 };
                }
                let w4 = self.mb_w * 4;

                let mut nzc = [0xffu8; 48];
                if let Some(t) = top {
                    let tn = mb_nzc.get(t).unwrap_or(&ZERO_NZC);
                    nzc[1..5].copy_from_slice(&tn[12..16]);
                    (nzc[0], nzc[5], nzc[29]) = (0, 0, 0);
                    (nzc[6], nzc[7]) = (tn[20], tn[21]);
                    (nzc[30], nzc[31]) = (tn[22], tn[23]);
                }
                if let Some(l) = left {
                    let ln = mb_nzc.get(l).unwrap_or(&ZERO_NZC);
                    (nzc[8], nzc[16], nzc[24], nzc[32]) = (ln[3], ln[7], ln[11], ln[15]);
                    (nzc[13], nzc[21], nzc[37], nzc[45]) = (ln[17], ln[21], ln[19], ln[23]);
                }

                let ndc = (top.and_then(|a| cbf_dc.get(a).copied()), left.and_then(|a| cbf_dc.get(a).copied()));
                let qpd = parse_mb_qp_delta_cabac(&mut cab, &mut last_delta_qp);
                self.step_qp(qpd)?;
                let qp = self.cur_qp;
                let mut cbfdc = 0u16;

                // Luma DC (iz=0, category I16_LUMA_DC, 16 coeffs) → Hadamard dequant.
                let mut dc_scan = [0i32; 16];
                parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 0, RP_I16_DC, true, ndc, &mut dc_scan);
                let recon_dc = self.dequant_luma_dc(&un_scan_4x4_dcac(&dc_scan), qp, 0);

                // Luma AC (iz 0..15, category I16_LUMA_AC, 15 coeffs) when cbp_luma set.
                // Materialised only when AC is actually coded — a DC-only
                // I_16x16 zeroed 1 KB of stack for nothing.
                let mut q_blocks: Option<[[i32; 16]; 16]> = None;
                for (iz, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
                    let total = if cbp_luma_15 {
                        let mut ac = [0i32; 16];
                        let t = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, iz, RP_I16_AC, true, ndc, &mut ac);
                        un_scan_4x4_ac_into(&ac, &mut q_blocks.get_or_insert_with(|| [[0i32; 16]; 16])[(lby & 3) * 4 + (lbx & 3)]);
                        t as u8
                    } else {
                        nzc[NZC_CACHE[iz.min(23)].min(47)] = 0;
                        0
                    };
                    if let Some(p) = self.nnz_y.get_mut((mby * 4 + lby) * w4 + (mbx * 4 + lbx)) {
                        *p = total;
                    }
                }

                let mut cdc = [[0i32; 4]; 2];
                let mut cac: Option<[[[i32; 16]; 4]; 2]> = None;
                if cbp_chroma >= 1 {
                    for i in 0..2usize {
                        parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4, RP_CHROMA_DC + i, true, ndc, &mut cdc[i]);
                    }
                }
                if cbp_chroma == 2 {
                    let cacm = cac.get_or_insert_with(|| [[[0i32; 16]; 4]; 2]);
                    for i in 0..2usize {
                        for id4 in 0..4usize {
                            parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4 + id4, RP_CHROMA_AC + i, true, ndc, &mut cacm[i][id4]);
                        }
                    }
                }

                // Luma recon: 16×16 intra prediction, then per-4×4 (dequant AC + injected DC).
                let top_ok = mby > 0 && self.nbr_in_slice(mbx, mby - 1) && self.intra_nbr_ok(mbx * 4, mby * 4 - 1);
                let left_ok = mbx > 0 && self.nbr_in_slice(mbx - 1, mby) && self.intra_nbr_ok(mbx * 4 - 1, mby * 4);
                self.recon_i16_luma(mbx, mby, pred_mode, top_ok, left_ok, q_blocks.as_ref(), &recon_dc, qp);
                self.recon_chroma_cabac(mbx, mby, chroma_mode, &cdc, cac.as_ref(), cbp_chroma, top_ok, left_ok);

                if let Some(p) = self.mb_qp.get_mut(addr) {
                    *p = self.cur_qp;
                }
                if let Some(p) = cbf_dc.get_mut(addr) {
                    *p = cbfdc;
                }
                let mut mn = [0u8; 24];
                for k in 0..4 {
                    mn[k] = nzc[9 + k];
                    mn[4 + k] = nzc[17 + k];
                    mn[8 + k] = nzc[25 + k];
                    mn[12 + k] = nzc[33 + k];
                }
                (mn[16], mn[17], mn[20], mn[21]) = (nzc[14], nzc[15], nzc[22], nzc[23]);
                (mn[18], mn[19], mn[22], mn[23]) = (nzc[38], nzc[39], nzc[46], nzc[47]);
                for v in mn.iter_mut() {
                    if *v == 0xff {
                        *v = 0;
                    }
                }
                if let Some(p) = mb_nzc.get_mut(addr) {
                    *p = mn;
                }

                let eos = cab.decode_terminate();
                addr += 1;
                    mbx += 1;
                if eos || addr >= total {
                    break;
                }
                continue;
            }
            if let Some(p) = cat.get_mut(addr) {
                *p = 0;
            }
            let w4 = self.mb_w * 4;
            // H-49: transform_size_8x8_flag. For I_NxN it precedes the intra pred
            // modes (spec §7.3.5); ctxIdx = 399 + condTermFlagA + condTermFlagB,
            // each 1 when that neighbour MB carries the flag. Omitting this read is
            // what desynced every High-profile stream.
            let t8 = self.transform_8x8_mode && {
                let a = left.map_or(0, |x| self.mb_t8x8.get(x).is_some_and(|&f| f) as usize);
                let b = top.map_or(0, |x| self.mb_t8x8.get(x).is_some_and(|&f| f) as usize);
                cab.decode_decision(399 + a + b) != 0
            };
            if let Some(p) = self.mb_t8x8.get_mut(addr) {
                *p = t8;
            }
            self.any_t8 |= t8;
            // Hoisted ABOVE the mode loop (it was computed after it) so the
            // per-block mode prediction can use it - see `predict_i4_mode_fast`.
            let top_ok = mby > 0
                && self.nbr_in_slice(mbx, mby - 1)
                && self.intra_nbr_ok(mbx * 4, mby * 4 - 1);
            let left_ok = mbx > 0
                && self.nbr_in_slice(mbx - 1, mby)
                && self.intra_nbr_ok(mbx * 4 - 1, mby * 4);
            // Brick 2.4 + recon: derive & store each intra mode (prev-flag → the
            // neighbour-predicted mode, else rem), exactly as the CAVLC path.
            let mut modes = [2u8; 16]; // raster [lby*4+lbx]
            let mut modes8 = [2u8; 4]; // one per 8×8 when t8
            if t8 {
                // One mode per 8×8, broadcast to its four 4×4 cells so neighbour
                // mode prediction keeps working unchanged.
                for b8 in 0..4usize {
                    let (b8x, b8y) = (b8 % 2, b8 / 2);
                    let (bx, by) = (mbx * 4 + b8x * 2, mby * 4 + b8y * 2);
                    let predicted =
                        self.predict_i4_mode_fast(bx, by, b8x * 2, b8y * 2, top_ok, left_ok);
                    let rr = parse_intra4x4_pred_mode_cabac(&mut cab);
                    let actual = if rr < 0 {
                        predicted
                    } else {
                        let rem = rr as u8;
                        if rem < predicted { rem } else { rem + 1 }
                    };
                    modes8[b8] = actual;
                    for dy in 0..2 {
                        for dx in 0..2 {
                            if let Some(p) = self.modes_y.get_mut((by + dy) * w4 + (bx + dx)) {
                                *p = actual;
                            }
                            modes[(b8y * 2 + dy) * 4 + (b8x * 2 + dx)] = actual;
                        }
                    }
                }
            } else {
                for &(lbx, lby) in &LUMA_4X4_SCAN_XY {
                    let (bx, by) = (mbx * 4 + lbx, mby * 4 + lby);
                    let predicted = self.predict_i4_mode_fast(bx, by, lbx, lby, top_ok, left_ok);
                    let rr = parse_intra4x4_pred_mode_cabac(&mut cab);
                    let actual = if rr < 0 {
                        predicted
                    } else {
                        let rem = rr as u8;
                        if rem < predicted { rem } else { rem + 1 }
                    };
                    if let Some(m) = self.modes_y.get_mut(by * w4 + bx) {
                        *m = actual;
                    }
                    modes[(lby & 3) * 4 + (lbx & 3)] = actual;
                }
            }
            let chroma_mode = parse_intra_chroma_pred_mode_cabac(&mut cab, cci) as u8;
            if let Some(p) = cmode.get_mut(addr) {
                *p = chroma_mode as i32;
            }
            let cbp = parse_cbp_cabac(&mut cab, top.and_then(|a| mb_cbp.get(a).copied()), left.and_then(|a| mb_cbp.get(a).copied()));
            if let Some(p) = mb_cbp.get_mut(addr) {
                *p = cbp as u8;
            }
            let (cbp_luma, cbp_chroma) = (cbp & 15, cbp >> 4);

            // Build the padded nzc cache from neighbours (openh264 WelsFillCacheNonZeroCount).
            let mut nzc = [0xffu8; 48];
            if let Some(t) = top {
                let tn = mb_nzc.get(t).unwrap_or(&ZERO_NZC);
                nzc[1..5].copy_from_slice(&tn[12..16]);
                (nzc[0], nzc[5], nzc[29]) = (0, 0, 0);
                (nzc[6], nzc[7]) = (tn[20], tn[21]);
                (nzc[30], nzc[31]) = (tn[22], tn[23]);
            }
            if let Some(l) = left {
                let ln = mb_nzc.get(l).unwrap_or(&ZERO_NZC);
                (nzc[8], nzc[16], nzc[24], nzc[32]) = (ln[3], ln[7], ln[11], ln[15]);
                (nzc[13], nzc[21], nzc[37], nzc[45]) = (ln[17], ln[21], ln[19], ln[23]);
            }

            // Bricks 2.6 + 2.7: mb_qp_delta + residual (I_4x4 luma 4×4 + chroma DC/AC),
            // storing scan-order coefficients for recon.
            let mut cbfdc = 0u16;
            // Both materialised only when the parse writes them: an I_8x8
            // macroblock never touches luma_scan (it carries luma8), and
            // cbp_chroma < 2 never touches cac.
            let mut luma_scan: Option<[[i32; 16]; 16]> = None; // per z-order 4×4 block
            let mut luma8: Option<[[i32; 64]; 4]> = None; // allocated only under t8
            let mut cdc = [[0i32; 4]; 2]; // chroma DC per plane
            let mut cac: Option<[[[i32; 16]; 4]; 2]> = None; // chroma AC per plane, per 4×4 block
            let mut i4n = [0u8; 16]; // parse-side per-block coeff counts (I_4x4)
            if cbp == 0 {
                last_delta_qp = 0;
            }
            if cbp != 0 {
                let ndc = (top.and_then(|a| cbf_dc.get(a).copied()), left.and_then(|a| cbf_dc.get(a).copied()));
                let qpd = parse_mb_qp_delta_cabac(&mut cab, &mut last_delta_qp);
                self.step_qp(qpd)?;
                for id8 in 0..4usize {
                    if cbp_luma & (1 << id8) != 0 {
                        if t8 {
                            // ctxBlockCat 5: ONE 64-coefficient block per 8×8, and no
                            // coded_block_flag — presence comes from cbp_luma alone.
                            let n = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, id8 * 4, RP_LUMA_8X8, true, ndc, &mut luma8.get_or_insert_with(|| [[0i32; 64]; 4])[id8]);
                            let (b8x, b8y) = (id8 % 2, id8 / 2);
                            for sy in 0..2 {
                                for sx in 0..2 {
                                    if let Some(p) = self.nnz_y.get_mut((mby * 4 + b8y * 2 + sy) * w4 + (mbx * 4 + b8x * 2 + sx)) {
                                        *p = n as u8;
                                    }
                                }
                            }
                        } else {
                            for id4 in 0..4usize {
                                let iz = id8 * 4 + id4;
                                // Capture the parse's own count — the recon loop
                                // used to re-scan all 16 coefficients per block.
                                i4n[iz] = parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, iz, RP_LUMA_4X4, true, ndc, &mut luma_scan.get_or_insert_with(|| [[0i32; 16]; 16])[iz]) as u8;
                            }
                        }
                    } else {
                        for k in 0..4 {
                            nzc[NZC_CACHE[(id8 * 4 + k).min(23)].min(47)] = 0;
                        }
                        if t8 {
                            let (b8x, b8y) = (id8 % 2, id8 / 2);
                            for sy in 0..2 {
                                for sx in 0..2 {
                                    if let Some(p) = self.nnz_y.get_mut((mby * 4 + b8y * 2 + sy) * w4 + (mbx * 4 + b8x * 2 + sx)) {
                                        *p = 0;
                                    }
                                }
                            }
                        }
                    }
                }
                if cbp_chroma >= 1 {
                    for i in 0..2usize {
                        parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4, RP_CHROMA_DC + i, true, ndc, &mut cdc[i]);
                    }
                }
                if cbp_chroma == 2 {
                    for i in 0..2usize {
                        for id4 in 0..4usize {
                            parse_residual_cabac(&mut cab, &mut nzc, &mut cbfdc, 16 + i * 4 + id4, RP_CHROMA_AC + i, true, ndc, &mut cac.get_or_insert_with(|| [[[0i32; 16]; 4]; 2])[i][id4]);
                        }
                    }
                }
            }
            if let Some(p) = self.mb_qp.get_mut(addr) {
                *p = self.cur_qp;
            }
            if let Some(p) = cbf_dc.get_mut(addr) {
                *p = cbfdc;
            }
            // Extract the MB's nzc (raster luma + chroma) for future neighbours.
            let mut mn = [0u8; 24];
            for k in 0..4 {
                mn[k] = nzc[9 + k];
                mn[4 + k] = nzc[17 + k];
                mn[8 + k] = nzc[25 + k];
                mn[12 + k] = nzc[33 + k];
            }
            (mn[16], mn[17], mn[20], mn[21]) = (nzc[14], nzc[15], nzc[22], nzc[23]);
            (mn[18], mn[19], mn[22], mn[23]) = (nzc[38], nzc[39], nzc[46], nzc[47]);
            for v in mn.iter_mut() {
                if *v == 0xff {
                    *v = 0;
                }
            }
            if let Some(p) = mb_nzc.get_mut(addr) {
                *p = mn;
            }

            // ---- Brick 4.3a: recon (I_4x4 luma + chroma) via the CAVLC-proven primitives.
            let qp = self.cur_qp;

            if t8 {
                // I_8x8 recon, reusing the CAVLC-proven primitives verbatim
                // (un_scan_8x8 / inv_quant8 / gather_i8 / intra8x8_pred /
                // add_residual_8x8). Only the ENTROPY half differed.
                for b8 in 0..4usize {
                    let (b8x, b8y) = (b8 % 2, b8 / 2);
                    let (bx, by) = (mbx * 4 + b8x * 2, mby * 4 + b8y * 2);
                    let coded = cbp_luma & (1 << b8) != 0;
                    let avail_top = b8y > 0 || top_ok;
                    let avail_left = b8x > 0 || left_ok;
                    self.recon_i8_block(bx, by, modes8[b8], avail_top, avail_left, luma8.as_ref().and_then(|l| coded.then(|| &l[b8])), qp);
                    for sy in 0..2 {
                        // Row fill: the 2x2 cell block is two contiguous PAIRS.
                        self.coded_y[(by + sy) * w4 + bx..][..2].fill(true);
                    }
                }
            }
            // The `t8` guard was INSIDE the loop (breaking on the first
            // iteration) and the `luma_scan` Option was re-resolved on EVERY one
            // of the sixteen blocks. Both are macroblock-invariant.
            if !t8 {
                let scans = luma_scan.as_ref().unwrap_or(&ZERO_LUMA_SCAN);
                for (blk, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
                    let (bx, by) = (mbx * 4 + lbx, mby * 4 + lby);
                    let at = lby > 0 || top_ok;
                    let al = lbx > 0 || left_ok;
                    let nnz = i4n[blk & 15];
                    if let Some(p) = self.nnz_y.get_mut(by * w4 + bx) {
                        *p = nnz;
                    }
                    self.recon_i4_block(
                        bx, by, modes[(lby & 3) * 4 + (lbx & 3)], at, al, &scans[blk & 15], nnz, qp,
                    );
                }
            }
            self.recon_chroma_cabac(mbx, mby, chroma_mode, &cdc, cac.as_ref(), cbp_chroma, top_ok, left_ok);

            // Brick 2.1: end_of_slice_flag.
            let eos = cab.decode_terminate();
            addr += 1;
                    mbx += 1;
            if eos || addr >= total {
                break;
            }
        }
        }
        if trace {
            eprintln!("# CABAC decoded {} MBs (of {total})", addr - first_mb);
        }
        self.edc_flush(); // slice end: no job crosses a slice boundary
        // Return the pooled slice scratch (an error exit forfeits it — the
        // next slice then refills fresh allocations, correctness unchanged).
        self.sc_cat = cat;
        self.sc_cbp = mb_cbp;
        self.sc_cmode = cmode;
        self.sc_nzc = mb_nzc;
        self.sc_cbfdc = cbf_dc;
        self.sc_skip = mb_skip;
        self.sc_ref = mb_ref;
        self.sc_mvd = mb_mvd;
        if want_b_grids {
            self.sc_ref1 = mb_ref1;
            self.sc_mvd1 = mb_mvd1;
            self.sc_direct = mb_direct;
        }
        Ok(addr)
    }

    /// CABAC chroma recon (mirrors `decode_chroma`'s reconstruction, driven by the
    /// CABAC-parsed DC/AC coefficients). `cdc[c]` = 2×2 DC (scan order); `cac[c][blk]`
    /// = 15 AC per 4×4 block (scan order).
    #[allow(clippy::too_many_arguments)]
    /// Add a CABAC-parsed inter residual to an already-built motion-comp prediction
    /// (`pred_y`/`c_pred`), writing the reconstruction. Shared by the P and B inter
    /// paths — same `reconstruct_4x4` as intra, MC output as the prediction, inter
    /// scaling lists (luma 3 / chroma 4+c). `luma_scan[z]`/`cdc`/`cac` are the
    /// scan-order coefficients; uncoded blocks are zero so recon == prediction.
    #[allow(clippy::too_many_arguments)]
    fn add_inter_residual(
        &mut self,
        mb_x: usize,
        mb_y: usize,
        pred_y: &[u8; 256],
        c_pred: &[[u8; 64]; 2],
        luma_scan: Option<&[[i32; 16]; 16]>,
        // `Some` when the macroblock carries transform_size_8x8_flag: four 8x8
        // blocks in 8x8 scan order, replacing the sixteen 4x4 luma blocks.
        luma8: Option<&[[i32; 64]; 4]>,
        cdc: &[[i32; 4]; 2],
        cac: Option<&[[[i32; 16]; 4]; 2]>,
        cbp_chroma: u32,
        // Parsed totalCoeff per block, indexed exactly as the parse's `iz`:
        // [0..16] luma 4x4 z-order (for t8, the 8x8 count sits at `id8*4`),
        // [16..24] chroma AC as `16 + c*4 + id4`. The parser already counted
        // every significant coefficient; re-deriving the counts here scanned
        // 16-64 array elements per block (~400 loads/MB) for information the
        // caller was holding — the diagnosis's stage-boundary re-derivation tax.
        nnzs: &[u8; 24],
    ) {
        // A `None` field means the parse wrote nothing there; every read below
        // is guarded by a zero-count test, so the shared zero plane is
        // read-equivalent to the per-macroblock zeroed stack array it replaces.
        let luma_scan = luma_scan.unwrap_or(&ZERO_LUMA_SCAN);
        let cac = cac.unwrap_or(&ZERO_CAC);
        let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecResidAdd);
        let qp = self.cur_qp;
        let qpc = self.chroma_qp_for(qp);
        let (w4r, w2r) = (self.mb_w * 4, self.mb_w * 2);
        if let Some(l8) = luma8 {
            // INTER 8x8 luma: same primitives the I_8x8 and CAVLC paths use.
            for b8 in 0..4usize {
                let (b8x, b8y) = (b8 % 2, b8 / 2);
                // PER-CELL, not one aggregate broadcast over all four cells. CAVLC
                // codes an 8x8 block as four 4x4 sub-blocks and its nC predictor
                // reads these per-4x4 counts from `nnz_y`, so the broadcast
                // corrupted the NEXT macroblock's nC and desynced the parse -- which
                // is why CAVLC 8x8 streams ffmpeg accepts would not decode here. The
                // worker copy of this function never wrote `nnz_y` at all, so the
                // threaded path was unaffected and hid the defect. CABAC has no
                // per-4x4 counts, so its callers put the 8x8 total in all four slots.
                let nnz: u32 = (0..4).map(|k| nnzs[b8 * 4 + k] as u32).sum();
                // Two row slices, not four whole-grid indexed stores. The pair
                // written per row is contiguous and `nnzs` is a fixed 24-entry
                // array, so both sides become provable.
                for sy in 0..2 {
                    let base = (mb_y * 4 + b8y * 2 + sy) * w4r + mb_x * 4 + b8x * 2;
                    self.nnz_y[base..][..2].copy_from_slice(&nnzs[b8 * 4 + sy * 2..][..2]);
                }
                // The 4x4 inter path marks coded_y per block; the 8x8 branch must too,
                // or a later intra macroblock's neighbour availability is wrong.
                for sy in 0..2 {
                    let base = (mb_y * 4 + b8y * 2 + sy) * w4r + mb_x * 4 + b8x * 2;
                    self.coded_y[base..][..2].fill(true);
                }
                let (px, py) = (mb_x * 16 + b8x * 8, mb_y * 16 + b8y * 8);
                if nnz == 0 {
                    // Zero residual: recon == pred — the 4x4 arm zero shortcut,
                    // ported to the 8x8 branch.
                    edcstat::bump(&edcstat::T8_ZERO, 1);
                    for dy in 0..8 {
                        let d = (py + dy) * self.cw + px;
                        let po = (b8y * 8 + dy) * 16 + b8x * 8;
                        self.rec_y[d..d + 8].copy_from_slice(&pred_y[po..po + 8]);
                    }
                } else {
                    let raster = un_scan_8x8(&l8[b8]);
                    // list 1 = INTER 8x8 luma scaling list (0 is the intra one).
                    let res8 = self.inv_quant8(&raster, qp, 1);
                    let predb: [i32; 64] =
                        std::array::from_fn(|i| pred_y[(b8y * 8 + i / 8) * 16 + (b8x * 8 + i % 8)] as i32);
                    let recon = add_residual_8x8(&res8, &predb);
                    // Eight row copies. This wrote SIXTY-FOUR individually
                    // bounds-checked samples into the luma plane per coded 8x8
                    // block — the same shape whose fix carried `recon_i8_block`.
                    // Present in BOTH the main path and the EDC worker twin.
                    for dy in 0..8 {
                        let d = (py + dy) * self.cw + px;
                        self.rec_y[d..][..8].copy_from_slice(&recon[dy * 8..][..8]);
                    }
                }
            }
        }
        for (blk, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
            if luma8.is_some() {
                break;
            }
            let nnz = nnzs[blk];
            if let Some(p) = self.nnz_y.get_mut((mb_y * 4 + lby) * w4r + (mb_x * 4 + lbx)) {
                *p = nnz;
            }
            let cw = self.cw;
            let p_off = (lby * 4) * 16 + lbx * 4;
            let r_off = (mb_y * 4 + lby) * 4 * cw + (mb_x * 4 + lbx) * 4;
            if nnz == 0 {
                // Zero residual → recon == prediction EXACTLY (the integer IDCT is
                // linear so zeros map to zeros, and pred is already 0..=255) — copy
                // the pred rows straight into the plane. On real (sparse-cbp)
                // streams this is MOST of the 4×4 blocks.
                for r in 0..4 {
                    self.rec_y[r_off + r * cw..r_off + r * cw + 4]
                        .copy_from_slice(&pred_y[p_off + r * 16..p_off + r * 16 + 4]);
                }
                continue;
            }
            // DC-ONLY: the sole significant coefficient is scan position 0 (the
            // zig-zag starts at DC, and un_scan keeps it at raster 0), so the
            // whole dequant + IDCT collapses to one multiply and a flat add.
            if nnz == 1 && luma_scan[blk][0] != 0 {
                let f = self.dequant_dc4(luma_scan[blk][0], qp, 3);
                reconstruct_4x4_dc_into((f + 32) >> 6, pred_y, p_off, 16, &mut self.rec_y, r_off, cw);
            } else {
                // Fused un-scan + dequant over ONLY the significant coefficients,
                // then IDCT + add + clip straight into the plane — no `qb`, no
                // `deq`-from-dense, no `predb` gather, no `s`, no `store` call.
                //
                // HYBRID: the scatter walks scan positions with a data-dependent
                // branch per slot, which beats the branchless dense 16-multiply
                // loop only while the block is SPARSE. The DC/zero fast paths
                // already removed the sparsest blocks, so the population here
                // skews denser — above ~6 coefficients the dense loop wins.
                let deq = if nnz <= 6 {
                    dequant_scatter_4x4(&luma_scan[blk], nnz, 0, qp, self.scaling.as_ref().map(|sc| &sc[3]))
                } else {
                    self.dequant(&un_scan_4x4_dcac(&luma_scan[blk]), qp, 3)
                };
                reconstruct_4x4_into(&deq, pred_y, p_off, 16, &mut self.rec_y, r_off, cw);
            }
        }
        let mut c_dc = [[0i32; 4]; 2];
        if cbp_chroma != 0 {
            for c in 0..2 {
                c_dc[c] = self.dequant_chroma_dc(&cdc[c], qpc, 4 + c);
            }
        }
        let ccw = self.ccw;
        for c in 0..2 {
            for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                let mut ac_nz = false;
                if cbp_chroma == 2 {
                    let n = nnzs[(16 + c * 4 + by * 2 + bx).min(23)];
                    if let Some(p) = self.nnz_c[c & 1].get_mut((mb_y * 2 + by) * w2r + (mb_x * 2 + bx)) {
                        *p = n;
                    }
                    ac_nz = n != 0;
                }
                let dc = c_dc[c & 1][(by * 2 + bx) & 3];
                let p_off = (by * 4) * 8 + bx * 4;
                let r_off = (mb_y * 2 + by) * 4 * ccw + (mb_x * 2 + bx) * 4;
                let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                if dc == 0 && !ac_nz {
                    // Zero residual (no AC, zero DC) → recon == prediction exactly.
                    for r in 0..4 {
                        plane[r_off + r * ccw..r_off + r * ccw + 4]
                            .copy_from_slice(&c_pred[c][p_off + r * 8..p_off + r * 8 + 4]);
                    }
                    continue;
                }
                // DC-ONLY (no coded AC — covers every cbp_chroma==1 block and the
                // AC-empty blocks of cbp_chroma==2): the chroma DC arrives ALREADY
                // dequantized, so the residual is `(dc + 32) >> 6` flat.
                if !ac_nz {
                    reconstruct_4x4_dc_into((dc + 32) >> 6, &c_pred[c], p_off, 8, plane, r_off, ccw);
                    continue;
                }
                // AC-only scan: index i is overall scan position i+1 (ac_shift=1).
                // Same sparse/dense hybrid as luma.
                let n = nnzs[(16 + c * 4 + by * 2 + bx).min(23)];
                let mut deq = if n <= 6 {
                    dequant_scatter_4x4(&cac[c & 1][(by * 2 + bx) & 3], n, 1, qpc, self.scaling.as_ref().map(|sc| &sc[4 + c]))
                } else {
                    let mut ac = [0i32; 16];
                    un_scan_4x4_ac_into(&cac[c & 1][(by * 2 + bx) & 3], &mut ac);
                    // Free-fn dequant: `self.dequant` borrows all of `self`, which
                    // conflicts with the live `plane` (&mut self.rec_u/v) borrow.
                    match &self.scaling {
                        Some(sc) => dequantize_weighted(&ac, qpc, &sc[4 + c]),
                        None => dequantize(&ac, qpc),
                    }
                };
                deq[0] = dc;
                reconstruct_4x4_into(&deq, &c_pred[c], p_off, 8, plane, r_off, ccw);
            }
        }
    }

    // ── SHARED INTRA RECON PRIMITIVES ──────────────────────────────────
    // ONE implementation per block family, called by BOTH entropy arms.
    // The per-coder recon twins are where routing rot lived: the residual
    // ladder and the DC-only collapse each had to be found and ported
    // twin-by-twin. The parse halves stay per-coder (that is the real
    // difference between the coders); the pixel halves live here — the
    // same convergence D14 gave the inter path via add_inter_residual.

    /// Intra 4x4 luma block: gather + predict + the residual ladder
    /// (zero / DC-only / sparse-scatter / dense), fused into the plane.
    /// `scan` = the block's coefficients in SCAN order; `nnz` its count
    /// (the caller has already committed nnz to its entropy-side state).
    /// Marks the block coded.
    #[allow(clippy::too_many_arguments)]
    fn recon_i4_block(&mut self, bx: usize, by: usize, mode: u8, at: bool, al: bool, scan: &[i32; 16], nnz: u8, qp: u8) {
        let (px, py) = (bx * 4, by * 4);
        let (t, l, corner) = self.gather_i4(px, py, at, al, bx, by);
        let pred = intra4x4_pred(mode, at, al, &t, &l, corner);
        let r_off = py * self.cw + px;
        let cw = self.cw;
        if nnz == 0 {
            edcstat::bump(&edcstat::I4_ZERO, 1);
            // ONE span for the 4x4 write window (rows `cw` apart), so the four
            // row copies share a single bounds check. This is the DOMINANT arm:
            // 63.4% of I_4x4 blocks are all-zero on all-intra content.
            let win = &mut self.rec_y[r_off..r_off + 3 * cw + 4];
            for r in 0..4 {
                win[r * cw..r * cw + 4].copy_from_slice(&pred[r * 4..r * 4 + 4]);
            }
        } else if nnz == 1 && scan[0] != 0 {
            edcstat::bump(&edcstat::I4_DC, 1);
            let f = self.dequant_dc4(scan[0], qp, 0);
            reconstruct_4x4_dc_into((f + 32) >> 6, &pred, 0, 4, &mut self.rec_y, r_off, cw);
        } else {
            let deq = if nnz <= 6 {
                edcstat::bump(&edcstat::I4_SPARSE, 1);
                dequant_scatter_4x4(scan, nnz, 0, qp, self.scaling.as_ref().map(|sc| &sc[0]))
            } else {
                edcstat::bump(&edcstat::I4_DENSE, 1);
                self.dequant(&un_scan_4x4_dcac(scan), qp, 0)
            };
            reconstruct_4x4_into(&deq, &pred, 0, 4, &mut self.rec_y, r_off, cw);
        }
        if let Some(c) = self.coded_y.get_mut(by * (self.mb_w * 4) + bx) {
            *c = true;
        }
    }

    /// Intra 8x8 luma block: predict + zero-arm or un-scan/quant/add.
    /// `coeffs` = SCAN-order 8x8 coefficients, `None` when the cbp bit is
    /// unset. `coded_y` marking stays with the callers (their orders differ).
    fn recon_i8_block(&mut self, bx: usize, by: usize, mode: u8, avail_top: bool, avail_left: bool, coeffs: Option<&[i32; 64]>, qp: u8) {
        let (px, py) = (bx * 4, by * 4);
        let (t, l, corner, avail_corner) = self.gather_i8(px, py, avail_top, avail_left, bx, by);
        let pred = intra8x8_pred(mode, avail_top, avail_left, avail_corner, &t, &l, corner);
        match coeffs {
            None => {
                // Zero residual: recon == pred exactly.
                edcstat::bump(&edcstat::T8_ZERO, 1);
                let (cw, base) = (self.cw, py * self.cw + px);
                let win = &mut self.rec_y[base..base + 7 * cw + 8];
                for dy in 0..8 {
                    win[dy * cw..dy * cw + 8].copy_from_slice(&pred[dy * 8..dy * 8 + 8]);
                }
            }
            Some(scan8) => {
                let raster = un_scan_8x8(scan8);
                let res8 = self.inv_quant8(&raster, qp, 0);
                // Written once rather than zeroed-then-filled.
                let predb: [i32; 64] = core::array::from_fn(|i| pred[i] as i32);
                let recon = add_residual_8x8(&res8, &predb);
                // ROW COPIES, NOT PER-PIXEL STORES. This wrote all 64 samples
                // one at a time, each separately bounds-checked, where the
                // destination is eight contiguous 8-byte runs `cw` apart.
                // REFUTED, do not retry: replacing this WINDOW + sub-slice with
                // eight direct `rec_y[d..][..8]` slices left the panic count
                // EXACTLY unchanged (12) and cost +3.0% instructions. Neither
                // form folds the check, but the window amortises the base
                // address computation across the eight rows. (Contrast
                // `gather_tile`, where a window cost +57.6% — a window pays only
                // when the rows it spans are written in one tight loop.)
                let (cw, base) = (self.cw, py * self.cw + px);
                let win = &mut self.rec_y[base..base + 7 * cw + 8];
                for dy in 0..8 {
                    win[dy * cw..dy * cw + 8].copy_from_slice(&recon[dy * 8..dy * 8 + 8]);
                }
            }
        }
    }

    /// I_16x16 luma: neighbor gather + prediction + the 16 4x4 AC blocks
    /// with the DC-only collapse. `q_blocks` = RASTER AC (slot 0 unused),
    /// `recon_dc` = the Hadamard-dequantized DC per block. Marks modes_y
    /// (I_16x16 predicts as DC for neighbors) + coded_y.
    #[allow(clippy::too_many_arguments)]
    fn recon_i16_luma(&mut self, mbx: usize, mby: usize, pred_mode: rusty_h264_common::predict::I16Mode, top_ok: bool, left_ok: bool, q_blocks: Option<&[[i32; 16]; 16]>, recon_dc: &[i32; 16], qp: u8) {
        // `None` on a DC-only I_16x16 macroblock (CodedBlockPatternLuma == 0):
        // no AC was parsed, so the shared zero plane is read-equivalent to the
        // 1 KB of stack this used to zero per macroblock.
        let q_blocks = q_blocks.unwrap_or(&ZERO_LUMA_SCAN);
        let w4 = self.mb_w * 4;
        let (lx, ly) = (mbx * 16, mby * 16);
        let mut t16 = [0u8; 16];
        let mut l16 = [0u8; 16];
        if top_ok {
            t16.copy_from_slice(self.top_y_row(ly, lx, 16));
        }
        if left_ok {
            // ONE check for the 16-sample column (see `gather_i4`).
            // `step_by` walk rather than a span + `col[i * cw]` (see `gather_i8`):
            // the span form's inner index stayed checked on all sixteen samples.
            let (cw, base) = (self.cw, ly * self.cw + lx - 1);
            for (s, &v) in l16.iter_mut().zip(self.rec_y[base..].iter().step_by(cw)) {
                *s = v;
            }
        }
        let corner = if top_ok && left_ok { self.top_y_px(ly, lx - 1) } else { 0 };
        let pred_l = luma16x16_pred(pred_mode, top_ok, left_ok, &t16, &l16, corner);
        for by in 0..4 {
            for bx in 0..4 {
                let p_off = (by * 4) * 16 + bx * 4;
                let r_off = (ly + by * 4) * self.cw + lx + bx * 4;
                if q_blocks[(by & 3) * 4 + (bx & 3)] == [0i32; 16] {
                    // Zero AC: the residual is the Hadamard DC alone.
                    edcstat::bump(&edcstat::I16_DCONLY, 1);
                    reconstruct_4x4_dc_into((recon_dc[by * 4 + bx] + 32) >> 6, &pred_l, p_off, 16, &mut self.rec_y, r_off, self.cw);
                } else {
                    let mut deq = self.dequant(&q_blocks[(by & 3) * 4 + (bx & 3)], qp, 0);
                    deq[0] = recon_dc[by * 4 + bx];
                    reconstruct_4x4_into(&deq, &pred_l, p_off, 16, &mut self.rec_y, r_off, self.cw);
                }
            }
        }
        // ROW FILLS. The mode/coded grids were written one 4x4 cell at a time
        // inside the recon loop; each macroblock row is four CONTIGUOUS cells,
        // so four fills replace sixteen indexed stores.
        for by in 0..4 {
            let r = (mby * 4 + by) * w4 + mbx * 4;
            self.modes_y[r..r + 4].fill(2);
            self.coded_y[r..r + 4].fill(true);
        }
    }

    /// Chroma 8x8 recon, both planes: prediction + four 4x4 blocks per
    /// plane with the DC-only collapse. `qac` = RASTER AC per plane/block
    /// (all-zero when uncoded), `dc` = the 2x2-Hadamard-dequantized DC.
    #[allow(clippy::too_many_arguments)]
    fn recon_chroma_blocks(&mut self, mb_x: usize, mb_y: usize, chroma_mode: u8, avail_top: bool, avail_left: bool, qac: &[[[i32; 16]; 4]; 2], dc: &[[i32; 4]; 2], qpc: u8) {
        let (cx, cy) = (mb_x * 8, mb_y * 8);
        for c in 0..2 {
            let mut ctop = [0u8; 8];
            let mut cleft = [0u8; 8];
            let mut ccorner = 0u8;
            {
                let rec_c = if c == 0 { &self.rec_u } else { &self.rec_v };
                if avail_top {
                    ctop.copy_from_slice(self.top_c_row(c, cy, cx, 8));
                }
                if avail_left {
                    // Strided WALK, as in `gather_i4`/`gather_i8`.
                    let cbase = cy * self.ccw + cx - 1;
                    for (o, &v) in cleft.iter_mut().zip(rec_c[cbase..].iter().step_by(self.ccw)) {
                        *o = v;
                    }
                }
                if avail_top && avail_left {
                    ccorner = self.top_c_px(c, cy, cx - 1);
                }
            }
            let pred8 = chroma8x8_pred(chroma_mode, avail_top, avail_left, &ctop, &cleft, ccorner);
            for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                let p_off = (by * 4) * 8 + bx * 4;
                let ccw = self.ccw;
                let r_off = (cy + by * 4) * ccw + cx + bx * 4;
                if qac[c & 1][(by * 2 + bx) & 3] == [0i32; 16] {
                    // Zero AC (cbp_chroma <= 1, the common case): DC-alone flat add.
                    edcstat::bump(&edcstat::I16_DCONLY, 1);
                    let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                    reconstruct_4x4_dc_into((dc[c & 1][(by * 2 + bx) & 3] + 32) >> 6, &pred8, p_off, 8, plane, r_off, ccw);
                } else {
                    let mut deq = self.dequant(&qac[c & 1][(by * 2 + bx) & 3], qpc, 1 + c);
                    deq[0] = dc[c & 1][(by * 2 + bx) & 3];
                    let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                    reconstruct_4x4_into(&deq, &pred8, p_off, 8, plane, r_off, ccw);
                }
            }
        }
    }

    fn recon_chroma_cabac(
        &mut self,
        mb_x: usize,
        mb_y: usize,
        chroma_mode: u8,
        cdc: &[[i32; 4]; 2],
        cac: Option<&[[[i32; 16]; 4]; 2]>,
        cbp_chroma: u32,
        avail_top: bool,
        avail_left: bool,
    ) {
        // `None` = no chroma AC was parsed; every read below is already gated
        // on cbp_chroma == 2, so the shared zero plane is read-equivalent.
        let cac = cac.unwrap_or(&ZERO_CAC);
        let qpc = self.chroma_qp_for(self.cur_qp);
        let mut c_dc = [[0i32; 4]; 2];
        if cbp_chroma != 0 {
            for c in 0..2 {
                c_dc[c] = self.dequant_chroma_dc(&cdc[c], qpc, 1 + c);
            }
        }
        // ENTROPY-SIDE half: un-scan the AC into raster + commit nnz_c; the
        // pixel half is the SHARED recon_chroma_blocks.
        let w2 = self.mb_w * 2;
        let mut qac = [[[0i32; 16]; 4]; 2];
        if cbp_chroma == 2 {
            for c in 0..2 {
                for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                    let cnt = cac[c & 1][(by * 2 + bx) & 3].iter().filter(|&&v| v != 0).count() as u8;
                    if let Some(p) = self.nnz_c[c & 1].get_mut((mb_y * 2 + by) * w2 + (mb_x * 2 + bx)) {
                        *p = cnt;
                    }
                    // Zero-skip: empty AC leaves the fresh-zero raster block.
                    if cnt != 0 {
                        un_scan_4x4_ac_into(&cac[c & 1][(by * 2 + bx) & 3], &mut qac[c & 1][(by * 2 + bx) & 3]);
                    }
                }
            }
        }
        self.recon_chroma_blocks(mb_x, mb_y, chroma_mode, avail_top, avail_left, &qac, &c_dc, qpc);
    }

    /// D14 — the CAVLC E-seam (P3 item 5). Mirrors `decode_slice_data_cabac`:
    /// overlap parse (this thread) with pixel reconstruction (a scoped worker
    /// owning the planes). Now possible because the CAVLC inter recon was
    /// converged onto `add_inter_residual`, so both entropy coders emit the SAME
    /// `PInterJob` and share one worker recon.
    pub fn decode_slice_data(
        &mut self,
        r: &mut BitReader,
        is_p: bool,
        first_mb: usize,
    ) -> Result<usize, MbError> {
        // Same cross-slice guard as the CABAC loop head.
        self.span_flush();
        let eligible = edc_on() && rowdb_on() && (is_p || self.is_b);
        let threaded = eligible && edc_spawn_worker(self.mb_w, self.mb_h, self.bits_per_mb, false);
        edcstat::bump(&edcstat::DISPATCH_ON, threaded as u64);
        edcstat::bump(&edcstat::DISPATCH_SEEN, eligible as u64);
        if !threaded {
            return self.decode_slice_cavlc_inner(r, is_p, first_mb);
        }
        let ctx = self.edc_take_ctx();
        let (tx, rx) = std::sync::mpsc::sync_channel::<EdcMsg>(edc_bound());
        let (ctx_tx, ctx_rx) = std::sync::mpsc::channel::<PixelCtx>();
        let (back_tx, back_rx) = std::sync::mpsc::channel::<PixelCtx>();
        let (res, ctx, panicked) = std::thread::scope(|sc| {
            let h = sc.spawn(move || edc_worker(ctx, rx, ctx_tx, back_rx));
            self.edc_tx = Some(tx);
            self.edc_ctx_rx = Some(ctx_rx);
            self.edc_back_tx = Some(back_tx);
            // UNWIND SAFETY (same trap the CABAC wrapper documents): the sender
            // lives in `self`, which outlives an unwind, so a panic in the parse
            // loop would leave the channel open, the worker alive and the scope
            // join blocking forever — turning a diagnosable panic into a silent
            // deadlock. Catch, clean up, join, restore, THEN resume.
            let r2 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                self.decode_slice_cavlc_inner(r, is_p, first_mb)
            }));
            self.edc_flush_batch();
            self.edc_giveback();
            self.edc_tx = None;
            self.edc_ctx_rx = None;
            self.edc_back_tx = None;
            match (r2, h.join()) {
                (Ok(res), Ok(ctx)) => (res, Some(ctx), None),
                (Err(pn), Ok(ctx)) => (Err(MbError::Truncated), Some(ctx), Some(pn)),
                (Ok(_), Err(pn)) | (Err(_), Err(pn)) => (Err(MbError::Truncated), None, Some(pn)),
            }
        });
        if let Some(ctx) = ctx {
            self.edc_restore_ctx(ctx);
        }
        if let Some(pn) = panicked {
            std::panic::resume_unwind(pn);
        }
        res
    }

    fn decode_slice_cavlc_inner(
        &mut self,
        r: &mut BitReader,
        is_p: bool,
        first_mb: usize,
    ) -> Result<usize, MbError> {
        let total = self.mb_w * self.mb_h;
        self.slice_first_mb = first_mb;
        self.slice_bounds.push((first_mb, self.cur_idc2));
        self.any_idc2 |= self.cur_idc2;
        self.edc_active = edc_on();
        let mut addr = first_mb;
        // Same malformed-header divide-by-zero as the sibling slice loop above.
        let mbw_nz = self.mb_w.max(1);
        let (mut mbx, mut mby) = (addr % mbw_nz, addr / mbw_nz);
        let mbw_c = self.mb_w;
        while addr < total {
            if mbx == mbw_c {
                mbx = 0;
                mby += 1;
            }
            self.row_hook_at(addr, mby);
            if is_p || self.is_b {
                let skip_run = {
                    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
                    r.read_ue()?
                } as usize;
                // A run past the picture end is a corrupt stream (ffmpeg errors
                // here too); a run TO the end is legal. Silently clamping used
                // to fill the remainder with skip MBs.
                if skip_run > total - addr {
                    return Err(MbError::Truncated);
                }
                // The run length is KNOWN here (CAVLC codes it as one syntax
                // element). P runs: after the first skip commits (0,0), every
                // later run MB is FORCED (0,0) by the zero-MV rule — process
                // the remainder SEGMENT-WISE: one span extension + one mb_qp
                // fill per row segment instead of a per-MB call + span match +
                // store. Non-(0,0) runs and B runs keep the per-MB loop. The
                // per-MB `addr >= total` check is gone: the run was validated
                // against `total - addr` above.
                let mut remaining = skip_run;
                while remaining > 0 {
                    debug_assert!(addr < total);
                    if mbx == mbw_c {
                        mbx = 0;
                        mby += 1;
                    }
                    if self.is_b {
                        if !self.b_skip_hot(mbx, mby) {
                            self.decode_b_skip(mbx, mby)?;
                        }
                        if let Some(p) = self.mb_qp.get_mut(addr) {
                            *p = self.cur_qp;
                        } // skip inherits QPy
                        addr += 1;
                        mbx += 1;
                        remaining -= 1;
                        continue;
                    }
                    self.decode_p_skip(mbx, mby)?;
                    if let Some(p) = self.mb_qp.get_mut(addr) {
                        *p = self.cur_qp;
                    }
                    addr += 1;
                    mbx += 1;
                    remaining -= 1;
                    // Segment-wise remainder: forced (0,0) continuation holds
                    // exactly while skip_zero_next tracks addr (decode_p_skip
                    // set it iff this skip committed (0,0)).
                    // Worker mode (edc_tx) must route per-MB jobs through the
                    // channel — the parse thread no longer owns the planes.
                    while remaining > 0
                        && self.skip_zero_next == addr
                        && !self.k_no_runmv
                        && self.edc_tx.is_none()
                    {
                        if mbx == mbw_c {
                            mbx = 0;
                            mby += 1;
                        }
                        // Row segment: run to row end or run end.
                        let seg = remaining.min(mbw_c - mbx);
                        let recon = self.edc_tx.is_none()
                            && (self.weights.is_none() || self.weights_id0);
                        for k in 0..seg {
                            self.pz_push(mbx + k, mby, recon);
                        }
                        edcstat::bump(&edcstat::SKIPMV_FORCED, seg as u64);
                        self.route_skip_mbs += seg as u32;
                        self.mb_qp[addr..addr + seg].fill(self.cur_qp);
                        if !recon {
                            for k in 0..seg {
                                self.edc_jobs.push(EdcJob::Skip { mbx: mbx + k, mby, mv: (0, 0) });
                            }
                        }
                        addr += seg;
                        mbx += seg;
                        remaining -= seg;
                        self.skip_zero_next = addr;
                    }
                }
                if addr >= total {
                    break;
                }
                // A trailing skip run with no following macroblock ends the slice.
                if skip_run > 0 && !r.more_rbsp_data() {
                    break;
                }
            }
            // The skip run above may have crossed a row boundary within this
            // iteration — wrap before the non-skip MB decodes.
            if mbx == mbw_c {
                mbx = 0;
                mby += 1;
            }
            if self.is_b {
                // ORDER: B reconstructs inline (not seam-ready).
                self.edc_intra_sync();
                self.decode_b_mb(r, mbx, mby)?;
            } else {
                // Non-skip CAVLC MB: inter MV prediction + intra gathers
                // read the grids — flush deferred spans.
                self.span_flush();
                self.decode_mb(r, mbx, mby, is_p)?;
            }
            if let Some(p) = self.mb_qp.get_mut(addr) {
                *p = self.cur_qp;
            }
            addr += 1;
            mbx += 1;
            // CAVLC slice end: no more data after this macroblock.
            if !r.more_rbsp_data() {
                break;
            }
        }
        self.edc_flush(); // slice end: no job crosses a slice boundary
        Ok(addr)
    }

    fn decode_mb(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        is_p: bool,
    ) -> Result<(), MbError> {
        self.wait_refs_for_mb(mb_y);
        let mut mb_type = {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
            r.read_ue()?
        };
        if is_p {
            // In P-slices, mb_type 0/1/2 are inter (16×16, 16×8, 8×16),
            // 3 = P_8x8, 4 = P_8x8ref0 (ref_idx forced 0), 5+ intra.
            if mb_type <= 2 {
                return self.decode_inter(r, mb_x, mb_y, mb_type as u8);
            }
            if mb_type == 3 || mb_type == 4 {
                return self.decode_p8x8(r, mb_x, mb_y, mb_type == 4);
            }
            mb_type -= 5;
        }
        // ORDER: intra reconstruction reads neighbour PIXELS, so the worker
        // must have applied every deferred job before this point.
        self.edc_intra_sync();
        self.decode_intra_mb(r, mb_x, mb_y, mb_type)
    }

    /// Decodes an intra macroblock given its intra `mb_type` (0 = I_4x4,
    /// 1..=24 = I_16x16, 25 = I_PCM) — shared by I-, P- and B-slice paths.
    fn decode_intra_mb(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        mb_type: u32,
    ) -> Result<(), MbError> {
        // H-48: this scope was DECLARED and never wired, which is precisely why the
        // stage table left 19.8% unaccounted — 66,120 of 475,200 macroblocks on the
        // reference stream are I-type and had no scope at all.
        let _gi = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMbI);
        if let Some(p) = self.mb_kind.get_mut(mb_y * self.mb_w + mb_x) {
            *p = rusty_h264_common::deblock::MB_KIND_INTRA;
        }
        if mb_type == 0 {
            // I_NxN: transform_size_8x8_flag (when enabled) selects I_8x8 vs I_4x4.
            if self.transform_8x8_mode && r.read_bit()? {
                self.decode_i8x8(r, mb_x, mb_y)?;
            } else {
                self.decode_i4x4(r, mb_x, mb_y)?;
            }
        } else if (1..=24).contains(&mb_type) {
            self.decode_i16(r, mb_x, mb_y, mb_type - 1)?;
        } else if mb_type == 25 {
                        // ORDER: I_PCM writes pixels directly.
            self.edc_intra_sync();
            self.decode_ipcm(r, mb_x, mb_y)?;
        } else {
            return Err(MbError::Unsupported("only I_4x4 / I_16x16 / I_PCM macroblocks"));
        }
        // Mark all luma blocks coded for the next macroblock's top-right.
        // Four contiguous cells per macroblock row - `fill`, not sixteen
        // separately bounds-checked indexed stores.
        let w4 = self.mb_w * 4;
        for lby in 0..4usize {
            let a = (mb_y * 4 + lby) * w4 + mb_x * 4;
            self.coded_y[a..a + 4].fill(true);
        }
        Ok(())
    }

    /// Reconstructs an inter macroblock (`mode` 0 = P_L0_16x16, 1 = P_16x8,
    /// 2 = P_8x16): parse the per-partition motion vectors and residual,
    /// motion-compensate each partition, and add the residual.
    fn decode_inter(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        mode: u8,
    ) -> Result<(), MbError> {
        if self.refs.is_empty() {
            return Err(MbError::Unsupported("inter without reference"));
        }
        // DEBLOCK CLASS: mode 0 is P_L0_16x16 — ONE partition, so all 16 blocks
        // share a reference and motion vector and no internal edge can reach
        // strength 1. Internal strengths then follow from coefficients alone, i.e.
        // 16 nnz bytes instead of a 24-block gather across 5-7 grids. Modes 1/2
        // (P_16x8 / P_8x16) have two partitions with independent motion and stay
        // UNSET (blind path).
        if mode == 0 {
            if let Some(k) = self.mb_kind.get_mut(mb_y * self.mb_w + mb_x) {
                *k = rusty_h264_common::deblock::MB_KIND_INTER_UNIFORM;
            }
        }
        // QP (qp/qpc) is bound after mb_qp_delta is read below.
        let w4 = self.mb_w * 4;
        let (ch, cch) = (self.mb_h * 16, self.mb_h * 8);
        let num_refs = self.refs.len();
        let layout = inter_partitions(mode);

        // mb_pred order (spec 7.3.5.1): all ref_idx_l0 first (only when more than
        // one reference is active), then all mvd_l0.
        let nparts = layout.len();
        let mut ref_idxs = [0i32; 4];
        if self.num_ref_active > 1 {
            for ri in ref_idxs[..nparts].iter_mut() {
                *ri = read_ref_idx(r, self.num_ref_active)?;
                if *ri as usize >= num_refs {
                    return Err(MbError::Truncated); // references a non-existent picture
                }
            }
        }

        // Phase 1: per partition, ref-aware MV prediction + mvd, committing the
        // motion grid so a later partition predicts from an earlier one.
        let mut part_mv = [(0i32, (0i32, 0i32)); 4];
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::MvGrid);
            for (part, &(rx, ry, rw, rh)) in layout.iter().enumerate() {
                let refi = ref_idxs[part];
                let (pbx, pby) = ((mb_x * 4 + rx / 4) as isize, (mb_y * 4 + ry / 4) as isize);
                let [a, b, c] = self.mv_neighbors_block(pbx, pby, (rw / 4) as isize);
                let pmv = predict_partition_mv(mode, part, a, b, c, refi);
                let mvd_x = read_mvd(r)?;
                let mvd_y = read_mvd(r)?;
                let mv = (pmv.0 + mvd_x, pmv.1 + mvd_y);
                part_mv[part] = (refi, mv);
                for by in ry / 4..ry / 4 + rh / 4 {
                    for bx in rx / 4..rx / 4 + rw / 4 {
                        let idx = (mb_y * 4 + by) * w4 + (mb_x * 4 + bx);
                        if let (Some(m), Some(it), Some(rf), Some(cd)) = (
                            self.mv_y.get_mut(idx),
                            self.inter_y.get_mut(idx),
                            self.ref_idx_y.get_mut(idx),
                            self.coded_y.get_mut(idx),
                        ) {
                            (*m, *it, *rf, *cd) = (mv, true, refi, true);
                        }
                    }
                }
            }
        }

        // Phase 2: motion-compensate each partition from its reference.
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        // D8-CAVLC: the double-stage ablation, extended to the CAVLC loop. The
        // CABAC measurement could not run here at all (`edc_active` is false on
        // this path, so nothing replays through `edc_flush` and `doubled` read
        // 0) — yet CAVLC is exactly the population P3 item 5 targets, and its
        // cheaper parse should make the PIXEL share larger. Doubling the whole
        // partition loop is idempotent: pass 2 overwrites `pred_y` with fresh MC
        // BEFORE `weight_partition` runs, so weighting cannot apply twice.
        // This doubles MC only (not the residual add inside `inter_finish`), so
        // it is a LOWER BOUND on the CAVLC pixel share.
        // D14 (CAVLC E-seam): when the seam is live the WORKER motion-compensates
        // from the committed MV grids, so skip MC here rather than computing a
        // prediction that would be discarded.
        let defer = self.edc_tx.is_some() || self.edc_active;
        let mc_passes = if defer { 0 } else if double_recon() { 2 } else { 1 };
        for _pass in 0..mc_passes {
        if _pass > 0 {
            edcstat::bump(&edcstat::DOUBLED, 1);
        }
        for (part, &(rx, ry, rw, rh)) in layout.iter().enumerate() {
            let (refi, mv) = part_mv[part & 3];
            let Some(reference) = self.refs.get(refi as usize) else { continue };
            let mut tmp = [0u8; 256];
            mc_luma_padded(&*reference.luma_guard(reference.ch), reference.lstride(), crate::LPAD, self.cw, ch, mb_x * 16 + rx, mb_y * 16 + ry, rw, rh, mv.0, mv.1, &mut tmp);
            {
                let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
                restride(&mut pred_y, 16, rx, ry, &tmp, rw, rh);
            }
            let (crx, cry, crw, crh) = (rx / 2, ry / 2, rw / 2, rh / 2);
            for cc in 0..2 {
                let rc = if cc == 0 { &*reference.chroma_guard(0, reference.ch) } else { &*reference.chroma_guard(1, reference.ch) };
                let mut tc = [0u8; 64];
                mc_chroma_padded(rc, reference.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8 + crx, mb_y * 8 + cry, crw, crh, mv.0, mv.1, &mut tc);
                {
                    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
                    restride(&mut c_pred[cc], 8, crx, cry, &tc, crw, crh);
                }
            }
            self.weight_partition(&mut pred_y, &mut c_pred, 0, refi as usize, rx, ry, rw, rh);
        }
        }

        // 16×16/16×8/8×16 partitions are all ≥ 8×8, so the 8×8 transform is allowed.
        self.inter_finish(r, mb_x, mb_y, &pred_y, &c_pred, true, defer)
    }

    /// Shared inter tail: parse `coded_block_pattern` + `mb_qp_delta`, decode the
    /// luma/chroma residual, and add it to the already-built motion-compensated
    /// prediction. Used by both the 16×16/16×8/8×16 path and `P_8x8`.
    fn inter_finish(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        pred_y: &[u8; 256],
        c_pred: &[[u8; 64]; 2],
        allow_8x8: bool,
        // D14: emit a worker job instead of reconstructing. Only the CAVLC
        // 16x16/16x8/8x16 path sets this; B and P_8x8 stay inline.
        defer: bool,
    ) -> Result<(), MbError> {
        let vt = vlc_tables();
        let w4 = self.mb_w * 4;
        let cbp = {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
            read_cbp_inter(r)?
        };
        let cbp_luma = cbp & 15;
        let cbp_chroma = cbp >> 4;
        // transform_size_8x8_flag follows cbp (before mb_qp_delta) when luma has
        // coefficients, the 8×8 transform is enabled, and every partition ≥ 8×8.
        let t8x8 = cbp_luma > 0 && self.transform_8x8_mode && allow_8x8 && r.read_bit()?;
        if t8x8 {
            if let Some(f) = self.mb_t8x8.get_mut(mb_y * self.mb_w + mb_x) {
                *f = true;
            }
            self.any_t8 = true;
        }
        if cbp != 0 {
            self.step_qp(r.read_se()?)?;
        }
        let (qp, _qpc) = (self.cur_qp, self.chroma_qp_for(self.cur_qp));

        // ---- luma residual ----
        self.nnz_cache_load(mb_x, mb_y);
        let mut luma_scan = [[0i32; 16]; 16];
        let mut nnzs = [0u8; 24];
        let mut luma8: Option<[[i32; 64]; 4]> = None; // allocated only under t8x8
        // BUILD THE MACROBLOCK'S nnz RASTER ON THE STACK, COPY IT ROW-WISE ONCE.
        // Both arms below scattered sixteen individually bounds-checked stores
        // into the frame grid while the entropy parse ran. Nothing reads
        // `nnz_y` for THIS macroblock before the function returns - `nc_pred`
        // predicts from the separate `nnz_cache` - so the writes can be
        // deferred. The zero arm then costs NOTHING: the raster already holds
        // zeros.
        let mut nnz_raster = [0u8; 16];
        if t8x8 {
            for b8 in 0..4 {
                let (b8x, b8y) = (b8 % 2, b8 / 2);
                let (bx, by) = (mb_x * 4 + b8x * 2, mb_y * 4 + b8y * 2);
                let _ = (bx, by);
                if cbp_luma & (1 << b8) != 0 {
                    let mut scan8 = [0i32; 64];
                    for sub in 0..4 {
                        let (sx, sy) = (sub % 2, sub / 2);
                        let (cx, cy) = (b8x * 2 + sx, b8y * 2 + sy);
                        let nc = self.nc_pred(cx, cy);
                        let (blk, total) = decode_residual_block_with(vt, r, 16, nc)?;
                        self.nnz_cache_set(cx, cy, total);
                        nnz_raster[cy * 4 + cx] = total;
                        // The PER-SUB-BLOCK count the next macroblock's nC prediction
                        // depends on -- summing these into one slot and letting the
                        // recon helper broadcast it back is what broke CAVLC 8x8.
                        nnzs[b8 * 4 + sub] = total;
                        for k in 0..16 {
                            scan8[4 * k + sub] = blk[k];
                        }
                    }
                    // RAW: `add_inter_residual` applies un_scan_8x8 + inv_quant8
                    // itself, exactly as it does for the CABAC path.
                    luma8.get_or_insert_with(|| [[0i32; 64]; 4])[b8] = scan8;
                } else {
                    for sub in 0..4 {
                        let (sx, sy) = (sub % 2, sub / 2);
                        self.nnz_cache_set(b8x * 2 + sx, b8y * 2 + sy, 0);
                        // `nnz_raster` is already zero here - no store needed.
                    }
                }
            }
        } else {
            for (blk, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
                let (bx, by) = (mb_x * 4 + lbx, mb_y * 4 + lby);
                let total = if cbp_luma & (1 << (blk / 4)) != 0 {
                    let nc = self.nc_pred(lbx, lby);
                    let (scan16, total) = decode_residual_block_with(vt, r, 16, nc)?;
                    luma_scan[blk] = scan16; // RAW scan order, like CABAC
                    total
                } else {
                    0
                };
                self.nnz_cache_set(lbx, lby, total);
                let _ = (bx, by);
                nnz_raster[(lby & 3) * 4 + (lbx & 3)] = total;
                nnzs[blk] = total;
            }
        }
        // ONE contiguous copy per macroblock row.
        for by in 0..4usize {
            let a = (mb_y * 4 + by) * w4 + mb_x * 4;
            self.nnz_y[a..a + 4].copy_from_slice(&nnz_raster[by * 4..by * 4 + 4]);
        }

        // ---- chroma residual ----
        let mut c_recon_dc = [[0i32; 4]; 2];
        if cbp_chroma != 0 {
            for slot in c_recon_dc.iter_mut() {
                let (dc, _) = decode_residual_block_with(vt, r, 4, -1)?;
                *slot = [dc[0], dc[1], dc[2], dc[3]]; // RAW; dequantised in the helper
            }
        }
        let mut c_q = [[[0i32; 16]; 4]; 2];
        if cbp_chroma == 2 {
            self.chroma_cache_load(mb_x, mb_y);
            let w2 = self.mb_w * 2;
            let mut cnnz = [[0u8; 4]; 2];
            for c in 0..2 {
                for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                    let nc = self.chroma_nc_pred(c, bx, by);
                    let (ac, total) = decode_residual_block_with(vt, r, 15, nc)?;
                    self.chroma_nnz_cache_set(c, bx, by, total);
                    cnnz[c][by * 2 + bx] = total;
                    c_q[c][by * 2 + bx] = ac; // RAW scan order
                    nnzs[(16 + c * 4 + by * 2 + bx).min(23)] = total;
                }
                for by in 0..2usize {
                    let a = (mb_y * 2 + by) * w2 + mb_x * 2;
                    self.nnz_c[c][a..a + 2].copy_from_slice(&cnnz[c][by * 2..by * 2 + 2]);
                }
            }
        }

        // ---- reconstruction ----
        //
        // D13: this used to be a 109-line hand-rolled copy of the residual add.
        // It now calls the SAME `add_inter_residual` the CABAC path uses, which
        // is what makes the CAVLC E-seam possible at all: the two paths had
        // different residual representations (CAVLC pre-applied un_scan and
        // inv_quant at PARSE time; CABAC carries raw scan-order coefficients and
        // dequantises inside the helper), so no job could be shared. Carrying the
        // raw forms — which CAVLC already had in hand — converges them, deletes
        // a duplicate implementation, and lets a deferred job reuse the existing
        // worker recon instead of needing a second copy that could drift.
        if defer {
            // The residual representation now matches CABAC exactly (the
            // convergence commit), so the SAME `PInterJob` and the SAME worker
            // `recon_p_inter` serve both entropy coders — no second recon
            // implementation exists that could drift.
            let (mut gmv, mut gref) = ([(0i32, 0i32); 16], [0u8; 16]);
            let w4r = self.mb_w * 4;
            // ROW SLICES over BOTH grids. This was the single densest panic site
            // left in the decoder crate: sixteen iterations reading two PARALLEL
            // frame grids at the same index, and `mv_y`'s bound proved nothing
            // about `ref_idx_y`, so all thirty-two loads carried their own check.
            // Each macroblock row is four contiguous cells in both.
            for by in 0..4usize {
                let base = (mb_y * 4 + by) * w4r + mb_x * 4;
                let mvr = &self.mv_y[base..][..4];
                let rfr = &self.ref_idx_y[base..][..4];
                gmv[by * 4..][..4].copy_from_slice(mvr);
                for bx in 0..4usize {
                    gref[by * 4 + bx] = rfr[bx].clamp(0, 15) as u8;
                }
            }
            // D9 applies here too: `cbp == 0` means all 2,592 coefficient bytes
            // of the 2,784-byte job are ZERO, so ship the 176-byte motion-only
            // form. Discovered on the CABAC path; it transfers for free because
            // the CAVLC arm now emits the SAME job type.
            let ej = if cbp == 0 && nores_on() {
                edcstat::bump(&edcstat::J_NORES_SENT, 1);
                EdcJob::InterNoRes(Box::new(PInterNoResJob {
                    mbx: mb_x, mby: mb_y, t8: t8x8, gmv, gref,
                }))
            } else {
                EdcJob::Inter(Box::new(PInterJob {
                    mbx: mb_x, mby: mb_y, qp,
                    cbp_chroma, gmv, gref,
                    luma_scan: Some(luma_scan), luma8, cdc: c_recon_dc, cac: Some(c_q), nnzs,
                }))
            };
            if self.edc_tx.is_some() {
                self.edc_giveback();
                self.edc_send_job(ej);
            } else {
                self.edc_jobs.push(ej);
            }
        } else {
            self.add_inter_residual(
                mb_x, mb_y, pred_y, c_pred, Some(&luma_scan),
                luma8.as_ref(),
                &c_recon_dc, Some(&c_q), cbp_chroma, &nnzs,
            );
        }

        // MV grid + coded flags were set per partition; mark modes as DC.
        // Four contiguous cells per row - `fill`, not sixteen indexed stores.
        for lby in 0..4usize {
            let a = (mb_y * 4 + lby) * w4 + mb_x * 4;
            self.modes_y[a..a + 4].fill(2);
        }
        Ok(())
    }

    // ---------------------------------------------------------------------
    // B-slice macroblock decoding
    // ---------------------------------------------------------------------

    /// Per-list (`list` 0 or 1) MV-prediction neighbors for the block region at
    /// `(pbx, pby)` of width `pwb` blocks — the L0/L1 analogue of
    /// `mv_neighbors_block`.
    fn mv_neighbors_list(&self, pbx: isize, pby: isize, pwb: isize, list: usize) -> [MvNeighbor; 3] {
        self.mv_neighbors_block_grid(pbx, pby, pwb, list)
    }

    /// Spatial-direct A/B/C at the MB origin — same for every 8×8 in the MB
    /// (spec §8.4.1.2.2). B_8x8 callers hoist this once; 16×16 skip/direct walk
    /// once inside `decode_b_direct`.
    #[inline]
    fn b_direct_nbrs(&self, mb_x: usize, mb_y: usize) -> ([MvNeighbor; 3], [MvNeighbor; 3]) {
        self.mv_neighbors_both((mb_x * 4) as isize, (mb_y * 4) as isize, 4)
    }

    /// FUSED dual-list gather at arbitrary partition geometry: A/B/C positions
    /// and their availability (bounds + coded + slice) are list-independent —
    /// compute once, load both lists' grids from the same resolved index.
    fn mv_neighbors_both(&self, pbx: isize, pby: isize, pwb: isize) -> ([MvNeighbor; 3], [MvNeighbor; 3]) {
        let (w4, h4) = ((self.mb_w * 4) as isize, (self.mb_h * 4) as isize);
        let get2 = |bx: isize, by: isize| -> (MvNeighbor, MvNeighbor) {
            if bx < 0
                || by < 0
                || bx >= w4
                || by >= h4
                || !self.coded_y.get((by * w4 + bx) as usize).copied().unwrap_or(false)
                || !self.nbr_in_slice(bx as usize / 4, by as usize / 4)
            {
                (MvNeighbor::NONE, MvNeighbor::NONE)
            } else {
                // FOUR PARALLEL GRIDS at one index. The `coded_y` guard above
                // bounds none of them — they are separate Vecs — so each carried
                // its own panic path. `MvNeighbor::NONE` is the established
                // "no such neighbour" value, so the fallible form degrades into
                // the branch directly above it.
                let idx = (by * w4 + bx) as usize;
                match (self.mv_y.get(idx), self.ref_idx_y.get(idx), self.mv1.get(idx), self.ref_idx1.get(idx)) {
                    (Some(&m0), Some(&r0), Some(&m1), Some(&r1)) => (
                        MvNeighbor { available: true, mv: m0, ref_idx: r0 },
                        MvNeighbor { available: true, mv: m1, ref_idx: r1 },
                    ),
                    _ => (MvNeighbor::NONE, MvNeighbor::NONE),
                }
            }
        };
        let (a0, a1) = get2(pbx - 1, pby);
        let (b0, b1) = get2(pbx, pby - 1);
        let (mut c0, mut c1) = get2(pbx + pwb, pby - 1);
        if !c0.available {
            // The C fallback is position-driven (topright unavailable ⇒
            // topleft), so both lists fall back together — same decision the
            // two per-list gathers made independently.
            let t = get2(pbx - 1, pby - 1);
            c0 = t.0;
            c1 = t.1;
        }
        ([a0, b0, c0], [a1, b1, c1])
    }

    fn mv_neighbors_block_grid(&self, pbx: isize, pby: isize, pwb: isize, list: usize) -> [MvNeighbor; 3] {
        let (w4, h4) = ((self.mb_w * 4) as isize, (self.mb_h * 4) as isize);
        let (mvg, refg) = if list == 0 {
            (&self.mv_y, &self.ref_idx_y)
        } else {
            (&self.mv1, &self.ref_idx1)
        };
        let get = |bx: isize, by: isize| -> MvNeighbor {
            if bx < 0
                || by < 0
                || bx >= w4
                || by >= h4
                || !self.coded_y.get((by * w4 + bx) as usize).copied().unwrap_or(false)
                || !self.nbr_in_slice(bx as usize / 4, by as usize / 4)
            {
                MvNeighbor::NONE
            } else {
                let idx = (by * w4 + bx) as usize;
                match (mvg.get(idx), refg.get(idx)) {
                    (Some(&m), Some(&r)) => MvNeighbor { available: true, mv: m, ref_idx: r },
                    _ => MvNeighbor::NONE,
                }
            }
        };
        let a = get(pbx - 1, pby);
        let b = get(pbx, pby - 1);
        let mut c = get(pbx + pwb, pby - 1);
        if !c.available {
            c = get(pbx - 1, pby - 1);
        }
        [a, b, c]
    }

    /// `colZeroFlag` for the 4×4 block at absolute block coords `(bx, by)`: true
    /// when `RefPicList1[0]` is a short-term picture whose co-located block uses
    /// reference 0 with a near-zero motion vector (spec §8.4.1.2.2).
    /// Co-located 4x4 block coords for the current block's `(bx4, by4)` within the
    /// macroblock, per spec 8.4.1.2.1. Under `direct_8x8_inference_flag` every 4x4
    /// in an 8x8 takes that 8x8's OUTER CORNER (`luma4x4BlkIdx = 5 * mbPartIdx`,
    /// i.e. (0,0) (3,0) (0,3) (3,3)); otherwise motion is genuinely per-4x4.
    ///
    /// 8.4.1.2.1 is SHARED by both direct modes, so spatial and temporal must map
    /// identically. They did not: temporal mapped the corner and spatial read the
    /// block's own coords, which is invisible while every 4x4 in the co-located 8x8
    /// carries the same motion -- true of every stream until sub-8x8 P partitions
    /// (x264 `--partitions p4x4`) make them differ. Hence one function.
    #[inline]
    fn col_block(&self, bx4: usize, by4: usize) -> (usize, usize) {
        if self.direct_8x8_inference {
            ((bx4 / 2) * 3, (by4 / 2) * 3)
        } else {
            (bx4, by4)
        }
    }

    fn col_zero(&self, bx: usize, by: usize) -> bool {
        // Fast path (1T frozen colocated, the default): the invariant checks
        // were hoisted to set_b_context; two grid loads + the threshold test.
        if self.col_ok {
            let Some(col) = self.refs1.first() else { return false };
            let idx = by * self.col_w4 + bx;
            // `.get` on EVERY parallel array, not a length test on one of them.
            // The `idx >= ref_idx.len()` guard proved nothing about `mv`,
            // `ref_idx1` or `mv1` — separate Vecs with independent lengths — so
            // each of those reads carried its own panic path. They are built
            // together and always agree; the fallible form states that instead of
            // asserting it, and keeps the "no panic on malformed input" contract.
            let (cref, cmv) = match col.ref_idx.get(idx) {
                Some(&r0) if r0 >= 0 => match col.mv.get(idx) {
                    Some(&m) => (r0, m),
                    None => return false,
                },
                Some(_) => match (col.ref_idx1.get(idx), col.mv1.get(idx)) {
                    (Some(&r1), Some(&m)) if r1 >= 0 => (r1, m),
                    _ => return false,
                },
                None => return false,
            };
            return cref == 0 && cmv.0.abs() <= 1 && cmv.1.abs() <= 1;
        }
        let Some(col) = self.refs1.first() else { return false };
        if let Some(live) = col.live.as_ref() {
            col.wait_motion_ready();
            let meta = live.meta.read().unwrap();
            if meta.long_term || meta.w4 == 0 {
                return false;
            }
            let idx = by * meta.w4 + bx;
            // Same `.get`-per-array shape as the frozen-colocated path above.
            let (cref, cmv) = match meta.ref_idx.get(idx) {
                Some(&r0) if r0 >= 0 => match meta.mv.get(idx) {
                    Some(&m) => (r0, m),
                    None => return false,
                },
                Some(_) => match (meta.ref_idx1.get(idx), meta.mv1.get(idx)) {
                    (Some(&r1), Some(&m)) if r1 >= 0 => (r1, m),
                    _ => return false,
                },
                None => return false,
            };
            return cref == 0 && cmv.0.abs() <= 1 && cmv.1.abs() <= 1;
        }
        if col.long_term || col.w4 == 0 {
            return false;
        }
        let idx = by * col.w4 + bx;
        if idx >= col.ref_idx.len() {
            return false;
        }
        let (cref, cmv) = match col.ref_idx.get(idx) {
            Some(&r0) if r0 >= 0 => match col.mv.get(idx) {
                Some(&m) => (r0, m),
                None => return false,
            },
            Some(_) => match (col.ref_idx1.get(idx), col.mv1.get(idx)) {
                (Some(&r1), Some(&m)) if r1 >= 0 => (r1, m),
                _ => return false,
            },
            None => return false,
        };
        cref == 0 && cmv.0.abs() <= 1 && cmv.1.abs() <= 1
    }

    /// Implicit bi-prediction weights `(w0, w1)` from POC distances (spec
    /// §8.4.2.3.2), or `None` for the plain average (idc≠2, uni-pred, or the
    /// equidistant / out-of-range fall-back to 32:32 which equals the average).
    fn implicit_weights(&self, refi0: i32, refi1: i32) -> Option<(i32, i32)> {
        if self.weighted_bipred_idc != 2 || refi0 < 0 || refi1 < 0 {
            return None;
        }
        let (Some(r0), Some(r1)) = (self.refs.get(refi0 as usize), self.refs1.get(refi1 as usize))
        else {
            return None;
        };
        let td = (r1.pic_poc() - r0.pic_poc()).clamp(-128, 127);
        let tb = (self.cur_poc - r0.pic_poc()).clamp(-128, 127);
        if td == 0 || r0.long_term || r1.long_term {
            return None; // 32:32 → identical to the average
        }
        let tx = tx_for_td(td);
        let dsf = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
        let w1 = dsf >> 2;
        if !(-64..=128).contains(&w1) {
            return None; // out of range → 32:32 average
        }
        Some((64 - w1, w1))
    }

    /// Motion-compensates a region with the given per-list refs/MVs. Bi-prediction
    /// is the simple `(a+b+1)>>1` average, or POC-weighted when implicit weighting
    /// (idc 2) is active. Writes into `pred_y`/`c_pred`.
    #[allow(clippy::too_many_arguments)]
    fn b_mc(
        &self,
        mb_x: usize,
        mb_y: usize,
        px: usize,
        py: usize,
        rw: usize,
        rh: usize,
        refi0: i32,
        mv0: (i32, i32),
        refi1: i32,
        mv1: (i32, i32),
        pred_y: &mut [u8; 256],
        c_pred: &mut [[u8; 64]; 2],
    ) {
        let _gb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBMc);
        // Malformed-stream armor, mirroring the P path: now that B slices actually
        // PARSE ref_idx (they used to be hardcoded to 0), a mutated stream can hand
        // us an index past the end of either list. Clamp rather than panic — the
        // crate is `forbid(unsafe_code)` and fuzz-gated to never panic, and a
        // wrong picture on garbage input carries no conformance duty.
        let refi0 = if refi0 >= 0 { (refi0 as usize).min(self.refs.len().saturating_sub(1)) as i32 } else { -1 };
        let refi1 = if refi1 >= 0 { (refi1 as usize).min(self.refs1.len().saturating_sub(1)) as i32 } else { -1 };
        if (refi0 >= 0 && self.refs.is_empty()) || (refi1 >= 0 && self.refs1.is_empty()) {
            return;
        }
        let (ch, cch) = (self.mb_h * 16, self.mb_h * 8);
        let weights = {
            let _gw = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBWeights);
            self.implicit_weights(refi0, refi1)
        };
        // Bi-prediction blend: the weights decision is LOOP-INVARIANT, so every
        // blend site below matches on `weights` ONCE and runs a branch-free
        // pixel loop — the unweighted `(p+q+1)>>1` average then autovectorizes
        // (the per-pixel closure this replaces hid the invariant behind a
        // capture, and its chroma form was a &dyn call PER PIXEL).
        // FULL-WIDTH regions (px == 0, rw == 16 — every 16×16/16×8 partition and
        // most direct regions) occupy contiguous rows of `pred_y`, so MC writes
        // the destination DIRECTLY: uni-pred needs no staging at all, bi-pred
        // stages only the second list and blends in place. The staging arrays
        // (512 B zeroed per call before this) now exist only on the branches
        // that read them. Same fusion as the P path's mc_rect (WHYS Part 8).
        let full = px == 0 && rw == 16;
        if refi0 >= 0 && refi1 >= 0 && mv0.0 % 4 == 0 && mv0.1 % 4 == 0 && mv1.0 % 4 == 0 && mv1.1 % 4 == 0 {
            edcstat::bump(&edcstat::BMC_BI_FP, 1);
        }
        let _gl = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBLuma);
        // One scratch borrow for the whole region — both bi-pred passes included.
        // The closure yields whether the arm already ran the chroma half (the
        // bi-pred full-width arm does, to keep its staging alive) — a plain
        // `return` inside would exit the CLOSURE only and chroma would run twice.
        let chroma_done = rusty_h264_common::inter::with_mc_scratch(|scr| match (refi0 >= 0, refi1 >= 0, full) {
            (true, false, true) => {
                let Some(rf) = self.refs.get(refi0 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv0.0, mv0.1, &mut pred_y[py * 16..py * 16 + rw * rh]);
                false
            }
            (false, true, true) => {
                let Some(rf) = self.refs1.get(refi1 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv1.0, mv1.1, &mut pred_y[py * 16..py * 16 + rw * rh]);
                false
            }
            (true, true, true) => {
                let Some(rf) = self.refs.get(refi0 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv0.0, mv0.1, &mut pred_y[py * 16..py * 16 + rw * rh]);
                let mut b = [0u8; 256];
                let Some(rf) = self.refs1.get(refi1 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv1.0, mv1.1, &mut b[..rw * rh]);
                drop(_gl);
                let _gbl = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBBlend);
                // SLICE-then-zip: proving the bounds ONCE lets rustc emit the whole
                // 256-byte average as 8 straight-line vpavgb ops (verified in
                // isolation, x86-64-v3); the indexed form kept a per-iteration
                // bounds check and a loop. A hand AVX2 kernel is refuted — the
                // compiler already emits the ideal instruction.
                let dst = &mut pred_y[py * 16..py * 16 + rw * rh];
                match weights {
                    None => {
                        for (d, s) in dst.iter_mut().zip(&b[..rw * rh]) {
                            *d = ((*d as u16 + *s as u16 + 1) >> 1) as u8;
                        }
                    }
                    Some((w0, w1)) => {
                        for (d, s) in dst.iter_mut().zip(&b[..rw * rh]) {
                            *d = ((*d as i32 * w0 + *s as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                        }
                    }
                }
                let _gc = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBChroma);
                self.b_mc_chroma(mb_x, mb_y, px, py, rw, rh, refi0, mv0, refi1, mv1, c_pred, weights, cch);
                true
            }
            _ => {
                // Narrow region — rows are strided in `pred_y`; stage and copy.
                let (mut a, mut b) = ([0u8; 256], [0u8; 256]);
                if refi0 >= 0 {
                    let Some(rf) = self.refs.get(refi0 as usize) else { return false };
                    rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16 + px, mb_y * 16 + py, rw, rh, mv0.0, mv0.1, &mut a[..rw * rh]);
                }
                if refi1 >= 0 {
                    let Some(rf) = self.refs1.get(refi1 as usize) else { return false };
                    rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16 + px, mb_y * 16 + py, rw, rh, mv1.0, mv1.1, &mut b[..rw * rh]);
                }
                drop(_gl);
                let _gbl = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBBlend);
                match (refi0 >= 0, refi1 >= 0) {
                    (true, true) => {
                        for dy in 0..rh {
                            let (ar, br) = (&a[dy * rw..dy * rw + rw], &b[dy * rw..dy * rw + rw]);
                            let base = (py + dy) * 16 + px;
                            let dst = &mut pred_y[base..base + rw];
                            match weights {
                                None => {
                                    for ((d, p), q) in dst.iter_mut().zip(ar).zip(br) {
                                        *d = ((*p as u16 + *q as u16 + 1) >> 1) as u8;
                                    }
                                }
                                Some((w0, w1)) => {
                                    for ((d, p), q) in dst.iter_mut().zip(ar).zip(br) {
                                        *d = ((*p as i32 * w0 + *q as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                                    }
                                }
                            }
                        }
                    }
                    (true, false) => {
                        for dy in 0..rh {
                            let d = (py + dy) * 16 + px;
                            pred_y[d..d + rw].copy_from_slice(&a[dy * rw..dy * rw + rw]);
                        }
                    }
                    _ => {
                        for dy in 0..rh {
                            let d = (py + dy) * 16 + px;
                            pred_y[d..d + rw].copy_from_slice(&b[dy * rw..dy * rw + rw]);
                        }
                    }
                }
                false
            }
        });
        if chroma_done {
            return;
        }
        let _gc = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBChroma);
        self.b_mc_chroma(mb_x, mb_y, px, py, rw, rh, refi0, mv0, refi1, mv1, c_pred, weights, cch);
    }

    /// Chroma half of `b_mc`, with the same full-width direct-write fusion
    /// (crw == 8 rows are contiguous in the 8-wide `c_pred` planes).
    #[allow(clippy::too_many_arguments)]
    /// Chroma half of `b_mc`. U and V share every piece of MC geometry, so
    /// each list is ONE `mc_chroma_padded_pair` call (setup + range check paid
    /// once, kernels unchanged) instead of two per-plane calls — the per-plane
    /// pixel math is byte-identical to the old per-plane flow.
    #[allow(clippy::too_many_arguments)]
    fn b_mc_chroma(
        &self,
        mb_x: usize,
        mb_y: usize,
        px: usize,
        py: usize,
        rw: usize,
        rh: usize,
        refi0: i32,
        mv0: (i32, i32),
        refi1: i32,
        mv1: (i32, i32),
        c_pred: &mut [[u8; 64]; 2],
        weights: Option<(i32, i32)>,
        cch: usize,
    ) {
        use rusty_h264_common::inter::mc_chroma_padded_pair;
        let (crx, cry, crw, crh) = (px / 2, py / 2, rw / 2, rh / 2);
        let full = crx == 0 && crw == 8;
        let n = crw * crh;
        // RESOLVE BOTH SLOTS ONCE, then let the match patterns bind them. Every
        // arm below re-indexed `refs`/`refs1` by a raw `refi` — six checked Vec
        // indexes across the four arms — although `a0`/`a1` already meant
        // exactly "this slot is present". Carrying `Option<&RefPic>` instead of
        // a bool makes "present" and "in range" the same fact.
        let rf0 = (refi0 >= 0).then(|| self.refs.get(refi0 as usize)).flatten();
        let rf1 = (refi1 >= 0).then(|| self.refs1.get(refi1 as usize)).flatten();
        let (a0, a1) = (rf0.is_some(), rf1.is_some());
        let [cu, cv] = c_pred;
        match (a0, a1, full) {
            (true, false, true) | (false, true, true) => {
                let (Some(rf), mv) = (if a0 { rf0 } else { rf1 }, if a0 { mv0 } else { mv1 }) else {
                    return;
                };
                let (gu, gv) = (rf.chroma_guard(0, rf.ch), rf.chroma_guard(1, rf.ch));
                mc_chroma_padded_pair(&gu, &gv, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv.0, mv.1, &mut cu[cry * 8..cry * 8 + n], &mut cv[cry * 8..cry * 8 + n]);
            }
            (true, true, true) => {
                let (Some(rfa), Some(rfb)) = (rf0, rf1) else { return };
                {
                    let rf = rfa;
                    let (gu, gv) = (rf.chroma_guard(0, rf.ch), rf.chroma_guard(1, rf.ch));
                    mc_chroma_padded_pair(&gu, &gv, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv0.0, mv0.1, &mut cu[cry * 8..cry * 8 + n], &mut cv[cry * 8..cry * 8 + n]);
                }
                let (mut bu, mut bv) = ([0u8; 64], [0u8; 64]);
                {
                    let rf = rfb;
                    let (gu, gv) = (rf.chroma_guard(0, rf.ch), rf.chroma_guard(1, rf.ch));
                    mc_chroma_padded_pair(&gu, &gv, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv1.0, mv1.1, &mut bu[..n], &mut bv[..n]);
                }
                for (dst, stage) in [(&mut *cu, &bu), (&mut *cv, &bv)] {
                    let d = &mut dst[cry * 8..cry * 8 + n];
                    match weights {
                        None => {
                            for (o, q) in d.iter_mut().zip(&stage[..n]) {
                                *o = ((*o as u16 + *q as u16 + 1) >> 1) as u8;
                            }
                        }
                        Some((w0, w1)) => {
                            for (o, q) in d.iter_mut().zip(&stage[..n]) {
                                *o = ((*o as i32 * w0 + *q as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                            }
                        }
                    }
                }
            }
            _ => {
                // Narrow region — rows are strided in the 8-wide pred planes;
                // stage per list (paired), then copy/blend strided per plane.
                let (mut au, mut av, mut bu, mut bv) = ([0u8; 64], [0u8; 64], [0u8; 64], [0u8; 64]);
                if let Some(rf) = rf0 {
                    let (gu, gv) = (rf.chroma_guard(0, rf.ch), rf.chroma_guard(1, rf.ch));
                    mc_chroma_padded_pair(&gu, &gv, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8 + crx, mb_y * 8 + cry, crw, crh, mv0.0, mv0.1, &mut au[..n], &mut av[..n]);
                }
                if let Some(rf) = rf1 {
                    let (gu, gv) = (rf.chroma_guard(0, rf.ch), rf.chroma_guard(1, rf.ch));
                    mc_chroma_padded_pair(&gu, &gv, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8 + crx, mb_y * 8 + cry, crw, crh, mv1.0, mv1.1, &mut bu[..n], &mut bv[..n]);
                }
                for (dst, sa, sb) in [(&mut *cu, &au, &bu), (&mut *cv, &av, &bv)] {
                    for dy in 0..crh {
                        let base = (cry + dy) * 8 + crx;
                        let d = &mut dst[base..base + crw];
                        match (a0, a1) {
                            (true, true) => {
                                let (pr, qr) = (&sa[dy * crw..dy * crw + crw], &sb[dy * crw..dy * crw + crw]);
                                match weights {
                                    None => {
                                        for ((o, pp), q) in d.iter_mut().zip(pr).zip(qr) {
                                            *o = ((*pp as u16 + *q as u16 + 1) >> 1) as u8;
                                        }
                                    }
                                    Some((w0, w1)) => {
                                        for ((o, pp), q) in d.iter_mut().zip(pr).zip(qr) {
                                            *o = ((*pp as i32 * w0 + *q as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                                        }
                                    }
                                }
                            }
                            (true, false) => d.copy_from_slice(&sa[dy * crw..dy * crw + crw]),
                            _ => d.copy_from_slice(&sb[dy * crw..dy * crw + crw]),
                        }
                    }
                }
            }
        }
    }

    /// Commits a region's per-list motion to the 4×4 grids (and marks coded).
    #[allow(clippy::too_many_arguments)]
    fn b_set_motion(&mut self, mb_x: usize, mb_y: usize, px: usize, py: usize, rw: usize, rh: usize, refi0: i32, mv0: (i32, i32), refi1: i32, mv1: (i32, i32)) {
        let _gs = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBSet);
        let w4 = self.mb_w * 4;
        let mv0w = if refi0 >= 0 { mv0 } else { (0, 0) };
        let mv1w = if refi1 >= 0 { mv1 } else { (0, 0) };
        let by0 = mb_y * 4 + py / 4;
        let bx0 = mb_x * 4 + px / 4;
        let (bw, bh) = (rw / 4, rh / 4);
        // Contiguous per-row slices: fill instead of per-4x4 stores (same values).
        // SEVEN parallel grids, seven separate range checks — they are disjoint
        // fields of `self`, so one `get_mut` apiece resolves them all together
        // and a short row simply writes nothing rather than panicking.
        for by in by0..by0 + bh {
            let row = by * w4 + bx0;
            let end = row + bw;
            let (Some(r0), Some(m0), Some(r1), Some(m1)) = (
                self.ref_idx_y.get_mut(row..end),
                self.mv_y.get_mut(row..end),
                self.ref_idx1.get_mut(row..end),
                self.mv1.get_mut(row..end),
            ) else {
                continue;
            };
            r0.fill(refi0);
            m0.fill(mv0w);
            r1.fill(refi1);
            m1.fill(mv1w);
            let (Some(it), Some(cd), Some(md)) = (
                self.inter_y.get_mut(row..end),
                self.coded_y.get_mut(row..end),
                self.modes_y.get_mut(row..end),
            ) else {
                continue;
            };
            it.fill(true);
            cd.fill(true);
            md.fill(2);
        }
    }

    /// Spatial direct prediction for a region (whole MB or an 8×8): derives the
    /// per-list reference indices and base MVs, then motion-compensates each 4×4
    /// sub-block (applying `colZeroFlag`) and commits the motion (spec §8.4.1.2.2).
    #[allow(clippy::too_many_arguments)]
    /// Splits a `w`×`h` block region (4×4-block units) into the fewest rectangles
    /// whose contents are `uniform`, preferring partition-shaped cuts (whole →
    /// horizontal halves → vertical halves → quadrants). Emits at most w·h rects
    /// (the all-different worst case degenerates to per-block, i.e. the old loop).
    fn coalesce_region<U: Fn(usize, usize, usize, usize) -> bool, E: FnMut(usize, usize, usize, usize)>(
        x: usize,
        y: usize,
        w: usize,
        h: usize,
        uniform: &U,
        emit: &mut E,
    ) {
        if uniform(x, y, w, h) {
            emit(x, y, w, h);
            return;
        }
        if h > 1 && uniform(x, y, w, h / 2) && uniform(x, y + h / 2, w, h / 2) {
            emit(x, y, w, h / 2);
            emit(x, y + h / 2, w, h / 2);
            return;
        }
        if w > 1 && uniform(x, y, w / 2, h) && uniform(x + w / 2, y, w / 2, h) {
            emit(x, y, w / 2, h);
            emit(x + w / 2, y, w / 2, h);
            return;
        }
        match (w > 1, h > 1) {
            (true, true) => {
                for q in 0..4usize {
                    Self::coalesce_region(x + (q % 2) * (w / 2), y + (q / 2) * (h / 2), w / 2, h / 2, uniform, emit);
                }
            }
            (true, false) => {
                Self::coalesce_region(x, y, w / 2, h, uniform, emit);
                Self::coalesce_region(x + w / 2, y, w / 2, h, uniform, emit);
            }
            (false, true) => {
                Self::coalesce_region(x, y, w, h / 2, uniform, emit);
                Self::coalesce_region(x, y + h / 2, w, h / 2, uniform, emit);
            }
            (false, false) => emit(x, y, 1, 1),
        }
    }

    fn decode_b_direct(&mut self, mb_x: usize, mb_y: usize, px: usize, py: usize, rw: usize, rh: usize, pred_y: &mut [u8; 256], c_pred: &mut [[u8; 64]; 2]) {
        if !self.direct_spatial {
            return self.decode_b_direct_temporal(mb_x, mb_y, px, py, rw, rh, pred_y, c_pred);
        }
        let (n0, n1) = self.b_direct_nbrs(mb_x, mb_y);
        self.decode_b_direct_n(mb_x, mb_y, px, py, rw, rh, pred_y, c_pred, n0, n1);
    }

    /// Spec §8.4.1.2.2: the spatial-direct reference indices (min positive over
    /// the three neighbors, per list) and the predicted MVs. `direct_zero` is
    /// the both-lists-unavailable case, which forces ref 0 / mv (0,0). Shared
    /// by `decode_b_direct_n` and the B_Skip zero-bi fast path — ONE derivation,
    /// no drift.
    #[inline]
    fn b_direct_refs_mvs(n0: &[MvNeighbor; 3], n1: &[MvNeighbor; 3]) -> (i32, i32, (i32, i32), (i32, i32), bool) {
        let min_pos = |a: i32, b: i32| if a < 0 { b } else if b < 0 { a } else { a.min(b) };
        let rid = |n: &[MvNeighbor; 3]| min_pos(min_pos(n[0].ref_idx, n[1].ref_idx), n[2].ref_idx);
        let (mut refi0, mut refi1) = (rid(n0), rid(n1));
        let direct_zero = refi0 < 0 && refi1 < 0;
        if direct_zero {
            refi0 = 0;
            refi1 = 0;
        }
        let mv0 = if refi0 >= 0 && !direct_zero { predict_mv(n0[0], n0[1], n0[2], refi0) } else { (0, 0) };
        let mv1 = if refi1 >= 0 && !direct_zero { predict_mv(n1[0], n1[1], n1[2], refi1) } else { (0, 0) };
        (refi0, refi1, mv0, mv1, direct_zero)
    }

    fn decode_b_direct_n(
        &mut self,
        mb_x: usize,
        mb_y: usize,
        px: usize,
        py: usize,
        rw: usize,
        rh: usize,
        pred_y: &mut [u8; 256],
        c_pred: &mut [[u8; 64]; 2],
        n0: [MvNeighbor; 3],
        n1: [MvNeighbor; 3],
    ) {
        let _gb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBDirect);
        // H-48: DERIVATION-ONLY scope, dropped before the MC loop below. DecBDirect
        // wraps this function whole and therefore INCLUDES the `b_mc` calls it makes,
        // so its 1460 ns/call was never "MV derivation is slow" — that read was wrong.
        // This guard is what separates the two.
        let gd = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBDeriv);
        let derived = Self::b_direct_refs_mvs(&n0, &n1);
        drop(gd);
        self.b_direct_region(mb_x, mb_y, px, py, rw, rh, pred_y, c_pred, derived);
    }

    /// The post-derivation half of spatial direct: czg probing (gated), region
    /// coalescing, MC + motion commit. Split out so B_8x8 direct subs derive
    /// ONCE per MB (the A/B/C neighbours and the rid/median result are
    /// MB-level; only czg varies per 8x8).
    #[allow(clippy::too_many_arguments)]
    fn b_direct_region(
        &mut self,
        mb_x: usize,
        mb_y: usize,
        px: usize,
        py: usize,
        rw: usize,
        rh: usize,
        pred_y: &mut [u8; 256],
        c_pred: &mut [[u8; 64]; 2],
        derived: (i32, i32, (i32, i32), (i32, i32), bool),
    ) {
        let (refi0, refi1, mv0, mv1, direct_zero) = derived;
        // Per 4×4 sub-block: colZeroFlag zeroes the ref-0 motion vector. cz is the
        // ONLY per-block variable (two possible (m0,m1) values for the region), and
        // the MC filters + bi-blend are per-output-pixel — so sub-blocks with equal
        // cz coalesce into one wider `b_mc`, BIT-IDENTICAL. A 16×16 direct MB paid
        // 16 bi-pred b_mc calls (~96 MC kernel entries) before this; typically 1 now.
        let (bx0, by0, bw, bh) = (px / 4, py / 4, rw / 4, rh / 4);
        // MASKED at every use below. The loop bounds are the region's `bw`/`bh` in
    // 4x4 units, which are always <= 4 for a macroblock but are RUNTIME values,
    // so none of the eight indexes into this fixed 4x4 grid was provable.
    let mut czg = [[false; 4]; 4]; // region-local, [dy][dx]
        // colZeroFlag can only change a list whose ref is 0 AND whose predicted
        // MV is nonzero (it zeroes MVs; zeroing (0,0) is a no-op). When neither
        // list qualifies, skip the probing entirely: czg stays false, the
        // region is uniform, and the m values are identical — the only change
        // is FEWER b_mc calls where the old czg would have split rects with
        // equal values (tiles of the same math, byte-identical).
        let cz_matters = (refi0 == 0 && mv0 != (0, 0)) || (refi1 == 0 && mv1 != (0, 0));
        // Uniformity is KNOWN after the probe fill — when every probe agreed,
        // the 16-bool coalesce scan and its recursion are skipped outright.
        let mut cz_mixed = false;
        if cz_matters && !direct_zero && self.direct_8x8_inference {
            // Under direct_8x8_inference every 4×4 in an 8×8 shares one colZeroFlag
            // (col_block collapses to the MB-corner). Probe once per 8×8 — same
            // czg, fewer wait_motion_ready / meta locks on the live-ref path.
            let mut oy = 0usize;
            while oy < bh {
                let h = (bh - oy).min(2);
                let mut ox = 0usize;
                while ox < bw {
                    let w = (bw - ox).min(2);
                    let (colx, coly) = self.col_block(bx0 + ox, by0 + oy);
                    let cz = self.col_zero(mb_x * 4 + colx, mb_y * 4 + coly);
                    cz_mixed |= cz != czg[0][0] && !(ox == 0 && oy == 0);
                    for dy in oy..oy + h {
                        for dx in ox..ox + w {
                            czg[dy & 3][dx & 3] = cz;
                        }
                    }
                    ox += w;
                }
                oy += h;
            }
        } else if cz_matters && !direct_zero {
            for dy in 0..bh {
                for dx in 0..bw {
                    let (colx, coly) = self.col_block(bx0 + dx, by0 + dy);
                    let cz = self.col_zero(mb_x * 4 + colx, mb_y * 4 + coly);
                    cz_mixed |= cz != czg[0][0] && !(dx == 0 && dy == 0);
                    czg[dy & 3][dx & 3] = cz;
                }
            }
        }
        let mut rects: [(usize, usize, usize, usize); 16] = [(0, 0, 0, 0); 16];
        let mut n = 0usize;
        if !cz_mixed {
            rects[0] = (0, 0, bw, bh);
            n = 1;
        } else {
            let uniform = |x: usize, y: usize, w: usize, h: usize| -> bool {
                let t = czg[y & 3][x & 3];
                (y..y + h).all(|dy| (x..x + w).all(|dx| czg[dy & 3][dx & 3] == t))
            };
            Self::coalesce_region(0, 0, bw, bh, &uniform, &mut |x, y, w, h| {
                rects[n & 15] = (x, y, w, h);
                n += 1;
            });
        }
        let recording = self.edc_regions.is_some();
        if rw == 16 && rh == 16 {
            edcstat::bump(&edcstat::BSK_FULLMB, 1);
            if n == 1 {
                edcstat::bump(&edcstat::BSK_1RECT, 1);
                let cz = czg[0][0];
                let m0 = if refi0 == 0 && cz { (0, 0) } else { mv0 };
                let m1 = if refi1 == 0 && cz { (0, 0) } else { mv1 };
                let (a0, a1) = (refi0 >= 0, refi1 >= 0);
                if a0 && a1 && m0 == (0, 0) && m1 == (0, 0) {
                    edcstat::bump(&edcstat::BSK_ZBI, 1);
                } else if (a0 != a1) && (if a0 { m0 } else { m1 }) == (0, 0) {
                    edcstat::bump(&edcstat::BSK_ZUNI, 1);
                } else if (!a0 || (m0.0 % 4 == 0 && m0.1 % 4 == 0))
                    && (!a1 || (m1.0 % 4 == 0 && m1.1 % 4 == 0))
                {
                    edcstat::bump(&edcstat::BSK_FP, 1);
                }
                if self.bsk_last == Some((mb_x.wrapping_sub(1), mb_y, refi0, refi1, m0, m1)) {
                    edcstat::bump(&edcstat::BSK_RUNCONT, 1);
                }
                self.bsk_last = Some((mb_x, mb_y, refi0, refi1, m0, m1));
            } else {
                self.bsk_last = None;
            }
        }
        for &(x, y, w, h) in &rects[..n] {
            let cz = czg[y & 3][x & 3];
            let m0 = if refi0 == 0 && cz { (0, 0) } else { mv0 };
            let m1 = if refi1 == 0 && cz { (0, 0) } else { mv1 };
            let (lx, ly, lw, lh) = ((bx0 + x) * 4, (by0 + y) * 4, w * 4, h * 4);
            if recording {
                self.b_mc_or_record(mb_x, mb_y, lx, ly, lw, lh, refi0, m0, refi1, m1, pred_y, c_pred);
            } else {
                self.b_mc(mb_x, mb_y, lx, ly, lw, lh, refi0, m0, refi1, m1, pred_y, c_pred);
            }
            self.b_set_motion(mb_x, mb_y, lx, ly, lw, lh, refi0, m0, refi1, m1);
        }
    }

    /// Temporal direct prediction for a region (spec §8.4.1.2.3): for each 4×4
    /// (or per-8×8 corner under `direct_8x8_inference`), take the co-located
    /// List-0 motion from `RefPicList1[0]`, map its reference into the current
    /// List-0 by POC, and scale the motion vector by the POC distances.
    #[allow(clippy::too_many_arguments)]
    fn decode_b_direct_temporal(&mut self, mb_x: usize, mb_y: usize, px: usize, py: usize, rw: usize, rh: usize, pred_y: &mut [u8; 256], c_pred: &mut [[u8; 64]; 2]) {
        let poc1 = self.refs1.first().map_or(0, |f| f.pic_poc());
        let infer = self.direct_8x8_inference;
        // Under direct_8x8_inference every 4×4 in an 8×8 takes the same MB-corner
        // co-located motion, so motion-compensate the whole 8×8 in one call — this
        // hits the width-8 MC asm and pays the per-call tile/blend setup 4× less.
        // Without inference, motion is genuinely per-4×4. Bit-identical either way
        // (MC of an 8×8 with one MV == four 4×4 MCs with that same MV).
        let step = if infer { 8 } else { 4 };
        let mut sy = py;
        while sy < py + rh {
            let mut sx = px;
            while sx < px + rw {
                // Co-located 4×4 (the 8×8's MB-corner under inference) — shared with
                // the spatial path's colZeroFlag, which must map identically.
                let (colx, coly) = self.col_block(sx / 4, sy / 4);
                let (mvcol, refpoc) = {
                    let Some(col) = self.refs1.first() else { return };
                    if let Some(live) = col.live.as_ref() {
                        col.wait_motion_ready();
                        let meta = live.meta.read().unwrap();
                        let idx = (mb_y * 4 + coly) * meta.w4 + (mb_x * 4 + colx);
                        // `mv` and `ref_poc` are PARALLEL Vecs: the `mv.len()`
                        // guard said nothing about `ref_poc`.
                        match (meta.mv.get(idx), meta.ref_poc.get(idx)) {
                            (Some(&m), Some(&pc)) if meta.w4 != 0 && pc != i32::MIN => (m, pc),
                            _ => ((0, 0), i32::MIN),
                        }
                    } else {
                        let idx = (mb_y * 4 + coly) * col.w4 + (mb_x * 4 + colx);
                        // intra co-located → zero motion, refIdxL0 = 0
                        match (col.mv.get(idx), col.ref_poc.get(idx)) {
                            (Some(&m), Some(&pc)) if col.w4 != 0 && pc != i32::MIN => (m, pc),
                            _ => ((0, 0), i32::MIN),
                        }
                    }
                };
                // MapColToList0: the current-list index of the co-located reference.
                let (refi0, mvc) = if refpoc == i32::MIN {
                    (0, (0, 0))
                } else {
                    let r = self
                        .refs
                        .iter()
                        .position(|f| f.pic_poc() == refpoc)
                        .unwrap_or(0) as i32;
                    (r, mvcol)
                };
                let Some(r0) = self.refs.get(refi0 as usize) else { return };
        let poc0 = r0.pic_poc();
                let td = (poc1 - poc0).clamp(-128, 127);
                let tb = (self.cur_poc - poc0).clamp(-128, 127);
                let (mv0, mv1) = if td == 0 || r0.long_term {
                    (mvc, (0, 0))
                } else {
                    let tx = tx_for_td(td);
                    let dsf = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
                    let m0 = ((dsf * mvc.0 + 128) >> 8, (dsf * mvc.1 + 128) >> 8);
                    (m0, (m0.0 - mvc.0, m0.1 - mvc.1))
                };
                self.b_mc_or_record(mb_x, mb_y, sx, sy, step, step, refi0, mv0, 0, mv1, pred_y, c_pred);
                self.b_set_motion(mb_x, mb_y, sx, sy, step, step, refi0, mv0, 0, mv1);
                sx += step;
            }
            sy += step;
        }
    }

    /// Reads `ref_idx_lX` for a B partition (te(v)/ue(v) by the list's active
    /// count), bounds-checked against the available reference count.
    fn read_b_ref(&self, r: &mut BitReader, list: usize) -> Result<i32, MbError> {
        let (active, avail) = if list == 0 {
            (self.num_ref_active, self.refs.len())
        } else {
            (self.num_ref_active1, self.refs1.len())
        };
        let v = if active > 1 { read_ref_idx(r, active)? } else { 0 };
        if v as usize >= avail {
            return Err(MbError::Truncated);
        }
        Ok(v)
    }

    /// Reconstructs a `B_Skip` macroblock: spatial-direct prediction, no residual.
    /// Defer one fast B_Skip's grid commit + recon into the pending row span.
    /// Continuation requires position adjacency AND kind equality.
    #[inline]
    fn bz_push(&mut self, mb_x: usize, mb_y: usize, kind: BzKind) {
        match self.bzspan {
            Some((row, x0, ref mut n, k)) if row == mb_y && x0 + *n == mb_x && k == kind => {
                *n += 1
            }
            _ => {
                self.bz_flush();
                self.bzspan = Some((mb_y, mb_x, 1, kind));
            }
        }
    }

    /// Range-fill the pending span's grids. MUST run before anything reads
    /// the motion/coded/mode/nnz grids of a deferred MB: decode_b_mb entry,
    /// decode_b_skip's b_direct_nbrs, bS derivation (derive_bs_row callers
    /// via row_hook + deblock), and slice end (edc_flush covers it).
    #[inline(always)]
    fn bz_flush(&mut self) {
        if self.bzspan.is_some() {
            self.bz_flush_slow();
        }
    }

    fn bz_flush_slow(&mut self) {
        let _sg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BSpanRecon);
        let Some((row, x0, n, kind)) = self.bzspan.take() else { return };
        edcstat::bump(&edcstat::BZ_SPANS, 1);
        edcstat::bump(&edcstat::BZ_SPAN_MBS, n as u64);
        // Grid values per kind (mirrors b_set_motion's inactive-list zeroing).
        let (g_r0, g_r1, g_m0, g_m1): (i32, i32, (i32, i32), (i32, i32)) = match kind {
            BzKind::ZeroBi => (0, 0, (0, 0), (0, 0)),
            BzKind::ZeroUni(0, ri) => (ri as i32, -1, (0, 0), (0, 0)),
            BzKind::ZeroUni(_, ri) => (-1, ri as i32, (0, 0), (0, 0)),
            BzKind::Fp { r0, r1, m0, m1 } => {
                let mm0 = if r0 >= 0 { (m0.0 as i32, m0.1 as i32) } else { (0, 0) };
                let mm1 = if r1 >= 0 { (m1.0 as i32, m1.1 as i32) } else { (0, 0) };
                (r0 as i32, r1 as i32, mm0, mm1)
            }
        };
        let w4 = self.mb_w * 4;
        let (b0, len) = (x0 * 4, n * 4);
        for dy in 0..4 {
            let a = (row * 4 + dy) * w4 + b0;
            self.ref_idx_y[a..a + len].fill(g_r0);
            self.mv_y[a..a + len].fill(g_m0);
            self.ref_idx1[a..a + len].fill(g_r1);
            self.mv1[a..a + len].fill(g_m1);
            self.inter_y[a..a + len].fill(true);
            self.coded_y[a..a + len].fill(true);
            self.modes_y[a..a + len].fill(2);
            self.nnz_y[a..a + len].fill(0);
        }
        match kind {
            BzKind::ZeroBi => self.bz_recon_band_bi(row, x0, n),
            BzKind::ZeroUni(list, ri) => self.bz_recon_band_copy(row, x0, n, list as usize, ri as usize, (0, 0)),
            BzKind::Fp { r0, r1, m0, m1 } => {
                let mv0 = (m0.0 as i32, m0.1 as i32);
                let mv1 = (m1.0 as i32, m1.1 as i32);
                match (r0 >= 0, r1 >= 0) {
                    (true, true) => self.bz_recon_band_fp_bi(row, x0, n, r0 as usize, r1 as usize, mv0, mv1),
                    (true, false) => self.bz_recon_band_copy(row, x0, n, 0, r0 as usize, mv0),
                    _ => self.bz_recon_band_copy(row, x0, n, 1, r1 as usize, mv1),
                }
            }
        }
    }

    /// ZeroBi band: rows of 16n averaged from both padded refs (index 0).
    fn bz_recon_band_bi(&mut self, row: usize, x0: usize, n: usize) {
        // Byte-identical to n recon_b_skip_zero_bi(_, _, 0, 0) calls: each
        // output byte is the same (a + b + 1) >> 1 of the same source bytes.
        let w = n * 16;
        let Some(rf0) = self.refs.first() else { return };
        let Some(rf1) = self.refs1.first() else { return };
        let (l0st, l1st) = (rf0.lstride(), rf1.lstride());
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            let (ly0, ly1) = (rf0.luma_guard(rf0.ch), rf1.luma_guard(rf1.ch));
            for dy in 0..16 {
                let y = row * 16 + dy;
                let s0 = (y + crate::LPAD) * l0st + crate::LPAD + x0 * 16;
                let s1 = (y + crate::LPAD) * l1st + crate::LPAD + x0 * 16;
                let d = y * self.cw + x0 * 16;
                for ((dst, a), b) in self.rec_y[d..d + w].iter_mut().zip(&ly0[s0..s0 + w]).zip(&ly1[s1..s1 + w]) {
                    *dst = ((*a as u16 + *b as u16 + 1) >> 1) as u8;
                }
            }
        }
        let (c0st, c1st) = (rf0.cstride(), rf1.cstride());
        let wc = n * 8;
        for c in 0..2 {
            let rc0 = rf0.chroma_guard(c, rf0.ch);
            let rc1 = rf1.chroma_guard(c, rf1.ch);
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for dy in 0..8 {
                let y = row * 8 + dy;
                let s0 = (y + crate::CPAD) * c0st + crate::CPAD + x0 * 8;
                let s1 = (y + crate::CPAD) * c1st + crate::CPAD + x0 * 8;
                let d = y * self.ccw + x0 * 8;
                for ((dst, a), b) in plane[d..d + wc].iter_mut().zip(&rc0[s0..s0 + wc]).zip(&rc1[s1..s1 + wc]) {
                    *dst = ((*a as u16 + *b as u16 + 1) >> 1) as u8;
                }
            }
        }
    }

    /// Full-pel offset copy band from ONE list's padded planes. The caller
    /// prevalidated (per MB, at push): mv%8 == 0 both components and luma +
    /// chroma windows inside the padded planes — contiguous MB windows tile,
    /// so the span's union window is valid by induction.
    #[allow(clippy::too_many_arguments)]
    fn bz_recon_band_copy(&mut self, row: usize, x0: usize, n: usize, list: usize, ri: usize, mv: (i32, i32)) {
        let Some(rf) = (if list == 0 { self.refs.get(ri) } else { self.refs1.get(ri) }) else {
            return;
        };
        let lst = rf.lstride();
        let (dx, dy) = ((mv.0 / 4) as isize, (mv.1 / 4) as isize);
        let w = n * 16;
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            let ly = rf.luma_guard(rf.ch);
            for r in 0..16 {
                let y = (row * 16 + r) as isize + dy;
                let src = ((y + crate::LPAD as isize) * lst as isize
                    + crate::LPAD as isize
                    + x0 as isize * 16
                    + dx) as usize;
                let d = (row * 16 + r) * self.cw + x0 * 16;
                self.rec_y[d..d + w].copy_from_slice(&ly[src..src + w]);
            }
        }
        let cst = rf.cstride();
        let (cdx, cdy) = ((mv.0 / 8) as isize, (mv.1 / 8) as isize);
        let wc = n * 8;
        for c in 0..2 {
            let rc = rf.chroma_guard(c, rf.ch);
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for r in 0..8 {
                let y = (row * 8 + r) as isize + cdy;
                let src = ((y + crate::CPAD as isize) * cst as isize
                    + crate::CPAD as isize
                    + x0 as isize * 8
                    + cdx) as usize;
                let d = (row * 8 + r) * self.ccw + x0 * 8;
                plane[d..d + wc].copy_from_slice(&rc[src..src + wc]);
            }
        }
    }

    /// Full-pel bi band: rows of 16n averaged from two offset windows
    /// (prevalidated as above; implicit weights None/(32,32) guaranteed by
    /// the pushing arm).
    #[allow(clippy::too_many_arguments)]
    fn bz_recon_band_fp_bi(&mut self, row: usize, x0: usize, n: usize, r0: usize, r1: usize, mv0: (i32, i32), mv1: (i32, i32)) {
        let (Some(rf0), Some(rf1)) = (self.refs.get(r0), self.refs1.get(r1)) else {
            return;
        };
        let (l0, l1) = (rf0.lstride(), rf1.lstride());
        let off = |st: usize, pad: isize, yy: isize, xx: isize| (((yy + pad) * st as isize) + pad + xx) as usize;
        let w = n * 16;
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            let (ly0, ly1) = (rf0.luma_guard(rf0.ch), rf1.luma_guard(rf1.ch));
            for r in 0..16 {
                let y = (row * 16 + r) as isize;
                let s0 = off(l0, crate::LPAD as isize, y + (mv0.1 / 4) as isize, x0 as isize * 16 + (mv0.0 / 4) as isize);
                let s1 = off(l1, crate::LPAD as isize, y + (mv1.1 / 4) as isize, x0 as isize * 16 + (mv1.0 / 4) as isize);
                let d = (row * 16 + r) * self.cw + x0 * 16;
                for ((dst, a), b) in self.rec_y[d..d + w].iter_mut().zip(&ly0[s0..s0 + w]).zip(&ly1[s1..s1 + w]) {
                    *dst = ((*a as u16 + *b as u16 + 1) >> 1) as u8;
                }
            }
        }
        let (c0, c1) = (rf0.cstride(), rf1.cstride());
        let wc = n * 8;
        for c in 0..2 {
            let rc0 = rf0.chroma_guard(c, rf0.ch);
            let rc1 = rf1.chroma_guard(c, rf1.ch);
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for r in 0..8 {
                let y = (row * 8 + r) as isize;
                let s0 = off(c0, crate::CPAD as isize, y + (mv0.1 / 8) as isize, x0 as isize * 8 + (mv0.0 / 8) as isize);
                let s1 = off(c1, crate::CPAD as isize, y + (mv1.1 / 8) as isize, x0 as isize * 8 + (mv1.0 / 8) as isize);
                let d = (row * 8 + r) * self.ccw + x0 * 8;
                for ((dst, a), b) in plane[d..d + wc].iter_mut().zip(&rc0[s0..s0 + wc]).zip(&rc1[s1..s1 + wc]) {
                    *dst = ((*a as u16 + *b as u16 + 1) >> 1) as u8;
                }
            }
        }
    }

    /// Per-MB prevalidation for an Fp span push: mv%8 both components (chroma
    /// copies at mv/8) and luma + chroma windows inside the padded planes for
    /// every active list. False ⇒ the arm recons immediately instead.
    fn bz_fp_valid(&self, mbx: usize, mby: usize, r0: Option<usize>, r1: Option<usize>, mv0: (i32, i32), mv1: (i32, i32)) -> bool {
        let chk = |rf: &crate::Ref, mv: (i32, i32)| -> bool {
            if mv.0 % 8 != 0 || mv.1 % 8 != 0 {
                return false;
            }
            let lst = rf.lstride();
            let lpad = crate::LPAD as isize;
            let cx = mbx as isize * 16 + (mv.0 / 4) as isize + lpad;
            let cy = mby as isize * 16 + (mv.1 / 4) as isize + lpad;
            let lrows = rf.lrows() as isize;
            if cx < 0 || cx + 16 > lst as isize || cy < 0 || cy + 16 > lrows {
                return false;
            }
            let cst = rf.cstride();
            let cpad = crate::CPAD as isize;
            let ccx = mbx as isize * 8 + (mv.0 / 8) as isize + cpad;
            let ccy = mby as isize * 8 + (mv.1 / 8) as isize + cpad;
            let crows = rf.crows() as isize;
            ccx >= 0 && ccx + 8 <= cst as isize && ccy >= 0 && ccy + 8 <= crows
        };
        r0.is_none_or(|i| self.refs.get(i).is_some_and(|r| chk(r, mv0)))
            && r1.is_none_or(|i| self.refs1.get(i).is_some_and(|r| chk(r, mv1)))
    }

    /// Defer one (0,0) P_Skip's grid commit into the pending P span.
    #[inline]
    fn pz_push(&mut self, mb_x: usize, mb_y: usize, recon: bool) {
        match self.pzspan {
            Some((row, x0, ref mut n, r)) if row == mb_y && x0 + *n == mb_x && r == recon => {
                *n += 1
            }
            _ => {
                self.pz_flush();
                self.pzspan = Some((mb_y, mb_x, 1, recon));
            }
        }
    }

    /// Range-fill the pending P span's grids (the deferral constants of
    /// decode_p_skip's commit: list-0 ref 0, mv (0,0), inter, coded, DC mode,
    /// deblock kind SKIP). Same flush points as the B span (span_flush).
    #[inline(always)]
    fn pz_flush(&mut self) {
        if self.pzspan.is_some() {
            self.pz_flush_slow();
        }
    }

    fn pz_flush_slow(&mut self) {
        let _sg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BSpanRecon);
        let Some((row, x0, n, recon)) = self.pzspan.take() else { return };
        edcstat::bump(&edcstat::PZ_SPANS, 1);
        edcstat::bump(&edcstat::PZ_SPAN_MBS, n as u64);
        let w4 = self.mb_w * 4;
        let (b0, len) = (x0 * 4, n * 4);
        for dy in 0..4 {
            let a = (row * 4 + dy) * w4 + b0;
            self.mv_y[a..a + len].fill((0, 0));
            self.inter_y[a..a + len].fill(true);
            self.ref_idx_y[a..a + len].fill(0);
            self.coded_y[a..a + len].fill(true);
            self.modes_y[a..a + len].fill(2);
        }
        self.mb_kind[row * self.mb_w + x0..row * self.mb_w + x0 + n]
            .fill(rusty_h264_common::deblock::MB_KIND_SKIP);
        if recon {
            // The recon deferred with the commit: one band copy from ref[0]
            // replaces n queued EdcJob::Skip pushes AND the flush-time
            // run-coalescing scan that used to rediscover this very run.
            self.recon_p_skip_band(x0, row, n);
        }
    }

    /// Flush BOTH pending grid spans — the one call every grid reader makes.
    #[inline]
    fn span_flush(&mut self) {
        self.bz_flush();
        self.pz_flush();
    }

    /// Hot prefix of decode_b_skip: the FORCED zero-bi run continuation,
    /// small enough to inline into the slice loops. Returns true when the MB
    /// was fully handled (deferred into the span); false falls to the cold
    /// body. Exactly the forced arm's conditions — no behavior change.
    #[inline(always)]
    fn b_skip_hot(&mut self, mb_x: usize, mb_y: usize) -> bool {
        if !self.direct_spatial || self.edc_tx.is_some() || self.k_no_bskipfast {
            return false;
        }
        let mbw = self.mb_w;
        let addr = mb_y * mbw + mb_x;
        // ONE slice that ENDS at `addr` proves all three neighbour reads. Each
        // was a separate check against the whole `bzero` grid even though every
        // index is strictly below `addr` (the guards above establish that), and
        // the trailing `bzero[addr] = true` a fourth. `get(..=addr)` states the
        // bound once, in the form the neighbour indexes are already inside.
        // The `get(..=addr)` slice did NOT fold these: it bounds the reads from
        // above, but LLVM still has to chain `mb_x > 0 => addr >= 1` and
        // `mb_y > 0 => addr >= mbw` through the `&&` sequence, and it will not.
        // Fallible reads state each one where it is made; a missing neighbour is
        // "not zero", which is the conservative answer this guard wants.
        let up = addr.wrapping_sub(mbw);
        if !(mb_x > 0
            && mb_y > 0
            && mb_x + 1 < mbw
            && up >= self.slice_first_mb
            && self.bzero.get(addr - 1).copied().unwrap_or(false)
            && self.bzero.get(up).copied().unwrap_or(false)
            && self.bzero.get(up + 1).copied().unwrap_or(false))
        {
            return false;
        }
        let wgt = self.iw00();
        if !(wgt.is_none() || wgt == Some((32, 32))) {
            return false;
        }
        self.route_skip_mbs += 1;
        edcstat::bump(&edcstat::BSKB_FORCED, 1);
        let _sg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BSkipHot);
        edcstat::bump(&edcstat::BSKB_FAST, 1);
        self.bz_push(mb_x, mb_y, BzKind::ZeroBi);
        if let Some(b) = self.bzero.get_mut(addr) {
            *b = true;
        }
        true
    }

    /// Zero this macroblock's 16 luma nnz entries, walking rows by adding `w4`
    /// instead of recomputing `(mb_y * 4 + dy) * w4 + mb_x * 4` four times.
    /// Shared by the three sites in decode_b_skip that had it open-coded.
    #[inline]
    fn clear_mb_nnz(&mut self, mb_x: usize, mb_y: usize, w4: usize) {
        let mut a = (mb_y * 4) * w4 + mb_x * 4;
        for _ in 0..4 {
            self.nnz_y[a..a + 4].fill(0);
            a += w4;
        }
    }

    /// The B_Skip SLOW half: full spatial-direct recon plus the zero-residual
    /// plane copy. Split out so `pred_y`/`c_pred` (384 B) are built ONLY when a
    /// macroblock actually reaches it — the zero-bi / zero-uni / full-pel fast
    /// paths in decode_b_skip all return before this, and on LIGHT streams they
    /// take 90%+ of the calls.
    fn b_skip_slow(
        &mut self,
        mb_x: usize,
        mb_y: usize,
        nbrs: Option<([MvNeighbor; 3], [MvNeighbor; 3])>,
        w4: usize,
    ) -> Result<(), MbError> {
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        match nbrs {
            // Reuses the already-probed neighbours — the grid walk is the
            // expensive half of the derivation and paying it twice leaned on
            // fall-through-heavy streams (stockholm).
            Some((n0, n1)) => {
                self.decode_b_direct_n(mb_x, mb_y, 0, 0, 16, 16, &mut pred_y, &mut c_pred, n0, n1)
            }
            None => self.decode_b_direct(mb_x, mb_y, 0, 0, 16, 16, &mut pred_y, &mut c_pred),
        }
        if let Some(regions) = self.edc_regions.take() {
            // nnz clears are PARSE state; the pixel copy is the worker's.
            self.clear_mb_nnz(mb_x, mb_y, w4);
            self.edc_giveback();
            self.edc_send_job(EdcJob::BSkip { mbx: mb_x, mby: mb_y, regions });
            return Ok(());
        }
        // Zero residual: the prediction IS the reconstruction — copy it row-wise,
        // stepping the destination by the stride rather than multiplying per row.
        let mut d = (mb_y * 16) * self.cw + mb_x * 16;
        for dy in 0..16 {
            self.rec_y[d..d + 16].copy_from_slice(&pred_y[dy * 16..dy * 16 + 16]);
            d += self.cw;
        }
        let (ccw, cx0) = (self.ccw, mb_x * 8);
        for c in 0..2 {
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            let mut d = (mb_y * 8) * ccw + cx0;
            for dy in 0..8 {
                plane[d..d + 8].copy_from_slice(&c_pred[c][dy * 8..dy * 8 + 8]);
                d += ccw;
            }
        }
        // nnz stays 0 (no residual) — clear the grids for neighbour context.
        self.clear_mb_nnz(mb_x, mb_y, w4);
        Ok(())
    }

    fn decode_b_skip(&mut self, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        let _sg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::BSkipCold);
        self.route_skip_mbs += 1;
        self.wait_refs_for_mb(mb_y);
        // Each list length read ONCE: the emptiness test and every later
        // `len() - 1` clamp (six reads in all) come from these two.
        let (nref0, nref1) = (self.refs.len(), self.refs1.len());
        if nref0 == 0 || nref1 == 0 {
            return Err(MbError::Unsupported("B without references"));
        }
        let (lref0, lref1) = (nref0 - 1, nref1 - 1);
        let mbw = self.mb_w;
        let addr = mb_y * mbw + mb_x;
        let w4 = mbw * 4;
        // ZERO-BI FAST PATH: when spatial direct derives (0,0)/(0,0) bi motion,
        // colZeroFlag is IRRELEVANT (it only zeroes MVs that are already zero),
        // so the colocated probing, region split, b_mc staging and the pred
        // round-trip all collapse into one fused row-average from the two
        // padded refs straight into the recon planes. b_mc's bi blend applies
        // only IMPLICIT weights, so `None` or (32,32) (both exactly
        // (a+b+1)>>1) is the whole identity condition. FourPeople-class LIGHT
        // streams put 90%+ of their B_Skips here (BSK_ZBI counter).
        // pred_y / c_pred now live in `b_skip_slow` — see there.
        if self.direct_spatial && self.edc_tx.is_none() && !self.k_no_bskipfast {
            // (The FORCED zero-bi run continuation lives in b_skip_hot, inlined
            // at the loop call sites — this cold body only sees non-forced MBs.)
            // A pending span can only occupy the LEFT gather position, and the
            // left member's committed grid values are fully determined by the
            // span KIND — synthesize them instead of flushing, for EVERY kind
            // (the same mapping bz_flush writes).
            let patch = match self.bzspan {
                Some((r, x0, n, k)) if r == mb_y && x0 + n == mb_x => Some(k),
                _ => None,
            };
            if patch.is_none() {
                self.bz_flush();
            }
            let (mut n0, mut n1) = self.b_direct_nbrs(mb_x, mb_y);
            if let Some(k) = patch {
                let (r0, r1, m0, m1): (i32, i32, (i32, i32), (i32, i32)) = match k {
                    BzKind::ZeroBi => (0, 0, (0, 0), (0, 0)),
                    BzKind::ZeroUni(0, ri) => (ri as i32, -1, (0, 0), (0, 0)),
                    BzKind::ZeroUni(_, ri) => (-1, ri as i32, (0, 0), (0, 0)),
                    BzKind::Fp { r0, r1, m0, m1 } => {
                        let mm0 = if r0 >= 0 { (m0.0 as i32, m0.1 as i32) } else { (0, 0) };
                        let mm1 = if r1 >= 0 { (m1.0 as i32, m1.1 as i32) } else { (0, 0) };
                        (r0 as i32, r1 as i32, mm0, mm1)
                    }
                };
                n0[0] = MvNeighbor { available: true, mv: m0, ref_idx: r0 };
                n1[0] = MvNeighbor { available: true, mv: m1, ref_idx: r1 };
            }
            let (refi0, refi1, mv0, mv1, _dz) = Self::b_direct_refs_mvs(&n0, &n1);
            let (a0, a1) = (refi0 >= 0, refi1 >= 0);
            let fast = if a0 && a1 && mv0 == (0, 0) && mv1 == (0, 0) {
                // Same malformed-stream ref clamp as b_mc.
                let r0 = (refi0 as usize).min(lref0);
                let r1 = (refi1 as usize).min(lref1);
                // (0,0) dominates here and is already cached slice-wide by iw00.
                let wgt = if r0 == 0 && r1 == 0 {
                    self.iw00()
                } else {
                    self.implicit_weights(r0 as i32, r1 as i32)
                };
                if wgt.is_none() || wgt == Some((32, 32)) {
                    if refi0 == 0 && refi1 == 0 {
                        if let Some(b) = self.bzero.get_mut(addr) {
            *b = true;
        }
                        // Same constants as the forced arm: recon AND commit
                        // both defer into the span.
                        self.bz_push(mb_x, mb_y, BzKind::ZeroBi);
                        edcstat::bump(&edcstat::BSKB_FAST, 1);
                        return Ok(());
                    }
                    self.recon_b_skip_zero_bi(mb_x, mb_y, r0, r1);
                    true
                } else {
                    false
                }
            } else if a0 != a1 && (if a0 { mv0 } else { mv1 }) == (0, 0) {
                // ZERO-UNI: one active list at (0,0) — b_mc's uni arms are plain
                // unweighted copies. Defer as a memcpy-band span.
                let (list, ri) = if a0 {
                    (0u8, (refi0 as usize).min(lref0) as u8)
                } else {
                    (1u8, (refi1 as usize).min(lref1) as u8)
                };
                self.bz_push(mb_x, mb_y, BzKind::ZeroUni(list, ri));
                edcstat::bump(&edcstat::BSKB_FAST, 1);
                return Ok(());
            } else if (!a0 || (mv0.0 % 4 == 0 && mv0.1 % 4 == 0))
                && (!a1 || (mv1.0 % 4 == 0 && mv1.1 % 4 == 0))
                && self.direct_8x8_inference
            {
                // FULL-PEL arm (the pan case — shields): nonzero MVs make
                // colZeroFlag matter, so probe the four 8x8 corners; a UNIFORM
                // czg keeps the MB one region and the MC is an offset read.
                // Non-uniform czg or an out-of-pad window falls through.
                let mut cz_ok = true;
                let mut czv = false;
                // Same cz-relevance gate as decode_b_direct_n: only a ref-0
                // list with a nonzero MV can be changed by colZeroFlag (fp-arm
                // MVs are nonzero by construction, so refs alone decide).
                let cz_need = refi0 == 0 || refi1 == 0;
                // LOOP-INVARIANT: this gated a `break` INSIDE the probe loop, so
                // a fact known before the loop was re-tested on every probe.
                if cz_need {
                    // Absolute block base, hoisted out of the four probes.
                    let (bx4, by4) = (mb_x * 4, mb_y * 4);
                    for (k, &(ox, oy)) in [(0usize, 0usize), (2, 0), (0, 2), (2, 2)].iter().enumerate() {
                        // col_block takes MB-LOCAL block coords (the whole MB is
                        // the region here); col_zero takes absolute — same
                        // convention as decode_b_direct_n's probe loop.
                        let (colx, coly) = self.col_block(ox, oy);
                        let cz = self.col_zero(bx4 + colx, by4 + coly);
                        if k == 0 {
                            czv = cz;
                        } else if cz != czv {
                            cz_ok = false;
                            break;
                        }
                    }
                }
                if cz_ok {
                    let m0 = if refi0 == 0 && czv { (0, 0) } else { mv0 };
                    let m1 = if refi1 == 0 && czv { (0, 0) } else { mv1 };
                    let r0c = (refi0 as usize).min(lref0);
                    let r1c = (refi1 as usize).min(lref1);
                    let (or0, or1) = (a0.then_some(r0c), a1.then_some(r1c));
                    let wgt_ok = !(a0 && a1) || {
                        let wgt = self.implicit_weights(r0c as i32, r1c as i32);
                        wgt.is_none() || wgt == Some((32, 32))
                    };
                    // SPAN path: prevalidated windows + %8 chroma ⇒ defer as
                    // an offset copy/avg band; otherwise the immediate per-MB
                    // recon below (which handles interpolating chroma).
                    if wgt_ok && self.bz_fp_valid(mb_x, mb_y, or0, or1, m0, m1) {
                        let kind = BzKind::Fp {
                            r0: if a0 { r0c as i8 } else { -1 },
                            r1: if a1 { r1c as i8 } else { -1 },
                            m0: (m0.0 as i16, m0.1 as i16),
                            m1: (m1.0 as i16, m1.1 as i16),
                        };
                        self.bz_push(mb_x, mb_y, kind);
                        edcstat::bump(&edcstat::BSKB_FP, 1);
                        return Ok(());
                    }
                    let ok = wgt_ok && self.recon_b_skip_fp(mb_x, mb_y, or0, or1, m0, m1);
                    if ok {
                        edcstat::bump(&edcstat::BSKB_FP, 1);
                        self.b_set_motion(mb_x, mb_y, 0, 0, 16, 16, refi0, m0, refi1, m1);
                        self.clear_mb_nnz(mb_x, mb_y, w4);
                        return Ok(());
                    }
                }
                false
            } else {
                false
            };
            if fast {
                edcstat::bump(&edcstat::BSKB_FAST, 1);
                self.b_set_motion(mb_x, mb_y, 0, 0, 16, 16, refi0, (0, 0), refi1, (0, 0));
                self.clear_mb_nnz(mb_x, mb_y, w4);
                return Ok(());
            }
            // Fall-through hands the ALREADY-probed neighbours to the slow
            // half so the grid walk is not paid twice.
            return self.b_skip_slow(mb_x, mb_y, Some((n0, n1)), w4);
        } else {
            if self.edc_tx.is_some() {
                self.edc_regions = Some(Vec::with_capacity(4));
            }
            return self.b_skip_slow(mb_x, mb_y, None, w4);
        }
    }

    /// Reconstructs a B macroblock (spec Table 7-14): direct, L0/L1/Bi partitions,
    /// `B_8x8`, or intra.
    fn decode_b_mb(&mut self, r: &mut BitReader, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        // Non-skip B MBs gather neighbor motion/modes — flush any deferred
        // spans before those grids are read.
        self.span_flush();
        self.wait_refs_for_mb(mb_y);
        let mb_type = r.read_ue()?;
        if mb_type >= 23 {
            return self.decode_intra_mb(r, mb_x, mb_y, mb_type - 23);
        }
        if self.refs.is_empty() || self.refs1.is_empty() {
            return Err(MbError::Unsupported("B without references"));
        }
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];

        if mb_type == 0 {
            // B_Direct_16x16 — 8×8 transform allowed only with direct_8x8_inference.
            // FORCED derivation via the zero-bi bitmap (CAVLC parity with the
            // CABAC direct arm): gather + rid/median skipped, chains extended.
            let addr_f = mb_y * self.mb_w + mb_x;
            let forced = self.direct_spatial
                && self.edc_tx.is_none()
                && mb_x > 0
                && mb_y > 0
                && mb_x + 1 < self.mb_w
                && addr_f - self.mb_w >= self.slice_first_mb
                && self.bzero.get(addr_f - 1).copied().unwrap_or(false)
                && self.bzero.get(addr_f.wrapping_sub(self.mb_w)).copied().unwrap_or(false)
                && self
                    .bzero
                    .get(addr_f.wrapping_sub(self.mb_w) + 1)
                    .copied()
                    .unwrap_or(false);
            if forced {
                self.b_direct_region(mb_x, mb_y, 0, 0, 16, 16, &mut pred_y, &mut c_pred, (0, 0, (0, 0), (0, 0), false));
                if let Some(b) = self.bzero.get_mut(addr_f) {
                *b = true;
            }
            } else {
                self.decode_b_direct(mb_x, mb_y, 0, 0, 16, 16, &mut pred_y, &mut c_pred);
            }
            return self.inter_finish(r, mb_x, mb_y, &pred_y, &c_pred, self.direct_8x8_inference, false);
        }
        if mb_type == 22 {
            return self.decode_b_8x8(r, mb_x, mb_y);
        }

        // 16x16 / 16x8 / 8x16 partitions with per-partition L0/L1/Bi.
        let (layout, mvmode, preds) = b_inter_layout(mb_type);
        // mb_pred order: ref_idx_l0 (all L0 parts), ref_idx_l1, mvd_l0, mvd_l1.
        let mut refi = [[-1i32; 2]; 2]; // [part][list]
        for (p, &(_, _, _, _)) in layout.iter().enumerate() {
            if preds[p & 1].uses(0) {
                refi[p][0] = self.read_b_ref(r, 0)?;
            }
        }
        for (p, _) in layout.iter().enumerate() {
            if preds[p & 1].uses(1) {
                refi[p][1] = self.read_b_ref(r, 1)?;
            }
        }
        let mut mvd = [[(0i32, 0i32); 2]; 2];
        for (p, _) in layout.iter().enumerate() {
            if preds[p & 1].uses(0) {
                mvd[p][0] = (read_mvd(r)?, read_mvd(r)?);
            }
        }
        for (p, _) in layout.iter().enumerate() {
            if preds[p & 1].uses(1) {
                mvd[p][1] = (read_mvd(r)?, read_mvd(r)?);
            }
        }
        // Per partition: predict + commit each list's MV, then motion-compensate.
        for (p, &(rx, ry, rw, rh)) in layout.iter().enumerate() {
            let (pbx, pby) = ((mb_x * 4 + rx / 4) as isize, (mb_y * 4 + ry / 4) as isize);
            let pwb = (rw / 4) as isize;
            let mut mv = [(0i32, 0i32); 2];
            for list in 0..2 {
                if refi[p][list] >= 0 {
                    let n = self.mv_neighbors_list(pbx, pby, pwb, list);
                    let pmv = predict_partition_mv(mvmode, p, n[0], n[1], n[2], refi[p][list]);
                    mv[list] = (pmv.0 + mvd[p][list].0, pmv.1 + mvd[p][list].1);
                }
            }
            self.b_set_motion(mb_x, mb_y, rx, ry, rw, rh, refi[p & 3][0], mv[0], refi[p & 3][1], mv[1]);
            // Spec-correct bi-prediction (average of L0 and L1), matching the CABAC
            // path. This used to replicate an openh264 bug for a Bi 16x8/8x16
            // partition -- openh264 mis-handles the destination buffer there, so
            // partition 0 came out List-1-only and partition 1 List-0-only. That was
            // deliberate when openh264's h264dec WAS the conformance oracle, but the
            // gate is ffmpeg now and the CABAC path already went spec-correct; the
            // CAVLC path was simply left behind. Measured: mb_type 12..21 (every B
            // 16x8/8x16 with at least one Bi partition) were 100% wrong vs ffmpeg,
            // while 1..11 (no Bi partition) were only collaterally damaged.
            self.b_mc_or_record(mb_x, mb_y, rx, ry, rw, rh, refi[p & 3][0], mv[0], refi[p & 3][1], mv[1], &mut pred_y, &mut c_pred);
        }
        self.inter_finish(r, mb_x, mb_y, &pred_y, &c_pred, true, false)
    }

    /// Reconstructs a `B_8x8` macroblock: four 8×8 sub-macroblock partitions, each
    /// direct or L0/L1/Bi with its own sub-partitioning (spec Table 7-18).
    fn decode_b_8x8(&mut self, r: &mut BitReader, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        let mut sub = [0u32; 4];
        for s in sub.iter_mut() {
            let v = r.read_ue()?;
            if v > 12 {
                return Err(MbError::Unsupported("invalid B sub_mb_type"));
            }
            *s = v;
        }
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        // ref_idx for all 8×8 partitions (L0 batch, then L1 batch), for the
        // non-direct sub-partitions.
        let mut refi = [[-1i32; 2]; 4];
        for (p, &st) in sub.iter().enumerate() {
            if st != 0 && b_sub_uses(st, 0) {
                refi[p][0] = self.read_b_ref(r, 0)?;
            }
        }
        for (p, &st) in sub.iter().enumerate() {
            if st != 0 && b_sub_uses(st, 1) {
                refi[p][1] = self.read_b_ref(r, 1)?;
            }
        }
        // mvd: all mvd_l0 (partition-major, sub-partition order), then all mvd_l1.
        //
        // FIXED ARRAYS, NOT `Vec::new()` + push. These are per-MACROBLOCK on every
        // B_8x8, and a growing Vec allocated (and reallocated) twice per MB — on a
        // B-heavy stream that is thousands of allocations per frame for data whose
        // maximum size is a compile-time constant: 4 partitions x at most 4
        // sub-partitions = 16 entries. Indexing a fixed array cannot exceed that, and
        // an out-of-range index would panic rather than misbehave, so the bound is
        // enforced either way and this crate stays forbid(unsafe).
        const MAX_MVD: usize = 16;
        let mut mvd0 = [(0i32, 0i32); MAX_MVD];
        let mut mvd1 = [(0i32, 0i32); MAX_MVD];
        let (mut n0, mut n1) = (0usize, 0usize);
        for &st in &sub {
            if st != 0 && b_sub_uses(st, 0) {
                for _ in b_sub_parts(st) {
                    mvd0[n0] = (read_mvd(r)?, read_mvd(r)?);
                    n0 += 1;
                }
            }
        }
        for &st in &sub {
            if st != 0 && b_sub_uses(st, 1) {
                for _ in b_sub_parts(st) {
                    mvd1[n1] = (read_mvd(r)?, read_mvd(r)?);
                    n1 += 1;
                }
            }
        }
        // Decode each 8×8 partition.
        // Spatial-direct A/B/C are MB-level — walk once if any sub is direct.
        // `dmemo=0` rewalks every direct 8×8 (A/B oracle).
        let hoisted = if self.direct_spatial
            && direct_memo_on()
            && sub.iter().any(|&t| t == 0)
        {
            Some(self.b_direct_nbrs(mb_x, mb_y))
        } else {
            None
        };
        let (mut i0, mut i1) = (0usize, 0usize);
        for (p, &st) in sub.iter().enumerate() {
            let (b8x, b8y) = ((p % 2) * 8, (p / 2) * 8);
            if st == 0 {
                match hoisted {
                    Some((n0, n1)) => self.decode_b_direct_n(
                        mb_x, mb_y, b8x, b8y, 8, 8, &mut pred_y, &mut c_pred, n0, n1,
                    ),
                    None => self.decode_b_direct(
                        mb_x, mb_y, b8x, b8y, 8, 8, &mut pred_y, &mut c_pred,
                    ),
                }
                continue;
            }
            for &(sx, sy, sw, sh) in b_sub_parts(st) {
                let (px, py) = (b8x + sx, b8y + sy);
                let (pbx, pby) = ((mb_x * 4 + px / 4) as isize, (mb_y * 4 + py / 4) as isize);
                let pwb = (sw / 4) as isize;
                let mut mv = [(0i32, 0i32); 2];
                if b_sub_uses(st, 0) {
                    let n = self.mv_neighbors_list(pbx, pby, pwb, 0);
                    let pmv = predict_mv(n[0], n[1], n[2], refi[p & 3][0]);
                    let d = mvd0[i0 & 15];
                    i0 += 1;
                    mv[0] = (pmv.0 + d.0, pmv.1 + d.1);
                }
                if b_sub_uses(st, 1) {
                    let n = self.mv_neighbors_list(pbx, pby, pwb, 1);
                    let pmv = predict_mv(n[0], n[1], n[2], refi[p & 3][1]);
                    let d = mvd1[i1 & 15];
                    i1 += 1;
                    mv[1] = (pmv.0 + d.0, pmv.1 + d.1);
                }
                self.b_set_motion(mb_x, mb_y, px, py, sw, sh, refi[p & 3][0], mv[0], refi[p & 3][1], mv[1]);
                self.b_mc_or_record(mb_x, mb_y, px, py, sw, sh, refi[p & 3][0], mv[0], refi[p & 3][1], mv[1], &mut pred_y, &mut c_pred);
            }
        }
        // noSubMbPartSizeLessThan8x8: each sub-partition must be ≥ 8×8 (direct
        // counts only with the 8×8 inference flag).
        let allow_8x8 = sub
            .iter()
            .all(|&st| if st == 0 { self.direct_8x8_inference } else { st <= 3 });
        self.inter_finish(r, mb_x, mb_y, &pred_y, &c_pred, allow_8x8, false)
    }

    /// Reconstructs a `P_8x8` macroblock: four 8×8 sub-macroblock partitions,
    /// each independently split (8×8 / 8×4 / 4×8 / 4×4) with its own motion
    /// vector(s). `ref0` is `P_8x8ref0` (every `ref_idx` forced to 0, not coded).
    fn decode_p8x8(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        ref0: bool,
    ) -> Result<(), MbError> {
        if self.refs.is_empty() {
            return Err(MbError::Unsupported("inter without reference"));
        }
        let w4 = self.mb_w * 4;
        let (ch, cch) = (self.mb_h * 16, self.mb_h * 8);
        let num_refs = self.refs.len();

        // mb_pred order (spec §7.3.5.2): all sub_mb_type, then all ref_idx_l0,
        // then all mvd_l0 (partition-major, sub-partition order within each).
        let mut sub_types = [0u32; 4];
        for st in sub_types.iter_mut() {
            let v = r.read_ue()?;
            if v > 3 {
                return Err(MbError::Unsupported("B-slice / invalid sub_mb_type"));
            }
            *st = v;
        }
        let mut ref_idxs = [0i32; 4];
        if self.num_ref_active > 1 && !ref0 {
            for ri in ref_idxs.iter_mut() {
                *ri = read_ref_idx(r, self.num_ref_active)?;
                if *ri as usize >= num_refs {
                    return Err(MbError::Truncated); // references a non-existent picture
                }
            }
        }

        // Per sub-partition (in decoding order): median MV prediction from the
        // committed neighbor grid, mvd, commit, then motion-compensate. Committing
        // before the next prediction is what lets sub-partitions chain correctly.
        // D14b: P_8x8 defers too. Syncing before it instead cost 9,772 pipeline
        // drains per stream (45 per 1000 MBs, vs CABAC's 3.3) because P_8x8 is
        // common in CAVLC P slices — and the seam measured 1.65-1.97x SLOWER
        // for it. Deferring is byte-identical for sub-partitions: the worker
        // motion-compensates per 4x4 from the committed grids, which is exactly
        // how the CABAC path already handles P_8x8, and a 6-tap filter applied
        // per-4x4 with the same MV gives the same pixels as one 8x8 call.
        let defer = self.edc_tx.is_some() || self.edc_active;

        // ── PHASE 1: PARSE + COMMIT. Must always run to completion. ──────────
        //
        // These two are interleaved BY NECESSITY: each sub-partition's MV
        // prediction reads the grids the previous one committed, so they cannot
        // be separated from each other. But they consume BITSTREAM, so nothing
        // here may ever be skipped conditionally.
        //
        // This phase split is a STRUCTURAL guard, not a tidy-up. When MC lived
        // inside this loop, deferring it was written as a `break` — which also
        // skipped the `read_se` mvd reads, desynced the bitstream, and
        // mis-parsed as a B-slice sub_mb_type on a Baseline stream. It happened
        // to crash; a desync that stayed IN RANGE would have produced plausible
        // garbage instead. With MC in its own pass below, skipping pixel work
        // cannot reach the bitstream at all — the mistake is unavailable.
        let mut regions: [(usize, usize, usize, usize, i32, (i32, i32)); 16] =
            [(0, 0, 0, 0, 0, (0, 0)); 16];
        let mut nreg = 0usize;
        for part in 0..4usize {
            let refi = ref_idxs[part];
            let (b8x, b8y) = ((part % 2) * 8, (part / 2) * 8);
            for &(srx, sry, srw, srh) in sub_mb_partitions(sub_types[part]) {
                let (px, py) = (b8x + srx, b8y + sry);
                let (pbx, pby) = ((mb_x * 4 + px / 4) as isize, (mb_y * 4 + py / 4) as isize);
                let [a, b, c] = self.mv_neighbors_block(pbx, pby, (srw / 4) as isize);
                let pmv = predict_mv(a, b, c, refi);
                let mvd_x = read_mvd(r)?;
                let mvd_y = read_mvd(r)?;
                let mv = (pmv.0 + mvd_x, pmv.1 + mvd_y);
                for by in py / 4..py / 4 + srh / 4 {
                    for bx in px / 4..px / 4 + srw / 4 {
                        let idx = (mb_y * 4 + by) * w4 + (mb_x * 4 + bx);
                        if let (Some(m), Some(it), Some(rf), Some(cd)) = (
                            self.mv_y.get_mut(idx),
                            self.inter_y.get_mut(idx),
                            self.ref_idx_y.get_mut(idx),
                            self.coded_y.get_mut(idx),
                        ) {
                            (*m, *it, *rf, *cd) = (mv, true, refi, true);
                        }
                    }
                }
                regions[nreg & 15] = (px, py, srw, srh, refi, mv);
                nreg += 1;
            }
        }

        // ── PHASE 2: PIXEL WORK ONLY. Reads no bitstream; safe to skip. ──────
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        if !defer {
            for &(px, py, srw, srh, refi, mv) in &regions[..nreg] {
                let Some(reference) = self.refs.get(refi as usize) else { continue };
                let mut tmp = [0u8; 256];
                mc_luma_padded(&*reference.luma_guard(reference.ch), reference.lstride(), crate::LPAD, self.cw, ch, mb_x * 16 + px, mb_y * 16 + py, srw, srh, mv.0, mv.1, &mut tmp);
                restride(&mut pred_y, 16, px, py, &tmp, srw, srh);
                let (crx, cry, crw, crh) = (px / 2, py / 2, srw / 2, srh / 2);
                for cc in 0..2 {
                    let rc = if cc == 0 { &*reference.chroma_guard(0, reference.ch) } else { &*reference.chroma_guard(1, reference.ch) };
                    let mut tc = [0u8; 64];
                    mc_chroma_padded(rc, reference.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8 + crx, mb_y * 8 + cry, crw, crh, mv.0, mv.1, &mut tc);
                    restride(&mut c_pred[cc], 8, crx, cry, &tc, crw, crh);
                }
                self.weight_partition(
                    &mut pred_y, &mut c_pred, 0, refi as usize, px, py, srw, srh,
                );
            }
        }

        // P_8x8 allows the 8×8 transform only when every sub-partition is 8×8.
        let allow_8x8 = sub_types.iter().all(|&t| t == 0);
        self.inter_finish(r, mb_x, mb_y, &pred_y, &c_pred, allow_8x8, defer)
    }

    /// Reconstructs a `P_Skip` macroblock: motion-compensate from the reference
    /// at the skip MV, with no residual.
    /// Records a B MC region (threaded mode) or executes it inline — the SAME
    /// arguments as `b_mc`; the recorded arm resolves the implicit weights at
    /// parse time (identical function, parse-side data).
    #[allow(clippy::too_many_arguments)]
    fn b_mc_or_record(&mut self, mb_x: usize, mb_y: usize, px: usize, py: usize, rw: usize, rh: usize, refi0: i32, mv0: (i32, i32), refi1: i32, mv1: (i32, i32), pred_y: &mut [u8; 256], c_pred: &mut [[u8; 64]; 2]) {
        if self.edc_regions.is_some() {
            // Mirror `b_mc`'s malformed-stream armor EXACTLY before touching the
            // ref lists: the inline path clamps the indices and bails on empty
            // lists BEFORE computing weights; calling `implicit_weights` with the
            // raw indices re-introduced the panic the armor exists to prevent
            // (found by the fuzzer, via the unwind-guard that turned the
            // resulting worker deadlock back into a diagnosable failure).
            let cr0 = if refi0 >= 0 { (refi0 as usize).min(self.refs.len().saturating_sub(1)) as i32 } else { -1 };
            let cr1 = if refi1 >= 0 { (refi1 as usize).min(self.refs1.len().saturating_sub(1)) as i32 } else { -1 };
            let w = if (cr0 >= 0 && self.refs.is_empty()) || (cr1 >= 0 && self.refs1.is_empty()) {
                None // the worker's port returns before reading the weights
            } else {
                self.implicit_weights(cr0, cr1)
            };
            // Cannot bind above: `implicit_weights` needs `&mut self` between the
            // guard and here. The guard already proved this is `Some`, so the
            // `else` is unreachable -- but an unreachable no-op is the correct
            // shape for armor code, not an `unwrap` that can abort a decode.
            if let Some(regions) = self.edc_regions.as_mut() {
                regions.push(BRegion { px, py, rw, rh, refi0, refi1, mv0, mv1, w });
            }
            return;
        }
        self.b_mc(mb_x, mb_y, px, py, rw, rh, refi0, mv0, refi1, mv1, pred_y, c_pred);
    }

    /// Builds the worker's owned pixel context from `self` (planes MOVED out,
    /// shared read-only state cloned, filter inputs snapshotted).
    fn edc_take_ctx(&mut self) -> PixelCtx {
        PixelCtx {
            rec_y: std::mem::take(&mut self.rec_y),
            rec_u: std::mem::take(&mut self.rec_u),
            rec_v: std::mem::take(&mut self.rec_v),
            bak_y: std::mem::take(&mut self.bak_y),
            bak_u: std::mem::take(&mut self.bak_u),
            bak_v: std::mem::take(&mut self.bak_v),
            refs: self.refs.clone(),
            refs1: self.refs1.clone(),
            weights: self.weights.clone(),
            weights_l0id: self.weights_l0id,
            scaling: self.scaling,
            scaling8: self.scaling8,
            cw: self.cw,
            ccw: self.ccw,
            mb_w: self.mb_w,
            mb_h: self.mb_h,
            chroma_qp_offset: self.chroma_qp_offset,
            flt_rows: self.flt_rows,
            db_ena: self.db_ena,
            db_oa: self.db_oa,
            db_ob: self.db_ob,
            cur_qp: self.cur_qp,
            qp_grid: self.mb_qp.clone(),
            t8_grid: self.mb_t8x8.clone(),
            bs_store: self.bs_frame.clone(),
            progress: self.progress.clone(),
        }
    }

    /// Restores the planes (and the filter watermark) from a returned context.
    fn edc_restore_ctx(&mut self, ctx: PixelCtx) {
        self.rec_y = ctx.rec_y;
        self.rec_u = ctx.rec_u;
        self.rec_v = ctx.rec_v;
        self.bak_y = ctx.bak_y;
        self.bak_u = ctx.bak_u;
        self.bak_v = ctx.bak_v;
        self.flt_rows = ctx.flt_rows;
    }

    /// Intra macroblocks read neighbour PIXELS: fetch the context from the
    /// worker (which drains all prior jobs first — the channel is FIFO) and
    /// install the planes so the inline intra path runs unchanged. The context
    /// is given back lazily at the next job/row/slice-end (`edc_giveback`), so
    /// consecutive intra macroblocks pay ONE round-trip.
    /// Queue a pixel job for the worker (D10). Batched per row; see `EdcMsg::Batch`.
    #[inline]
    fn edc_send_job(&mut self, job: EdcJob) {
        edcstat::bump(&edcstat::JOBS, 1);
        if !batch_on() {
            self.edc_tx
                .as_ref()
                .unwrap()
                .send(EdcMsg::Job(job))
                .expect("worker alive");
            return;
        }
        self.edc_batch.push(job);
    }

    /// Ship the accumulated row batch. MUST be called before anything that
    /// depends on those jobs having been applied: the row's `Row` filter
    /// message, a `NeedCtx` handover, and slice end.
    fn edc_flush_batch(&mut self) {
        if self.edc_batch.is_empty() {
            return;
        }
        // Replace with a PRE-RESERVED buffer rather than the empty Vec
        // `mem::take` would leave: otherwise each row reallocs and regrows from
        // zero, trading 208k channel sends for ~7 reallocs x 3k rows.
        let cap = self.edc_batch.capacity().max(self.mb_w);
        let jobs = std::mem::replace(&mut self.edc_batch, Vec::with_capacity(cap));
        edcstat::bump(&edcstat::BATCHES, 1);
        self.edc_tx
            .as_ref()
            .unwrap()
            .send(EdcMsg::Batch(jobs))
            .expect("worker alive");
    }

    fn edc_intra_sync(&mut self) {
        if self.edc_tx.is_none() {
            self.edc_flush();
            return;
        }
        if self.edc_parked.is_some() {
            return; // already holding
        }
        // ORDER: drain the batch before taking the planes, or those jobs would
        // be applied to a context the parse thread is concurrently holding.
        self.edc_flush_batch();
        edcstat::bump(&edcstat::NEEDCTX, 1);
        self.edc_tx.as_ref().unwrap().send(EdcMsg::NeedCtx).expect("worker alive");
        let mut ctx = self.edc_ctx_rx.as_ref().unwrap().recv().expect("worker ctx");
        self.rec_y = std::mem::take(&mut ctx.rec_y);
        self.rec_u = std::mem::take(&mut ctx.rec_u);
        self.rec_v = std::mem::take(&mut ctx.rec_v);
        self.bak_y = std::mem::take(&mut ctx.bak_y);
        self.bak_u = std::mem::take(&mut ctx.bak_u);
        self.bak_v = std::mem::take(&mut ctx.bak_v);
        self.flt_rows = ctx.flt_rows;
        self.edc_parked = Some(ctx);
    }

    /// Returns a held context to the worker (inverse of `edc_intra_sync`).
    /// NOTE (D10): this is called per-macroblock on the job paths, so it must
    /// NOT flush the batch — that would undo the batching. It is safe: the
    /// parked state is only ever entered through `edc_intra_sync`, which
    /// flushes before taking the planes, so nothing can be queued-but-unsent
    /// while the parse thread holds them.
    fn edc_giveback(&mut self) {
        if let Some(mut parked) = self.edc_parked.take() {
            parked.rec_y = std::mem::take(&mut self.rec_y);
            parked.rec_u = std::mem::take(&mut self.rec_u);
            parked.rec_v = std::mem::take(&mut self.rec_v);
            parked.bak_y = std::mem::take(&mut self.bak_y);
            parked.bak_u = std::mem::take(&mut self.bak_u);
            parked.bak_v = std::mem::take(&mut self.bak_v);
            parked.flt_rows = self.flt_rows;
            // Fail-soft: on the unwind path the worker may already be gone;
            // dropping the parked context is acceptable there (the planes are
            // lost, but the panic is being propagated anyway).
            let _ = self.edc_back_tx.as_ref().unwrap().send(parked);
        }
    }

    /// Parse-side twin of the nnz/coded grid writes `add_inter_residual` does
    /// inline — the worker's port omits them (they are PARSE state: deblock
    /// derivation and the CAVLC nC contexts read them), so the threaded path
    /// commits them here, from the same parsed counts (their equality with the
    /// recon-side recount is the Part 8 nnz-threading brick's own invariant).
    fn edc_commit_nnz(&mut self, mbx: usize, mby: usize, t8: bool, nnzs: &[u8; 24], cbp_chroma: u32) {
        // BUILD THE RASTER LOCALLY, THEN COPY ROW-WISE. Both luma arms scattered
        // sixteen individually bounds-checked stores into the frame grid (the t8
        // arm through a 2x2-of-2x2 nest, the other through the z-order scan
        // table); chroma scattered eight more. Assembling the macroblock's own
        // 4x4 raster on the stack first turns that into four contiguous row
        // copies per plane.
        let (w4r, w2r) = (self.mb_w * 4, self.mb_w * 2);
        let mut raster = [0u8; 16];
        if t8 {
            for b8 in 0..4usize {
                let (b8x, b8y) = (b8 % 2, b8 / 2);
                let n = nnzs[b8 * 4];
                for sy in 0..2 {
                    for sx in 0..2 {
                        raster[(b8y * 2 + sy) * 4 + b8x * 2 + sx] = n;
                    }
                }
            }
        } else {
            for (blk, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
                raster[lby * 4 + lbx] = nnzs[blk];
            }
        }
        for by in 0..4usize {
            let a = (mby * 4 + by) * w4r + mbx * 4;
            self.nnz_y[a..a + 4].copy_from_slice(&raster[by * 4..by * 4 + 4]);
        }
        if cbp_chroma == 2 {
            for c in 0..2usize {
                let mut cr = [0u8; 4];
                for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                    cr[by * 2 + bx] = nnzs[(16 + c * 4 + by * 2 + bx).min(23)];
                }
                for by in 0..2usize {
                    let a = (mby * 2 + by) * w2r + mbx * 2;
                    self.nnz_c[c][a..a + 2].copy_from_slice(&cr[by * 2..by * 2 + 2]);
                }
            }
        }
    }

    /// Flush the entropy-decouple job queue: replay every deferred pixel job
    /// in parse order. Called before any intra macroblock (its reconstruction
    /// reads neighbour PIXELS), before row filtering, at B-branch entry, at
    /// slice end, and at `deblock()` as a backstop.
    /// Per-macroblock guard: the B arm calls this once per B MB — the empty
    /// test inlines, the drain body stays outlined.
    #[inline(always)]
    fn edc_flush(&mut self) {
        if self.edc_jobs.is_empty() {
            return;
        }
        self.edc_flush_slow();
    }

    fn edc_flush_slow(&mut self) {
        let jobs = std::mem::take(&mut self.edc_jobs);
        // Band identity holds unweighted OR under identity weights (the x264
        // weightp=2 common case: a table in every P slice, identity outside fades).
        let band_ok = self.weights.is_none() || self.weights_id0;
        // Measurement: nonzero-MV skips sitting in same-row runs of >=2 EQUAL
        // MVs (the next band candidate). counted_until stops double-counting.
        let mut counted_until = 0usize;
        let mut i = 0usize;
        while i < jobs.len() {
            let j = &jobs[i];
            match j {
                EdcJob::Skip { mbx, mby, mv } => {
                    // mb_skip_run band coalescing: gather the maximal run of
                    // consecutive same-row (0,0)-skips and recon it as ONE
                    // band copy (weighted-P falls back — the copy identity
                    // only holds unweighted).
                    if *mv == (0, 0) && band_ok && !no_skipband() {
                        let (x0, y0) = (*mbx, *mby);
                        let mut n = 1usize;
                        while let Some(EdcJob::Skip { mbx: nx, mby: ny, mv: nmv }) = jobs.get(i + n) {
                            if *ny == y0 && *nx == x0 + n && *nmv == (0, 0) {
                                n += 1;
                            } else {
                                break;
                            }
                        }
                        self.recon_p_skip_band(x0, y0, n);
                        if double_recon() {
                            edcstat::bump(&edcstat::DOUBLED, n as u64);
                            self.recon_p_skip_band(x0, y0, n);
                        }
                        i += n;
                        continue;
                    }
                    edcstat::bump(&edcstat::SKIP_SINGLES, 1);
                    if *mv != (0, 0) && i >= counted_until && edcstat::on() {
                        let (x0, y0) = (*mbx, *mby);
                        let mut n2 = 1usize;
                        while let Some(EdcJob::Skip { mbx: nx, mby: ny, mv: nmv }) = jobs.get(i + n2) {
                            if *ny == y0 && *nx == x0 + n2 && nmv == mv { n2 += 1; } else { break; }
                        }
                        if n2 >= 2 {
                            let fp = mv.0 % 4 == 0 && mv.1 % 4 == 0;
                            edcstat::bump(if fp { &edcstat::PEQ_FP } else { &edcstat::PEQ_FRAC }, n2 as u64);
                        }
                        counted_until = i + n2;
                    }
                    self.recon_p_skip(*mbx, *mby, *mv);
                    if double_recon() {
                        edcstat::bump(&edcstat::DOUBLED, 1);
                        self.recon_p_skip(*mbx, *mby, *mv);
                    }
                }
                EdcJob::Inter(job) => {
                    self.recon_p_inter(job);
                    if double_recon() {
                        edcstat::bump(&edcstat::DOUBLED, 1);
                        self.recon_p_inter(job);
                    }
                }
                EdcJob::InterNoRes(job) => {
                    // D9b: do NOT to_full() — that memset ~2.5 KB of zeros per MB
                    // then walked add_inter_residual's all-zero path. MC + plane copy.
                    self.recon_p_inter_nores(job);
                    if double_recon() {
                        edcstat::bump(&edcstat::DOUBLED, 1);
                        self.recon_p_inter_nores(job);
                    }
                }
                // B jobs exist only in worker (MT) mode and are never queued
                // here — the single-thread seam keeps B inline. Not reachable
                // from any input (the push sites are gated on `edc_tx`).
                EdcJob::B(_) | EdcJob::BSkip { .. } => unreachable!("B jobs are worker-only"),
            }
            i += 1;
        }
        // Hand the (now empty) Vec back so its allocation is reused.
        self.edc_jobs = jobs;
        self.edc_jobs.clear();
    }

    /// Reconstructs one CABAC P inter macroblock from its parse job — the
    /// pixel half of the entropy-decouple seam (docs/entropy-decouple-plan.md
    /// E1). Reads NOTHING from parse state except the frame grids this MB's
    /// parse already committed (its own block MVs/refs, re-gathered below —
    /// stable after commit) and the immutable DPB; called either inline
    /// (seam off / flush disabled) or in-order at a flush point. Byte-
    /// identical to the former inline block by construction: replay order
    /// equals inline order at every pixel-observable point (intra reads, row
    /// filtering) because flushes precede both.
    /// The P-inter reconstruction body, taking its inputs directly rather than
    /// through a `PInterJob`. Split out so the residual planes can be passed as
    /// `Option`s (absent == nothing was parsed) instead of forcing every caller
    /// to own a zeroed copy. NOTE: it re-gathers `gmv`/`gref` from the frame
    /// grids rather than reading the job's copies — those are for the worker,
    /// which must not touch the parse thread's grids.
    #[allow(clippy::too_many_arguments)]
    fn recon_p_inter_parts(
        &mut self,
        mbx: usize,
        mby: usize,
        qp: u8,
        cbp_chroma: u32,
        luma_scan: Option<&[[i32; 16]; 16]>,
        luma8: Option<&[[i32; 64]; 4]>,
        cdc: &[[i32; 4]; 2],
        cac: Option<&[[[i32; 16]; 4]; 2]>,
        nnzs: &[u8; 24],
    ) {
        let mbw = self.mb_w;
        // `add_inter_residual` (and anything under it) reads `self.cur_qp`,
        // which at FLUSH time belongs to a later macroblock — replay must
        // restore this MB's qp. The x264 corpus (near-constant QP) could not
        // see this; the encoder's delta-QP roundtrip stream caught it.
        let saved_qp = self.cur_qp;
        self.cur_qp = qp;
                    // ---- Recon: motion-comp (per 4×4 luma / co-located 2×2 chroma using the
                    // committed grid MV — the 6-tap/bilinear filter is per-output-pixel, so
                    // per-block MC is bit-identical to per-partition MC) + residual add via the
                    // SAME reconstruct_4x4 as intra, with the MC output as the prediction.
                    let w4r = mbw * 4;
                    let mut pred_y = [0u8; 256];
                    let mut c_pred = [[0u8; 64]; 2];
                    {
                        // MC-CALL COALESCING (side-by-side descent, dec target #2): the old
                        // loop paid 16 mc_luma(4×4) + 32 mc_chroma(2×2) per MB regardless of
                        // partitioning — 48 calls even for a single-MV 16×16 MB, and the
                        // per-call glue around 2.4M calls was ~40% of decoding real-world
                        // (x264) streams. The 6-tap/bilinear filters are per-output-pixel,
                        // so merging blocks with equal (mv, ref) into one wider MC call is
                        // BIT-IDENTICAL; the rect ladder mirrors the partition shapes.
                        let _ms = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMcStage);
                        let (rh16, cch) = (self.mb_h * 16, self.mb_h * 8);
                        let mut gmv = [(0i32, 0i32); 16];
                        let mut gref = [0usize; 16];
                        let _gg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::MvGrid);
                        let nrefs = self.refs.len() - 1;
                        for by in 0..4usize {
                            // Row-contiguous: one slice copy for the MVs.
                            let row = (mby * 4 + by) * w4r + mbx * 4;
                            gmv[by * 4..by * 4 + 4].copy_from_slice(&self.mv_y[row..row + 4]);
                            let ridx = &self.ref_idx_y[row..row + 4];
                            for bx in 0..4usize {
                                // Per-block reference (multi-ref P): ref_idx_l0 committed to the
                                // grid. Clamp — a corrupt stream can over-range it (never panic).
                                gref[by * 4 + bx] = (ridx[bx].max(0) as usize).min(nrefs);
                            }
                        }
                        drop(_gg);
                        // All blocks of the rect (in 4×4-block units) match its top-left?
                        let rect_eq = |x4: usize, y4: usize, w4: usize, h4: usize| -> bool {
                            let t = y4 * 4 + x4;
                            (0..h4).all(|dy| {
                                (0..w4).all(|dx| {
                                    let b = ((y4 + dy) * 4 + (x4 + dx)) & 15;
                                    gmv[b] == gmv[t] && gref[b] == gref[t]
                                })
                            })
                        };
                        let refs = &self.refs;
                        let (cw, ccw) = (self.cw, self.ccw);
                        let mc_rect = |x4: usize,
                                           y4: usize,
                                           w4: usize,
                                           h4: usize,
                                           pred_y: &mut [u8; 256],
                                           c_pred: &mut [[u8; 64]; 2]| {
                            let b = y4 * 4 + x4;
                            let (mv, gr) = (gmv[b & 15], gref[b & 15]);
                            // `gref` holds a reference-list slot; a slot the list
                            // does not have means there is nothing to predict from,
                            // so the rect is left as it stands.
                            let Some(reference) = refs.get(gr) else { return };
                            let (w, h) = (w4 * 4, h4 * 4);
                            // A FULL-WIDTH rect (w == 16, so x4 == 0) occupies contiguous
                            // whole rows of `pred_y` — the MC output layout and the
                            // destination layout coincide, so MC writes the prediction
                            // buffer DIRECTLY. The staging copy exists only for narrow
                            // rects, whose rows really are strided in `pred_y`. This is
                            // the diagnosis's "stage-boundary materialization" tax paid
                            // by the dominant 16×16/16×8 shapes: 256 B of `t` zeroing
                            // plus a 256 B copy per rect, for nothing.
                            if w == 16 {
                                rusty_h264_common::inter::with_mc_scratch(|scr| rusty_h264_common::inter::mc_luma_padded_pre(scr, &*reference.luma_guard(reference.ch), reference.lstride(), crate::LPAD, cw, rh16, mbx * 16, mby * 16 + y4 * 4, w, h, mv.0, mv.1, &mut pred_y[y4 * 64..y4 * 64 + w * h]));
                            } else {
                                let mut t = [0u8; 256];
                                rusty_h264_common::inter::with_mc_scratch(|scr| rusty_h264_common::inter::mc_luma_padded_pre(scr, &*reference.luma_guard(reference.ch), reference.lstride(), crate::LPAD, cw, rh16, mbx * 16 + x4 * 4, mby * 16 + y4 * 4, w, h, mv.0, mv.1, &mut t[..w * h]));
                                let _pb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
                                for dy in 0..h {
                                    pred_y[(y4 * 4 + dy) * 16 + x4 * 4..][..w]
                                        .copy_from_slice(&t[dy * w..dy * w + w]);
                                }
                            }
                            let (cw4, ch4) = (w4 * 2, h4 * 2);
                            let nc = cw4 * ch4;
                            let (gu, gv) = (reference.chroma_guard(0, reference.ch), reference.chroma_guard(1, reference.ch));
                            // U+V paired: one setup serves both planes (see
                            // mc_chroma_padded_pair). Full-width coincidence:
                            // cw4 == 8 rows are contiguous in the 8-wide plane.
                            if cw4 == 8 {
                                let [cu, cv] = &mut *c_pred;
                                rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, reference.cstride(), crate::CPAD, ccw, cch, mbx * 8, mby * 8 + y4 * 2, cw4, ch4, mv.0, mv.1, &mut cu[y4 * 16..y4 * 16 + nc], &mut cv[y4 * 16..y4 * 16 + nc]);
                            } else {
                                let (mut tu, mut tv) = ([0u8; 64], [0u8; 64]);
                                rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, reference.cstride(), crate::CPAD, ccw, cch, mbx * 8 + x4 * 2, mby * 8 + y4 * 2, cw4, ch4, mv.0, mv.1, &mut tu[..nc], &mut tv[..nc]);
                                let _pb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
                                for (cc, tc) in [(0usize, &tu), (1, &tv)] {
                                    for dy in 0..ch4 {
                                        c_pred[cc][(y4 * 2 + dy) * 8 + x4 * 2..][..cw4]
                                            .copy_from_slice(&tc[dy * cw4..dy * cw4 + cw4]);
                                    }
                                }
                            }
                        };
                        if rect_eq(0, 0, 4, 4) {
                            mc_rect(0, 0, 4, 4, &mut pred_y, &mut c_pred);
                        } else if rect_eq(0, 0, 4, 2) && rect_eq(0, 2, 4, 2) {
                            mc_rect(0, 0, 4, 2, &mut pred_y, &mut c_pred);
                            mc_rect(0, 2, 4, 2, &mut pred_y, &mut c_pred);
                        } else if rect_eq(0, 0, 2, 4) && rect_eq(2, 0, 2, 4) {
                            mc_rect(0, 0, 2, 4, &mut pred_y, &mut c_pred);
                            mc_rect(2, 0, 2, 4, &mut pred_y, &mut c_pred);
                        } else {
                            for q in 0..4usize {
                                let (qx, qy) = ((q % 2) * 2, (q / 2) * 2);
                                if rect_eq(qx, qy, 2, 2) {
                                    mc_rect(qx, qy, 2, 2, &mut pred_y, &mut c_pred);
                                } else if rect_eq(qx, qy, 2, 1) && rect_eq(qx, qy + 1, 2, 1) {
                                    mc_rect(qx, qy, 2, 1, &mut pred_y, &mut c_pred);
                                    mc_rect(qx, qy + 1, 2, 1, &mut pred_y, &mut c_pred);
                                } else if rect_eq(qx, qy, 1, 2) && rect_eq(qx + 1, qy, 1, 2) {
                                    mc_rect(qx, qy, 1, 2, &mut pred_y, &mut c_pred);
                                    mc_rect(qx + 1, qy, 1, 2, &mut pred_y, &mut c_pred);
                                } else {
                                    for j in 0..4usize {
                                        mc_rect(qx + (j % 2), qy + (j / 2), 1, 1, &mut pred_y, &mut c_pred);
                                    }
                                }
                            }
                        }
                        // EXPLICIT WEIGHTED PREDICTION (spec 8.4.2.3). The CAVLC inter
                        // path weights each partition after MC; the MC-call-coalescing
                        // rewrite of this CABAC path lost it, and nothing caught that
                        // because the effect is invisible unless a stream actually
                        // carries non-default weights. x264's `weightp` DUPLICATES a
                        // reference and distinguishes the copy ONLY by its weights, so
                        // every macroblock picking the weighted index decoded unweighted
                        // -- a silent, accumulating luma drift.
                        //
                        // Applied per 4x4 block rather than per partition: the weight
                        // depends solely on the block's reference index, so the two are
                        // equivalent, and `gref` already holds it for every block
                        // regardless of which rect ladder rung ran.
                        if self.weights.is_some() {
                            for by in 0..4usize {
                                for bx in 0..4usize {
                                    let refi = gref[by * 4 + bx];
                                    self.weight_partition(
                                        &mut pred_y, &mut c_pred, 0, refi, bx * 4, by * 4, 4, 4,
                                    );
                                }
                            }
                        }
                    }
                    // Residual add — the SAME helper the B path uses (this inline
                    // copy was a duplicate; deduped when the zero-block fast path
                    // landed so both paths share it).
                    self.add_inter_residual(mbx, mby, &pred_y, &c_pred, luma_scan, luma8, cdc, cac, cbp_chroma, nnzs);
        self.cur_qp = saved_qp;
    }

    /// Job-shaped entry point (EDC replay + the `double_recon` A/B knob).
    fn recon_p_inter(&mut self, j: &PInterJob) {
        self.recon_p_inter_parts(
            j.mbx,
            j.mby,
            j.qp,
            j.cbp_chroma,
            j.luma_scan.as_ref(),
            j.luma8.as_ref(),
            &j.cdc,
            j.cac.as_ref(),
            &j.nnzs,
        );
    }

    /// D9b: P inter with `cbp == 0` — MC + plane copy, no coeff memset / residual walk.
    /// Byte-identical to `recon_p_inter` on a zero-residual job: prediction is the recon.
    fn recon_p_inter_nores(&mut self, j: &PInterNoResJob) {
        let w4r = self.mb_w * 4;
        // Parse-side nnz for single-thread EDC flush (MT commits earlier via edc_commit_nnz).
        // ROW FILLS. Both arms touch the same sixteen cells - four contiguous
        // per macroblock row - and wrote them one indexed store at a time (the
        // t8 arm through a 2x2-of-2x2 nest, the other through the z-order scan).
        for by in 0..4usize {
            let r = (j.mby * 4 + by) * w4r + j.mbx * 4;
            self.nnz_y[r..r + 4].fill(0);
            if j.t8 {
                self.coded_y[r..r + 4].fill(true);
            }
        }
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        // `self.refs.len() - 1` was re-loaded on every one of the sixteen
        // iterations; it is a per-macroblock invariant. Written once, not
        // zeroed-then-filled.
        let nrefs = self.refs.len() - 1;
        let gref: [usize; 16] = core::array::from_fn(|k| (j.gref[k] as usize).min(nrefs));
        coalesce_p_inter_mc(
            &self.refs,
            self.cw,
            self.ccw,
            self.mb_h,
            j.mbx,
            j.mby,
            &j.gmv,
            &gref,
            &mut pred_y,
            &mut c_pred,
        );
        // The identity early-out lives INSIDE `weight_partition`, so an x264
        // stream - which carries a pred_weight_table in EVERY P slice, identity
        // outside fades - still paid sixteen calls per macroblock to be told
        // there was nothing to do. Hoisted to one test.
        if self.weights.is_some() && !self.weights_l0id {
            for by in 0..4usize {
                for bx in 0..4usize {
                    let refi = gref[by * 4 + bx];
                    self.weight_partition(&mut pred_y, &mut c_pred, 0, refi, bx * 4, by * 4, 4, 4);
                }
            }
        }
        // ONE span per plane: the destination is a stack of contiguous runs a
        // fixed stride apart, so the rows share a single bounds check instead of
        // one each (16 + 8 + 8 of them).
        let (cw, ccw) = (self.cw, self.ccw);
        let ybase = (j.mby * 16) * cw + j.mbx * 16;
        let ywin = &mut self.rec_y[ybase..ybase + 15 * cw + 16];
        for dy in 0..16 {
            ywin[dy * cw..dy * cw + 16].copy_from_slice(&pred_y[dy * 16..dy * 16 + 16]);
        }
        let cbase = (j.mby * 8) * ccw + j.mbx * 8;
        for c in 0..2 {
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            let cwin = &mut plane[cbase..cbase + 7 * ccw + 8];
            for dy in 0..8 {
                cwin[dy * ccw..dy * ccw + 8].copy_from_slice(&c_pred[c][dy * 8..dy * 8 + 8]);
            }
        }
    }

    fn decode_p_skip(&mut self, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        self.route_skip_mbs += 1;
        self.wait_refs_for_mb(mb_y);
        // DEBLOCK CLASS: a P_Skip macroblock carries no coefficients and one
        // (ref, mv) for all 16 blocks, so every internal boundary strength is 0 by
        // §8.7.2.1 and the loop filter needs 9 block loads instead of 24. This is
        // the single highest-value classification: the MB-kind census measures Skip
        // at 36.4% (CAVLC) / 65.0% (main) / 57.8% (high) of real x264 corpora.
        // Written HERE because both the CAVLC and the CABAC slice loops funnel
        // through this one function.
        //
        // Deliberately NOT done for `B_Skip` — its motion is direct-derived and can
        // differ per 4×4 sub-block, so its internal edges can legally reach
        // strength 1. B_Skip stays UNSET and takes the blind path.
        // (kind commit moved into the span/immediate arms below.)
        // P_Skip always references index 0 (the most recent picture). Borrow it —
        // a full-frame `.cloned()` here was ~86% of total decode time (one ~3 MB
        // plane copy per skip MB, thousands per frame).
        if self.refs.is_empty() {
            return Err(MbError::Unsupported("P_Skip without reference"));
        }
        let addr = mb_y * self.mb_w + mb_x;
        // mb_x == 0: the left neighbor is off-frame, so §8.4.1.1's
        // unavailability rule forces (0,0) with no gather at all.
        let mv = if (mb_x == 0 || self.skip_zero_next == addr) && !self.k_no_runmv {
            edcstat::bump(&edcstat::SKIPMV_FORCED, 1);
            (0, 0)
        } else {
            // The gather reads the grids; the pending spans cannot contain
            // this MB's left (a non-forced skip means the previous MB was not
            // a (0,0) committer) — flush both before deriving.
            self.span_flush();
            edcstat::bump(&edcstat::SKIPMV_DERIVED, 1);
            self.skip_mv(mb_x, mb_y)
        };
        self.skip_zero_next = if mv == (0, 0) { addr + 1 } else { usize::MAX };
        // Grid commits are PARSE state — (0,0) skips defer them into the P
        // span (the deferral constants); nonzero-MV skips commit immediately.
        if mv == (0, 0) {
            // Recon defers too when the band identity holds (1T, no/identity
            // weights) — the span flush band-copies instead of queueing jobs.
            let recon = self.edc_tx.is_none() && (self.weights.is_none() || self.weights_id0);
            self.pz_push(mb_x, mb_y, recon);
            if recon {
                return Ok(());
            }
        } else {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            if let Some(p) = self.mb_kind.get_mut(mb_y * self.mb_w + mb_x) {
                *p = rusty_h264_common::deblock::MB_KIND_SKIP;
            }
            self.set_mb_mv(mb_x, mb_y, mv, true, 0);
            let w4 = self.mb_w * 4;
            for dy in 0..4 {
                let a = (mb_y * 4 + dy) * w4 + mb_x * 4;
                self.coded_y[a..a + 4].fill(true);
                self.modes_y[a..a + 4].fill(2);
            }
        }
        if self.edc_tx.is_some() {
            self.edc_giveback();
            self.edc_send_job(EdcJob::Skip { mbx: mb_x, mby: mb_y, mv });
            return Ok(());
        }
        if self.edc_active {
            self.edc_jobs.push(EdcJob::Skip { mbx: mb_x, mby: mb_y, mv });
            return Ok(());
        }
        self.recon_p_skip(mb_x, mb_y, mv);
        if double_recon() {
            self.recon_p_skip(mb_x, mb_y, mv);
        }
        Ok(())
    }

    /// Pixel half of P_Skip (see the E1 seam note on `recon_p_inter`).
    /// Run-coalesced P_Skip reconstruction: `n` consecutive skip MBs on one
    /// row, all with `mv == (0,0)` and NO weighted prediction. At full-pel
    /// zero motion, MC is the identity read of `refs[0]` — so the recon is a
    /// straight band copy from the padded reference plane, no staging, no MC
    /// calls. Byte-identical to `n` calls of `recon_p_skip` by construction
    /// (mc_luma_padded/mc_chroma_padded at mv 0 return exactly these bytes).
    ///
    /// The (0,0) run theorem that makes ONE derivation cover the run: once a
    /// skip MB commits (ref 0, mv (0,0)), every later MB of the run derives
    /// (0,0) too — its left neighbour (or a row-start's missing neighbour)
    /// triggers §8.4.1.1's zero-MV rule in `skip_mv`.
    fn recon_p_skip_band(&mut self, mbx0: usize, mby: usize, n: usize) {
        let w = n * 16;
        let Some(rf0) = self.refs.first() else { return };
        let lst = rf0.lstride();
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            let ly = rf0.luma_guard(rf0.ch);
            for dy in 0..16 {
                let y = mby * 16 + dy;
                let src = (y + crate::LPAD) * lst + crate::LPAD + mbx0 * 16;
                let dst = y * self.cw + mbx0 * 16;
                // ARMOR (fuzz find, inline-execution.md 11.11): on a MALFORMED
                // stream a reference can carry geometry that does not match the
                // open picture (mutated parameter sets / truncated ref planes),
                // so the in-frame band's ref window can leave the guard slice.
                // The band REFUSES rather than panics; a conformant stream
                // cannot take this arm (repro: scratchpad repro.264, plane 6400
                // vs index 6416). Output on malformed input is unspecified —
                // absence of panic is the contract the fuzz gate enforces.
                let (Some(d), Some(sr)) = (
                    self.rec_y.get_mut(dst..dst + w),
                    ly.get(src..src + w),
                ) else {
                    return;
                };
                d.copy_from_slice(sr);
            }
        }
        let cst = rf0.cstride();
        let wc = n * 8;
        for c in 0..2 {
            let rc = rf0.chroma_guard(c, rf0.ch);
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for dy in 0..8 {
                let y = mby * 8 + dy;
                let src = (y + crate::CPAD) * cst + crate::CPAD + mbx0 * 8;
                let dst = y * self.ccw + mbx0 * 8;
                // Same armor as the luma band above.
                let (Some(d), Some(sr)) = (plane.get_mut(dst..dst + wc), rc.get(src..src + wc))
                else {
                    return;
                };
                d.copy_from_slice(sr);
            }
        }
        edcstat::bump(&edcstat::SKIPBAND_MBS, n as u64);
        edcstat::bump(&edcstat::SKIPBAND_RUNS, 1);
    }

    /// B_Skip zero-bi recon: rec = avg(ref0, ref1') row-wise, straight from the
    /// padded planes. Byte-identical to b_mc at mv (0,0)/(0,0): full-pel MC is
    /// an identity read and the unweighted bi blend is exactly (a+b+1)>>1 —
    /// which the compiler emits as pavgb over the sliced zips, same as b_mc's
    /// blend site.
    fn recon_b_skip_zero_bi(&mut self, mbx: usize, mby: usize, r0i: usize, r1i: usize) {
        let (Some(rf0), Some(rf1)) = (self.refs.get(r0i), self.refs1.get(r1i)) else {
            return;
        };
        let (l0st, l1st) = (rf0.lstride(), rf1.lstride());
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            let (ly0, ly1) = (rf0.luma_guard(rf0.ch), rf1.luma_guard(rf1.ch));
            for dy in 0..16 {
                let y = mby * 16 + dy;
                let s0 = (y + crate::LPAD) * l0st + crate::LPAD + mbx * 16;
                let s1 = (y + crate::LPAD) * l1st + crate::LPAD + mbx * 16;
                let d = y * self.cw + mbx * 16;
                for ((dst, a), b) in self.rec_y[d..d + 16].iter_mut().zip(&ly0[s0..s0 + 16]).zip(&ly1[s1..s1 + 16]) {
                    *dst = ((*a as u16 + *b as u16 + 1) >> 1) as u8;
                }
            }
        }
        let (c0st, c1st) = (rf0.cstride(), rf1.cstride());
        for c in 0..2 {
            let rc0 = rf0.chroma_guard(c, rf0.ch);
            let rc1 = rf1.chroma_guard(c, rf1.ch);
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for dy in 0..8 {
                let y = mby * 8 + dy;
                let s0 = (y + crate::CPAD) * c0st + crate::CPAD + mbx * 8;
                let s1 = (y + crate::CPAD) * c1st + crate::CPAD + mbx * 8;
                let d = y * self.ccw + mbx * 8;
                for ((dst, a), b) in plane[d..d + 8].iter_mut().zip(&rc0[s0..s0 + 8]).zip(&rc1[s1..s1 + 8]) {
                    *dst = ((*a as u16 + *b as u16 + 1) >> 1) as u8;
                }
            }
        }
    }

    /// Full-pel P_Skip single: rec window = ref\[0\] window at an integer offset.
    /// Returns false (touching nothing) when any window leaves the padded
    /// plane — mc's edge clamping takes over there. Luma needs mv%4==0;
    /// chroma needs mv%8==0 (its frac is mv&7), so odd full-pel MVs copy luma
    /// and interpolate chroma.
    fn recon_p_skip_fullpel(&mut self, mbx: usize, mby: usize, mv: (i32, i32)) -> bool {
        let (dx, dy) = ((mv.0 / 4) as isize, (mv.1 / 4) as isize);
        let Some(rf0) = self.refs.first() else { return false };
        let lst = rf0.lstride();
        let lpad = crate::LPAD as isize;
        let cx = mbx as isize * 16 + dx + lpad;
        let cy = mby as isize * 16 + dy + lpad;
        {
            let ly = rf0.luma_guard(rf0.ch);
            let lrows = rf0.lrows() as isize;
            if cx < 0 || cx + 16 > lst as isize || cy < 0 || cy + 16 > lrows {
                return false;
            }
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            // ONE span each side: sixteen rows a fixed stride apart, so the
            // source and destination checks are paid once instead of per row.
            let (cw, sb) = (self.cw, cy as usize * lst + cx as usize);
            let db = (mby * 16) * cw + mbx * 16;
            let sw = &ly[sb..sb + 15 * lst + 16];
            let dw = &mut self.rec_y[db..db + 15 * cw + 16];
            for r in 0..16 {
                dw[r * cw..r * cw + 16].copy_from_slice(&sw[r * lst..r * lst + 16]);
            }
        }
        let cst = rf0.cstride();
        let cpad = crate::CPAD as isize;
        if mv.0 % 8 == 0 && mv.1 % 8 == 0 {
            let ccx = mbx as isize * 8 + (mv.0 / 8) as isize + cpad;
            let ccy = mby as isize * 8 + (mv.1 / 8) as isize + cpad;
            let crows = rf0.crows() as isize;
            if ccx >= 0 && ccx + 8 <= cst as isize && ccy >= 0 && ccy + 8 <= crows {
                for c in 0..2 {
                    let rc = rf0.chroma_guard(c, rf0.ch);
                    let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                    let (ccw, sb) = (self.ccw, ccy as usize * cst + ccx as usize);
                    let db = (mby * 8) * ccw + mbx * 8;
                    let sw = &rc[sb..sb + 7 * cst + 8];
                    let dw = &mut plane[db..db + 7 * ccw + 8];
                    for r in 0..8 {
                        dw[r * ccw..r * ccw + 8].copy_from_slice(&sw[r * cst..r * cst + 8]);
                    }
                }
                edcstat::bump(&edcstat::SKIP_FP_FULL, 1);
                return true;
            }
        }
        // Odd full-pel (or chroma window out of pad): luma is already copied,
        // chroma still interpolates — identical to the mc path's chroma half.
        let cch = self.mb_h * 8;
        for c in 0..2 {
            let mut pc = [0u8; 64];
            let rc = if c == 0 { &*rf0.chroma_guard(0, rf0.ch) } else { &*rf0.chroma_guard(1, rf0.ch) };
            mc_chroma_padded(rc, cst, crate::CPAD, self.ccw, cch, mbx * 8, mby * 8, 8, 8, mv.0, mv.1, &mut pc);
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for r in 0..8 {
                let d = (mby * 8 + r) * self.ccw + mbx * 8;
                plane[d..d + 8].copy_from_slice(&pc[r * 8..r * 8 + 8]);
            }
        }
        edcstat::bump(&edcstat::SKIP_FP_LUMA, 1);
        true
    }

    /// B_Skip full-pel recon with per-list integer offsets: uni = offset row
    /// copy, bi = offset row average ((a+b+1)>>1). Luma always copies here
    /// (caller guarantees mv%4==0); chroma copies at mv%8==0 and otherwise
    /// interpolates via b_mc_chroma — identical to the b_mc path's chroma
    /// half with no implicit weights. Returns false untouched when a luma
    /// window leaves the padded plane.
    fn recon_b_skip_fp(&mut self, mbx: usize, mby: usize, r0: Option<usize>, r1: Option<usize>, mv0: (i32, i32), mv1: (i32, i32)) -> bool {
        let lpad = crate::LPAD as isize;
        // (start-row, start-col, stride, rows) of each active list's luma window.
        let win = |rf: &crate::RefFrame, mv: (i32, i32)| -> Option<(usize, usize)> {
            let lst = rf.lstride();
            let cx = mbx as isize * 16 + (mv.0 / 4) as isize + lpad;
            let cy = mby as isize * 16 + (mv.1 / 4) as isize + lpad;
            let lrows = rf.lrows() as isize;
            if cx < 0 || cx + 16 > lst as isize || cy < 0 || cy + 16 > lrows {
                None
            } else {
                Some((cy as usize * lst + cx as usize, lst))
            }
        };
        let w0 = match r0 {
            Some(i) => match self.refs.get(i).and_then(|rr| win(rr, mv0)) {
                Some(w) => Some(w),
                None => return false,
            },
            None => None,
        };
        let w1 = match r1 {
            Some(i) => match self.refs1.get(i).and_then(|rr| win(rr, mv1)) {
                Some(w) => Some(w),
                None => return false,
            },
            None => None,
        };
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            match (w0, w1) {
                (Some((s0, l0)), Some((s1, l1))) => {
                    let Some(rf0) = r0.and_then(|i| self.refs.get(i)) else { return false };
                    // Same shape as the `rf0` line above: `w1` is `Some` only when
                    // `r1` is `Some(i)` AND `refs1.get(i)` returned a frame, so the
                    // `else` is unreachable -- but it is a REFUSAL, not a panic, and
                    // `recon_b_skip_fp` already answers `false` for every case it
                    // cannot fast-path. Indexing a `Vec` with an unwrapped `Option`
                    // spent a discriminant test, an `unwrap_failed` call and a bounds
                    // check to restate an invariant the caller had already proven.
                    let Some(rf1) = r1.and_then(|i| self.refs1.get(i)) else { return false };
                    let (ly0, ly1) = (rf0.luma_guard(rf0.ch), rf1.luma_guard(rf1.ch));
                    for r in 0..16 {
                        let d = (mby * 16 + r) * self.cw + mbx * 16;
                        let (a, b) = (&ly0[s0 + r * l0..s0 + r * l0 + 16], &ly1[s1 + r * l1..s1 + r * l1 + 16]);
                        for ((dst, p), q) in self.rec_y[d..d + 16].iter_mut().zip(a).zip(b) {
                            *dst = ((*p as u16 + *q as u16 + 1) >> 1) as u8;
                        }
                    }
                }
                (Some((s0, l0)), None) => {
                    let Some(rf0) = r0.and_then(|i| self.refs.get(i)) else { return false };
                    let ly = rf0.luma_guard(rf0.ch);
                    for r in 0..16 {
                        let d = (mby * 16 + r) * self.cw + mbx * 16;
                        self.rec_y[d..d + 16].copy_from_slice(&ly[s0 + r * l0..s0 + r * l0 + 16]);
                    }
                }
                (None, Some((s1, l1))) => {
                    // Same shape as the `rf0` line above: `w1` is `Some` only when
                    // `r1` is `Some(i)` AND `refs1.get(i)` returned a frame, so the
                    // `else` is unreachable -- but it is a REFUSAL, not a panic, and
                    // `recon_b_skip_fp` already answers `false` for every case it
                    // cannot fast-path. Indexing a `Vec` with an unwrapped `Option`
                    // spent a discriminant test, an `unwrap_failed` call and a bounds
                    // check to restate an invariant the caller had already proven.
                    let Some(rf1) = r1.and_then(|i| self.refs1.get(i)) else { return false };
                    let ly = rf1.luma_guard(rf1.ch);
                    for r in 0..16 {
                        let d = (mby * 16 + r) * self.cw + mbx * 16;
                        self.rec_y[d..d + 16].copy_from_slice(&ly[s1 + r * l1..s1 + r * l1 + 16]);
                    }
                }
                (None, None) => unreachable!("caller guarantees an active list"),
            }
        }
        // Chroma: interpolating half — route through b_mc_chroma into a stage
        // (weights None: the caller only enters at implicit None/(32,32), and
        // (32,32) IS the plain average b_mc_chroma computes for None).
        let cch = self.mb_h * 8;
        let mut c_pred = [[0u8; 64]; 2];
        let (ri0, ri1) = (r0.map_or(-1, |i| i as i32), r1.map_or(-1, |i| i as i32));
        self.b_mc_chroma(mbx, mby, 0, 0, 16, 16, ri0, mv0, ri1, mv1, &mut c_pred, None, cch);
        for c in 0..2 {
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for r in 0..8 {
                let d = (mby * 8 + r) * self.ccw + mbx * 8;
                plane[d..d + 8].copy_from_slice(&c_pred[c][r * 8..r * 8 + 8]);
            }
        }
        true
    }

    fn recon_p_skip(&mut self, mb_x: usize, mb_y: usize, mv: (i32, i32)) {
        // Full-pel + identity/no weights: MC is a pure offset read, so copy the
        // ref window straight into rec — no pred staging, no weight pass. The
        // window must sit inside the PADDED plane (outside it, mc's clamping
        // differs from a raw offset read, so fall through).
        if (self.weights.is_none() || self.weights_id0)
            && mv.0 % 4 == 0
            && mv.1 % 4 == 0
            && !no_skipfp()
            && self.recon_p_skip_fullpel(mb_x, mb_y, mv)
        {
            return;
        }
        let (ch, cch) = (self.mb_h * 16, self.mb_h * 8);

        let mut pred = [0u8; 256];
        let Some(rf0) = self.refs.first() else { return };
        mc_luma_padded(&*rf0.luma_guard(rf0.ch), rf0.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16, 16, 16, mv.0, mv.1, &mut pred);
        if let Some(wt) = &self.weights {
            if !self.weights_id0 || no_skipfp() {
                for p in pred.iter_mut() {
                    *p = wt.apply_luma(*p, 0, 0);
                }
            }
        }
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            // ONE span for the sixteen rows (see `recon_p_inter_nores`).
            let (cw, base) = (self.cw, (mb_y * 16) * self.cw + mb_x * 16);
            let win = &mut self.rec_y[base..base + 15 * cw + 16];
            for dy in 0..16 {
                win[dy * cw..dy * cw + 16].copy_from_slice(&pred[dy * 16..dy * 16 + 16]);
            }
        }
        let (mut pu, mut pv) = ([0u8; 64], [0u8; 64]);
        {
            let Some(rf0) = self.refs.first() else { return };
            let (gu, gv) = (rf0.chroma_guard(0, rf0.ch), rf0.chroma_guard(1, rf0.ch));
            rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, rf0.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8, 8, 8, mv.0, mv.1, &mut pu, &mut pv);
        }
        if let Some(wt) = &self.weights {
            if !self.weights_id0 || no_skipfp() {
                for p in pu.iter_mut() {
                    *p = wt.apply_chroma(*p, 0, 0, 0);
                }
                for p in pv.iter_mut() {
                    *p = wt.apply_chroma(*p, 0, 0, 1);
                }
            }
        }
        for (pc, plane) in [(&pu, &mut self.rec_u), (&pv, &mut self.rec_v)] {
            for dy in 0..8 {
                let d = (mb_y * 8 + dy) * self.ccw + mb_x * 8;
                plane[d..d + 8].copy_from_slice(&pc[dy * 8..dy * 8 + 8]);
            }
        }
    }

    /// Predicted `Intra_4x4` mode for the block at absolute coords `(bx, by)`.
    /// If either the left or top neighbor is outside the frame or in another
    /// slice, the prediction is DC (mode 2) (spec §8.3.1.1).
    /// `predict_i4_mode` with the MACROBLOCK-level availability already
    /// resolved by the caller (`top_ok` / `left_ok`).
    ///
    /// Twelve of a macroblock's sixteen blocks have BOTH neighbours inside the
    /// same macroblock, so their slice test is a foregone conclusion - yet the
    /// general form recomputed two `nbr_in_slice` products and two
    /// `intra_nbr_ok` tests for every one of them, ~1M times on all-intra
    /// content.
    ///
    /// `constrained_intra` is excluded deliberately: there the general form
    /// tests THIS macroblock's own `inter_y` cells for interior blocks, which
    /// the macroblock-level flags do not model, so that case defers unchanged.
    #[inline]
    fn predict_i4_mode_fast(
        &self,
        bx: usize,
        by: usize,
        lbx: usize,
        lby: usize,
        top_ok: bool,
        left_ok: bool,
    ) -> u8 {
        if self.constrained_intra {
            return self.predict_i4_mode(bx, by);
        }
        if !((lbx > 0 || left_ok) && (lby > 0 || top_ok)) {
            return 2;
        }
        let w4 = self.mb_w * 4;
        // Fallible reads: two checks on the same grid at two indexes. `2` is DC,
        // which is exactly what every unavailable-neighbour path above already
        // returns, so the fallback is the function's own existing semantics.
        let l = self.modes_y.get(by * w4 + (bx - 1)).copied().unwrap_or(2);
        let t = self.modes_y.get((by - 1) * w4 + bx).copied().unwrap_or(2);
        l.min(t)
    }

    fn predict_i4_mode(&self, bx: usize, by: usize) -> u8 {
        if bx == 0 || by == 0 {
            return 2;
        }
        // Left neighbor block (bx-1,by); top neighbor block (bx,by-1). A neighbor
        // in another slice — or, under constrained_intra, an inter neighbor — is
        // unavailable, forcing the predicted mode to DC.
        if !self.nbr_in_slice((bx - 1) / 4, by / 4)
            || !self.nbr_in_slice(bx / 4, (by - 1) / 4)
            || !self.intra_nbr_ok(bx - 1, by)
            || !self.intra_nbr_ok(bx, by - 1)
        {
            return 2;
        }
        let w4 = self.mb_w * 4;
        // Fallible reads: two checks on the same grid at two indexes. `2` is DC,
        // which is exactly what every unavailable-neighbour path above already
        // returns, so the fallback is the function's own existing semantics.
        let l = self.modes_y.get(by * w4 + (bx - 1)).copied().unwrap_or(2);
        let t = self.modes_y.get((by - 1) * w4 + bx).copied().unwrap_or(2);
        l.min(t)
    }

    /// Gathers 4×4 luma intra neighbors at pixel `(px, py)` from `rec_y`.
    fn gather_i4(
        &self,
        px: usize,
        py: usize,
        avail_top: bool,
        avail_left: bool,
        bx: usize,
        by: usize,
    ) -> ([u8; 8], [u8; 4], u8) {
        let (cw, w4) = (self.cw, self.mb_w * 4);
        let mut top = [0u8; 8];
        let mut left = [0u8; 4];
        let mut corner = 0;
        if avail_top {
            // Row-slice loads: the bak-vs-rec source branch runs once per row
            // segment instead of once per PIXEL (top_y_px paid it 8 times).
            top[..4].copy_from_slice(self.top_y_row(py, px, 4));
            let tr_avail = bx + 1 < w4
                && self.coded_y.get((by - 1) * w4 + (bx + 1)).copied().unwrap_or(false)
                && self.nbr_in_slice((bx + 1) / 4, (by - 1) / 4)
                && self.intra_nbr_ok(bx + 1, by - 1);
            if tr_avail {
                top[4..8].copy_from_slice(self.top_y_row(py, px + 4, 4));
            } else {
                let t3 = top[3];
                top[4..8].fill(t3);
            }
        }
        if avail_left {
            // STRIDED WALK. The span form this replaces claimed `i * cw <= 3 * cw`
            // was provable against the span's length; it is not — the same shape
            // left five live checks on `recon_i16_luma`'s sixteen-sample column.
            // `step_by` does the stride with no index, and `zip` bounds the count.
            let base = py * cw + px - 1;
            for (s, &v) in left.iter_mut().zip(self.rec_y[base..].iter().step_by(cw)) {
                *s = v;
            }
        }
        // The above-left corner has its own availability (block D); under
        // constrained_intra it is gone if that block is inter.
        if avail_top && avail_left && self.intra_nbr_ok(bx - 1, by - 1) {
            corner = self.top_y_px(py, px - 1);
        }
        (top, left, corner)
    }

    /// Reconstructs an `I_PCM` macroblock: byte-aligned raw 8-bit samples, no
    /// prediction/transform/quant (spec §7.3.5, §8.3.5).
    fn decode_ipcm(&mut self, r: &mut BitReader, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        r.align_to_byte()?;
        // ROW SLICES throughout. A PCM macroblock wrote 384 samples one at a
        // time, each a separately bounds-checked index into a whole plane, and
        // then 104 more scattered context stores below. Every extent here is a
        // literal (16, 8, 4, 2), so one slice per row makes the inner index
        // provable and the stores become a straight walk.
        let (lx, ly) = (mb_x * 16, mb_y * 16);
        for dy in 0..16 {
            let row = &mut self.rec_y[(ly + dy) * self.cw + lx..][..16];
            for px in row.iter_mut() {
                *px = r.read_bits(8)? as u8;
            }
        }
        let (cx, cy) = (mb_x * 8, mb_y * 8);
        let ccw = self.ccw;
        for plane in [&mut self.rec_u, &mut self.rec_v] {
            for dy in 0..8 {
                let row = &mut plane[(cy + dy) * ccw + cx..][..8];
                for px in row.iter_mut() {
                    *px = r.read_bits(8)? as u8;
                }
            }
        }
        // Neighbor context: an I_PCM block contributes TotalCoeff = 16, counts as
        // intra with DC mode for prediction, and has no motion (§9.2.1, §8.3.1.2.2).
        let (w4, w2) = (self.mb_w * 4, self.mb_w * 2);
        // The scan order is irrelevant when every written value is a constant:
        // the sixteen `LUMA_4X4_SCAN_XY` positions are exactly the macroblock's
        // 4x4 rectangle, so four row fills per array cover them.
        for ry in 0..4 {
            let base = (mb_y * 4 + ry) * w4 + mb_x * 4;
            self.nnz_y[base..][..4].fill(16);
            self.modes_y[base..][..4].fill(2);
            self.coded_y[base..][..4].fill(true);
            self.inter_y[base..][..4].fill(false);
            self.ref_idx_y[base..][..4].fill(-1);
            self.mv_y[base..][..4].fill((0, 0));
        }
        for c in 0..2 {
            for by in 0..2 {
                self.nnz_c[c][(mb_y * 2 + by) * w2 + mb_x * 2..][..2].fill(16);
            }
        }
        Ok(())
    }

    fn decode_i4x4(&mut self, r: &mut BitReader, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        let vt = vlc_tables();
        let w4 = self.mb_w * 4;

        // intra4x4 mode signalling
        let mut modes = [2u8; 16]; // raster [lby*4+lbx]
        for &(lbx, lby) in &LUMA_4X4_SCAN_XY {
            let (bx, by) = (mb_x * 4 + lbx, mb_y * 4 + lby);
            let predicted = self.predict_i4_mode(bx, by);
            let actual = if r.read_bit()? {
                predicted
            } else {
                let rem = r.read_bits(3)? as u8;
                if rem < predicted {
                    rem
                } else {
                    rem + 1
                }
            };
            if let Some(p) = self.modes_y.get_mut(by * w4 + bx) {
                *p = actual;
            }
            modes[(lby & 3) * 4 + (lbx & 3)] = actual;
        }

        let chroma_mode = r.read_ue()? as u8;
        let cbp = read_cbp_intra(r)?;
        let cbp_luma = cbp & 15;
        let cbp_chroma = cbp >> 4;
        if cbp != 0 {
            self.step_qp(r.read_se()?)?;
        }
        let qp = self.cur_qp;

        // luma residuals + serial reconstruction. Cross-MB neighbors are only
        // available when the adjacent macroblock is in this slice (and, under
        // constrained_intra_pred, is itself intra-coded).
        let top_mb_avail = mb_y > 0
            && self.nbr_in_slice(mb_x, mb_y - 1)
            && self.intra_nbr_ok(mb_x * 4, mb_y * 4 - 1);
        let left_mb_avail = mb_x > 0
            && self.nbr_in_slice(mb_x - 1, mb_y)
            && self.intra_nbr_ok(mb_x * 4 - 1, mb_y * 4);
        self.nnz_cache_load(mb_x, mb_y);
        let mut nnz_raster = [0u8; 16];
        for (blk, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
            let (bx, by) = (mb_x * 4 + lbx, mb_y * 4 + lby);
            let avail_top = lby > 0 || top_mb_avail;
            let avail_left = lbx > 0 || left_mb_avail;
            let mut scan16 = [0i32; 16];
            let total = if cbp_luma & (1 << (blk / 4)) != 0 {
                let nc = self.nc_pred(lbx, lby);
                let t;
                (scan16, t) = decode_residual_block_with(vt, r, 16, nc)?;
                t
            } else {
                0
            };
            self.nnz_cache_set(lbx, lby, total);
            nnz_raster[(lby & 3) * 4 + (lbx & 3)] = total;
            self.recon_i4_block(bx, by, modes[(lby & 3) * 4 + (lbx & 3)], avail_top, avail_left, &scan16, total, qp);
        }
        // Deferred: `recon_i4_block` gathers from `coded_y` / `rec_y`, never
        // from `nnz_y`, so one contiguous copy per row replaces sixteen stores.
        for by in 0..4usize {
            let a = (mb_y * 4 + by) * w4 + mb_x * 4;
            self.nnz_y[a..a + 4].copy_from_slice(&nnz_raster[by * 4..by * 4 + 4]);
        }

        self.decode_chroma(r, mb_x, mb_y, cbp_chroma, chroma_mode)
    }

    /// Decodes an `I_8x8` macroblock (High profile): four 8×8 luma blocks, each
    /// with its own intra mode, 8×8 transform residual (CAVLC = four interleaved
    /// 4×4 blocks), and 8×8 intra prediction.
    fn decode_i8x8(&mut self, r: &mut BitReader, mb_x: usize, mb_y: usize) -> Result<(), MbError> {
        let vt = vlc_tables();
        let w4 = self.mb_w * 4;
        if let Some(p) = self.mb_t8x8.get_mut(mb_y * self.mb_w + mb_x) {
            *p = true;
        }
        self.any_t8 = true;

        // intra8x8 mode signalling — one mode per 8×8 block (raster 0..3),
        // stored into all four of its 4×4 cells so neighbors can read it.
        let mut modes8 = [2u8; 4];
        for (b8, mode) in modes8.iter_mut().enumerate() {
            let (b8x, b8y) = (b8 % 2, b8 / 2);
            let (bx, by) = (mb_x * 4 + b8x * 2, mb_y * 4 + b8y * 2);
            let predicted = self.predict_i4_mode(bx, by);
            let actual = if r.read_bit()? {
                predicted
            } else {
                let rem = r.read_bits(3)? as u8;
                if rem < predicted { rem } else { rem + 1 }
            };
            *mode = actual;
            for sy in 0..2 {
                // Row fill: the 2x2 cell block is two contiguous PAIRS.
                self.modes_y[(by + sy) * w4 + bx..][..2].fill(actual);
            }
        }

        let chroma_mode = r.read_ue()? as u8;
        let cbp = read_cbp_intra(r)?;
        let cbp_luma = cbp & 15;
        let cbp_chroma = cbp >> 4;
        if cbp != 0 {
            self.step_qp(r.read_se()?)?;
        }
        let qp = self.cur_qp;

        let top_mb_avail = mb_y > 0
            && self.nbr_in_slice(mb_x, mb_y - 1)
            && self.intra_nbr_ok(mb_x * 4, mb_y * 4 - 1);
        let left_mb_avail = mb_x > 0
            && self.nbr_in_slice(mb_x - 1, mb_y)
            && self.intra_nbr_ok(mb_x * 4 - 1, mb_y * 4);
        self.nnz_cache_load(mb_x, mb_y);

        for b8 in 0..4 {
            let (b8x, b8y) = (b8 % 2, b8 / 2);
            let (bx, by) = (mb_x * 4 + b8x * 2, mb_y * 4 + b8y * 2);

            // residual: 8×8 CAVLC = four 4×4 sub-blocks, coeff k of sub-block s
            // mapping to 8×8 scan position 4·k + s (spec §7.3.5.3.2).
            let mut scan8 = [0i32; 64];
            let coded8 = cbp_luma & (1 << b8) != 0;
            if coded8 {
                for sub in 0..4 {
                    let (sx, sy) = (sub % 2, sub / 2);
                    let (cx, cy) = (b8x * 2 + sx, b8y * 2 + sy);
                    let nc = self.nc_pred(cx, cy);
                    let (blk, total) = decode_residual_block_with(vt, r, 16, nc)?;
                    self.nnz_cache_set(cx, cy, total);
                    if let Some(c) = self.nnz_y.get_mut((by + sy) * w4 + (bx + sx)) {
                        *c = total;
                    }
                    for k in 0..16 {
                        scan8[4 * k + sub] = blk[k];
                    }
                }
            } else {
                for sub in 0..4 {
                    let (sx, sy) = (sub % 2, sub / 2);
                    self.nnz_cache_set(b8x * 2 + sx, b8y * 2 + sy, 0);
                    if let Some(c) = self.nnz_y.get_mut((by + sy) * w4 + (bx + sx)) {
                        *c = 0;
                    }
                }
            }

            let avail_top = b8y > 0 || top_mb_avail;
            let avail_left = b8x > 0 || left_mb_avail;
            self.recon_i8_block(bx, by, modes8[b8], avail_top, avail_left, coded8.then_some(&scan8), qp);
            for sy in 0..2 {
                // Row fill: the 2x2 cell block is two contiguous PAIRS.
                self.coded_y[(by + sy) * w4 + bx..][..2].fill(true);
            }
        }

        self.decode_chroma(r, mb_x, mb_y, cbp_chroma, chroma_mode)
    }

    /// Dequantizes + inverse-transforms an 8×8 luma block, applying the scaling
    /// matrix `list` (0 = intra, 1 = inter) or flat weights.
    fn inv_quant8(&self, raster: &[i32; 64], qp: u8, list: usize) -> [i32; 64] {
        match &self.scaling8 {
            Some(s) => inverse_quant_8x8(raster, qp, &s[list]),
            None => inverse_quant_8x8(raster, qp, &[16i32; 64]),
        }
    }

    /// Gathers the 8×8 luma intra reference samples at pixel `(px, py)`: the 16
    /// top samples (8..15 substituted from the last when no top-right), 8 left
    /// samples, the above-left corner, and whether the corner is available.
    #[allow(clippy::too_many_arguments)]
    fn gather_i8(
        &self,
        px: usize,
        py: usize,
        avail_top: bool,
        avail_left: bool,
        bx: usize,
        by: usize,
    ) -> ([u8; 16], [u8; 8], u8, bool) {
        let (cw, w4) = (self.cw, self.mb_w * 4);
        let mut top = [0u8; 16];
        let mut left = [0u8; 8];
        let mut corner = 0;
        if avail_top {
            // Row-slice loads: one source branch per segment, not per pixel.
            top[..8].copy_from_slice(self.top_y_row(py, px, 8));
            let tr_avail = bx + 2 < w4
                && self.coded_y.get((by - 1) * w4 + (bx + 2)).copied().unwrap_or(false)
                && self.nbr_in_slice((bx + 2) / 4, (by - 1) / 4)
                && self.intra_nbr_ok(bx + 2, by - 1);
            if tr_avail {
                top[8..16].copy_from_slice(self.top_y_row(py, px + 8, 8));
            } else {
                let t7 = top[7];
                top[8..16].fill(t7);
            }
        }
        if avail_left {
            // STRIDED WALK, NOT STRIDED INDEXING. A span plus `col[i * cw]` still
            // checks, because `i * cw <= 7 * cw` is not something LLVM derives
            // against the span's own length; `step_by` on the iterator does the
            // stride with no index at all, and `zip` bounds the count.
            let base = py * cw + px - 1;
            for (s, &v) in left.iter_mut().zip(self.rec_y[base..].iter().step_by(cw)) {
                *s = v;
            }
        }
        let avail_corner = avail_top && avail_left && self.intra_nbr_ok(bx - 1, by - 1);
        if avail_corner {
            corner = self.top_y_px(py, px - 1);
        }
        (top, left, corner, avail_corner)
    }

    fn decode_i16(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        mt: u32,
    ) -> Result<(), MbError> {
        let vt = vlc_tables();
        let pred_mode = I16Mode::from_id(mt % 4);
        let cbp_chroma = (mt % 12) / 4;
        let cbp_luma_15 = mt / 12 == 1;
        let chroma_mode = r.read_ue()? as u8;
        self.step_qp(r.read_se()?)?;
        let qp = self.cur_qp;
        let w4 = self.mb_w * 4;

        // luma DC
        self.nnz_cache_load(mb_x, mb_y);
        let nc_dc = self.nc_pred(0, 0);
        let (dc_scan, _) = decode_residual_block_with(vt, r, 16, nc_dc)?;
        let dc_levels = un_scan_4x4_dcac(&dc_scan);
        let recon_dc = self.dequant_luma_dc(&dc_levels, qp, 0);

        // luma AC (nnz set for all 16 blocks: 0 when DC-only, matching the encoder)
        let mut nnz_raster = [0u8; 16];
        let mut q_blocks = [[0i32; 16]; 16];
        for &(bx, by) in &LUMA_4X4_SCAN_XY {
            let total = if cbp_luma_15 {
                let nc = self.nc_pred(bx, by);
                let (ac, t) = decode_residual_block_with(vt, r, 15, nc)?;
                // Zero-skip: an empty AC block leaves the fresh-zero raster
                // block untouched (un-scanning 16 zeros wrote zeros on zeros).
                if t != 0 {
                    un_scan_4x4_ac_into(&ac, &mut q_blocks[(by & 3) * 4 + (bx & 3)]);
                }
                t
            } else {
                0
            };
            self.nnz_cache_set(bx, by, total);
            nnz_raster[(by & 3) * 4 + (bx & 3)] = total;
        }
        // ONE contiguous copy per row (nothing reads `nnz_y` for this
        // macroblock in between - `nc_pred` predicts from `nnz_cache`).
        for by in 0..4usize {
            let a = (mb_y * 4 + by) * w4 + mb_x * 4;
            self.nnz_y[a..a + 4].copy_from_slice(&nnz_raster[by * 4..by * 4 + 4]);
        }

        // prediction + reconstruction
        let avail_top = mb_y > 0
            && self.nbr_in_slice(mb_x, mb_y - 1)
            && self.intra_nbr_ok(mb_x * 4, mb_y * 4 - 1);
        let avail_left = mb_x > 0
            && self.nbr_in_slice(mb_x - 1, mb_y)
            && self.intra_nbr_ok(mb_x * 4 - 1, mb_y * 4);
        self.recon_i16_luma(mb_x, mb_y, pred_mode, avail_top, avail_left, Some(&q_blocks), &recon_dc, qp);
        // I_16x16 blocks are treated as DC for neighbor mode prediction.
        for lby in 0..4usize {
            let a = (mb_y * 4 + lby) * w4 + mb_x * 4;
            self.modes_y[a..a + 4].fill(2);
        }

        self.decode_chroma(r, mb_x, mb_y, cbp_chroma, chroma_mode)
    }

    /// Reads and reconstructs the chroma residual (shared by both luma types).
    fn decode_chroma(
        &mut self,
        r: &mut BitReader,
        mb_x: usize,
        mb_y: usize,
        cbp_chroma: u32,
        chroma_mode: u8,
    ) -> Result<(), MbError> {
        let vt = vlc_tables();
        let qpc = self.chroma_qp_for(self.cur_qp);
        let avail_top = mb_y > 0
            && self.nbr_in_slice(mb_x, mb_y - 1)
            && self.intra_nbr_ok(mb_x * 4, mb_y * 4 - 1);
        let avail_left = mb_x > 0
            && self.nbr_in_slice(mb_x - 1, mb_y)
            && self.intra_nbr_ok(mb_x * 4 - 1, mb_y * 4);

        let mut c_recon_dc = [[0i32; 4]; 2];
        if cbp_chroma != 0 {
            for (c, slot) in c_recon_dc.iter_mut().enumerate() {
                let (dc, _) = decode_residual_block_with(vt, r, 4, -1)?;
                *slot = self.dequant_chroma_dc(&[dc[0], dc[1], dc[2], dc[3]], qpc, 1 + c);
            }
        }
        let mut c_q_blocks = [[[0i32; 16]; 4]; 2];
        if cbp_chroma == 2 {
            self.chroma_cache_load(mb_x, mb_y);
            let w2 = self.mb_w * 2;
            for c in 0..2 {
                for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                    let nc = self.chroma_nc_pred(c, bx, by);
                    let (ac, total) = decode_residual_block_with(vt, r, 15, nc)?;
                    self.chroma_nnz_cache_set(c, bx, by, total);
                    if let Some(n) = self.nnz_c[c & 1].get_mut((mb_y * 2 + by) * w2 + (mb_x * 2 + bx)) {
                        *n = total;
                    }
                    // Zero-skip: empty AC leaves the fresh-zero raster block.
                    if total != 0 {
                        un_scan_4x4_ac_into(&ac, &mut c_q_blocks[c][by * 2 + bx]);
                    }
                }
            }
        }
        self.recon_chroma_blocks(mb_x, mb_y, chroma_mode, avail_top, avail_left, &c_q_blocks, &c_recon_dc, qpc);
        Ok(())
    }

    /// Applies the in-loop deblocking filter to the reconstructed frame, with
    /// the slice's `FilterOffsetA`/`FilterOffsetB` (each = the coded `*_div2`
    /// value × 2).
    /// Per-frame per-MB dump for conformance bisection, keyed on `RH264_DUMP_MB`.
    /// Prints one char per macroblock: `i` = intra, otherwise the List-0 reference
    /// index of the MB's top-left 4x4 block. Directly comparable with ffmpeg's
    /// `-debug mb_type` map, which is the only per-MB ground truth we can get out
    /// of the reference decoder.
    fn dump_mb_map(&self) {
        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        if !*ON.get_or_init(|| std::env::var_os("RH264_DUMP_MB").is_some()) {
            return;
        }
        let w4 = self.mb_w * 4;
        let mut hist = [0usize; 4];
        eprintln!("--- frame poc {} ---", self.cur_poc);
        for mb_y in 0..self.mb_h {
            let mut row = String::new();
            for mb_x in 0..self.mb_w {
                let b = (mb_y * 4) * w4 + mb_x * 4;
                let Some(&r) = self.ref_idx_y.get(b) else { continue };
                if r < 0 {
                    row.push('i');
                } else {
                    if (r as usize) < 4 {
                        hist[r as usize] += 1;
                    }
                    row.push((b'0' + (r as u8).min(9)) as char);
                }
            }
            eprintln!("{row}");
        }
        eprintln!(
            "ref histogram: {hist:?}   num_ref_active={} refs.len()={}   OUT-OF-RANGE={}",
            self.num_ref_active,
            self.refs.len(),
            hist.iter().skip(self.refs.len()).sum::<usize>()
        );
        let list: Vec<String> = self
            .refs
            .iter()
            .enumerate()
            .map(|(i, f)| {
                // A synthesized frame_num-gap frame is uniform grey with w4 == 0;
                // flag it, because it silently displaces real pictures in the list.
                let synth = if f.w4 == 0 { " SYNTH-GREY" } else { "" };
                format!("[{i}] poc={} fn={}{synth}", f.poc, f.frame_num)
            })
            .collect();
        eprintln!("  RefPicList0: {}", list.join("  "));
    }

    pub fn deblock(&mut self, offset_a: i32, offset_b: i32) {
        self.span_flush(); // deferred grid spans feed bS derivation below
        self.edc_flush(); // backstop: no pixel job may survive to filtering
        self.dump_mb_map();
        // ROW MODE: finish any rows not derived during decode (mid-row slice
        // ends, error paths) FIRST, while `self` is still mutably borrowable.
        if rowdb_on() {
            while self.bs_rows < self.mb_h {
                let r = self.bs_rows;
                self.derive_bs_row(r);
                self.bs_rows += 1;
            }
        }
        // Deblock boundary strength uses the *transform block's* coded status. For
        // an 8×8-transform macroblock the unit is the whole 8×8, so every 4×4 cell
        // shares the 8×8's coefficient presence (OR of its four sub-block counts)
        // — distinct from the per-sub-block `nnz_y` used for the CAVLC nC context.
        // Only differs from `nnz_y` when some MB uses the 8×8 transform (High
        // profile). On Baseline (no 8×8) it's identical — skip the clone + rewrite.
        // Row-interleave already derived bS into `bs_frame`; the filter then
        // reads only `bs`+`t8x8`+qp — do not clone nnz or rebuild POC maps.
        let rowdb = rowdb_on();
        let nnz_db_storage;
        let nnz_db: &[u8] = if rowdb {
            &[]
        } else if self.mb_t8x8.iter().any(|&t| t) {
            let mut n = self.nnz_y.clone();
            let w4 = self.mb_w * 4;
            for mb_y in 0..self.mb_h {
                for mb_x in 0..self.mb_w {
                    if !self.mb_t8x8.get(mb_y * self.mb_w + mb_x).copied().unwrap_or(false) {
                        continue;
                    }
                    for b8 in 0..4 {
                        let (bx, by) = (mb_x * 4 + (b8 % 2) * 2, mb_y * 4 + (b8 / 2) * 2);
                        let any = (0..2)
                            .any(|sy| self.nnz_y[(by + sy) * w4 + bx..][..2].iter().any(|&v| v > 0));
                        for sy in 0..2 {
                            // Row fill: the 2x2 cell block is two contiguous PAIRS.
                            n[(by + sy) * w4 + bx..][..2].fill(u8::from(any));
                        }
                    }
                }
            }
            nnz_db_storage = n;
            &nnz_db_storage
        } else {
            &self.nnz_y
        };
        let mut info = rusty_h264_common::deblock::BlockInfo {
            inter: if rowdb { &[] } else { &self.inter_y },
            nnz: nnz_db,
            mv: if rowdb { &[] } else { &self.mv_y },
            ref_id: if rowdb { &[] } else { &self.ref_idx_y },
            mv1: if rowdb { &[] } else { &self.mv1 },
            ref_id1: if rowdb || self.ref_poc1.is_empty() {
                &[]
            } else {
                &self.ref_idx1
            },
            w4: self.mb_w * 4,
            t8x8: &self.mb_t8x8,
            bs: &[],
            poc0: if rowdb { &[] } else { &self.ref_poc0 },
            poc1: if rowdb { &[] } else { &self.ref_poc1 },
            kind: &self.mb_kind,
        };
        // ROW MODE (R2): rows were derived during decode; the remainder was
        // finished above (before `info` borrowed the grids). Fallback: the
        // Part 16/17 picture-end precompute; `RS_H264_BS_PRE=0` further falls
        // back to the pack-then-derive-in-loop pipeline.
        let bs_store;
        if rowdb {
            bs_store = std::mem::take(&mut self.bs_frame);
            info.bs = &bs_store;
        } else if bs_pre_on() {
            let mut buf = Vec::new();
            rusty_h264_common::deblock::precompute_bs_frame(&info, self.mb_w, self.mb_h, &mut buf);
            bs_store = buf;
            info.bs = &bs_store;
        } else {
            bs_store = Vec::new();
        }
        let first_row = if rowdb { self.flt_rows } else { 0 };
        rusty_h264_common::deblock::filter_frame_rows(
            &mut self.rec_y,
            &mut self.rec_u,
            &mut self.rec_v,
            self.mb_w,
            self.mb_h,
            first_row..self.mb_h,
            &self.mb_qp,
            self.chroma_qp_offset,
            offset_a,
            offset_b,
            &info,
        );
        drop(info);
        if rowdb {
            self.bs_frame = bs_store;
        }
    }

    /// Crops the reconstructed coded-size planes to the display window.
    /// `into_frame`, additionally handing the per-picture grids back for reuse by
    /// the next picture. See `GridPool` for why this is worth doing.
    pub fn into_frame_recycle(mut self, crop_r: usize, crop_b: usize) -> (YuvFrame, GridPool) {
        let [c0, c1] = std::mem::take(&mut self.nnz_c);
        let pool = GridPool {
            bits_per_mb: self.bits_per_mb,
            mb_qp: std::mem::take(&mut self.mb_qp),
            bs_frame: std::mem::take(&mut self.bs_frame),
            pk_prev: std::mem::take(&mut self.pk_prev),
            pk_cur: std::mem::take(&mut self.pk_cur),
            nnz_dbr: std::mem::take(&mut self.nnz_dbr),
            bak_y: std::mem::take(&mut self.bak_y),
            bak_u: std::mem::take(&mut self.bak_u),
            bak_v: std::mem::take(&mut self.bak_v),
            nnz_y: std::mem::take(&mut self.nnz_y),
            nnz_c0: c0,
            nnz_c1: c1,
            modes_y: std::mem::take(&mut self.modes_y),
            coded_y: std::mem::take(&mut self.coded_y),
            mv_y: std::mem::take(&mut self.mv_y),
            inter_y: std::mem::take(&mut self.inter_y),
            ref_idx_y: std::mem::take(&mut self.ref_idx_y),
            mv1: std::mem::take(&mut self.mv1),
            ref_idx1: std::mem::take(&mut self.ref_idx1),
            mb_t8x8: std::mem::take(&mut self.mb_t8x8),
            mb_kind: std::mem::take(&mut self.mb_kind),
            bzero: std::mem::take(&mut self.bzero),
            sc_cat: std::mem::take(&mut self.sc_cat),
            sc_cbp: std::mem::take(&mut self.sc_cbp),
            sc_cmode: std::mem::take(&mut self.sc_cmode),
            sc_nzc: std::mem::take(&mut self.sc_nzc),
            sc_cbfdc: std::mem::take(&mut self.sc_cbfdc),
            sc_skip: std::mem::take(&mut self.sc_skip),
            sc_ref: std::mem::take(&mut self.sc_ref),
            sc_mvd: std::mem::take(&mut self.sc_mvd),
            sc_ref1: std::mem::take(&mut self.sc_ref1),
            sc_mvd1: std::mem::take(&mut self.sc_mvd1),
            sc_direct: std::mem::take(&mut self.sc_direct),
            ref_poc0: std::mem::take(&mut self.ref_poc0),
            ref_poc1: std::mem::take(&mut self.ref_poc1),
        };
        (self.into_frame(crop_r, crop_b), pool)
    }

    pub fn into_frame(self, crop_r: usize, crop_b: usize) -> YuvFrame {
        // No cropping (the common case): the reconstruction planes ARE the output —
        // move them out instead of allocating + copying three full planes per frame.
        if crop_r == 0 && crop_b == 0 {
            return YuvFrame {
                width: self.cw,
                height: self.ch,
                y: self.rec_y,
                u: self.rec_u,
                v: self.rec_v,
            };
        }
        let dw = self.cw - 2 * crop_r;
        let dh = self.ch - 2 * crop_b;
        let mut y = vec![0u8; dw * dh];
        for row in 0..dh {
            y[row * dw..row * dw + dw].copy_from_slice(&self.rec_y[row * self.cw..row * self.cw + dw]);
        }
        let (cdw, cdh) = (dw / 2, dh / 2);
        let mut u = vec![0u8; cdw * cdh];
        let mut v = vec![0u8; cdw * cdh];
        for row in 0..cdh {
            u[row * cdw..row * cdw + cdw]
                .copy_from_slice(&self.rec_u[row * self.ccw..row * self.ccw + cdw]);
            v[row * cdw..row * cdw + cdw]
                .copy_from_slice(&self.rec_v[row * self.ccw..row * self.ccw + cdw]);
        }
        let _ = self.cch;
        YuvFrame {
            width: dw,
            height: dh,
            y,
            u,
            v,
        }
    }
}

/// Reads `ref_idx_l0` as `te(v)` with range `num_ref_active - 1`: a single flag
/// when exactly two references are active (cMax == 1), else `ue(v)`.
// ---- CABAC binarization engine helpers (openh264 cabac_decoder.cpp) ----

/// Unary bin (`DecodeUnaryBinCabac`): bin0 at `ctx`; if 1, count bins at `ctx+off`
/// (including the terminating 0) until a 0.
/// CAVLC `mvd_lX` with a sanity bound. `se(v)` can legally code ±2^31-1, but
/// every profile/level caps |MV| far below ±2^17 quarter-pel units; beyond
/// that is a corrupt stream, and the unchecked `pmv + mvd` addition would
/// overflow i32 (debug panic / release wrap into an absurd vector).
fn read_mvd(r: &mut BitReader) -> Result<i32, MbError> {
    let v = r.read_se()?;
    if v.unsigned_abs() > (1 << 17) {
        return Err(MbError::Truncated);
    }
    Ok(v)
}

fn cabac_unary(cab: &mut crate::cabac::Cabac, ctx: usize, off: usize) -> u32 {
    if cab.decode_decision(ctx) == 0 {
        return 0;
    }
    let mut sym = 0;
    loop {
        let bin = cab.decode_decision(ctx + off);
        sym += 1;
        // Cap the unary run: no valid H.264 element coded through this helper
        // (mb_qp_delta) exceeds a few dozen bins, but on malformed / buffer-exhausted
        // input the arithmetic engine keeps yielding 1s (it zero-fills past the end),
        // which would loop forever. 512 is far beyond any legal value.
        if bin == 0 || sym >= 512 {
            break;
        }
    }
    sym
}

/// k-th order Exp-Golomb in bypass (`DecodeExpBypassCabac`).
fn cabac_exp_bypass(cab: &mut crate::cabac::Cabac, mut count: i32) -> u32 {
    let mut sym = 0u32;
    loop {
        let c = cab.decode_bypass();
        if c == 1 {
            sym += 1 << count;
            count += 1;
        }
        if c == 0 || count == 16 {
            break;
        }
    }
    let mut sym2 = 0u32;
    while count > 0 {
        count -= 1;
        if cab.decode_bypass() != 0 {
            sym2 |= 1 << count;
        }
    }
    sym + sym2
}

/// UEG0 coeff-level suffix (`DecodeUEGLevelCabac`): TU prefix at `ctx` (≤13) then an
/// EG0 bypass suffix.
fn cabac_ueg_level(cab: &mut crate::cabac::Cabac, ctx: usize) -> u32 {
    if cab.decode_decision(ctx) == 0 {
        return 0;
    }
    let mut code = 0u32;
    let mut tmp;
    loop {
        tmp = cab.decode_decision(ctx);
        code += 1;
        if tmp == 0 || code == 12 {
            break;
        }
    }
    if tmp != 0 {
        code += cabac_exp_bypass(cab, 0) + 1;
    }
    code
}

/// `mb_qp_delta` CABAC (`ParseDeltaQpCabac`): ctxIdxOffset 60, ctxInc = (prev delta ≠ 0).
pub fn parse_mb_qp_delta_cabac(cab: &mut crate::cabac::Cabac, last_delta_qp: &mut i32) -> i32 {
    const O: usize = 60;
    let ctx_inc = (*last_delta_qp != 0) as usize;
    let mut qp_delta = 0;
    if cab.decode_decision(O + ctx_inc) != 0 {
        let code = cabac_unary(cab, O + 2, 1) + 1;
        qp_delta = ((code + 1) >> 1) as i32;
        if code & 1 == 0 {
            qp_delta = -qp_delta;
        }
    }
    *last_delta_qp = qp_delta;
    qp_delta
}

// Shared CABAC residual glue tables (NZC_CACHE, RES_*) now live in
// `cabac_tables` — both coders read the ONE copy.
use rusty_h264_common::cabac_tables::{NZC_CACHE, RES_CBF, RES_MAP, RES_MAXC2, RES_MAXPOS, RES_ONE};
// res-property values (post GetMbResProperty, CABAC): the ctx-table index.
const RP_I16_DC: usize = 1;
const RP_I16_AC: usize = 2;
const RP_LUMA_4X4: usize = 3;
const RP_CHROMA_DC: usize = 7; // U (V=8, same offsets)
const RP_CHROMA_AC: usize = 9; // U (V=10, same offsets)
/// Luma 8×8 (ctxBlockCat 5). Its RES_MAP/RES_CBF entries stay 0: cat 5 does NOT
/// share the `105 + off` / `166 + off` context bases the 4×4 categories use — it
/// has its own absolute bases (402 sig, 417 last) and its own per-position
/// ctxIdxInc maps below. RES_ONE[6] = 199 IS used, because 227 + 199 = 426 and
/// 232 + 199 = 431 reproduce the spec's coeff_abs_level_minus1 base exactly, so
/// the level loop needs no special case at all.
const RP_LUMA_8X8: usize = 6;

// SIG8X8 / LAST8X8 moved to `rusty_h264_common::cabac_tables` (R6-1) so the encoder's
// ctxBlockCat 5 writer shares the exact spec data this reader is validated against.
use rusty_h264_common::cabac_tables::{LAST8X8, SIG8X8};

/// One residual block (openh264 `ParseResidualBlockCabac`), generic over the 5 CABAC
/// block categories. `rp` selects the context offsets. DC categories (I16 luma DC,
/// chroma DC) take the cbf context from the per-MB `cbf_dc` bitmask + neighbour MB DC
/// cbf; AC categories from the padded nzc cache. Returns totalCoeffNum.
#[allow(clippy::too_many_arguments)]
fn parse_residual_cabac(
    cab: &mut crate::cabac::Cabac,
    nzc: &mut [u8; 48],
    cbf_dc: &mut u16,
    iz: usize,
    rp: usize,
    is_intra: bool,
    ndc: (Option<u16>, Option<u16>), // (top MB cbf_dc, left MB cbf_dc); None = unavailable
    out: &mut [i32],                 // scan-order coefficients written here (len ≥ maxPos+1)
) -> u32 {
    // The CABAC residual parse IS the decoder's entropy stage on Main-profile
    // streams — it was invisible (a ~47% residue) until this scope named it.
    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Entropy);
    // ---- coded_block_flag ----
    // ctxBlockCat 5 is the ONLY category with no coded_block_flag: its presence is
    // inferred from CodedBlockPatternLuma, so parsing one here would desync.
    let is8 = rp == RP_LUMA_8X8;
    let is_dc = rp == RP_I16_DC || rp == RP_CHROMA_DC || rp == RP_CHROMA_DC + 1;
    let (mut na, mut nb) = (is_intra as u8, is_intra as u8);
    // `nzc` is [u8; 48] and every `NZC_CACHE` entry lies in [9, 47], so this
    // clamp is a semantic no-op that hands LLVM BOTH bounds - which is what
    // makes `nzc[scan]`, `nzc[scan - 8]` and `nzc[scan - 1]` below provable
    // instead of three bounds checks. Same trick as `parse_mvd_partition`.
    let scan = NZC_CACHE[iz.min(23)].clamp(8, 47);
    if is_dc {
        if let Some(t) = ndc.0 {
            nb = ((t >> rp) & 1) as u8;
        }
        if let Some(l) = ndc.1 {
            na = ((l >> rp) & 1) as u8;
        }
    } else {
        let (nbc, nac) = (nzc[scan - 8], nzc[scan - 1]);
        if nbc != 0xff {
            nb = (nbc != 0) as u8;
        }
        if nac != 0xff {
            na = (nac != 0) as u8;
        }
    }
    if !is8 {
        let _sg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::EntCbf);
        let cbf = cab.decode_decision(85 + RES_CBF[rp] + (na + (nb << 1)) as usize);
        if cbf == 0 {
            if !is_dc {
                nzc[scan] = 0;
            }
            return 0;
        }
        if is_dc {
            *cbf_dc |= 1 << rp;
        }
    }
    // ---- significance map ----
    let maxpos = RES_MAXPOS[rp] as usize;
    // cat 5 uses its own absolute bases; the 4×4 categories share 105/166 + offset.
    let (map, last) = if is8 {
        (402, 417)
    } else {
        let m = RES_MAP[rp];
        (105 + m, 166 + m)
    };
    // SPARSE significance map: record each significant POSITION in `pos[..n]`
    // instead of marking a dense 64-entry array. Three costs disappear — the
    // 256-byte `sig` zeroing per call, the level loop's data-dependent
    // `sig[i] != 0` re-scan of every position (a branch mispredict per
    // transition on typical 2-4-coeff blocks), and the final dense copy into
    // `out`. Bin ORDER is unchanged: levels were decoded at descending
    // significant positions, which is exactly `pos[..n]` reversed.
    //
    // CONTRACT with the callers (all 10 sites): `out` is freshly zeroed, so
    // writing only the significant entries leaves the same contents the dense
    // copy produced. A reused non-zero `out` would be a correctness bug.
    let mut pos = [0u8; 64];
    let mut n = 0usize;
    let mut last_hit = false;
    let _sg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::EntSig);
    // 4×4: ctxIdxInc IS the scan position. 8×8: it comes from the folded maps.
    // NOTE (4:2:2 landmine): `(i, i)` is correct for every 4:2:0 category
    // only because chroma-DC (cat 3) has NumC8x8 == 1 here; spec §9.3.3.1.3
    // wants `Min(i / NumC8x8, 2)` for its sig/last ctxIdxInc, which
    // diverges the day 4:2:2 (NumC8x8 == 2) is admitted.
    //
    let (mi_is8, li_is8) = (is8, is8);
    let _ = (mi_is8, li_is8);
    for i in 0..maxpos {
        // Both tables are [u8; 64] and `i < maxpos <= 63`, so `& 63` changes no
        // value and folds the two bounds checks.
        let (mi, li) = if is8 {
            (SIG8X8[i & 63] as usize, LAST8X8[i & 63] as usize)
        } else {
            (i, i)
        };
        if cab.decode_decision(map + mi) != 0 {
            pos[n & 63] = i as u8;
            n += 1;
            if cab.decode_decision(last + li) != 0 {
                last_hit = true;
                break;
            }
        }
    }
    if !last_hit {
        pos[n & 63] = maxpos as u8;
        n += 1;
    }
    let coeff_num = n as u32;
    // ---- levels ----
    let one = 227 + RES_ONE[rp];
    let abs = one + 5;
    let maxc2 = RES_MAXC2[rp];
    let (mut c1, mut c2) = (1i32, 0i32);
    drop(_sg);
    let _lg = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::EntLvl);
    for k in (0..n).rev() {
        let mut level = 1 + cab.decode_decision(one + c1 as usize) as i32;
        if level == 2 {
            level += cabac_ueg_level(cab, abs + c2 as usize) as i32;
            c2 = (c2 + 1).min(maxc2);
            c1 = 0;
        } else if c1 != 0 {
            c1 = (c1 + 1).min(4);
        }
        if cab.decode_bypass() != 0 {
            level = -level;
        }
        // NOT A MASK — `.get_mut`. `out` is `&mut [i32]`, a RUNTIME-length slice
        // of maxPos+1, so no constant bound can be correct: an `& 15` here wrote
        // 8x8 coefficients (maxPos = 63) to the WRONG positions and failed the
        // corpus on tempete high/default. The distinction that matters is that a
        // mask silently RELOCATES an out-of-range write while `.get_mut` can only
        // drop it, and dropping is unreachable here (`pos` holds values <= maxPos).
        if let Some(o) = out.get_mut(pos[k & 63] as usize) {
            *o = level;
        }
    }
    if is8 {
        // One 8×8 covers four consecutive z-order 4×4 cells. Every later
        // coded_block_flag ctxIdxInc reads this cache, so all four must carry the
        // count — writing only `scan` would corrupt the NEXT macroblock's contexts.
        let cn = coeff_num as u8;
        for k in 0..4 {
            nzc[NZC_CACHE[(iz + k).min(23)].min(47)] = cn;
        }
    } else if !is_dc {
        nzc[scan] = coeff_num as u8;
    }
    coeff_num
}


// ============================================================================
// Entropy-decouple E2: the OWNED pixel context that crosses the thread
// boundary (docs/entropy-decouple-plan.md). The worker owns the planes, the
// backup rows, the DPB Arcs and its own qp/t8/bs grids (fed by Row messages);
// the parse thread keeps every syntax grid. The methods below are ports of
// the FrameDecoder pixel halves — grid writes removed (parse commits its own
// grids), motion carried in the job instead of re-gathered.
// ============================================================================

/// The committed-value class of a deferred B_Skip span. Continuation
/// requires kind EQUALITY: the flush range-fills grids and recons the band
/// from these values alone.
#[derive(Clone, Copy, PartialEq, Eq)]
enum BzKind {
    /// ref 0 both lists, (0,0)/(0,0) — band = avg of both padded refs.
    ZeroBi,
    /// One active list at (0,0): (list, clamped ref index) — band = memcpy.
    ZeroUni(u8, u8),
    /// Uniform full-pel direct: clamped refs (-1 = inactive) + adjusted MVs,
    /// windows PREVALIDATED per MB at push (contiguous tiles ⇒ the union
    /// window is valid) — band = offset copy/avg. Chroma requires mv%8==0
    /// (also prevalidated).
    Fp { r0: i8, r1: i8, m0: (i16, i16), m1: (i16, i16) },
}

/// Messages from the parse thread to the pixel worker.
enum EdcMsg {
    Job(EdcJob),
    /// A ROW's worth of pixel jobs in one message (D10).
    ///
    /// The seam sent ONE message per macroblock: 208k sends per 60-frame pass
    /// against 2,596 rows. The overhead is per-JOB (channel lock, park/unpark)
    /// while the prize is proportional to pixel WORK, so the per-job send was
    /// dividing the payoff by ~80 for nothing. Batching per row cuts the
    /// synchronisation events by that factor and moves not one byte of pixel
    /// work off the worker.
    ///
    /// ORDER IS THE CORRECTNESS CONDITION: the worker must see a row's jobs
    /// before that row's `Row` filter message, so the batch is flushed at every
    /// row boundary, before `NeedCtx`, and at slice end.
    Batch(Vec<EdcJob>),
    /// A macroblock row finished parsing: install its qp/t8/bs and filter it.
    Row {
        r: usize,
        bs: Vec<rusty_h264_common::deblock::MbBs>,
        qp: Vec<u8>,
        t8: Vec<bool>,
    },
    /// An intra macroblock needs the planes on the parse thread: send the
    /// context over and wait for it to come back.
    NeedCtx,
}

pub(crate) struct PixelCtx {
    rec_y: Vec<u8>,
    rec_u: Vec<u8>,
    rec_v: Vec<u8>,
    bak_y: Vec<u8>,
    bak_u: Vec<u8>,
    bak_v: Vec<u8>,
    refs: Vec<crate::Ref>,
    refs1: Vec<crate::Ref>,
    weights: Option<WeightTable>,
    /// `weights.list_identity(0)`, cached - mirrors `FrameDecoder::weights_l0id`
    /// so the worker twin does not have to walk the table per macroblock.
    weights_l0id: bool,
    scaling: Option<[[i32; 16]; 6]>,
    scaling8: Option<[[i32; 64]; 2]>,
    cw: usize,
    ccw: usize,
    mb_w: usize,
    mb_h: usize,
    chroma_qp_offset: i32,
    flt_rows: usize,
    db_ena: bool,
    db_oa: i32,
    db_ob: i32,
    cur_qp: u8,
    qp_grid: Vec<u8>,
    t8_grid: Vec<bool>,
    bs_store: Vec<rusty_h264_common::deblock::MbBs>,
    /// Frame-MT Phase B progress Arc (row publish from the EDC worker).
    progress: Option<crate::Ref>,
}

impl PixelCtx {
    /// Frame-MT Phase B: copy filtered MB rows into the shared progress Arc.
    fn publish_progress_rows(&self) {
        let Some(slot) = &self.progress else {
            return;
        };
        if !self.db_ena || self.flt_rows == 0 {
            return;
        }
        publish_filtered_rows_to_slot(
            slot,
            &self.rec_y,
            &self.rec_u,
            &self.rec_v,
            self.cw,
            self.ccw,
            self.mb_h * 16,
            self.flt_rows,
        );
    }

    fn chroma_qp_for(&self, qp: u8) -> u8 {
        rusty_h264_common::predict::chroma_qp(
            ((qp as i32 + self.chroma_qp_offset).clamp(0, 51)) as u8,
        )
    }

    fn dequant(&self, levels: &[i32; 16], qp: u8, list: usize) -> [i32; 16] {
        match &self.scaling {
            Some(sc) => dequantize_weighted(levels, qp, &sc[list]),
            None => dequantize(levels, qp),
        }
    }

    fn dequant_dc4(&self, level: i32, qp: u8, list: usize) -> i32 {
        rusty_h264_common::transform::dequantize_dc4(
            level,
            qp,
            self.scaling.as_ref().map(|sc| sc[list][0]),
        )
    }

    fn inv_quant8(&self, raster: &[i32; 64], qp: u8, list: usize) -> [i32; 64] {
        match &self.scaling8 {
            Some(sc) => inverse_quant_8x8(raster, qp, &sc[list]),
            None => inverse_quant_8x8(raster, qp, &[16i32; 64]),
        }
    }

    fn dequant_chroma_dc(&self, levels: &[i32; 4], qp: u8, list: usize) -> [i32; 4] {
        match &self.scaling {
            Some(sc) => inverse_quant_chroma_dc_weighted(levels, qp, sc[list][0]),
            None => inverse_quant_chroma_dc(levels, qp),
        }
    }

    fn weight_partition(
        &self,
        pred_y: &mut [u8; 256],
        c_pred: &mut [[u8; 64]; 2],
        list: usize,
        refi: usize,
        rx: usize,
        ry: usize,
        rw: usize,
        rh: usize,
    ) {
        let Some(wt) = &self.weights else { return };
        // REFUTED, reverted: row-slicing these loops measured +28% instructions
        // on `weight_partition` (the extents are runtime values, so the slice
        // bounds cost more than the per-sample checks they replaced). The real
        // win for this function was hoisting the identity test to its CALLERS,
        // which stands.
        // RESOLVE ONCE, APPLY MANY. `apply_luma` re-read `self.luma[list][refi]`
        // — an array index, a Vec deref and an element index, two of them bounds
        // checked — on EVERY sample, up to 256 luma plus 128 chroma per call.
        // The weight is a property of the partition, not of the pixel. (The loop
        // SHAPE is untouched: row-slicing it is refuted above.)
        // MASKED, not row-sliced. `pred_y` is a fixed `[u8; 256]` and `c_pred` a
        // `[[u8; 64]; 2]`, so `& 255` / `& 63` are no-ops that prove the index
        // outright — where SLICING these loops cost +28% (the extents are runtime
        // values, so the slice bounds outweigh the checks). Same lesson as
        // `luma_centre`: the refutation was of one SHAPE, not of the goal.
        let (lw, lo) = wt.luma_wo(list, refi);
        for dy in 0..rh {
            for dx in 0..rw {
                let i = ((ry + dy) * 16 + (rx + dx)) & 255;
                pred_y[i] = wt.apply_luma_wo(pred_y[i], lw, lo);
            }
        }
        let (crx, cry, crw, crh) = (rx / 2, ry / 2, rw / 2, rh / 2);
        for cc in 0..2 {
            let (cw, co) = wt.chroma_wo(list, refi, cc);
            let plane = &mut c_pred[cc & 1];
            for dy in 0..crh {
                for dx in 0..crw {
                    let i = ((cry + dy) * 8 + (crx + dx)) & 63;
                    plane[i] = wt.apply_chroma_wo(plane[i], cw, co);
                }
            }
        }
    }

        fn recon_p_inter(&mut self, j: &PInterJob) {
        crate::RefFrame::set_mc_row_need(j.mby, self.mb_h * 16);
        // `add_inter_residual` reads `self.cur_qp`; unlike the FrameDecoder copy
        // (which interleaves with parsing and must save/restore), every PixelCtx
        // job sets it from the job before any reader, so no restore is needed.
        self.cur_qp = j.qp;
                    // ---- Recon: motion-comp (per 4×4 luma / co-located 2×2 chroma using the
                    // committed grid MV — the 6-tap/bilinear filter is per-output-pixel, so
                    // per-block MC is bit-identical to per-partition MC) + residual add via the
                    // SAME reconstruct_4x4 as intra, with the MC output as the prediction.
                    let mut pred_y = [0u8; 256];
                    let mut c_pred = [[0u8; 64]; 2];
                    {
                        // MC-CALL COALESCING (side-by-side descent, dec target #2): the old
                        // loop paid 16 mc_luma(4×4) + 32 mc_chroma(2×2) per MB regardless of
                        // partitioning — 48 calls even for a single-MV 16×16 MB, and the
                        // per-call glue around 2.4M calls was ~40% of decoding real-world
                        // (x264) streams. The 6-tap/bilinear filters are per-output-pixel,
                        // so merging blocks with equal (mv, ref) into one wider MC call is
                        // BIT-IDENTICAL; the rect ladder mirrors the partition shapes.
                        let _ms = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMcStage);
                        let (rh16, cch) = (self.mb_h * 16, self.mb_h * 8);
                        // E2: the worker owns no syntax grids — the job carries the
                        // committed per-block motion (filled at parse time).
                        let gmv = j.gmv;
                        let mut gref = [0usize; 16];
                        for k in 0..16 {
                            gref[k] = (j.gref[k] as usize).min(self.refs.len() - 1);
                        }
                        // All blocks of the rect (in 4×4-block units) match its top-left?
                        let rect_eq = |x4: usize, y4: usize, w4: usize, h4: usize| -> bool {
                            let t = y4 * 4 + x4;
                            (0..h4).all(|dy| {
                                (0..w4).all(|dx| {
                                    let b = ((y4 + dy) * 4 + (x4 + dx)) & 15;
                                    gmv[b] == gmv[t] && gref[b] == gref[t]
                                })
                            })
                        };
                        let refs = &self.refs;
                        let (cw, ccw) = (self.cw, self.ccw);
                        let mc_rect = |x4: usize,
                                           y4: usize,
                                           w4: usize,
                                           h4: usize,
                                           pred_y: &mut [u8; 256],
                                           c_pred: &mut [[u8; 64]; 2]| {
                            let b = y4 * 4 + x4;
                            let (mv, gr) = (gmv[b & 15], gref[b & 15]);
                            // `gref` holds a reference-list slot; a slot the list
                            // does not have means there is nothing to predict from,
                            // so the rect is left as it stands.
                            let Some(reference) = refs.get(gr) else { return };
                            let (w, h) = (w4 * 4, h4 * 4);
                            // A FULL-WIDTH rect (w == 16, so x4 == 0) occupies contiguous
                            // whole rows of `pred_y` — the MC output layout and the
                            // destination layout coincide, so MC writes the prediction
                            // buffer DIRECTLY. The staging copy exists only for narrow
                            // rects, whose rows really are strided in `pred_y`. This is
                            // the diagnosis's "stage-boundary materialization" tax paid
                            // by the dominant 16×16/16×8 shapes: 256 B of `t` zeroing
                            // plus a 256 B copy per rect, for nothing.
                            if w == 16 {
                                rusty_h264_common::inter::with_mc_scratch(|scr| rusty_h264_common::inter::mc_luma_padded_pre(scr, &*reference.luma_guard(reference.ch), reference.lstride(), crate::LPAD, cw, rh16, j.mbx * 16, j.mby * 16 + y4 * 4, w, h, mv.0, mv.1, &mut pred_y[y4 * 64..y4 * 64 + w * h]));
                            } else {
                                let mut t = [0u8; 256];
                                rusty_h264_common::inter::with_mc_scratch(|scr| rusty_h264_common::inter::mc_luma_padded_pre(scr, &*reference.luma_guard(reference.ch), reference.lstride(), crate::LPAD, cw, rh16, j.mbx * 16 + x4 * 4, j.mby * 16 + y4 * 4, w, h, mv.0, mv.1, &mut t[..w * h]));
                                let _pb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
                                for dy in 0..h {
                                    pred_y[(y4 * 4 + dy) * 16 + x4 * 4..][..w]
                                        .copy_from_slice(&t[dy * w..dy * w + w]);
                                }
                            }
                            let (cw4, ch4) = (w4 * 2, h4 * 2);
                            let nc = cw4 * ch4;
                            let (gu, gv) = (reference.chroma_guard(0, reference.ch), reference.chroma_guard(1, reference.ch));
                            // U+V paired: one setup serves both planes (see
                            // mc_chroma_padded_pair). Full-width coincidence:
                            // cw4 == 8 rows are contiguous in the 8-wide plane.
                            if cw4 == 8 {
                                let [cu, cv] = &mut *c_pred;
                                rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, reference.cstride(), crate::CPAD, ccw, cch, j.mbx * 8, j.mby * 8 + y4 * 2, cw4, ch4, mv.0, mv.1, &mut cu[y4 * 16..y4 * 16 + nc], &mut cv[y4 * 16..y4 * 16 + nc]);
                            } else {
                                let (mut tu, mut tv) = ([0u8; 64], [0u8; 64]);
                                rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, reference.cstride(), crate::CPAD, ccw, cch, j.mbx * 8 + x4 * 2, j.mby * 8 + y4 * 2, cw4, ch4, mv.0, mv.1, &mut tu[..nc], &mut tv[..nc]);
                                let _pb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
                                for (cc, tc) in [(0usize, &tu), (1, &tv)] {
                                    for dy in 0..ch4 {
                                        c_pred[cc][(y4 * 2 + dy) * 8 + x4 * 2..][..cw4]
                                            .copy_from_slice(&tc[dy * cw4..dy * cw4 + cw4]);
                                    }
                                }
                            }
                        };
                        if rect_eq(0, 0, 4, 4) {
                            mc_rect(0, 0, 4, 4, &mut pred_y, &mut c_pred);
                        } else if rect_eq(0, 0, 4, 2) && rect_eq(0, 2, 4, 2) {
                            mc_rect(0, 0, 4, 2, &mut pred_y, &mut c_pred);
                            mc_rect(0, 2, 4, 2, &mut pred_y, &mut c_pred);
                        } else if rect_eq(0, 0, 2, 4) && rect_eq(2, 0, 2, 4) {
                            mc_rect(0, 0, 2, 4, &mut pred_y, &mut c_pred);
                            mc_rect(2, 0, 2, 4, &mut pred_y, &mut c_pred);
                        } else {
                            for q in 0..4usize {
                                let (qx, qy) = ((q % 2) * 2, (q / 2) * 2);
                                if rect_eq(qx, qy, 2, 2) {
                                    mc_rect(qx, qy, 2, 2, &mut pred_y, &mut c_pred);
                                } else if rect_eq(qx, qy, 2, 1) && rect_eq(qx, qy + 1, 2, 1) {
                                    mc_rect(qx, qy, 2, 1, &mut pred_y, &mut c_pred);
                                    mc_rect(qx, qy + 1, 2, 1, &mut pred_y, &mut c_pred);
                                } else if rect_eq(qx, qy, 1, 2) && rect_eq(qx + 1, qy, 1, 2) {
                                    mc_rect(qx, qy, 1, 2, &mut pred_y, &mut c_pred);
                                    mc_rect(qx + 1, qy, 1, 2, &mut pred_y, &mut c_pred);
                                } else {
                                    for j in 0..4usize {
                                        mc_rect(qx + (j % 2), qy + (j / 2), 1, 1, &mut pred_y, &mut c_pred);
                                    }
                                }
                            }
                        }
                        // EXPLICIT WEIGHTED PREDICTION (spec 8.4.2.3). The CAVLC inter
                        // path weights each partition after MC; the MC-call-coalescing
                        // rewrite of this CABAC path lost it, and nothing caught that
                        // because the effect is invisible unless a stream actually
                        // carries non-default weights. x264's `weightp` DUPLICATES a
                        // reference and distinguishes the copy ONLY by its weights, so
                        // every macroblock picking the weighted index decoded unweighted
                        // -- a silent, accumulating luma drift.
                        //
                        // Applied per 4x4 block rather than per partition: the weight
                        // depends solely on the block's reference index, so the two are
                        // equivalent, and `gref` already holds it for every block
                        // regardless of which rect ladder rung ran.
                        if self.weights.is_some() {
                            for by in 0..4usize {
                                for bx in 0..4usize {
                                    let refi = gref[by * 4 + bx];
                                    self.weight_partition(
                                        &mut pred_y, &mut c_pred, 0, refi, bx * 4, by * 4, 4, 4,
                                    );
                                }
                            }
                        }
                    }
                    // Residual add — the SAME helper the B path uses (this inline
                    // copy was a duplicate; deduped when the zero-block fast path
                    // landed so both paths share it).
                    self.add_inter_residual(j.mbx, j.mby, &pred_y, &c_pred, j.luma_scan.as_ref(), j.luma8.as_ref(), &j.cdc, j.cac.as_ref(), j.cbp_chroma, &j.nnzs);
    }

    /// D9b: P inter with `cbp == 0` — MC + plane copy (worker twin of FrameDecoder).
    fn recon_p_inter_nores(&mut self, j: &PInterNoResJob) {
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        // `self.refs.len() - 1` was re-loaded on every one of the sixteen
        // iterations; it is a per-macroblock invariant. Written once, not
        // zeroed-then-filled.
        let nrefs = self.refs.len() - 1;
        let gref: [usize; 16] = core::array::from_fn(|k| (j.gref[k] as usize).min(nrefs));
        coalesce_p_inter_mc(
            &self.refs,
            self.cw,
            self.ccw,
            self.mb_h,
            j.mbx,
            j.mby,
            &j.gmv,
            &gref,
            &mut pred_y,
            &mut c_pred,
        );
        // The identity early-out lives INSIDE `weight_partition`, so an x264
        // stream - which carries a pred_weight_table in EVERY P slice, identity
        // outside fades - still paid sixteen calls per macroblock to be told
        // there was nothing to do. Hoisted to one test.
        if self.weights.is_some() && !self.weights_l0id {
            for by in 0..4usize {
                for bx in 0..4usize {
                    let refi = gref[by * 4 + bx];
                    self.weight_partition(&mut pred_y, &mut c_pred, 0, refi, bx * 4, by * 4, 4, 4);
                }
            }
        }
        // ONE span per plane: the destination is a stack of contiguous runs a
        // fixed stride apart, so the rows share a single bounds check instead of
        // one each (16 + 8 + 8 of them).
        let (cw, ccw) = (self.cw, self.ccw);
        let ybase = (j.mby * 16) * cw + j.mbx * 16;
        let ywin = &mut self.rec_y[ybase..ybase + 15 * cw + 16];
        for dy in 0..16 {
            ywin[dy * cw..dy * cw + 16].copy_from_slice(&pred_y[dy * 16..dy * 16 + 16]);
        }
        let cbase = (j.mby * 8) * ccw + j.mbx * 8;
        for c in 0..2 {
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            let cwin = &mut plane[cbase..cbase + 7 * ccw + 8];
            for dy in 0..8 {
                cwin[dy * ccw..dy * ccw + 8].copy_from_slice(&c_pred[c][dy * 8..dy * 8 + 8]);
            }
        }
    }

    fn recon_p_skip(&mut self, mb_x: usize, mb_y: usize, mv: (i32, i32)) {
        crate::RefFrame::set_mc_row_need(mb_y, self.mb_h * 16);
        let (ch, cch) = (self.mb_h * 16, self.mb_h * 8);

        let mut pred = [0u8; 256];
        let Some(rf0) = self.refs.first() else { return };
        mc_luma_padded(&*rf0.luma_guard(rf0.ch), rf0.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16, 16, 16, mv.0, mv.1, &mut pred);
        if let Some(wt) = &self.weights {
            for p in pred.iter_mut() {
                *p = wt.apply_luma(*p, 0, 0);
            }
        }
        {
            let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::SkipRecon);
            // ONE span for the sixteen rows (see `recon_p_inter_nores`).
            let (cw, base) = (self.cw, (mb_y * 16) * self.cw + mb_x * 16);
            let win = &mut self.rec_y[base..base + 15 * cw + 16];
            for dy in 0..16 {
                win[dy * cw..dy * cw + 16].copy_from_slice(&pred[dy * 16..dy * 16 + 16]);
            }
        }
        for c in 0..2 {
            let mut pc = [0u8; 64];
            let Some(rf0) = self.refs.first() else { return };
            let rc = if c == 0 { &*rf0.chroma_guard(0, rf0.ch) } else { &*rf0.chroma_guard(1, rf0.ch) };
            mc_chroma_padded(rc, rf0.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8, 8, 8, mv.0, mv.1, &mut pc);
            if let Some(wt) = &self.weights {
                for p in pc.iter_mut() {
                    *p = wt.apply_chroma(*p, 0, 0, c);
                }
            }
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for dy in 0..8 {
                let d = (mb_y * 8 + dy) * self.ccw + mb_x * 8;
                plane[d..d + 8].copy_from_slice(&pc[dy * 8..dy * 8 + 8]);
            }
        }
    }

    fn add_inter_residual(
        &mut self,
        mb_x: usize,
        mb_y: usize,
        pred_y: &[u8; 256],
        c_pred: &[[u8; 64]; 2],
        luma_scan: Option<&[[i32; 16]; 16]>,
        // `Some` when the macroblock carries transform_size_8x8_flag: four 8x8
        // blocks in 8x8 scan order, replacing the sixteen 4x4 luma blocks.
        luma8: Option<&[[i32; 64]; 4]>,
        cdc: &[[i32; 4]; 2],
        cac: Option<&[[[i32; 16]; 4]; 2]>,
        cbp_chroma: u32,
        // Parsed totalCoeff per block, indexed exactly as the parse's `iz`:
        // [0..16] luma 4x4 z-order (for t8, the 8x8 count sits at `id8*4`),
        // [16..24] chroma AC as `16 + c*4 + id4`. The parser already counted
        // every significant coefficient; re-deriving the counts here scanned
        // 16-64 array elements per block (~400 loads/MB) for information the
        // caller was holding — the diagnosis's stage-boundary re-derivation tax.
        nnzs: &[u8; 24],
    ) {
        // A `None` field means the parse wrote nothing there; every read below
        // is guarded by a zero-count test, so the shared zero plane is
        // read-equivalent to the per-macroblock zeroed stack array it replaces.
        let luma_scan = luma_scan.unwrap_or(&ZERO_LUMA_SCAN);
        let cac = cac.unwrap_or(&ZERO_CAC);
        let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecResidAdd);
        let qp = self.cur_qp;
        let qpc = self.chroma_qp_for(qp);
        if let Some(l8) = luma8 {
            // INTER 8x8 luma: same primitives the I_8x8 and CAVLC paths use.
            for b8 in 0..4usize {
                let (b8x, b8y) = (b8 % 2, b8 / 2);
                // Summed, not slot 0: with per-4x4 counts in the CAVLC case, slot 0
                // is only the first sub-block and can be 0 while the block is coded.
                let nnz: u32 = (0..4).map(|k| nnzs[b8 * 4 + k] as u32).sum();
                let (px, py) = (mb_x * 16 + b8x * 8, mb_y * 16 + b8y * 8);
                if nnz == 0 {
                    // Zero residual: recon == pred — same shortcut as the
                    // FrameDecoder twin.
                    edcstat::bump(&edcstat::T8_ZERO, 1);
                    for dy in 0..8 {
                        let d = (py + dy) * self.cw + px;
                        let po = (b8y * 8 + dy) * 16 + b8x * 8;
                        self.rec_y[d..d + 8].copy_from_slice(&pred_y[po..po + 8]);
                    }
                } else {
                    let raster = un_scan_8x8(&l8[b8]);
                    // list 1 = INTER 8x8 luma scaling list (0 is the intra one).
                    let res8 = self.inv_quant8(&raster, qp, 1);
                    let predb: [i32; 64] =
                        std::array::from_fn(|i| pred_y[(b8y * 8 + i / 8) * 16 + (b8x * 8 + i % 8)] as i32);
                    let recon = add_residual_8x8(&res8, &predb);
                    // Eight row copies. This wrote SIXTY-FOUR individually
                    // bounds-checked samples into the luma plane per coded 8x8
                    // block — the same shape whose fix carried `recon_i8_block`.
                    // Present in BOTH the main path and the EDC worker twin.
                    for dy in 0..8 {
                        let d = (py + dy) * self.cw + px;
                        self.rec_y[d..][..8].copy_from_slice(&recon[dy * 8..][..8]);
                    }
                }
            }
        }
        for (blk, &(lbx, lby)) in LUMA_4X4_SCAN_XY.iter().enumerate() {
            if luma8.is_some() {
                break;
            }
            let nnz = nnzs[blk];
            let cw = self.cw;
            let p_off = (lby * 4) * 16 + lbx * 4;
            let r_off = (mb_y * 4 + lby) * 4 * cw + (mb_x * 4 + lbx) * 4;
            if nnz == 0 {
                // Zero residual → recon == prediction EXACTLY (the integer IDCT is
                // linear so zeros map to zeros, and pred is already 0..=255) — copy
                // the pred rows straight into the plane. On real (sparse-cbp)
                // streams this is MOST of the 4×4 blocks.
                for r in 0..4 {
                    self.rec_y[r_off + r * cw..r_off + r * cw + 4]
                        .copy_from_slice(&pred_y[p_off + r * 16..p_off + r * 16 + 4]);
                }
                continue;
            }
            // DC-ONLY: the sole significant coefficient is scan position 0 (the
            // zig-zag starts at DC, and un_scan keeps it at raster 0), so the
            // whole dequant + IDCT collapses to one multiply and a flat add.
            if nnz == 1 && luma_scan[blk][0] != 0 {
                let f = self.dequant_dc4(luma_scan[blk][0], qp, 3);
                reconstruct_4x4_dc_into((f + 32) >> 6, pred_y, p_off, 16, &mut self.rec_y, r_off, cw);
            } else {
                // Fused un-scan + dequant over ONLY the significant coefficients,
                // then IDCT + add + clip straight into the plane — no `qb`, no
                // `deq`-from-dense, no `predb` gather, no `s`, no `store` call.
                //
                // HYBRID: the scatter walks scan positions with a data-dependent
                // branch per slot, which beats the branchless dense 16-multiply
                // loop only while the block is SPARSE. The DC/zero fast paths
                // already removed the sparsest blocks, so the population here
                // skews denser — above ~6 coefficients the dense loop wins.
                let deq = if nnz <= 6 {
                    dequant_scatter_4x4(&luma_scan[blk], nnz, 0, qp, self.scaling.as_ref().map(|sc| &sc[3]))
                } else {
                    self.dequant(&un_scan_4x4_dcac(&luma_scan[blk]), qp, 3)
                };
                reconstruct_4x4_into(&deq, pred_y, p_off, 16, &mut self.rec_y, r_off, cw);
            }
        }
        let mut c_dc = [[0i32; 4]; 2];
        if cbp_chroma != 0 {
            for c in 0..2 {
                c_dc[c] = self.dequant_chroma_dc(&cdc[c], qpc, 4 + c);
            }
        }
        let ccw = self.ccw;
        for c in 0..2 {
            for &(bx, by) in &CHROMA_4X4_SCAN_XY {
                let mut ac_nz = false;
                if cbp_chroma == 2 {
                    let n = nnzs[(16 + c * 4 + by * 2 + bx).min(23)];
                    ac_nz = n != 0;
                }
                let dc = c_dc[c & 1][(by * 2 + bx) & 3];
                let p_off = (by * 4) * 8 + bx * 4;
                let r_off = (mb_y * 2 + by) * 4 * ccw + (mb_x * 2 + bx) * 4;
                let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                if dc == 0 && !ac_nz {
                    // Zero residual (no AC, zero DC) → recon == prediction exactly.
                    for r in 0..4 {
                        plane[r_off + r * ccw..r_off + r * ccw + 4]
                            .copy_from_slice(&c_pred[c][p_off + r * 8..p_off + r * 8 + 4]);
                    }
                    continue;
                }
                // DC-ONLY (no coded AC — covers every cbp_chroma==1 block and the
                // AC-empty blocks of cbp_chroma==2): the chroma DC arrives ALREADY
                // dequantized, so the residual is `(dc + 32) >> 6` flat.
                if !ac_nz {
                    reconstruct_4x4_dc_into((dc + 32) >> 6, &c_pred[c], p_off, 8, plane, r_off, ccw);
                    continue;
                }
                // AC-only scan: index i is overall scan position i+1 (ac_shift=1).
                // Same sparse/dense hybrid as luma.
                let n = nnzs[(16 + c * 4 + by * 2 + bx).min(23)];
                let mut deq = if n <= 6 {
                    dequant_scatter_4x4(&cac[c & 1][(by * 2 + bx) & 3], n, 1, qpc, self.scaling.as_ref().map(|sc| &sc[4 + c]))
                } else {
                    let mut ac = [0i32; 16];
                    un_scan_4x4_ac_into(&cac[c & 1][(by * 2 + bx) & 3], &mut ac);
                    // Free-fn dequant: `self.dequant` borrows all of `self`, which
                    // conflicts with the live `plane` (&mut self.rec_u/v) borrow.
                    match &self.scaling {
                        Some(sc) => dequantize_weighted(&ac, qpc, &sc[4 + c]),
                        None => dequantize(&ac, qpc),
                    }
                };
                deq[0] = dc;
                reconstruct_4x4_into(&deq, &c_pred[c], p_off, 8, plane, r_off, ccw);
            }
        }
    }

    fn filter_row(&mut self, r: usize) {
        // The precomputed consumer path reads ONLY `bs` + `t8x8` (+ the qp grid
        // passed as a parameter) — verified when the path landed (WHYS Part 15).
        let info = rusty_h264_common::deblock::BlockInfo {
            inter: &[],
            nnz: &[],
            mv: &[],
            ref_id: &[],
            mv1: &[],
            ref_id1: &[],
            w4: self.mb_w * 4,
            t8x8: &self.t8_grid,
            bs: &self.bs_store,
            poc0: &[],
            poc1: &[],
            kind: &[],
        };
        rusty_h264_common::deblock::filter_frame_rows(
            &mut self.rec_y,
            &mut self.rec_u,
            &mut self.rec_v,
            self.mb_w,
            self.mb_h,
            r..r + 1,
            &self.qp_grid,
            self.chroma_qp_offset,
            self.db_oa,
            self.db_ob,
            &info,
        );
    }

    fn save_bak(&mut self, r: usize) {
        let y0 = (r * 16 + 15) * self.cw;
        self.bak_y.copy_from_slice(&self.rec_y[y0..y0 + self.cw]);
        let c0 = (r * 8 + 7) * self.ccw;
        self.bak_u.copy_from_slice(&self.rec_u[c0..c0 + self.ccw]);
        self.bak_v.copy_from_slice(&self.rec_v[c0..c0 + self.ccw]);
    }
}

/// The pixel worker: replays jobs in parse order, filters rows as their
/// messages arrive, and hands the whole context to the parse thread (and
/// back) around intra macroblocks. Returns the context at slice end.
/// E2 SEAM COUNTERS (D7). Deterministic — one run is the verdict, no pinning.
/// `RS_H264_EDC_STATS=1` prints at decode end. Counts, not clocks: the question
/// "does one intra macroblock drain the pipeline" is a COUNT question.
pub(crate) mod edcstat {
    use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
    pub static NEEDCTX: AtomicU64 = AtomicU64::new(0);
    pub static JOBS: AtomicU64 = AtomicU64::new(0);
    pub static ROWS: AtomicU64 = AtomicU64::new(0);
    pub static ROWBYTES: AtomicU64 = AtomicU64::new(0);
    pub static MBS: AtomicU64 = AtomicU64::new(0);
    pub static J_INTER: AtomicU64 = AtomicU64::new(0);
    pub static DOUBLED: AtomicU64 = AtomicU64::new(0);
    pub static J_NORES_SENT: AtomicU64 = AtomicU64::new(0);
    pub static BATCHES: AtomicU64 = AtomicU64::new(0);
    pub static DISPATCH_ON: AtomicU64 = AtomicU64::new(0);
    pub static DISPATCH_SEEN: AtomicU64 = AtomicU64::new(0);
    /// mb_skip_run band path (big-oppy-decoder §6 KEY glue): P_Skip MBs
    /// reconstructed by run-coalesced band copies, and the runs themselves.
    /// DETERMINISTIC WIN counters — each banded MB removed 1 luma MC call,
    /// 2 chroma MC calls and the 256+128-byte pred staging round-trip.
    pub static SKIPBAND_MBS: AtomicU64 = AtomicU64::new(0);
    pub static SKIPBAND_RUNS: AtomicU64 = AtomicU64::new(0);
    pub static SKIP_SINGLES: AtomicU64 = AtomicU64::new(0);
    // MEASUREMENT counters sizing the next skip-band extensions (no behavior).
    // P side: singles that sit in a same-row run of >=2 EQUAL nonzero MVs,
    // split by full-pel (band-copy-with-offset eligible) vs fractional.
    pub static PEQ_FP: AtomicU64 = AtomicU64::new(0);
    pub static PEQ_FRAC: AtomicU64 = AtomicU64::new(0);
    // B side: full-16x16 spatial-direct calls (B_Skip + direct-16), how many
    // collapse to ONE uniform rect, and of those the zero-motion bi/uni and
    // full-pel populations + run adjacency (previous MB same params, same row).
    pub static BSK_FULLMB: AtomicU64 = AtomicU64::new(0);
    pub static BSK_1RECT: AtomicU64 = AtomicU64::new(0);
    pub static BSK_ZBI: AtomicU64 = AtomicU64::new(0);
    pub static BSK_ZUNI: AtomicU64 = AtomicU64::new(0);
    pub static BSK_FP: AtomicU64 = AtomicU64::new(0);
    pub static BSK_RUNCONT: AtomicU64 = AtomicU64::new(0);
    /// DETERMINISTIC WIN counter — B_Skip MBs taken by the zero-bi fast path.
    pub static BSKB_FAST: AtomicU64 = AtomicU64::new(0);
    /// P_Skip singles taken by the full-pel direct-copy path (both planes /
    /// luma only, chroma still interpolating at mv%8!=0).
    pub static SKIP_FP_FULL: AtomicU64 = AtomicU64::new(0);
    pub static SKIP_FP_LUMA: AtomicU64 = AtomicU64::new(0);
    /// B_Skip full-pel nonzero-MV MBs taken by the offset copy/avg path.
    pub static BSKB_FP: AtomicU64 = AtomicU64::new(0);
    /// P_Skip parse side: MBs whose skip MV was FORCED (0,0) by the run
    /// theorem (left = just-committed (0,0) skip, or out-of-slice) vs MBs
    /// that ran the 3-neighbor gather + rule.
    pub static SKIPMV_FORCED: AtomicU64 = AtomicU64::new(0);
    pub static SKIPMV_DERIVED: AtomicU64 = AtomicU64::new(0);
    /// B_Skips whose zero-bi derivation was FORCED by the known-zero bitmap
    /// (left+top+topright all recorded ref0/(0,0)-both-lists) — the 6-gather
    /// b_direct_nbrs walk skipped entirely.
    pub static BSKB_FORCED: AtomicU64 = AtomicU64::new(0);
    /// Zero-bi fast B_Skip grid commits batched into row spans: MBs covered
    /// and spans flushed (fills of 4N replace N MBs x 28 per-MB fills).
    pub static BZ_SPAN_MBS: AtomicU64 = AtomicU64::new(0);
    pub static BZ_SPANS: AtomicU64 = AtomicU64::new(0);
    /// P_Skip (0,0) grid-commit spans (parse-side mirror of BZ_*).
    pub static PZ_SPAN_MBS: AtomicU64 = AtomicU64::new(0);
    pub static PZ_SPANS: AtomicU64 = AtomicU64::new(0);
    /// Census: b_mc bi-pred regions where BOTH MVs are full-pel (fusable to a
    /// direct offset average — sizing only, no behavior).
    pub static BMC_BI_FP: AtomicU64 = AtomicU64::new(0);
    /// weight_partition passes skipped because the whole list-0 table is
    /// identity (384 apply ops avoided per full-MB pass).
    pub static WP_SKIPPED: AtomicU64 = AtomicU64::new(0);
    /// Intra I_4x4 luma residual dispatch (the inter ladder, ported): how many
    /// blocks took the zero / DC-only / sparse-scatter / dense arms.
    pub static I4_ZERO: AtomicU64 = AtomicU64::new(0);
    pub static I4_DC: AtomicU64 = AtomicU64::new(0);
    pub static I4_SPARSE: AtomicU64 = AtomicU64::new(0);
    pub static I4_DENSE: AtomicU64 = AtomicU64::new(0);
    /// 8x8 residual blocks (intra + inter t8) whose residual is entirely zero:
    /// recon == pred, the 64-px widen + add + clip skipped.
    pub static T8_ZERO: AtomicU64 = AtomicU64::new(0);
    /// I_16x16 4x4 sub-blocks with zero AC: the residual is the (already
    /// Hadamard-transformed) DC alone, so the dense dequant + IDCT collapse
    /// to one flat add.
    pub static I16_DCONLY: AtomicU64 = AtomicU64::new(0);
    pub static J_INTER_NORES: AtomicU64 = AtomicU64::new(0);
    // ---- deb:derive census (derive_bs_row) — sizing the bS derivation arms.
    /// Rows derived, and macroblocks derived across them.
    pub static DBS_ROWS: AtomicU64 = AtomicU64::new(0);
    pub static DBS_MB: AtomicU64 = AtomicU64::new(0);
    /// Arm split: Intra kind-arm / Skip|InterUniform kind-arm (only under
    /// RS_H264_KIND_LOADS=1) / the packed `derive_mb_records` default.
    pub static DBS_INTRA: AtomicU64 = AtomicU64::new(0);
    pub static DBS_KINDARM: AtomicU64 = AtomicU64::new(0);
    /// Macroblocks whose kind is Skip|InterUniform: the population that used
    /// to evaluate the `kind_loads()` OnceLock guard once EACH.
    pub static DBS_KINDGUARD: AtomicU64 = AtomicU64::new(0);
    pub static DBS_PACKED: AtomicU64 = AtomicU64::new(0);
    /// Of the packed arm: macroblocks whose derivation returned `flat_inter`
    /// (internal strengths 0 by construction — the early-return class).
    pub static DBS_FLAT: AtomicU64 = AtomicU64::new(0);
    /// Macroblocks whose FINAL stored MbBs is all-zero: the population the
    /// consumer's two-16-byte-compare early-out serves, and the denominator
    /// for the per-MB 128-byte bs_v/bs_h zero-init that precedes it.
    pub static DBS_ALLZERO: AtomicU64 = AtomicU64::new(0);
    /// nnz_dbr maintenance: rows copied wholesale vs rows that actually
    /// carried a transform-8x8 macroblock needing the 8x8 OR fixup.
    pub static DBS_NNZ_ROWCOPY: AtomicU64 = AtomicU64::new(0);
    pub static DBS_T8ROW: AtomicU64 = AtomicU64::new(0);
    pub static DBS_T8MB: AtomicU64 = AtomicU64::new(0);
    /// Rows that ran the disable_deblocking_filter_idc==2 crossing-edge pass.
    pub static DBS_IDC2ROW: AtomicU64 = AtomicU64::new(0);
    #[inline]
    pub fn bump(c: &AtomicU64, n: u64) {
        if on() {
            c.fetch_add(n, Relaxed);
        }
    }
    /// Off by default, yet read on EVERY bump — up to four times per B_Skip.
    /// `OnceLock::get_or_init` is an acquire load plus an initialised-state
    /// branch behind a non-inlined call; this is the relaxed AtomicU8 tri-state
    /// the other knobs in this file already use, and it inlines to one load.
    #[inline]
    pub fn on() -> bool {
        use std::sync::atomic::AtomicU8;
        static V: AtomicU8 = AtomicU8::new(0);
        match V.load(Relaxed) {
            1 => true,
            2 => false,
            _ => {
                let b = std::env::var_os("RS_H264_EDC_STATS").is_some();
                V.store(if b { 1 } else { 2 }, Relaxed);
                b
            }
        }
    }
    pub fn report() {
        if !on() {
            return;
        }
        eprintln!(
            "EDCDISPATCH threaded_slices={} eligible_slices={}",
            DISPATCH_ON.load(Relaxed), DISPATCH_SEEN.load(Relaxed)
        );
        eprintln!(
            "EDCSIZE EdcMsg={} EdcJob={} PInterJob={} BJob={}",
            std::mem::size_of::<super::EdcMsg>(),
            std::mem::size_of::<super::EdcJob>(),
            std::mem::size_of::<super::PInterJob>(),
            std::mem::size_of::<super::BJob>(),
        );
        let (n, j, r, b, m) = (
            NEEDCTX.load(Relaxed), JOBS.load(Relaxed), ROWS.load(Relaxed),
            ROWBYTES.load(Relaxed), MBS.load(Relaxed),
        );
        eprintln!(
            "EDCSTAT needctx={n} jobs={j} rows={r} rowbytes={b} mbs={m} batches={} jobs_per_batch={:.1} needctx_per_1k_mb={:.1} jobs_per_needctx={:.1}",
            BATCHES.load(Relaxed),
            j as f64 / BATCHES.load(Relaxed).max(1) as f64,
            1000.0 * n as f64 / m.max(1) as f64,
            j as f64 / n.max(1) as f64
        );
        eprintln!(
            "SKIPRUN band_mbs={} band_runs={} mbs_per_run={:.1} singles={} banded_pct={:.1}",
            SKIPBAND_MBS.load(Relaxed),
            SKIPBAND_RUNS.load(Relaxed),
            SKIPBAND_MBS.load(Relaxed) as f64 / SKIPBAND_RUNS.load(Relaxed).max(1) as f64,
            SKIP_SINGLES.load(Relaxed),
            100.0 * SKIPBAND_MBS.load(Relaxed) as f64
                / (SKIPBAND_MBS.load(Relaxed) + SKIP_SINGLES.load(Relaxed)).max(1) as f64,
        );
        eprintln!(
            "SKIPNEXT peq_fp={} peq_frac={} bsk_fullmb={} bsk_1rect={} bsk_zbi={} bsk_zuni={} bsk_fp={} bsk_runcont={} bskb_fast={} skip_fp_full={} skip_fp_luma={} bskb_fp={} skipmv_forced={} skipmv_derived={} bskb_forced={} bz_spans={} bz_span_mbs={} pz_spans={} pz_span_mbs={} bmc_bi_fp={} wp_skipped={} i4_zero={} i4_dc={} i4_sparse={} i4_dense={} t8_zero={} i16_dconly={}",
            PEQ_FP.load(Relaxed), PEQ_FRAC.load(Relaxed),
            BSK_FULLMB.load(Relaxed), BSK_1RECT.load(Relaxed),
            BSK_ZBI.load(Relaxed), BSK_ZUNI.load(Relaxed),
            BSK_FP.load(Relaxed), BSK_RUNCONT.load(Relaxed),
            BSKB_FAST.load(Relaxed),
            SKIP_FP_FULL.load(Relaxed), SKIP_FP_LUMA.load(Relaxed),
            BSKB_FP.load(Relaxed),
            SKIPMV_FORCED.load(Relaxed), SKIPMV_DERIVED.load(Relaxed),
            BSKB_FORCED.load(Relaxed),
            BZ_SPANS.load(Relaxed), BZ_SPAN_MBS.load(Relaxed),
            PZ_SPANS.load(Relaxed), PZ_SPAN_MBS.load(Relaxed),
            BMC_BI_FP.load(Relaxed),
            WP_SKIPPED.load(Relaxed),
            I4_ZERO.load(Relaxed), I4_DC.load(Relaxed),
            I4_SPARSE.load(Relaxed), I4_DENSE.load(Relaxed),
            T8_ZERO.load(Relaxed), I16_DCONLY.load(Relaxed),
        );
        let dmb = DBS_MB.load(Relaxed).max(1);
        eprintln!(
            "DBSDERIVE rows={} mb={} intra={} kindarm={} kindguard={} packed={} flat={} ({:.1}%) allzero={} ({:.1}%) nnz_rowcopy={} t8row={} t8mb={} idc2row={}",
            DBS_ROWS.load(Relaxed), DBS_MB.load(Relaxed),
            DBS_INTRA.load(Relaxed), DBS_KINDARM.load(Relaxed),
            DBS_KINDGUARD.load(Relaxed), DBS_PACKED.load(Relaxed),
            DBS_FLAT.load(Relaxed), 100.0 * DBS_FLAT.load(Relaxed) as f64 / dmb as f64,
            DBS_ALLZERO.load(Relaxed), 100.0 * DBS_ALLZERO.load(Relaxed) as f64 / dmb as f64,
            DBS_NNZ_ROWCOPY.load(Relaxed), DBS_T8ROW.load(Relaxed),
            DBS_T8MB.load(Relaxed), DBS_IDC2ROW.load(Relaxed),
        );
        let (ji, jn) = (J_INTER.load(Relaxed), J_INTER_NORES.load(Relaxed));
        eprintln!(
            "EDCMIX doubled={} nores_sent={} inter={ji} inter_no_residual={jn} ({:.1}% of inter) wasted_bytes={:.1} MB of {:.1} MB total inter payload",
            DOUBLED.load(Relaxed),
            J_NORES_SENT.load(Relaxed),
            100.0 * jn as f64 / ji.max(1) as f64,
            (jn * 2784) as f64 / 1.048576e6,
            (ji * 2784) as f64 / 1.048576e6,
        );
    }
}

fn edc_worker(
    mut ctx: PixelCtx,
    rx: std::sync::mpsc::Receiver<EdcMsg>,
    ctx_tx: std::sync::mpsc::Sender<PixelCtx>,
    back_rx: std::sync::mpsc::Receiver<PixelCtx>,
) -> PixelCtx {
    while let Ok(msg) = rx.recv() {
        match msg {
            EdcMsg::Batch(jobs) => {
                for j in jobs {
                    match j {
                        EdcJob::Skip { mbx, mby, mv } => ctx.recon_p_skip(mbx, mby, mv),
                        EdcJob::Inter(j) => ctx.recon_p_inter(&j),
                        EdcJob::InterNoRes(j) => ctx.recon_p_inter_nores(&j),
                        EdcJob::B(j) => ctx.recon_b(&j),
                        EdcJob::BSkip { mbx, mby, regions } => ctx.recon_b_skip(mbx, mby, &regions),
                    }
                }
            }
            EdcMsg::Job(EdcJob::Skip { mbx, mby, mv }) => ctx.recon_p_skip(mbx, mby, mv),
            EdcMsg::Job(EdcJob::Inter(j)) => ctx.recon_p_inter(&j),
            EdcMsg::Job(EdcJob::InterNoRes(j)) => ctx.recon_p_inter_nores(&j),
            EdcMsg::Job(EdcJob::B(j)) => ctx.recon_b(&j),
            EdcMsg::Job(EdcJob::BSkip { mbx, mby, regions }) => ctx.recon_b_skip(mbx, mby, &regions),
            EdcMsg::Row { r, bs, qp, t8 } => {
                let (w, base) = (ctx.mb_w, r * ctx.mb_w);
                ctx.bs_store[base..base + w].copy_from_slice(&bs);
                ctx.qp_grid[base..base + w].copy_from_slice(&qp);
                ctx.t8_grid[base..base + w].copy_from_slice(&t8);
                if ctx.db_ena {
                    ctx.save_bak(r);
                    ctx.filter_row(r);
                    ctx.flt_rows = r + 1;
                    ctx.publish_progress_rows();
                }
            }
            EdcMsg::NeedCtx => {
                ctx_tx.send(ctx).expect("parse thread alive");
                ctx = back_rx.recv().expect("ctx returned after intra");
            }
        }
    }
    ctx
}


/// One motion-compensation region of a B macroblock, recorded at parse time
/// (E3). Weights are the RESOLVED implicit pair — computing them needs the
/// ref lists' POCs, which are parse-side state.
pub(crate) struct BRegion {
    px: usize,
    py: usize,
    rw: usize,
    rh: usize,
    refi0: i32,
    refi1: i32,
    mv0: (i32, i32),
    mv1: (i32, i32),
    w: Option<(i32, i32)>,
}

/// A B macroblock's deferred pixel work: replay the regions into fresh
/// prediction buffers, then either copy them out (skip/direct, no residual)
/// or run the residual add.
pub(crate) struct BJob {
    mbx: usize,
    mby: usize,
    qp: u8,
    cbp_chroma: u32,
    skip: bool,
    regions: Vec<BRegion>,
    /// `None` when no 4x4 luma block was coded — t8 macroblocks included,
    /// since those carry `luma8` instead.
    luma_scan: Option<[[i32; 16]; 16]>,
    /// `Some` only under transform_size_8x8_flag.
    luma8: Option<[[i32; 64]; 4]>,
    cdc: [[i32; 4]; 2],
    /// `None` unless cbp_chroma == 2 (chroma AC coded).
    cac: Option<[[[i32; 16]; 4]; 2]>,
    nnzs: [u8; 24],
}

impl PixelCtx {
    fn b_mc(
        &self,
        mb_x: usize,
        mb_y: usize,
        px: usize,
        py: usize,
        rw: usize,
        rh: usize,
        refi0: i32,
        mv0: (i32, i32),
        refi1: i32,
        mv1: (i32, i32),
        pred_y: &mut [u8; 256],
        c_pred: &mut [[u8; 64]; 2],
        wparam: Option<(i32, i32)>,
    ) {
        let _gb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBMc);
        // Malformed-stream armor, mirroring the P path: now that B slices actually
        // PARSE ref_idx (they used to be hardcoded to 0), a mutated stream can hand
        // us an index past the end of either list. Clamp rather than panic — the
        // crate is `forbid(unsafe_code)` and fuzz-gated to never panic, and a
        // wrong picture on garbage input carries no conformance duty.
        let refi0 = if refi0 >= 0 { (refi0 as usize).min(self.refs.len().saturating_sub(1)) as i32 } else { -1 };
        let refi1 = if refi1 >= 0 { (refi1 as usize).min(self.refs1.len().saturating_sub(1)) as i32 } else { -1 };
        if (refi0 >= 0 && self.refs.is_empty()) || (refi1 >= 0 && self.refs1.is_empty()) {
            return;
        }
        let (ch, cch) = (self.mb_h * 16, self.mb_h * 8);
        // E3: implicit weights are PARSE-side (they read the ref lists' POCs);
        // the region carries the resolved pair.
        let weights = wparam;
        // Bi-prediction blend: the weights decision is LOOP-INVARIANT, so every
        // blend site below matches on `weights` ONCE and runs a branch-free
        // pixel loop — the unweighted `(p+q+1)>>1` average then autovectorizes
        // (the per-pixel closure this replaces hid the invariant behind a
        // capture, and its chroma form was a &dyn call PER PIXEL).
        // FULL-WIDTH regions (px == 0, rw == 16 — every 16×16/16×8 partition and
        // most direct regions) occupy contiguous rows of `pred_y`, so MC writes
        // the destination DIRECTLY: uni-pred needs no staging at all, bi-pred
        // stages only the second list and blends in place. The staging arrays
        // (512 B zeroed per call before this) now exist only on the branches
        // that read them. Same fusion as the P path's mc_rect (WHYS Part 8).
        let full = px == 0 && rw == 16;
        let _gl = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBLuma);
        // One scratch borrow for the whole region — both bi-pred passes included.
        // The closure yields whether the arm already ran the chroma half (the
        // bi-pred full-width arm does, to keep its staging alive) — a plain
        // `return` inside would exit the CLOSURE only and chroma would run twice.
        let chroma_done = rusty_h264_common::inter::with_mc_scratch(|scr| match (refi0 >= 0, refi1 >= 0, full) {
            (true, false, true) => {
                let Some(rf) = self.refs.get(refi0 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv0.0, mv0.1, &mut pred_y[py * 16..py * 16 + rw * rh]);
                false
            }
            (false, true, true) => {
                let Some(rf) = self.refs1.get(refi1 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv1.0, mv1.1, &mut pred_y[py * 16..py * 16 + rw * rh]);
                false
            }
            (true, true, true) => {
                let Some(rf) = self.refs.get(refi0 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv0.0, mv0.1, &mut pred_y[py * 16..py * 16 + rw * rh]);
                let mut b = [0u8; 256];
                let Some(rf) = self.refs1.get(refi1 as usize) else { return false };
                rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16, mb_y * 16 + py, rw, rh, mv1.0, mv1.1, &mut b[..rw * rh]);
                drop(_gl);
                let _gbl = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBBlend);
                // SLICE-then-zip: proving the bounds ONCE lets rustc emit the whole
                // 256-byte average as 8 straight-line vpavgb ops (verified in
                // isolation, x86-64-v3); the indexed form kept a per-iteration
                // bounds check and a loop. A hand AVX2 kernel is refuted — the
                // compiler already emits the ideal instruction.
                let dst = &mut pred_y[py * 16..py * 16 + rw * rh];
                match weights {
                    None => {
                        for (d, s) in dst.iter_mut().zip(&b[..rw * rh]) {
                            *d = ((*d as u16 + *s as u16 + 1) >> 1) as u8;
                        }
                    }
                    Some((w0, w1)) => {
                        for (d, s) in dst.iter_mut().zip(&b[..rw * rh]) {
                            *d = ((*d as i32 * w0 + *s as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                        }
                    }
                }
                let _gc = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBChroma);
                self.b_mc_chroma(mb_x, mb_y, px, py, rw, rh, refi0, mv0, refi1, mv1, c_pred, weights, cch);
                true
            }
            _ => {
                // Narrow region — rows are strided in `pred_y`; stage and copy.
                let (mut a, mut b) = ([0u8; 256], [0u8; 256]);
                if refi0 >= 0 {
                    let Some(rf) = self.refs.get(refi0 as usize) else { return false };
                    rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16 + px, mb_y * 16 + py, rw, rh, mv0.0, mv0.1, &mut a[..rw * rh]);
                }
                if refi1 >= 0 {
                    let Some(rf) = self.refs1.get(refi1 as usize) else { return false };
                    rusty_h264_common::inter::mc_luma_padded_pre(scr, &*rf.luma_guard(rf.ch), rf.lstride(), crate::LPAD, self.cw, ch, mb_x * 16 + px, mb_y * 16 + py, rw, rh, mv1.0, mv1.1, &mut b[..rw * rh]);
                }
                drop(_gl);
                let _gbl = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBBlend);
                match (refi0 >= 0, refi1 >= 0) {
                    (true, true) => {
                        for dy in 0..rh {
                            let (ar, br) = (&a[dy * rw..dy * rw + rw], &b[dy * rw..dy * rw + rw]);
                            let base = (py + dy) * 16 + px;
                            let dst = &mut pred_y[base..base + rw];
                            match weights {
                                None => {
                                    for ((d, p), q) in dst.iter_mut().zip(ar).zip(br) {
                                        *d = ((*p as u16 + *q as u16 + 1) >> 1) as u8;
                                    }
                                }
                                Some((w0, w1)) => {
                                    for ((d, p), q) in dst.iter_mut().zip(ar).zip(br) {
                                        *d = ((*p as i32 * w0 + *q as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                                    }
                                }
                            }
                        }
                    }
                    (true, false) => {
                        for dy in 0..rh {
                            let d = (py + dy) * 16 + px;
                            pred_y[d..d + rw].copy_from_slice(&a[dy * rw..dy * rw + rw]);
                        }
                    }
                    _ => {
                        for dy in 0..rh {
                            let d = (py + dy) * 16 + px;
                            pred_y[d..d + rw].copy_from_slice(&b[dy * rw..dy * rw + rw]);
                        }
                    }
                }
                false
            }
        });
        if chroma_done {
            return;
        }
        let _gc = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecBChroma);
        self.b_mc_chroma(mb_x, mb_y, px, py, rw, rh, refi0, mv0, refi1, mv1, c_pred, weights, cch);
    }

    fn b_mc_chroma(
        &self,
        mb_x: usize,
        mb_y: usize,
        px: usize,
        py: usize,
        rw: usize,
        rh: usize,
        refi0: i32,
        mv0: (i32, i32),
        refi1: i32,
        mv1: (i32, i32),
        c_pred: &mut [[u8; 64]; 2],
        weights: Option<(i32, i32)>,
        cch: usize,
    ) {
        let (crx, cry, crw, crh) = (px / 2, py / 2, rw / 2, rh / 2);
        let full = crx == 0 && crw == 8;
        for c in 0..2 {
            match (refi0 >= 0, refi1 >= 0, full) {
                (true, false, true) => {
                    let Some(rf) = self.refs.get(refi0 as usize) else { return };
                    let pl = if c == 0 { &*rf.chroma_guard(0, rf.ch) } else { &*rf.chroma_guard(1, rf.ch) };
                    mc_chroma_padded(pl, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv0.0, mv0.1, &mut c_pred[c][cry * 8..cry * 8 + crw * crh]);
                }
                (false, true, true) => {
                    let Some(rf) = self.refs1.get(refi1 as usize) else { return };
                    let pl = if c == 0 { &*rf.chroma_guard(0, rf.ch) } else { &*rf.chroma_guard(1, rf.ch) };
                    mc_chroma_padded(pl, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv1.0, mv1.1, &mut c_pred[c][cry * 8..cry * 8 + crw * crh]);
                }
                (true, true, true) => {
                    let Some(rf) = self.refs.get(refi0 as usize) else { return };
                    let pl = if c == 0 { &*rf.chroma_guard(0, rf.ch) } else { &*rf.chroma_guard(1, rf.ch) };
                    mc_chroma_padded(pl, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv0.0, mv0.1, &mut c_pred[c][cry * 8..cry * 8 + crw * crh]);
                    let mut cb = [0u8; 64];
                    let Some(rf) = self.refs1.get(refi1 as usize) else { return };
                    let pl = if c == 0 { &*rf.chroma_guard(0, rf.ch) } else { &*rf.chroma_guard(1, rf.ch) };
                    mc_chroma_padded(pl, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8, mb_y * 8 + cry, crw, crh, mv1.0, mv1.1, &mut cb[..crw * crh]);
                    let dst = &mut c_pred[c][cry * 8..cry * 8 + crw * crh];
                    match weights {
                        None => {
                            for (d, s) in dst.iter_mut().zip(&cb[..crw * crh]) {
                                *d = ((*d as u16 + *s as u16 + 1) >> 1) as u8;
                            }
                        }
                        Some((w0, w1)) => {
                            for (d, s) in dst.iter_mut().zip(&cb[..crw * crh]) {
                                *d = ((*d as i32 * w0 + *s as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                            }
                        }
                    }
                }
                _ => {
                    let (mut ca, mut cb) = ([0u8; 64], [0u8; 64]);
                    if refi0 >= 0 {
                        let Some(rf) = self.refs.get(refi0 as usize) else { return };
                        let pl = if c == 0 { &*rf.chroma_guard(0, rf.ch) } else { &*rf.chroma_guard(1, rf.ch) };
                        mc_chroma_padded(pl, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8 + crx, mb_y * 8 + cry, crw, crh, mv0.0, mv0.1, &mut ca[..crw * crh]);
                    }
                    if refi1 >= 0 {
                        let Some(rf) = self.refs1.get(refi1 as usize) else { return };
                        let pl = if c == 0 { &*rf.chroma_guard(0, rf.ch) } else { &*rf.chroma_guard(1, rf.ch) };
                        mc_chroma_padded(pl, rf.cstride(), crate::CPAD, self.ccw, cch, mb_x * 8 + crx, mb_y * 8 + cry, crw, crh, mv1.0, mv1.1, &mut cb[..crw * crh]);
                    }
                    match (refi0 >= 0, refi1 >= 0) {
                        (true, true) => {
                            for dy in 0..crh {
                                let (pr, qr) = (&ca[dy * crw..dy * crw + crw], &cb[dy * crw..dy * crw + crw]);
                                let base = (cry + dy) * 8 + crx;
                                let dst = &mut c_pred[c][base..base + crw];
                                match weights {
                                    None => {
                                        for ((d, p), q) in dst.iter_mut().zip(pr).zip(qr) {
                                            *d = ((*p as u16 + *q as u16 + 1) >> 1) as u8;
                                        }
                                    }
                                    Some((w0, w1)) => {
                                        for ((d, p), q) in dst.iter_mut().zip(pr).zip(qr) {
                                            *d = ((*p as i32 * w0 + *q as i32 * w1 + 32) >> 6).clamp(0, 255) as u8;
                                        }
                                    }
                                }
                            }
                        }
                        (true, false) => {
                            for dy in 0..crh {
                                let d = (cry + dy) * 8 + crx;
                                c_pred[c][d..d + crw].copy_from_slice(&ca[dy * crw..dy * crw + crw]);
                            }
                        }
                        _ => {
                            for dy in 0..crh {
                                let d = (cry + dy) * 8 + crx;
                                c_pred[c][d..d + crw].copy_from_slice(&cb[dy * crw..dy * crw + crw]);
                            }
                        }
                    }
                }
            }
        }
    }

    /// B_Skip replay: regions into fresh prediction buffers, then the plane
    /// copy — no residual, no coefficient arrays.
    fn recon_b_skip(&mut self, mbx: usize, mby: usize, regions: &[BRegion]) {
        crate::RefFrame::set_mc_row_need(mby, self.mb_h * 16);
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        for r in regions {
            self.b_mc(mbx, mby, r.px, r.py, r.rw, r.rh, r.refi0, r.mv0, r.refi1, r.mv1, &mut pred_y, &mut c_pred, r.w);
        }
        for dy in 0..16 {
            let d = (mby * 16 + dy) * self.cw + mbx * 16;
            self.rec_y[d..d + 16].copy_from_slice(&pred_y[dy * 16..dy * 16 + 16]);
        }
        for c in 0..2 {
            let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
            for dy in 0..8 {
                let d = (mby * 8 + dy) * self.ccw + mbx * 8;
                plane[d..d + 8].copy_from_slice(&c_pred[c][dy * 8..dy * 8 + 8]);
            }
        }
    }

    /// Replays one B macroblock's regions + residual (the worker half of the
    /// E3 seam). Mirrors the inline order exactly: MC regions in parse order
    /// into the prediction buffers, then the residual add (or the skip copy).
    fn recon_b(&mut self, j: &BJob) {
        crate::RefFrame::set_mc_row_need(j.mby, self.mb_h * 16);
        let mut pred_y = [0u8; 256];
        let mut c_pred = [[0u8; 64]; 2];
        for r in &j.regions {
            self.b_mc(j.mbx, j.mby, r.px, r.py, r.rw, r.rh, r.refi0, r.mv0, r.refi1, r.mv1, &mut pred_y, &mut c_pred, r.w);
        }
        if j.skip {
            for dy in 0..16 {
                let d = (j.mby * 16 + dy) * self.cw + j.mbx * 16;
                self.rec_y[d..d + 16].copy_from_slice(&pred_y[dy * 16..dy * 16 + 16]);
            }
            for c in 0..2 {
                let plane = if c == 0 { &mut self.rec_u } else { &mut self.rec_v };
                for dy in 0..8 {
                    let d = (j.mby * 8 + dy) * self.ccw + j.mbx * 8;
                    plane[d..d + 8].copy_from_slice(&c_pred[c][dy * 8..dy * 8 + 8]);
                }
            }
        } else {
            self.cur_qp = j.qp;
            self.add_inter_residual(j.mbx, j.mby, &pred_y, &c_pred, j.luma_scan.as_ref(), j.luma8.as_ref(), &j.cdc, j.cac.as_ref(), j.cbp_chroma, &j.nnzs);
        }
    }
}


/// D9b: MC-call coalescing for a P inter MB from committed per-block (mv, ref).
/// Shared by residual and no-residual recon — filters are per-output-pixel so
/// wider rects are bit-identical to sixteen 4×4 calls.
fn coalesce_p_inter_mc(
    refs: &[crate::Ref],
    cw: usize,
    ccw: usize,
    mb_h: usize,
    mbx: usize,
    mby: usize,
    gmv: &[(i32, i32); 16],
    gref: &[usize; 16],
    pred_y: &mut [u8; 256],
    c_pred: &mut [[u8; 64]; 2],
) {
    let _ms = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::DecMcStage);
    let (rh16, cch) = (mb_h * 16, mb_h * 8);
    let rect_eq = |x4: usize, y4: usize, w4: usize, h4: usize| -> bool {
        let t = y4 * 4 + x4;
        (0..h4).all(|dy| {
            (0..w4).all(|dx| {
                // 4x4 block grid: the index is always < 16, but LLVM cannot
                // infer it from the nested ranges. `& 15` states it.
                let b = ((y4 + dy) * 4 + (x4 + dx)) & 15;
                gmv[b] == gmv[t] && gref[b] == gref[t]
            })
        })
    };
    let mut mc_rect = |x4: usize, y4: usize, w4: usize, h4: usize| {
        let b = y4 * 4 + x4;
        let (mv, gr) = (gmv[b & 15], gref[b & 15]);
        let Some(reference) = refs.get(gr) else { return };
        let (w, h) = (w4 * 4, h4 * 4);
        if w == 16 {
            rusty_h264_common::inter::with_mc_scratch(|scr| {
                rusty_h264_common::inter::mc_luma_padded_pre(
                    scr,
                    &*reference.luma_guard(reference.ch),
                    reference.lstride(),
                    crate::LPAD,
                    cw,
                    rh16,
                    mbx * 16,
                    mby * 16 + y4 * 4,
                    w,
                    h,
                    mv.0,
                    mv.1,
                    &mut pred_y[y4 * 64..y4 * 64 + w * h],
                )
            });
        } else {
            let mut t = [0u8; 256];
            rusty_h264_common::inter::with_mc_scratch(|scr| {
                rusty_h264_common::inter::mc_luma_padded_pre(
                    scr,
                    &*reference.luma_guard(reference.ch),
                    reference.lstride(),
                    crate::LPAD,
                    cw,
                    rh16,
                    mbx * 16 + x4 * 4,
                    mby * 16 + y4 * 4,
                    w,
                    h,
                    mv.0,
                    mv.1,
                    &mut t[..w * h],
                )
            });
            let _pb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
            for dy in 0..h {
                pred_y[(y4 * 4 + dy) * 16 + x4 * 4..][..w]
                    .copy_from_slice(&t[dy * w..dy * w + w]);
            }
        }
        let (cw4, ch4) = (w4 * 2, h4 * 2);
        let nc = cw4 * ch4;
        let (gu, gv) = (reference.chroma_guard(0, reference.ch), reference.chroma_guard(1, reference.ch));
        // U+V paired: one setup serves both planes (see mc_chroma_padded_pair).
        if cw4 == 8 {
            let [cu, cv] = &mut *c_pred;
            rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, reference.cstride(), crate::CPAD, ccw, cch, mbx * 8, mby * 8 + y4 * 2, cw4, ch4, mv.0, mv.1, &mut cu[y4 * 16..y4 * 16 + nc], &mut cv[y4 * 16..y4 * 16 + nc]);
        } else {
            let (mut tu, mut tv) = ([0u8; 64], [0u8; 64]);
            rusty_h264_common::inter::mc_chroma_padded_pair(&gu, &gv, reference.cstride(), crate::CPAD, ccw, cch, mbx * 8 + x4 * 2, mby * 8 + y4 * 2, cw4, ch4, mv.0, mv.1, &mut tu[..nc], &mut tv[..nc]);
            let _pb = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::PredBuf);
            for (cc, tc) in [(0usize, &tu), (1, &tv)] {
                for dy in 0..ch4 {
                    c_pred[cc][(y4 * 2 + dy) * 8 + x4 * 2..][..cw4]
                        .copy_from_slice(&tc[dy * cw4..dy * cw4 + cw4]);
                }
            }
        }
    };
    if rect_eq(0, 0, 4, 4) {
        mc_rect(0, 0, 4, 4);
    } else if rect_eq(0, 0, 4, 2) && rect_eq(0, 2, 4, 2) {
        mc_rect(0, 0, 4, 2);
        mc_rect(0, 2, 4, 2);
    } else if rect_eq(0, 0, 2, 4) && rect_eq(2, 0, 2, 4) {
        mc_rect(0, 0, 2, 4);
        mc_rect(2, 0, 2, 4);
    } else {
        for q in 0..4usize {
            let (qx, qy) = ((q % 2) * 2, (q / 2) * 2);
            if rect_eq(qx, qy, 2, 2) {
                mc_rect(qx, qy, 2, 2);
            } else if rect_eq(qx, qy, 2, 1) && rect_eq(qx, qy + 1, 2, 1) {
                mc_rect(qx, qy, 2, 1);
                mc_rect(qx, qy + 1, 2, 1);
            } else if rect_eq(qx, qy, 1, 2) && rect_eq(qx + 1, qy, 1, 2) {
                mc_rect(qx, qy, 1, 2);
                mc_rect(qx + 1, qy, 1, 2);
            } else {
                for j in 0..4usize {
                    mc_rect(qx + (j % 2), qy + (j / 2), 1, 1);
                }
            }
        }
    }
}

/// One deferred pixel-reconstruction job (entropy-decouple E1 seam).
enum EdcJob {
    Skip { mbx: usize, mby: usize, mv: (i32, i32) },
    Inter(Box<PInterJob>),
    B(Box<BJob>),
    /// B_Skip / no-residual direct: regions only. The full `BJob` carried
    /// 2.6 KB of ZEROED coefficient arrays for ~60% of B macroblocks — the
    /// wall-time regression's main CPU tax (B-heavy MT arm measured +45% CPU).
    BSkip { mbx: usize, mby: usize, regions: Vec<BRegion> },
    /// P inter with `cbp == 0` — the P-side twin of `BSkip` (D9).
    InterNoRes(Box<PInterNoResJob>),
}

/// A P inter macroblock with NO residual (`cbp == 0`) — motion only.
///
/// D9. `PInterJob` is 2,784 bytes and **93% of that is coefficient arrays**
/// (`luma_scan` 1024 + `luma8` 1024 + `cac` 512 + `cdc` 32 = 2,592). When
/// `cbp == 0` every one of them is ZERO, and the seam was heap-allocating,
/// filling, channel-passing and freeing all 2,592 bytes of nothing —
/// 12.8-37.5% of inter jobs on the x264 corpus, 15.8-44.1 MB per 60-frame pass.
///
/// This is the same pathology `EdcJob::BSkip` was introduced to fix on the B
/// side ("2.6 KB of ZEROED coefficient arrays for ~60% of B macroblocks — the
/// wall-time regression's main CPU tax"). It was never ported to P.
///
/// Consumer uses `recon_p_inter_nores` (MC + plane copy) — bit-identical to
/// `recon_p_inter` on zero residuals, without memset of 2.5 KB coeff arrays.
/// (`RS_H264_NORES=0` keeps the old full-job path for A/B — routed at the
/// CONSTRUCTOR, so this job carries only what nores recon reads.)
struct PInterNoResJob {
    mbx: usize,
    mby: usize,
    t8: bool,
    gmv: [(i32, i32); 16],
    gref: [u8; 16],
}


/// The compact inputs of one CABAC P inter macroblock's reconstruction.
/// Shared all-zero residual planes. An Option-shaped residual field is `None`
/// exactly when the parse wrote nothing into it, and every consumer read is
/// already guarded by a zero-count test — so a `None` reader would have seen
/// zeros anyway. Pointing at one static beats zero-initialising 1 KB (luma) or
/// 512 B (chroma AC) of stack per macroblock.
static ZERO_LUMA_SCAN: [[i32; 16]; 16] = [[0; 16]; 16];
/// `(16384 + |td|/2) / td` for every `td` the spec can present. `td` is
/// `.clamp(-128, 127)` at both call sites (spec 8.4.1.2.3), so the divide has
/// exactly 256 possible inputs and a table replaces it EXACTLY -- this is not an
/// approximation, it is the same arithmetic evaluated ahead of time. `td == 0`
/// is guarded by the caller and maps to 0 here so the table has no hole.
static TX_FOR_TD: [i32; 256] = {
    let mut t = [0i32; 256];
    let mut i = 0usize;
    while i < 256 {
        let td = i as i32 - 128; // index 0 => -128 .. index 255 => 127
        t[i] = if td == 0 { 0 } else { (16384 + td.abs() / 2) / td };
        i += 1;
    }
    t
};

#[inline(always)]
fn tx_for_td(td: i32) -> i32 {
    debug_assert!((-128..=127).contains(&td), "td must be clamped before this");
    TX_FOR_TD[(td.clamp(-128, 127) + 128) as usize]
}

/// The "no coefficients" neighbour record. `mb_nzc` reads are reached only
/// through `if let Some(..) = top/left`, so an out-of-range index is
/// unreachable; this is what the unavailable branches already imply.
static ZERO_NZC: [u8; 24] = [0u8; 24];
static ZERO_CAC: [[[i32; 16]; 4]; 2] = [[[0; 16]; 4]; 2];

struct PInterJob {
    mbx: usize,
    mby: usize,
    qp: u8,
    cbp_chroma: u32,
    /// The committed per-block motion, copied at parse time so the worker
    /// never reads the parse thread's grids (E2). Ref indices clamped by the
    /// consumer, kept u8 (spec max 15).
    gmv: [(i32, i32); 16],
    gref: [u8; 16],
    /// `None` when no 4x4 luma block was coded — t8 macroblocks included,
    /// since those carry `luma8` instead.
    luma_scan: Option<[[i32; 16]; 16]>,
    /// `Some` only under transform_size_8x8_flag.
    luma8: Option<[[i32; 64]; 4]>,
    cdc: [[i32; 4]; 2],
    /// `None` unless cbp_chroma == 2 (chroma AC coded).
    cac: Option<[[[i32; 16]; 4]; 2]>,
    nnzs: [u8; 24],
}

/// Entropy-decouple master knob — DEFAULT ON since 2026-08-05 (`RS_H264_EDC=0`
/// opts out). E1 was expected to be cost-neutral scaffolding for the E2
/// thread; it BANKED on its own: 13/15 pairs, z=2.84, median +4.0% (pooled
/// 19/24, z=2.86). Mechanism: LOOP FISSION — batching a row's parsing and
/// then a row's reconstruction keeps each large code path's I-cache and
/// branch state hot, instead of alternating two giant bodies per macroblock.
fn edc_on() -> bool {
    use std::sync::atomic::{AtomicU8, Ordering};
    static ON: AtomicU8 = AtomicU8::new(0);
    match ON.load(Ordering::Relaxed) {
        0 => {
            let v = !std::env::var_os("RS_H264_EDC").is_some_and(|v| v == "0");
            ON.store(if v { 1 } else { 2 }, Ordering::Relaxed);
            v
        }
        n => n == 1,
    }
}

/// E2/E3 worker-thread knob.
///
/// **Default OFF (2026-08-11).** ffmpeg's parallel unit is the PICTURE
/// (`decode_slice` + `hl_decode_mb` on the same thread). `edc_worker` is a
/// nested recon thread — the wrong function:
///   * 1T (`ffmpeg -threads 1`, pinvs pin): two threads thrash one core
///   * frame-MT (`ffmpeg -threads N`): each picture worker would spawn another
/// Frame-MT (`RS_H264_FRAME_THREADS=N`) is the ffmpeg-shaped pool. This
/// pipeline stays as an explicit oracle (`RS_H264_EDC_MT=1`) / old auto-gate
/// (`=auto`). `=0` forces inline.
/// D8: run every pixel reconstruction TWICE (the second pass is discarded work,
/// not discarded output -- recon is idempotent, so the bytes are unchanged).
/// `t(double) - t(single)` IS the pixel half's cost, which is the parallel
/// fraction the E2 seam can address. Byte-identity is the proof the ablation
/// did not change the program (unlike removing the stage, which cascades).
/// D9 compact no-residual P inter jobs. `RS_H264_NORES=0` restores the old
/// always-full-payload path for A/B (the arm must PIN the value, never inherit
/// a default -- an "off" arm that only omits an override measures
/// default-vs-default and prints all zeros).
/// D10 row batching — **DEFAULT ON. A DELIBERATE THROUGHPUT-OVER-LATENCY TRADE.**
///
/// Ships a row's pixel jobs in one message instead of one per macroblock:
/// 207,949 sends -> 3,086 (**67-70x fewer**), and **~3% less CPU**.
///
/// ⚠ IT COSTS 2-4% WALL on a single stream — 0.963x / 0.980x, **11/11 pairs on
/// two clips**, A/B'd against itself at a fixed queue bound. That is measured,
/// reproducible, and ACCEPTED, not an oversight. Do not "fix" it by flipping
/// the default; read this first.
///
/// WHY IT COSTS WALL: batching trades pipelining for synchronisation.
/// Per-macroblock sends let the worker start on job 1 immediately; a row batch
/// makes it idle until ~70 macroblocks are parsed, then hands it a burst.
///
/// WHY IT IS STILL THE RIGHT DEFAULT: wall time here is SINGLE-STREAM LATENCY;
/// CPU is THROUGHPUT. A host decoding many streams concurrently is CPU-bound,
/// not latency-bound, so 3% less CPU is ~3% more capacity while the 2-4% wall
/// cost falls on a dimension that is not the constraint. The 67x drop in
/// channel operations also removes a park/unpark storm that scales with the
/// number of runnable threads — it gets better, not worse, as the box fills.
///
/// `RS_H264_BATCH=0` restores per-macroblock sends for the latency-sensitive
/// single-stream case (playback, seek preview, anything where first-frame time
/// dominates).
fn batch_on() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| !std::env::var_os("RS_H264_BATCH").is_some_and(|v| v == "0"))
}

fn nores_on() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| !std::env::var_os("RS_H264_NORES").is_some_and(|v| v == "0"))
}

/// D13 A/B: always allocate B-only CABAC neighbour grids even on P/I slices.
fn fat_slice_on() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_FAT_SLICE").is_some_and(|v| v == "1"))
}

/// MEASUREMENT KNOB — `RS_H264_NO_SKIPBAND=1` forces the per-MB skip path so the
/// mb_skip_run band coalescer can be A/B'd paired on ONE binary. Inert when unset.
fn no_skipband() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_NO_SKIPBAND").is_some_and(|v| v == "1"))
}

/// MEASUREMENT KNOB — `RS_H264_NO_RUNMV=1` forces the full skip_mv derivation
/// on every P_Skip (disables the run-theorem forced-(0,0) branch) for paired A/B.
fn no_runmv() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_NO_RUNMV").is_some_and(|v| v == "1"))
}

/// MEASUREMENT KNOB — `RS_H264_NO_SKIPFP=1` disables the P_Skip single fast
/// paths (full-pel direct copy + identity-weight-pass skip) for paired A/B.
fn no_skipfp() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_NO_SKIPFP").is_some_and(|v| v == "1"))
}

/// MEASUREMENT KNOB — `RS_H264_NO_BSKIPFAST=1` forces the full decode_b_direct
/// path for B_Skip so the zero-bi fast path can be A/B'd paired on ONE binary.
fn no_bskipfast() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_NO_BSKIPFAST").is_some_and(|v| v == "1"))
}

fn double_recon() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    // `== "1"`, not `is_some()`: the old presence test meant even
    // `RS_H264_DOUBLE_RECON=0` DOUBLED the recon work — the one knob in the
    // inventory whose "off" spelling turned it on (2026-08-27 audit, site 8).
    *V.get_or_init(|| std::env::var_os("RS_H264_DOUBLE_RECON").is_some_and(|v| v == "1"))
}

fn edc_bound() -> usize {
    static V: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *V.get_or_init(|| {
        std::env::var("RS_H264_EDC_BOUND")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(256)
    })
}

/// D12 — E2 THREADING DISPATCH. Fires on `720p-or-smaller AND bits/MB > 38.4`.
///
/// The seam threads unconditionally before this, and that shipped a REGRESSION:
/// 8-10% slower wall on main profile for 38-56% more CPU. It cannot pay in
/// general — the pixel half is only ~15.6% of decode, so Amdahl caps two
/// threads at 1.085x — but it DOES win on some streams, so the answer is a
/// dispatch, not abandonment.
///
/// Fitted with `bench/examples/gate_optimizer.rs` over **28 interleaved
/// configurations** (12 clips x core counts 4-8, `bench/pinmtx.ps1`):
/// **net +29.40 of +30.70 perfect**, train +25.10 AND holdout +4.30, worst
/// fired class **+2.94**, precision 0.80. It forgoes +0.40 of wins to avoid
/// **169.90** of losses. Calibration: depth-2 **2/300** rules passed (0.67%),
/// so the separation carries information.
///
/// Per clause, both load-bearing (dropping either: -20.50 / -50.60, 6-7 big
/// losers):
/// * `bits/MB > 38.4` — coefficient density is the runtime proxy for PIXEL
///   SHARE: more coefficients means more residual work on the far side of the
///   seam. Threshold sits in an open gap (highest excluded 35.4, lowest firing
///   41.4). Note this is the OPPOSITE direction to an earlier hand-fitted
///   `bits < 65`, which was fitted to one clip and falsified.
/// * frame <= 720p — every 1080p configuration measured loses, including a
///   low-density one, so density alone is not sufficient.
/// * `cabac` — ADDED 2026-08-07 after the CAVLC arm made those units
///   measurable. bits/MB DOES NOT TRANSFER ACROSS ENTROPY CODERS: CAVLC needs
///   more bits for the SAME coefficients, so its density (62-65) reads deep
///   inside the firing region while its pixel work is unchanged. Without this
///   clause the rule routed CAVLC into threading, where it measured 1.29-1.49x
///   SLOWER — net -52.30, worst class -40.85. With it, +29.40 and worst class
///   +2.94. `gate_optimizer` could not find this: the rule needs THREE clauses
///   and the search is depth-2 (both depth-2 pairs fail, -20.50 / -50.60).
///
/// The estimate comes from ALREADY-DECODED slices, so the first slice of a
/// stream runs INLINE (the safe arm) until a measurement exists. Both arms are
/// byte-identical, so the choice can never affect output.
/// Invoked only by `RS_H264_EDC_MT=auto` (the pre-2026-08-11 default).
fn edc_dispatch(mb_w: usize, mb_h: usize, bits_per_mb: f64, cabac: bool) -> bool {
    const BITS_MIN: f64 = 38.4;
    const MAX_MBS: usize = 5000; // 720p = 3600, 1080p = 8160
    // The `cabac` clause is NOT cosmetic — see the header note. Without it this
    // rule scores net -52.30 with worst class -40.85 once CAVLC units are in the
    // corpus, because CAVLC's bits/MB is inflated by a less efficient entropy
    // coder rather than by more pixel work.
    cabac && bits_per_mb > BITS_MIN && mb_w * mb_h <= MAX_MBS
}

fn edc_mt() -> Option<bool> {
    static V: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
    *V.get_or_init(|| match std::env::var("RS_H264_EDC_MT").ok().as_deref() {
        Some("0") => Some(false),
        Some("1") => Some(true),
        Some("auto") => None,
        _ => Some(false),
    })
}

/// Spawn `edc_worker`? ffmpeg never does this: the picture thread owns recon.
/// Frame-MT workers (`FRAME_THREADS>1`) always inline. Otherwise honor the knob
/// (`1` / `0` / `auto`→[`edc_dispatch`]; unset = inline).
fn edc_spawn_worker(mb_w: usize, mb_h: usize, bits_per_mb: f64, cabac: bool) -> bool {
    if crate::frame_mt::frame_threads() > 1 {
        return false;
    }
    edc_mt().unwrap_or_else(|| edc_dispatch(mb_w, mb_h, bits_per_mb, cabac))
}



/// Picture-end bS precompute (rowdb-off fallback). `RS_H264_BS_PRE=0` opts out.
fn bs_pre_on() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| !std::env::var_os("RS_H264_BS_PRE").is_some_and(|v| v == "0"))
}

/// Row-interleaved deblocking master knob: `RS_H264_ROWDB=0` opts out,
/// restoring the picture-end pipeline (WHYS Part 17) as the A/B comparator.
/// MEASUREMENT KNOB — `RS_H264_KIND_LOADS=1` restores the Blk::load-based
/// kind arms in derive_bs_row (see the routing comment there) for paired A/B.
fn kind_loads() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_KIND_LOADS").is_some_and(|v| v == "1"))
}

fn rowdb_on() -> bool {
    use std::sync::atomic::{AtomicU8, Ordering};
    static ON: AtomicU8 = AtomicU8::new(0);
    match ON.load(Ordering::Relaxed) {
        0 => {
            let v = !std::env::var_os("RS_H264_ROWDB").is_some_and(|v| v == "0");
            ON.store(if v { 1 } else { 2 }, Ordering::Relaxed);
            v
        }
        n => n == 1,
    }
}

/// A/B: per-MB `row_hook` body even when no row has completed (old behaviour).
fn rowhook_eager() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RS_H264_ROWHOOK_EAGER").is_some_and(|v| v == "1"))
}

/// A/B: `RS_H264_DIRECT_MEMO=0` rewalks spatial-direct neighbours every 8×8.
#[inline]
fn direct_memo_on() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| !std::env::var_os("RS_H264_DIRECT_MEMO").is_some_and(|v| v == "0"))
}

/// 4×4-block (z-order) → 30-entry (6-stride) mv/ref/mvd cache index (openh264
/// g_kCache30ScanIdx). Top neighbour = cache[idx-6], left = cache[idx-1].
use rusty_h264_common::cabac_tables::CACHE30;

/// z-order 4×4-block → raster index (openh264 g_kuiScan4). Per-MB mvd/ref state is
/// stored raster-indexed (matching how neighbour blocks 3/7/11/15 and 12..15 are read).
use rusty_h264_common::cabac_tables::G_SCAN4;

/// P `sub_mb_type` CABAC (openh264 `ParseSubMBTypeCabac`, ctx 21). 0=8×8, 1=8×4, 2=4×8, 3=4×4.
fn parse_sub_mb_type_p_cabac(cab: &mut crate::cabac::Cabac) -> u32 {
    const S: usize = 21;
    if cab.decode_decision(S) != 0 {
        return 0;
    }
    if cab.decode_decision(S + 1) != 0 {
        3 - cab.decode_decision(S + 2)
    } else {
        1
    }
}

/// Intra `mb_type` sub-parse for P/B slices (openh264 `DecodeCabacIntraMbType`, `base`=32
/// for B). Returns 0 = I_4x4, 1..=24 = I_16x16, 25 = I_PCM (in the intra numbering).
fn parse_intra_mb_type_cabac(cab: &mut crate::cabac::Cabac, base: usize) -> u32 {
    if cab.decode_decision(base) == 0 {
        return 0; // I_4x4
    }
    if cab.decode_terminate() {
        return 25; // I_PCM
    }
    let mut t = 1 + 12 * cab.decode_decision(base + 1) as u32; // cbp_luma != 0
    if cab.decode_decision(base + 2) != 0 {
        t += 4 + 4 * cab.decode_decision(base + 2) as u32;
    }
    t += 2 * cab.decode_decision(base + 3) as u32;
    t += cab.decode_decision(base + 3) as u32;
    t
}

/// B `mb_type` CABAC (openh264 `ParseMBTypeBSliceCabac`, ctx base 27). `ctx_inc` = (left
/// avail & !direct) + (top avail & !direct). Returns 0 = B_Direct_16x16, 1..=21 = the
/// L0/L1/Bi 16×16/16×8/8×16 shapes, 22 = B_8x8, 23.. = intra (mb_type − 23).
/// Test-only alias so the ENCODER crate can gate `cb_mb_type_b` against this
/// parser directly — they are exact inverses, so a round-trip is a complete gate.
#[doc(hidden)]
pub fn parse_mb_type_b(cab: &mut crate::cabac::Cabac, ctx_inc: usize) -> u32 {
    parse_mb_type_b_cabac(cab, ctx_inc)
}

#[inline]
fn parse_mb_type_b_cabac(cab: &mut crate::cabac::Cabac, ctx_inc: usize) -> u32 {
    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
    const B: usize = 27;
    if cab.decode_decision(B + ctx_inc) == 0 {
        return 0; // B_Direct_16x16
    }
    if cab.decode_decision(B + 3) == 0 {
        return 1 + cab.decode_decision(B + 5) as u32; // 16×16 L0 / L1
    }
    let mut m = (cab.decode_decision(B + 4) as u32) << 3;
    m |= (cab.decode_decision(B + 5) as u32) << 2;
    m |= (cab.decode_decision(B + 5) as u32) << 1;
    m |= cab.decode_decision(B + 5) as u32;
    if m < 8 {
        return m + 3;
    }
    if m == 13 {
        return parse_intra_mb_type_cabac(cab, 32) + 23;
    }
    if m == 14 {
        return 11; // B_Bi_8x16
    }
    if m == 15 {
        return 22; // B_8x8
    }
    m = (m << 1) | cab.decode_decision(B + 5) as u32;
    m - 4
}

/// B `sub_mb_type` CABAC (openh264 `ParseBSubMBTypeCabac`, ctx base 36). Returns 0..=12
/// per spec Table 7-18 (0 = B_Direct_8x8, 1 = B_L0_8x8, …, 12 = B_Bi_4x4).
fn parse_sub_mb_type_b_cabac(cab: &mut crate::cabac::Cabac) -> u32 {
    const B: usize = 36;
    if cab.decode_decision(B) == 0 {
        return 0; // B_Direct_8x8
    }
    if cab.decode_decision(B + 1) == 0 {
        return 1 + cab.decode_decision(B + 3) as u32; // B_L0_8x8 / B_L1_8x8
    }
    let mut st = 3u32;
    if cab.decode_decision(B + 2) != 0 {
        if cab.decode_decision(B + 3) != 0 {
            return 11 + cab.decode_decision(B + 3) as u32; // B_L1_4x4 / B_Bi_4x4
        }
        st += 4;
    }
    st += 2 * cab.decode_decision(B + 3) as u32;
    st += cab.decode_decision(B + 3) as u32;
    st
}

/// Parse one motion partition's `mvd` (x,y) and splat it into the 30-entry cache + the
/// per-MB raster mvd/ref state. `part_idx` = the partition's top-left z-order block (for
/// the ctxInc neighbour lookup); `zblocks` = every z-order 4×4 block the partition covers.
fn parse_mvd_partition(
    cab: &mut crate::cabac::Cabac,
    part_idx: usize,
    zblocks: &[usize],
    mvdc: &mut [[i16; 2]; 30],
    refc: &mut [i8; 30],
    mmvd: &mut [[i16; 2]; 16],
    mref: &mut [i8; 16],
    ref_idx: i8,
) -> (i32, i32) {
    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
    // `CACHE30` is [usize; 16] and every entry lies in [7, 28]; the mask and
    // clamp are semantic no-ops that hand LLVM the ranges it cannot infer, so
    // the `refc[s - 6]` / `mvdc[s - 1]` indexes into the 30-entry caches become
    // provable instead of bounds-checked.
    let s = CACHE30[part_idx & 15].clamp(6, 29);
    // Neighbour AVAILABILITY is per-neighbour, not per-component: the old closure
    // re-tested both refc slots for each of x and y, four loads to answer two
    // questions. Resolve once, then sum each component.
    let (av_b, av_a) = (refc[s - 6] >= 0, refc[s - 1] >= 0);
    let (nb, na) = (mvdc[s - 6], mvdc[s - 1]);
    let ctx = |comp: usize| -> usize {
        let mut a = 0i32;
        if av_b {
            a += nb[comp].unsigned_abs() as i32;
        }
        if av_a {
            a += na[comp].unsigned_abs() as i32;
        }
        if a >= 3 {
            1 + (a > 32) as usize
        } else {
            0
        }
    };
    let (cx, cy) = (ctx(0), ctx(1));
    let mvx = parse_mvd_cabac(cab, 0, cx);
    let mvy = parse_mvd_cabac(cab, 1, cy);
    let mvd = [mvx, mvy];
    if zblocks.len() == 16 {
        // Whole-macroblock partition (the dominant B shape): every raster slot
        // takes the same value — one fill each instead of 16 indexed stores.
        mmvd.fill(mvd);
        mref.fill(ref_idx);
        for &zb in zblocks {
            let c = CACHE30[zb & 15];
            mvdc[c] = mvd;
            refc[c] = ref_idx;
        }
    } else {
        for &zb in zblocks {
            // Each table was being read twice per block.
            let (c, g) = (CACHE30[zb & 15], G_SCAN4[zb & 15]);
            mvdc[c] = mvd;
            refc[c] = ref_idx;
            mmvd[g] = mvd;
            mref[g] = ref_idx;
        }
    }
    (mvx as i32, mvy as i32)
}

/// `ref_idx_l0` (P) CABAC — mirror of the encoder `cb_ref_idx`. Unary, ctxIdxOffset
/// 54: binIdx 0 → `ctx0` (condTermFlagA + 2·condTermFlagB), binIdx 1 → 4, binIdx ≥2 → 5.
pub fn parse_ref_idx_cabac(cab: &mut crate::cabac::Cabac, ctx0: usize) -> i8 {
    const B: usize = 54;
    let mut r = 0i8;
    let mut bin_idx = 0u32;
    // Cap the unary length: valid ref_idx ≤ 15 (16 refs max); the cap keeps a corrupt
    // stream from looping unboundedly. The MC clamps the index, so an over-range value
    // is decoded as garbage (never a panic) — the robustness contract, not correctness.
    while bin_idx < 32 {
        let ctx = match bin_idx {
            0 => ctx0,
            1 => 4,
            _ => 5,
        };
        if cab.decode_decision(B + ctx) == 0 {
            break;
        }
        r += 1;
        bin_idx += 1;
    }
    r
}

/// UEG3 mvd suffix (openh264 `DecodeUEGMvCabac`): TU prefix at `base + {0,1,2,3,3,..}`
/// (≤7), then EG3 bypass.
fn decode_ueg_mv(cab: &mut crate::cabac::Cabac, base: usize) -> u32 {
    const P2C: [usize; 8] = [0, 1, 2, 3, 3, 3, 3, 3];
    if cab.decode_decision(base) == 0 {
        return 0;
    }
    let mut code = 0u32;
    let mut count = 1usize;
    let mut tmp;
    loop {
        tmp = cab.decode_decision(base + P2C[count]);
        code += 1;
        count += 1;
        if tmp == 0 || count == 8 {
            break;
        }
    }
    if tmp != 0 {
        code += cabac_exp_bypass(cab, 3) + 1;
    }
    code
}

/// One `mvd` component (openh264 `ParseMvdInfoCabac`). `ctx_inc` (0/1/2) from the
/// neighbour |mvd| sum. ctxIdxOffset 40 (x) / 47 (y).
fn parse_mvd_cabac(cab: &mut crate::cabac::Cabac, comp: usize, ctx_inc: usize) -> i16 {
    let base = 40 + comp * 7; // NEW_CTX_OFFSET_MVD + comp*CTX_NUM_MVD
    if cab.decode_decision(base + ctx_inc) == 0 {
        return 0;
    }
    let mag = (decode_ueg_mv(cab, base + 3) + 1) as i16;
    if cab.decode_bypass() != 0 {
        -mag
    } else {
        mag
    }
}

/// `mb_skip_flag` CABAC (openh264 `ParseSkipFlagCabac`). `ctx_inc` = base 11 (P) or 24
/// (B) + (left avail & not-skip) + (top avail & not-skip). Returns true if skipped.
#[inline]
fn parse_mb_skip_cabac(cab: &mut crate::cabac::Cabac, ctx_inc: usize) -> bool {
    cab.decode_decision(ctx_inc) != 0
}

/// P-slice `mb_type` CABAC (openh264 `ParseMBTypePSliceCabac`). Returns 0..3 = inter
/// (P_L0_16x16 / P_16x8 / P_8x16 / P_8x8), 5 = I_4x4, 6..29 = I_16x16, 30 = I_PCM.
#[inline]
fn parse_mb_type_p_cabac(cab: &mut crate::cabac::Cabac) -> u32 {
    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
    const S: usize = 11; // NEW_CTX_OFFSET_SKIP; P mb_type contexts hang off it
    if cab.decode_decision(S + 3) == 0 {
        // inter
        return if cab.decode_decision(S + 4) != 0 {
            if cab.decode_decision(S + 6) != 0 { 1 } else { 2 }
        } else if cab.decode_decision(S + 5) != 0 {
            3
        } else {
            0
        };
    }
    // intra (prefix bit was 1)
    if cab.decode_decision(S + 6) == 0 {
        return 5; // I_4x4
    }
    if cab.decode_terminate() {
        return 30; // I_PCM
    }
    let mut t = 6 + cab.decode_decision(S + 7) * 12;
    if cab.decode_decision(S + 8) != 0 {
        t += 4;
        if cab.decode_decision(S + 8) != 0 {
            t += 4;
        }
    }
    t += cab.decode_decision(S + 9) << 1;
    t += cab.decode_decision(S + 9);
    t
}

/// I-slice `mb_type` CABAC parse (spec §9.3.2.5 / openh264 `ParseMBTypeISliceCabac`).
/// `ctx_inc` = (left MB is I_16x16/non-intra) + (top MB is …), i.e. 0..2; the corner
/// MB has no neighbours so `ctx_inc = 0`. Returns the raw mb_type: 0 = I_NxN (I_4x4/
/// I_8x8), 1..24 = I_16x16 (pred-mode/cbp packed), 25 = I_PCM.
fn parse_mb_type_i_cabac(cab: &mut crate::cabac::Cabac, ctx_inc: usize) -> u32 {
    const O: usize = 3; // ctxIdxOffset for I-slice mb_type
    if cab.decode_decision(O + ctx_inc) == 0 {
        return 0; // I_NxN
    }
    if cab.decode_terminate() {
        return 25; // I_PCM
    }
    let mut t = 1 + cab.decode_decision(O + 3) * 12; // CBP luma: 0 or 12
    if cab.decode_decision(O + 4) != 0 {
        t += 4; // CBP chroma 1 or 2
        if cab.decode_decision(O + 5) != 0 {
            t += 4;
        }
    }
    t += cab.decode_decision(O + 6) << 1; // I_16x16 pred mode (2 bins)
    t += cab.decode_decision(O + 7);
    t
}

/// One `Intra_4x4` (or `8x8`) pred-mode CABAC parse (openh264 `ParseIntraPredModeLuma
/// Cabac`): `prev_intra4x4_pred_mode_flag` (ctx 68) then, if 0, `rem_intra4x4_pred_mode`
/// (3 bins at ctx 69). Returns `-1` for "use predicted mode", else the 0..7 remainder.
fn parse_intra4x4_pred_mode_cabac(cab: &mut crate::cabac::Cabac) -> i32 {
    const IPR: usize = 68;
    if cab.decode_decision(IPR) == 1 {
        return -1; // prev_intra4x4_pred_mode_flag = 1
    }
    let mut m = cab.decode_decision(IPR + 1) as i32;
    m |= (cab.decode_decision(IPR + 1) as i32) << 1;
    m |= (cab.decode_decision(IPR + 1) as i32) << 2;
    m
}

/// `intra_chroma_pred_mode` CABAC parse (openh264 `ParseIntraPredModeChromaCabac`):
/// TU(cMax=3) — bin0 at ctx `64 + ctx_inc` (ctx_inc from neighbour chroma modes, 0 for
/// the corner MB), the rest at ctx 67. Returns the mode 0..3.
fn parse_intra_chroma_pred_mode_cabac(cab: &mut crate::cabac::Cabac, ctx_inc: usize) -> u32 {
    const CIPR: usize = 64;
    if cab.decode_decision(CIPR + ctx_inc) == 0 {
        return 0;
    }
    if cab.decode_decision(CIPR + 3) == 0 {
        return 1;
    }
    if cab.decode_decision(CIPR + 3) == 0 {
        return 2;
    }
    3
}

/// `coded_block_pattern` CABAC parse (openh264 `ParseCbpInfoCabac`), corner-MB variant
/// (top/left neighbours unavailable → their terms are 0). ctxIdxOffset 73 (luma) with 4
/// z-order 8×8 bins whose ctxInc uses the EARLIER-decoded bits within this MB, then
/// chroma bits at 77/81. Returns cbp: bits 0-3 = luma 8×8, bits 4-5 = chroma pattern.
pub fn parse_cbp_cabac(cab: &mut crate::cabac::Cabac, top: Option<u8>, left: Option<u8>) -> u32 {
    let _g = rusty_h264_common::prof::scope(rusty_h264_common::prof::Stage::Syntax);
    const CBP: usize = 73;
    let t = |m: u32| top.map_or(0u32, |c| ((c as u32 & m) == 0) as u32);
    let l = |m: u32| left.map_or(0u32, |c| ((c as u32 & m) == 0) as u32);
    let nb = |x: u32| (x == 0) as u32; // earlier 8×8 bin within this MB was NOT coded
    // Luma, 4 8×8 blocks in z-order. Top uses cbp bits 2/3, left uses 1/3.
    let b0 = cab.decode_decision(CBP + (l(1 << 1) + (t(1 << 2) << 1)) as usize);
    let b1 = cab.decode_decision(CBP + (nb(b0) + (t(1 << 3) << 1)) as usize);
    let b2 = cab.decode_decision(CBP + (l(1 << 3) + (nb(b0) << 1)) as usize);
    let b3 = cab.decode_decision(CBP + (nb(b2) + (nb(b1) << 1)) as usize);
    let mut cbp = b0 | (b1 << 1) | (b2 << 2) | (b3 << 3);
    // Chroma (4:2:0). ctxInc from neighbour chroma cbp (>>4).
    let ct = top.map_or(0u32, |c| ((c >> 4) != 0) as u32);
    let cl = left.map_or(0u32, |c| ((c >> 4) != 0) as u32);
    if cab.decode_decision(CBP + 4 + (cl + (ct << 1)) as usize) != 0 {
        let ct2 = top.map_or(0u32, |c| ((c >> 4) == 2) as u32);
        let cl2 = left.map_or(0u32, |c| ((c >> 4) == 2) as u32);
        let c1 = cab.decode_decision(CBP + 8 + (cl2 + (ct2 << 1)) as usize);
        cbp |= 1 << (4 + c1);
    }
    cbp
}

fn read_ref_idx(r: &mut BitReader, num_ref_active: usize) -> Result<i32, OutOfData> {
    if num_ref_active == 2 {
        Ok(if r.read_bit()? { 0 } else { 1 }) // te(v): value = !bit
    } else {
        Ok(r.read_ue()? as i32)
    }
}

/// B-partition prediction direction.
#[derive(Clone, Copy, PartialEq)]
enum BPred {
    L0,
    L1,
    Bi,
}
impl BPred {
    /// Whether this direction uses reference list `list` (0 or 1).
    fn uses(self, list: usize) -> bool {
        matches!(
            (self, list),
            (BPred::L0, 0) | (BPred::L1, 1) | (BPred::Bi, 0) | (BPred::Bi, 1)
        )
    }
}

const B16X16: &[(usize, usize, usize, usize)] = &[(0, 0, 16, 16)];
const B16X8: &[(usize, usize, usize, usize)] = &[(0, 0, 16, 8), (0, 8, 16, 8)];
const B8X16: &[(usize, usize, usize, usize)] = &[(0, 0, 8, 16), (8, 0, 8, 16)];

/// A partition region `(x, y, w, h)` in samples.
type Region = (usize, usize, usize, usize);

/// B `mb_type` 1..=21 → (partition layout, MV-prediction mode 0/1/2 for 16×16/
/// 16×8/8×16, per-partition prediction direction) (spec Table 7-14).
/// Test-only view of [`b_inter_layout`] for the ENCODER crate: `(mvmode, p0, p1)`
/// with pred coded 1 = L0, 2 = L1, 3 = Bi — the encoder's `b_part_mb_type` is the
/// exact inverse, so a round-trip over 4..=21 gates the two tables against drift.
pub fn b_inter_shape(mb_type: u32) -> (u8, u8, u8) {
    let (_, mvmode, preds) = b_inter_layout(mb_type);
    let code = |p: BPred| match (p.uses(0), p.uses(1)) {
        (true, true) => 3,
        (true, false) => 1,
        _ => 2,
    };
    (mvmode, code(preds[0]), code(preds[1]))
}

fn b_inter_layout(mb_type: u32) -> (&'static [Region], u8, [BPred; 2]) {
    use BPred::*;
    match mb_type {
        1 => (B16X16, 0, [L0, L0]),
        2 => (B16X16, 0, [L1, L1]),
        3 => (B16X16, 0, [Bi, Bi]),
        4 => (B16X8, 1, [L0, L0]),
        5 => (B8X16, 2, [L0, L0]),
        6 => (B16X8, 1, [L1, L1]),
        7 => (B8X16, 2, [L1, L1]),
        8 => (B16X8, 1, [L0, L1]),
        9 => (B8X16, 2, [L0, L1]),
        10 => (B16X8, 1, [L1, L0]),
        11 => (B8X16, 2, [L1, L0]),
        12 => (B16X8, 1, [L0, Bi]),
        13 => (B8X16, 2, [L0, Bi]),
        14 => (B16X8, 1, [L1, Bi]),
        15 => (B8X16, 2, [L1, Bi]),
        16 => (B16X8, 1, [Bi, L0]),
        17 => (B8X16, 2, [Bi, L0]),
        18 => (B16X8, 1, [Bi, L1]),
        19 => (B8X16, 2, [Bi, L1]),
        20 => (B16X8, 1, [Bi, Bi]),
        _ => (B8X16, 2, [Bi, Bi]), // 21
    }
}

/// Whether a B `sub_mb_type` (1..=12) uses reference list `list`.
fn b_sub_uses(st: u32, list: usize) -> bool {
    let pred = match st {
        1 | 4 | 5 | 10 => 0,  // L0
        2 | 6 | 7 | 11 => 1,  // L1
        _ => 2,               // Bi (3, 8, 9, 12)
    };
    (list == 0 && pred != 1) || (list == 1 && pred != 0)
}

/// Sub-partition shapes within an 8×8 for a B `sub_mb_type` (1..=12).
fn b_sub_parts(st: u32) -> &'static [(usize, usize, usize, usize)] {
    match st {
        1..=3 => &[(0, 0, 8, 8)],
        4 | 6 | 8 => &[(0, 0, 8, 4), (0, 4, 8, 4)],
        5 | 7 | 9 => &[(0, 0, 4, 8), (4, 0, 4, 8)],
        _ => &[(0, 0, 4, 4), (4, 0, 4, 4), (0, 4, 4, 4), (4, 4, 4, 4)], // 10/11/12
    }
}

/// Sub-macroblock partition layout `(x, y, w, h)` in samples within an 8×8, for
/// a P-slice `sub_mb_type` (0 = 8×8, 1 = 8×4, 2 = 4×8, 3 = 4×4).
fn sub_mb_partitions(sub_type: u32) -> &'static [(usize, usize, usize, usize)] {
    match sub_type {
        0 => &[(0, 0, 8, 8)],
        1 => &[(0, 0, 8, 4), (0, 4, 8, 4)],
        2 => &[(0, 0, 4, 8), (4, 0, 4, 8)],
        _ => &[(0, 0, 4, 4), (4, 0, 4, 4), (0, 4, 4, 4), (4, 4, 4, 4)],
    }
}

/// Copy a contiguous `w`x`h` block into a strided destination at `(x0, y0)`.
///
/// The width is SPECIALISED. Written as a per-pixel loop bounded by a runtime `w`,
/// this lowers to a bounds-checked store per pixel — and where it is a row copy of
/// runtime length, to a variable-length `memcpy` CALL per row. Both are the same
/// codegen trap the ENCODER fixed long ago ("H-17"); the decoder's copy of it was
/// never fixed, and it costs the most on exactly the streams a real encoder emits,
/// because x264's sub-16x16 partitions call it far more often than our own
/// 16x16-dominated bitstreams ever did. Byte-identical to the scalar form.
#[inline]
fn restride(dst: &mut [u8], dst_stride: usize, x0: usize, y0: usize, src: &[u8], w: usize, h: usize) {
    macro_rules! rows {
        ($n:expr) => {{
            for dy in 0..h {
                dst[(y0 + dy) * dst_stride + x0..][..$n].copy_from_slice(&src[dy * $n..][..$n]);
            }
        }};
    }
    match w {
        16 => rows!(16),
        8 => rows!(8),
        4 => rows!(4),
        2 => rows!(2),
        _ => {
            for dy in 0..h {
                dst[(y0 + dy) * dst_stride + x0..][..w].copy_from_slice(&src[dy * w..][..w]);
            }
        }
    }
}

/// Un-scans an 8×8 block from frame zig-zag scan order to raster (spec Table 8-12).
fn un_scan_8x8(scan: &[i32; 64]) -> [i32; 64] {
    const ZZ8: [usize; 64] = [
        0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
        20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
        58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
    ];
    let mut out = [0i32; 64];
    for k in 0..64 {
        out[ZZ8[k]] = scan[k];
    }
    out
}

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

    fn fd(qp: u8, offset: i32) -> FrameDecoder {
        FrameDecoder::new(1, 1, qp, offset, Vec::new(), 1, false, false, true)
    }

    #[test]
    fn mb_qp_delta_accumulates_mod_52() {
        let mut d = fd(26, 0);
        assert_eq!(d.cur_qp, 26, "QPy starts at the slice QP");
        d.step_qp(4).unwrap();
        assert_eq!(d.cur_qp, 30); // 26 + 4
        d.step_qp(-10).unwrap();
        assert_eq!(d.cur_qp, 20); // carries from the previous MB, not the slice
        // Wrap-around: (20 + 40 + 52) % 52 = 112 % 52 = 8.
        d.step_qp(40).unwrap();
        assert_eq!(d.cur_qp, 8);
        // Negative wrap: (8 - 20 + 52) % 52 = 40.
        d.step_qp(-20).unwrap();
        assert_eq!(d.cur_qp, 40);
    }

    #[test]
    fn chroma_qp_index_offset_applied_and_clamped() {
        // Offset 0 reproduces the bare luma->chroma table (QP30 -> 29).
        assert_eq!(fd(0, 0).chroma_qp_for(30), 29);
        // Positive offset shifts the table lookup (QP30 + 2 -> table[2] = 31).
        assert_eq!(fd(0, 2).chroma_qp_for(30), 31);
        // The qPi index is clamped into 0..=51 before the lookup.
        assert_eq!(fd(0, -12).chroma_qp_for(5), chroma_qp(0));
        assert_eq!(fd(0, 99).chroma_qp_for(40), chroma_qp(51));
    }
}